public override Type ResolveType(Serialize.Linq.Nodes.TypeNode node) { if (node.Name == typeof(RemoteObjectQuery<>).FullName) { return typeof(NhQueryable<>); } return base.ResolveType(node); }
/// <summary> /// Returns configuration information formatted as an .ini file as /// specified by <see cref="Config" />. /// </summary> /// <param name="settings">Provider specific settings.</param> /// <param name="cacheFile">File path to use for cached settings.</param> /// <param name="machineName">The requesting machine's name.</param> /// <param name="exeFile">The unqualified name of the current process' executable file.</param> /// <param name="exeVersion">The version number of the current executable file.</param> /// <param name="usage">Used to indicate a non-default usage for this application instance.</param> /// <returns>The configuration file data (or <c>null</c>).</returns> /// <remarks> /// <para> /// The settings parameter must specify the <b>RouterEP</b> and <b>CloudEP</b> setting values, /// (the rest are optional): /// </para> /// <code language="none"> /// RouterEP = <Router Physical Endpoint> /// CloudEP = <IP Endpoint> /// ConfigEP = <logical or physical endpoint> (optional) /// EnableP2P = 0 | 1 (optional) /// </code> /// <para> /// <b>RouterEP</b> specifies the unique physical endpoint to be assigned to the /// bootstrap router. This must be unique across all routers so it's best to /// use the $(Guid) environment variable somewhere within the definition. /// </para> /// <para> /// <b>CloudEP</b> specifies the IP endpoint to be used by a bootstrap /// message router to discover the other routers on the network, and <b>ConfigEP</b> /// specifies the logical or physical messaging endpoint of the configuration service. /// The class uses this information to start a leaf bootstrap router which will /// be used to discover and communicate with the configuration service. /// </para> /// <para> /// The <b>EnableP2P</b> setting indicates whether the bootstrap router should be /// peer-to-peer enabled. This parameter is optional and defaults to "1". This /// setting is present for scalability reasons. P2P enabling the bootstrap router /// will cause a lot of network traffic in environments with a lot of servers since /// every other P2P enabled router will establish a connection to the bootstrap /// router to discover its logical routes. This is a significant overhead for a /// router that exposes no routes. <b>EnableP2P</b> should be set to "0" in production /// environments with a lot of servers and with a hub server present to avoid this /// problem. /// </para> /// <para> /// The cacheFile parameter specifies the name of the file where the provider /// may choose to cache configuration settings. This implementation will save a copy /// of the last set of settings returned by a remote service in this file and /// then use these settings if the remote service is unavailable the next time /// the service is started. This improves the operational robustness of a /// large network of servers. Choosing to implement this behavior is completely /// up to the discretion of the provider. Specify <b>(no-cache)</b> to disable /// caching behavior. /// </para> /// <para> /// Note that the method will return null if the requested configuration /// information could not be loaded for any reason. /// </para> /// <para> /// This class queries the configuration service via the following message /// endpoints: /// </para> /// <code language="none"> /// abstract://LillTek/DataCenter/ConfigService /// </code> /// <para> /// This may be remapped to another logical endpoint via the message /// routers <b>MsgRouter.AbstractMap</b> configuation setting. /// </para> /// </remarks> public string GetConfig(ArgCollection settings, string cacheFile, string machineName, string exeFile, Version exeVersion, string usage) { LeafRouter router = null; RouterSettings rSettings; string s; MsgEP routerEP; IPEndPoint cloudEP; MsgEP configEP; bool enableP2P; GetConfigAck ack; string configText = null; Exception queryException = null; // Make sure that the assembly's message types have been // registered with the LillTek.Messaging subsystem. Global.RegisterMsgTypes(); // Parse the settings s = settings["RouterEP"]; if (s == null) { throw new ArgumentException("[RouterEP] setting expected.", "settings"); } try { routerEP = MsgEP.Parse(s); } catch { throw new ArgumentException("[RouterEP] is invalid.", "settings"); } if (!routerEP.IsPhysical) { throw new ArgumentException("[RouterEP] must specify a physical endpoint.", "settings"); } s = settings["CloudEP"]; if (s == null) { throw new ArgumentException("[CloudEP] setting expected.", "settings"); } cloudEP = Serialize.Parse(s, new IPEndPoint(IPAddress.Any, 0)); if (cloudEP == new IPEndPoint(IPAddress.Any, 0)) { throw new ArgumentException("[CloudEP] setting is invalid.", "settings"); } configEP = Serialize.Parse(settings["ConfigEP"], GetConfigEP); enableP2P = Serialize.Parse(settings["EnableP2P"], true); // Crank up a bootstrap leaf router and perform the query. try { router = new LeafRouter(); rSettings = new RouterSettings(routerEP); rSettings.AppName = rSettings.AppName + " (config boot)"; rSettings.CloudEP = cloudEP; rSettings.EnableP2P = enableP2P; router.Start(rSettings); ack = (GetConfigAck)router.Query(configEP, new GetConfigMsg(machineName, exeFile, exeVersion, usage)); configText = ack.ConfigText; } catch (Exception e) { queryException = e; configText = null; } finally { if (router != null) { router.Stop(); } } if (configText != null) { // Cache the query result if requested if (!string.IsNullOrWhiteSpace(cacheFile) && String.Compare(cacheFile, "(no-cache)", true) != 0) { StreamWriter writer; try { writer = new StreamWriter(cacheFile); writer.Write(configText); writer.Close(); } catch { } } } else { // Try loading a cached configuration if (string.IsNullOrWhiteSpace(cacheFile)) { SysLog.LogException(queryException, "GetConfig query failed with no cached settings."); } else { StreamReader reader; SysLog.LogWarning("GetConfig query failed: Loading cached settings."); try { reader = new StreamReader(cacheFile); configText = reader.ReadToEnd(); reader.Close(); } catch { configText = null; } } } return(configText); }
private async void Run(string item) { try { Logger.Log(LogLevel.Error, "Unable to login.\n\n"); var settings = (KeepCommandSettings)Settings; var googleClient = new GPSOAuthClient(settings.GoogleUserName, settings.GooglePassword); if (string.IsNullOrEmpty(_token)) { _token = await GetMasterToken(googleClient); } Dictionary <string, string> oauthResponse = await GetOauthResponse(googleClient).ConfigureAwait(false); if (!oauthResponse.ContainsKey("Auth")) { _token = await GetMasterToken(googleClient); } oauthResponse = await GetOauthResponse(googleClient).ConfigureAwait(false); if (!oauthResponse.ContainsKey("Auth")) { throw new Exception("Auth token was missing from oauth login response."); } var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", oauthResponse["Auth"]); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); client.DefaultRequestHeaders.Connection.Add("keep-alive"); KeepRequest keepRequest = _keepRequestFactoryFactory.Create(); HttpContent content = GetRequest(keepRequest.ToJson()); HttpResponseMessage response = await client.PostAsync("https://www.googleapis.com/notes/v1/changes", content).ConfigureAwait(false); string json = await GetJson(response).ConfigureAwait(false); KeepResponse keepResponse = Serialize.FromJson(json); Node[] newNodes = new Node[2]; string parentNodeId = settings.ListId; newNodes[0] = keepResponse.Nodes.Single(n => n.Id == parentNodeId); newNodes[1] = new Node { Text = item, ParentId = parentNodeId, ParentServerId = newNodes[0].ServerId, Type = "LIST_ITEM", Timestamps = new Timestamps { Created = DateTimeOffset.Now, Updated = DateTimeOffset.Now }, Id = new RandomHelper().GetNodeId() }; keepRequest = _keepRequestFactoryFactory.Create(newNodes, keepResponse.ToVersion); content = GetRequest(keepRequest.ToJson()); response = await client.PostAsync("https://www.googleapis.com/notes/v1/changes", content).ConfigureAwait(false); json = GetJson(response).ConfigureAwait(false).GetAwaiter().GetResult(); Logger.Log(LogLevel.Info, json); } catch (Exception ex) { Logger.Log(LogLevel.Fatal, ex); } }
/// <summary> /// Initializes a new instance of the <see cref="EncoderInfo"/> class. /// </summary> /// <param name="tag"> /// The tag. /// </param> /// <param name="encode"> /// The encode delegate. /// </param> internal EncoderInfo(Tags tag, Encode encode) { this.Tag = tag; this.encode = encode; this.serialize = null; }
public override void ice_response(Serialize.Small r, Serialize.Small o) { test(o.i == 99); test(r.i == 99); callback.called(); }
/// <summary> /// Register a custom serializer by the type and tag specified. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="tag"> /// The tag. /// </param> /// <param name="serialize"> /// The serialize delegate. /// </param> /// <returns> /// <c>true</c> if the deserialize delegate has been registered successfully, otherwise <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="serialize"/> is null. /// </exception> internal static bool Register(Type type, Tags tag, Serialize serialize) { if (type == null) { throw new ArgumentNullException("type"); } if (serialize == null) { throw new ArgumentNullException("serialize"); } return EncoderInfos.TryAdd(type, new EncoderInfo(tag, serialize)); }
public override Task<MyClass_OpSerialStructCSharpResult> opSerialStructCSharpAsync(Serialize.Struct i, Ice.Current current) { return Task.FromResult<MyClass_OpSerialStructCSharpResult>(new MyClass_OpSerialStructCSharpResult(i, i)); }
public object Deserialize(IStorage storage, Serialize.Data.Node data, object result) { return this.GetFromStringCast(data.Type).Invoke(null, System.Reflection.BindingFlags.Static, null, new object[] { data is Data.String ? (data as Data.String).Value : null }, System.Globalization.CultureInfo.InvariantCulture); }
public void ProcessRequest(HttpContext c) { var v = c.Request.QueryString["v"].ToLower().Replace("/", "."); var t = int.Parse(c.Request.QueryString["t"]); var data = (byte[])null; XFace face = null; var assb = Assembly.Load("X.App"); try { face = assb.CreateInstance(String.Format("X.App.{0}.{1}", (t == 1 ? "Views" : "Apis"), v)) as XFace; if (face == null) { throw new XExcep((t == 1 ? "0x0001" : "0x0002"), v); } face.Init(c); data = face.GetResponse(); } catch (XExcep fe) { var rsp = new XResp(fe.ErrCode, fe.ErrMsg); if (t == 1) { var view = assb.CreateInstance(String.Format("X.App.Views.{0}.err", v.Split('.')[0])) as Views.View; if (view == null) { view = assb.CreateInstance("X.App.Views.com.err") as Views.View; } view.Init(c); view.dict.Add("rsp", rsp); view.dict.Add("backurl", Secret.ToBase64(c.Request.RawUrl)); data = view.GetResponse(); } else { data = Encoding.UTF8.GetBytes(Serialize.ToJson(rsp)); } if (fe.ErrCode != "0x0001") { Loger.Error(Serialize.ToJson(rsp)); } } catch (Exception ex) { if (ex is ThreadAbortException) { return; } var resp = new XResp(Guid.NewGuid().ToString(), ex.Message); data = Encoding.UTF8.GetBytes(Serialize.ToJson(resp)); Loger.Fatal(GetType(), ex); } if (data != null) { c.Response.Clear(); c.Response.ContentEncoding = Encoding.UTF8; c.Response.OutputStream.Write(data, 0, data.Length); c.Response.End(); } }
private void btnCompute_Click(object sender, EventArgs e) { if (spec1 == null || spec2 == null) { MessageBox.Show(string.Format("第{0}条光谱为空,请先选择。", spec1 == null ? 1 : 2), "信息提示"); return; } int mwin = 0; if (!int.TryParse(txbmwin.Text, out mwin)) { MessageBox.Show("移动窗口大小必须为整数", "信息提示"); return; } IList <IFilter> filters = new List <IFilter>(); if (this._model != null) { if (this._model is IdentifyModel) { filters = ((IdentifyModel)this._model).Filters; } else if (this._model is FittingModel) { filters = ((FittingModel)this._model).Filters; } } var s1 = spec1.Clone(); var s2 = spec2.Clone(); //对光谱预处理 if (filters != null) { var ya = new MWNumericArray(s1.Data.Lenght, 1, s1.Data.Y); var yb = new MWNumericArray(s2.Data.Lenght, 1, s2.Data.Y); bool splitadd = false; var y1 = (MWNumericArray)ya.Clone(); var y2 = (MWNumericArray)yb.Clone(); var x1 = Serialize.DeepClone <double[]>(s1.Data.X); var x2 = Serialize.DeepClone <double[]>(s2.Data.X); var y1lst = new List <MWNumericArray>(); var x1lst = new List <double[]>(); var y2lst = new List <MWNumericArray>(); var x2lst = new List <double[]>(); foreach (var tf in filters) { var f = RIPP.Lib.Serialize.DeepClone <RIPP.NIR.Data.Filter.IFilter>(tf); if (f is Spliter) { if (splitadd) { x1lst.Add(x1); y1lst.Add(y1); x2lst.Add(x2); y2lst.Add(y2); } splitadd = false; y1 = (MWNumericArray)ya.Clone(); y2 = (MWNumericArray)yb.Clone(); x1 = Serialize.DeepClone <double[]>(s1.Data.X); x2 = Serialize.DeepClone <double[]>(s2.Data.X); } else { splitadd = true; } y1 = f.Process(y1); y2 = f.Process(y2); if (f.FType == FilterType.VarFilter) { x1 = f.VarProcess(x1); x2 = f.VarProcess(x2); } } if (splitadd) { x1lst.Add(x1); y1lst.Add(y1); x2lst.Add(x2); y2lst.Add(y2); } //合并 if (x1lst.Count > 0) { s1.Data.X = x1lst[0]; s1.Data.Y = (double[])y1lst[0].ToVector(MWArrayComponent.Real); s2.Data.X = x2lst[0]; s2.Data.Y = (double[])y2lst[0].ToVector(MWArrayComponent.Real); for (int i = 1; i < x1lst.Count; i++) { s1.Data.X = RIPP.NIR.Data.Tools.InsertColumn(s1.Data.X, x1lst[i], s1.Data.X.Length + 1); s1.Data.Y = RIPP.NIR.Data.Tools.InsertColumn(s1.Data.Y, (double[])y1lst[i].ToVector(MWArrayComponent.Real), s1.Data.Y.Length + 1); s2.Data.X = RIPP.NIR.Data.Tools.InsertColumn(s2.Data.X, x2lst[i], s2.Data.X.Length + 1); s2.Data.Y = RIPP.NIR.Data.Tools.InsertColumn(s2.Data.Y, (double[])y2lst[i].ToVector(MWArrayComponent.Real), s2.Data.Y.Length + 1); } } else { s1.Data.X = x1; s1.Data.Y = (double[])y1.ToVector(MWArrayComponent.Real); s2.Data.X = x2; s2.Data.Y = (double[])y2.ToVector(MWArrayComponent.Real); } //s1.Data.Y = (double[])y1.ToVector(MWArrayComponent.Real); //s2.Data.Y = (double[])y2.ToVector(MWArrayComponent.Real); } if (this._model is FittingModel) { var f = ((FittingModel)this._model).IdRegion; s1.Data.X = f.VarProcess(s1.Data.X); s2.Data.X = f.VarProcess(s2.Data.X); s1.Data.Y = f.VarProcess(s1.Data.Y); s2.Data.Y = f.VarProcess(s2.Data.Y); } //绘制 var lst = new List <Spectrum>(); lst.Add(s1); lst.Add(s2); this.specGraph3.DrawSpec(lst); this.specGraph3.SetTitle("预处理后光谱"); double[] tSQ; double tTQ; RIPP.NIR.Data.Tools.MWCorr(s1.Data.Y, s2.Data.Y, mwin, out tTQ, out tSQ); var spec = RIPP.Lib.Serialize.DeepClone <Spectrum>(s1); spec.Data.Y = tSQ; spec.Name = "SQ"; spec.Color = Color.Blue; this.specGraph2.DrawSpec(new List <Spectrum>() { spec }); this.txbTQ.Text = tTQ.ToString("f3"); this.txbSQ.Text = tSQ.Min().ToString("f3"); }
private static void ExcelToXml(string className) { string path = REGXMLPATH + className + ".xml"; Dictionary <string, SheetClass> allSheetDict = ReadRegXml(path); string excelPath = EXCELPATH + className + ".xlsx"; Dictionary <string, SheetData> sheetDataDict = new Dictionary <string, SheetData>(); try { using (FileStream fs = new FileStream(excelPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (ExcelPackage package = new ExcelPackage(fs)) { ExcelWorksheets excelWorksheets = package.Workbook.Worksheets; for (int i = 0; i < excelWorksheets.Count; i++) { ExcelWorksheet worksheet = excelWorksheets[i + 1]; SheetData sheetData = new SheetData(); SheetClass sheetClass = allSheetDict[worksheet.Name]; for (int j = 0; j < sheetClass.VarList.Count; j++) { sheetData.AllName.Add(sheetClass.VarList[j].Name); sheetData.AllType.Add(sheetClass.VarList[j].Type); } int rowCount = worksheet.Dimension.End.Row; int colCount = worksheet.Dimension.End.Column; for (int m = 1; m < rowCount; m++) { RowData rowData = new RowData(); int n = 0; if (!string.IsNullOrEmpty(sheetClass.ParentVar.Foreign)) { rowData.ForeignValue = worksheet.Cells[m + 1, 1].Value.ToString().Trim(); n = 1; } for (; n < colCount; n++) { ExcelRange range = worksheet.Cells[m + 1, n + 1]; string propertyName = GetNameByCol(sheetClass.VarList, worksheet.Cells[1, n + 1].Value.ToString().Trim()); string value = range.Value.ToString().Trim(); if (string.IsNullOrEmpty(value)) { Debug.LogError("Excel存在数据为空:[" + (m + 1) + "," + (n + 1) + "]"); continue; } rowData.RowDataDict.Add(propertyName, value); } sheetData.AllRowData.Add(rowData); } sheetDataDict.Add(worksheet.Name, sheetData); } } } } catch (Exception e) { Debug.LogError(e); return; } Type type = GetType(className); object objClass = null; if (type != null) { objClass = System.Activator.CreateInstance(type); } List <string> outKeyList = new List <string>(); foreach (string key in allSheetDict.Keys) { if (allSheetDict[key].Depth == 1) { outKeyList.Add(key); } } for (int i = 0; i < outKeyList.Count; i++) { string key = outKeyList[i]; ReadDataToClass(objClass, allSheetDict[key], sheetDataDict[key], allSheetDict, sheetDataDict, null); } Serialize.XmlSerialize(XMLPATH + className + ".xml", objClass); Debug.Log(excelPath + "表导入Unity成功!"); AssetDatabase.Refresh(); }
/// <summary> /// 读取xml转excel的配置表 /// </summary> private static void ReadRegXmlToExcel(string className) { string path = REGXMLPATH + className + ".xml"; Dictionary <string, SheetClass> allSheetDict = ReadRegXml(path); Dictionary <string, SheetData> sheetDataDict = new Dictionary <string, SheetData>(); object data = null; Type type = GetType(className); if (type != null) { data = Serialize.XmlDeSerializeEditor(XMLPATH + className + ".xml", type); } List <SheetClass> outSheetList = new List <SheetClass>(); foreach (string key in allSheetDict.Keys) { if (allSheetDict[key].Depth == 1) { outSheetList.Add(allSheetDict[key]); } } for (int i = 0; i < outSheetList.Count; i++) { ReadSheetData(data, outSheetList[i], allSheetDict, sheetDataDict, string.Empty); } string excelPath = EXCELPATH + className + ".xlsx"; try { if (IsFileUsed(excelPath)) { Debug.LogError(excelPath + "文件正在使用,不能进行更改!"); return; } using (FileStream fs = new FileStream(excelPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { using (ExcelPackage package = new ExcelPackage(fs)) { foreach (string str in sheetDataDict.Keys) { SheetData sheetData = sheetDataDict[str]; ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(str); worksheet.Cells.AutoFitColumns(); for (int i = 0; i < sheetData.AllName.Count; i++) { ExcelRange range = worksheet.Cells[1, i + 1]; range.Value = sheetData.AllName[i]; range.AutoFitColumns(); } for (int i = 0; i < sheetData.AllRowData.Count; i++) { RowData rowData = sheetData.AllRowData[i]; for (int j = 0; j < rowData.RowDataDict.Count; j++) { ExcelRange range = worksheet.Cells[i + 2, j + 1]; range.Value = rowData.RowDataDict[sheetData.AllName[j]]; range.AutoFitColumns(); } } } package.Save(); } } } catch (Exception e) { Debug.LogError(e); return; } Debug.Log("生成Excel成功:" + excelPath); }
Expression GenerateSerialize(Serialize serialize, IParser parser) { return(GenerateSerialize(serialize, parser, writer.Param, inline: false)); }
/// <summary> /// Initializes a new instance of the <see cref="EncoderInfo"/> class. /// </summary> /// <param name="tag"> /// The tag. /// </param> /// <param name="serialize"> /// The serialize delegate. /// </param> internal EncoderInfo(Tags tag, Serialize serialize) { this.Tag = tag; this.encode = null; this.serialize = serialize; }
public static TestMachine ParseObject(string data) { TestMachine h = Serialize.ReadFromXMLFile <TestMachine>(data); return(h); }
public override System.Linq.Expressions.ParameterExpression GetParameterExpression(Serialize.Linq.Nodes.ParameterExpressionNode node) { return base.GetParameterExpression(node); }
private void IOHandler() { while (m_Status == RoomSrvStatus.STATUS_RUNNING) { try { m_NetServer.MessageReceivedEvent.WaitOne(1000); long startTime = TimeUtility.GetElapsedTimeUs(); NetIncomingMessage im; for (int ct = 0; ct < 1024; ++ct) { try { if ((im = m_NetServer.ReadMessage()) != null) { switch (im.MessageType) { case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.VerboseDebugMessage: LogSys.Log(LOG_TYPE.DEBUG, "Debug Message: {0}", im.ReadString()); break; case NetIncomingMessageType.ErrorMessage: LogSys.Log(LOG_TYPE.DEBUG, "Error Message: {0}", im.ReadString()); break; case NetIncomingMessageType.WarningMessage: LogSys.Log(LOG_TYPE.DEBUG, "Warning Message: {0}", im.ReadString()); break; case NetIncomingMessageType.StatusChanged: NetConnectionStatus status = (NetConnectionStatus)im.ReadByte(); string reason = im.ReadString(); if (null != im.SenderConnection) { RoomPeer peer = RoomPeerMgr.Instance.GetPeerByConnection(im.SenderConnection); if (null != peer) { LogSys.Log(LOG_TYPE.DEBUG, "Network Status Changed: {0} reason:{1} EndPoint:{2} Key:{3} User:{4}\nStatistic:{5}", status, reason, im.SenderEndPoint.ToString(), peer.GetKey(), peer.Guid, im.SenderConnection.Statistics.ToString()); } else { LogSys.Log(LOG_TYPE.DEBUG, "Network Status Changed: {0} reason:{1} EndPoint:{2}\nStatistic:{3}", status, reason, im.SenderEndPoint.ToString(), im.SenderConnection.Statistics.ToString()); } } else { LogSys.Log(LOG_TYPE.DEBUG, "Network Status Changed:{0} reason:{1}", status, reason); } break; case NetIncomingMessageType.Data: int id = 0; object msg = null; byte[] data = null; try { data = im.ReadBytes(im.LengthBytes); msg = Serialize.Decode(data, out id); } catch { if (null != im.SenderConnection) { RoomPeer peer = RoomPeerMgr.Instance.GetPeerByConnection(im.SenderConnection); if (null != peer) { LogSys.Log(LOG_TYPE.WARN, "room server decode message error !!! from User:{0}({1})", peer.Guid, peer.GetKey()); } } } if (msg != null) { m_Dispatch.Dispatch(id, msg, im.SenderConnection); } else { if (null != im.SenderConnection) { RoomPeer peer = RoomPeerMgr.Instance.GetPeerByConnection(im.SenderConnection); if (null != peer) { LogSys.Log(LOG_TYPE.DEBUG, "got unknow message !!! from User:{0}({1})", peer.Guid, peer.GetKey()); } else { LogSys.Log(LOG_TYPE.DEBUG, "got unknow message !!!"); } } else { LogSys.Log(LOG_TYPE.DEBUG, "got unknow message !!!"); } } break; default: break; } m_NetServer.Recycle(im); } else { break; } } catch (Exception ex) { LogSys.Log(LOG_TYPE.ERROR, "Exception {0}\n{1}", ex.Message, ex.StackTrace); } } RoomPeerMgr.Instance.Tick(); long endTime = TimeUtility.GetElapsedTimeUs(); if (endTime - startTime >= 10000) { LogSys.Log(LOG_TYPE.DEBUG, "Warning, IOHandler() cost {0} us !\nNetPeer Statistic:{1}", endTime - startTime, m_NetServer.Statistics.ToString()); } } catch (Exception ex) { LogSys.Log(LOG_TYPE.ERROR, "Exception {0}\n{1}", ex.Message, ex.StackTrace); } Thread.Sleep(10); } }
public override Serialize.Small opSerialSmallCSharp(Serialize.Small i, out Serialize.Small o, Ice.Current current) { o = i; return i; }
public virtual void ReadWrite(Serialize stream) { throw new NotImplementedException(); }
/// <summary> /// Register a custom serializer by the type and type code specified. /// </summary> /// <param name="typeCode"> /// The type code. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="serialize"> /// The serialize delegate. /// </param> /// <returns> /// <c>true</c> if the deserialize delegate has been registered successfully, otherwise <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="serialize"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="typeCode"/> is not in the valid range. /// </exception> public static bool Register(int typeCode, Type type, Serialize serialize) { if (type == null) { throw new ArgumentNullException("type"); } if (serialize == null) { throw new ArgumentNullException("serialize"); } Register(typeCode, type); var internalTypeCode = ToInternalTypeCode(typeCode); return EncoderInfos.TryAdd(type, new EncoderInfo((Tags)internalTypeCode, serialize)); }
public void ReadWrite(Serialize stream) { stream.ReadWrite(LeftToken); stream.ReadWrite(RightToken); stream.ReadWrite(ref Price); }
public override void opSerialStructCSharp_async(AMD_MyClass_opSerialStructCSharp cb, Serialize.Struct i, Ice.Current current) { cb.ice_response(i, i); }
internal static IStrutsConfigXml getStrutsConfig(string strutsConfigFile, ITilesDefinitions tilesDefinitions, IValidationXml validation) { var strutsConfigXml = new KStrutsConfigXml(); try { var strutsConfig = ((strutsconfig)Serialize.getDeSerializedObjectFromXmlFile(strutsConfigFile, typeof(strutsconfig))); if (strutsConfig != null) { if (strutsConfig.formbeans != null) { // first add the forms foreach (var formBean in strutsConfig.formbeans) { var newFormBean = new KStrutsConfig_FormBean() { name = formBean.name, type = formBean.type, extends = formBean.extends, }; if (formBean.formproperty != null) { foreach (var formProperty in formBean.formproperty) { var field = new KStrutsConfig_FormBean_Field() { name = formProperty.name, type = formProperty.type, initial = formProperty.initial }; newFormBean.fields.Add(formProperty.name, field); //newFormBean.properties.Add(formProperty.name, formProperty.type); } } strutsConfigXml.formBeans.Add(newFormBean); } // now map the validation if (validation != null) { var validationForms = new Dictionary <string, IValidation_Form>(); foreach (var validationForm in validation.forms) { if (false == validationForms.ContainsKey(validationForm.name)) { validationForms.Add(validationForm.name, validationForm); } else { PublicDI.log.error("Duplicate form validator: {0}", validationForm.name); //var asd = validationForms[validationForm.name].fields; } } foreach (var formBean in strutsConfigXml.formBeans) { if (false == validationForms.ContainsKey(formBean.name)) { formBean.hasValidationMapping = false; } else { var validatorForm = validationForms[formBean.name]; foreach (var field in formBean.fields) { if (validatorForm.fields.ContainsKey(field.Key)) { field.Value.hasValidationMapping = true; field.Value.depends = validatorForm.fields[field.Key].depends; foreach (var var in validatorForm.fields[field.Key].vars) { field.Value.validators.Add(var.Key, var.Value); } } else { field.Value.hasValidationMapping = false; } } //formBean.properties //foreach(var ) formBean.hasValidationMapping = true; } } } } if (strutsConfig.globalforwards != null) { foreach (var globalForward in strutsConfig.globalforwards) { strutsConfigXml.globalForwards.Add(globalForward.name, globalForward.path); } } if (strutsConfig.actionmappings != null) { foreach (var action in strutsConfig.actionmappings) { var newActionMapping = new KStrutsConfig_Action() { name = action.name, path = action.path, input = action.input, scope = action.scope, type = action.type, validate = action.validate.ToString(), unknown = action.unknown, extends = action.extends, parameter = action.parameter }; if (action.forward != null) { foreach (var forward in action.forward) { var newForward = new KStrutsConfig_Action_Forward() { name = forward.name, path = forward.path, redirect = forward.redirect }; newActionMapping.forwards.Add(newForward); } } strutsConfigXml.actionmappings.Add(newActionMapping); } } if (strutsConfig.plugin != null) { foreach (var plugin in strutsConfig.plugin) { var newPlugIn = new KStrutsConfig_PlugIn() { className = plugin.className }; if (plugin.setproperty != null) { foreach (var property in plugin.setproperty) { newPlugIn.properties.Add(property.property, property.value); } } strutsConfigXml.plugIns.Add(newPlugIn); } } if (tilesDefinitions != null) { foreach (var titleDefinition in tilesDefinitions.definitions) { //var value = titleDefinition.page ?? titleDefinition.path ?? ""; var value = titleDefinition.page ?? titleDefinition.path; addTileDefinition(strutsConfigXml.resolvedViews, titleDefinition.name, value); foreach (var put in titleDefinition.puts) { addTileDefinition(strutsConfigXml.resolvedViews, titleDefinition.name, put.Value); } /*if (value != null) * if (false == strutsConfigXml.resolvedViews.ContainsKey(titleDefinition.name)) * strutsConfigXml.resolvedViews.Add(titleDefinition.name, value); * else * DI.log.error("in mapping TilesDefinition, there was a duplicate key: {0} with value {1}", * titleDefinition.name, value); */ } } } } catch (Exception ex) { PublicDI.log.error("in getStrutsConfig: {0}", ex.Message); } return(strutsConfigXml); }
public override void ice_response(Serialize.Struct r, Serialize.Struct o) { test(o.o == null); test(o.o2 != null); test(((Serialize.Struct)(o.o2)).o == null); test(((Serialize.Struct)(o.o2)).o2 == o.o2); test(o.s == null); test(o.s2.Equals("Hello")); test(r.o == null); test(r.o2 != null); test(((Serialize.Struct)(r.o2)).o == null); test(((Serialize.Struct)(r.o2)).o2 == r.o2); test(r.s == null); test(r.s2.Equals("Hello")); callback.called(); }
public static IWebXml getWebXml(string pathToWebXmlFile) { // hack to handle prob with XSD schema (which doesn't load when ...) var fileContents = Files.getFileContents(pathToWebXmlFile); if (fileContents.IndexOf("<web-app>") > -1) { fileContents = fileContents.Replace("<web-app>", "<web-app version=\"2.4\" xmlns=\"http://java.sun.com/xml/ns/j2ee\">"); pathToWebXmlFile = PublicDI.config.getTempFileInTempDirectory("web.xml"); Files.WriteFileContent(pathToWebXmlFile, fileContents); } var webXml = new KWebXml(); var webAppType = ((webappType)Serialize.getDeSerializedObjectFromXmlFile(pathToWebXmlFile, typeof(webappType))); if (webAppType != null) { foreach (var item in webAppType.Items) { switch (item.GetType().Name) { case "displaynameType": var displayName = (displaynameType)item; webXml.displayName = displayName.Value; break; case "descriptionType": var description = (descriptionType)item; webXml.description = description.Value; break; case "paramvalueType": var paramvalue = (paramvalueType)item; PublicDI.log.debug("paramvalueType: {0} = {1}", paramvalue.paramname.Value, paramvalue.paramvalue.Value); //webXml.displayName = displayName.Value; break; case "filterType": var filter = (filterType)item; webXml.filters.Add( new KWebXml_Filter { filterClass = (filter.filterclass != null ? filter.filterclass.Value : ""), filterName = filter.filtername != null ? filter.filtername.Value : "" }); break; case "filtermappingType": var filterMapping = (filtermappingType)item; var newFilterMapping = new kWebXml_Filter_Mapping() { filterName = filterMapping.filtername != null ? filterMapping.filtername.Value : "", dispatcher = filterMapping.filtername != null ? filterMapping.filtername.Value : "" }; if (filterMapping.Item != null) { if (filterMapping.Item is urlpatternType) { newFilterMapping.urlPattern = ((urlpatternType)filterMapping.Item).Value; } } webXml.filterMappings.Add(newFilterMapping); break; case "listenerType": var listenerType = (listenerType)item; webXml.listenerClass = listenerType.listenerclass.Value; break; case "servletType": var servletType = (servletType)item; var newServlet = new KWebXml_Servlet { servletName = (servletType.servletname != null) ? servletType.servletname.Value : "", loadOnStartUp = (servletType.loadonstartup != null) ? servletType.loadonstartup.Value : "" }; if (servletType.Item is fullyqualifiedclassType) { newServlet.servletClass = servletType.Item.Value; } if (servletType.initparam != null) { foreach (var _initParam in servletType.initparam) { newServlet.initParam.Add(_initParam.paramname.Value, _initParam.paramvalue.Value); } } webXml.servlets.Add(newServlet); break; case "servletmappingType": var servletMapping = (servletmappingType)item; var newServletMapping = new KWebXml_Servlet_Mapping() { servletName = servletMapping.servletname.Value, urlPattern = servletMapping.urlpattern.Value }; webXml.servletMappings.Add(newServletMapping); break; default: PublicDI.log.info("no mapping for :" + item.GetType().Name); break; } } } return(webXml); }
//TODO: Maybe change param private void InsertCard(EventLabel el) { ResetCommand(); //Ausgehend davon, das die Labels schon eingelagert worden sind und geupdatet //Ebenfalls Themen List <Theme> themeList = el.getThemeList(); List <Card> cardList = new List <Card>(); ContentCard cc; QACard qa; foreach (Theme th in themeList) { cardList.AddRange(th.GetContent()); cardList.AddRange(th.GetQA()); foreach (Card ca in cardList) { ResetCommand(); if (ca.ICreated) { //Find right tabular if (ca is ContentCard) { cc = (ContentCard)ca; //Insert into contentCard command.CommandText = "INSERT INTO ContentCards (ThemeID,Tag, serialized) VALUES (" + th.IDatabaseID + ",0, ?);"; command.CreateParameter(); SQLiteParameter param = new SQLiteParameter(); command.Parameters.Add(param); param.Value = Serialize.GetSerializeByte(cc); command.ExecuteNonQuery(); } else if (ca is QACard) { qa = (QACard)ca; //InSert into QA command.CommandText = "INSERT INTO QACard (ThemeID,Tag, serialized) VALUES (" + th.IDatabaseID + ",0, ?);"; command.CreateParameter(); SQLiteParameter param = new SQLiteParameter(); command.Parameters.Add(param); param.Value = Serialize.GetSerializeByte(qa); command.ExecuteNonQuery(); } else { throw new Exception("Developers haben wieder mistgebaut..."); } } else if (ca.IModified) { //Find right tabular and the entry //Just Update all if (ca is ContentCard) { cc = (ContentCard)ca; //Insert into contentCard command.CommandText = "UPDATE ContentCards SET ThemeID = " + th.IDatabaseID + ", Tag = 0, serialized = ? where ID = " + cc.IDatabaseID + ";"; command.CreateParameter(); SQLiteParameter param = new SQLiteParameter(); command.Parameters.Add(param); param.Value = Serialize.GetSerializeByte(cc); command.ExecuteNonQuery(); } else if (ca is QACard) { //TODO: Tags are currently 0 evrytime qa = (QACard)ca; command.CommandText = "UPDATE QACard SET ThemeID = " + th.IDatabaseID + ", Tag = 0, serialized = ? where ID = " + qa.IDatabaseID + ";"; command.CreateParameter(); SQLiteParameter param = new SQLiteParameter(); command.Parameters.Add(param); param.Value = Serialize.GetSerializeByte(qa); command.ExecuteNonQuery(); } } else { continue; } } } }
public static IValidationXml getValidationXml(string fileToMap) { var validatorXml = new KValidationXml(); try { var formvalidation = ((formvalidation)Serialize.getDeSerializedObjectFromXmlFile(fileToMap, typeof(formvalidation))); if (formvalidation != null && formvalidation.formset != null) { foreach (var formset in formvalidation.formset) { foreach (var form in formset.form) { var validationForm = new KValidation_Form() { name = form.name }; if (form.field != null) { foreach (var field in form.field) { var formField = new KValidation_Form_Field() { depends = field.depends, property = field.property }; if (field.var != null) { foreach (var _var in field.var) { formField.vars.Add(_var.varname, _var.varvalue); } } if (validationForm.fields.ContainsKey(field.property)) { //DI.log.error("Duplicate form field validation entry: form:{0} field:{1}", form.name, field.property); // already exists so lets update the existing one: validationForm.fields[field.property].depends += ", " + formField.depends; foreach (var var in formField.vars) { if (validationForm.fields[field.property].vars.ContainsKey(var.Key)) { if (var.Value != "") { validationForm.fields[field.property].vars[var.Key] += ", " + var.Value; } } else { validationForm.fields[field.property].vars.Add(var.Key, var.Value); } } } else { validationForm.fields.Add(field.property, formField); } } } validatorXml.forms.Add(validationForm); } } } } catch (Exception ex) { PublicDI.log.error("in getValidationXml: {0}", ex.Message); } return(validatorXml); }
throw new InvalidOperationException(Serialize(result));
/// <summary> /// Returns true if the text provided cannot be serialized into an KO2Config object /// </summary> /// <param name="content"></param> /// <returns></returns> private bool doesTextBreaksO2ConfigSchema(string content) { return(null == Serialize.getDeSerializedObjectFromString(content, typeof(KO2Config), false)); }
/// <summary> /// Register custom type handlers for your own types not natively handled by fastJSON /// </summary> /// <param name="type"></param> /// <param name="serializer"></param> /// <param name="deserializer"></param> public static void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { Reflection.Instance.RegisterCustomType(type, serializer, deserializer); }
body: GetBytes(Serialize(message)) );
internal void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { if (type == null || serializer == null || deserializer == null) return; _customSerializer.Add(type, serializer); _customDeserializer.Add(type, deserializer); // reset property cache Instance.ResetPropertyCache(); }
public override string ToString() => Serialize.ToJson(this);
public bool InsertOrder(SaveOrderRequest request) { using (SqlConnection connection = new SqlConnection(configuration["ConnectionStrings:DataBase"])) { try { connection.Open(); string success = request.Success ? "1" : "0"; string query = $"INSERT INTO Pedidos(Facturado, ValorTotal, Productos) VALUES ({success}, {request.TotalValue}, '{Serialize.SerializeObject(request.Request)}')"; SqlCommand command = new SqlCommand(query, connection); int affectedRows = command.ExecuteNonQuery(); return(affectedRows > 0); } catch (Exception) { return(false); } } }
public FormState DeepClone() { return(Serialize.TryDeepClone(this)); }
public override Serialize.Large opSerialLargeCSharp(Serialize.Large i, out Serialize.Large o, Ice.Current current) { o = i; return i; }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { Build_BSO pBso = new Build_BSO(); if (!pBso.HasBuildPermission(Ado, SamAccountName, "create")) { Response.error = Label.Get("error.privilege"); return(false); } Matrix matrix = new Matrix(DTO) { MainSpec = new Matrix.Specification(DTO.matrixDto.LngIsoCode, DTO), TheLanguage = DTO.LngIsoCode, FormatType = DTO.Format.FrmType, FormatVersion = DTO.Format.FrmVersion }; //Get the Specifications if (DTO.DimensionList.Count > 1) { IEnumerable <string> otherLanguages = from lng in DTO.DimensionList where lng.LngIsoCode != DTO.matrixDto.LngIsoCode select lng.LngIsoCode; matrix.OtherLanguageSpec = new List <Matrix.Specification>(); List <string> otherLang = new List <string>(); foreach (var lang in otherLanguages) { matrix.OtherLanguageSpec.Add(new Matrix.Specification(lang, DTO)); otherLang.Add(lang); } matrix.OtherLanguages = otherLang; } //Create the blank csv with titles to enable the user to fill in their own data for the update matrix.Cells = GetBlankCells(matrix); //We should be able to validate the newly created matrix now... MatrixValidator mValidator = new MatrixValidator(); if (!mValidator.Validate(matrix)) { Response.error = Label.Get("error.validation"); return(false); } matrix.ValidateMyMaps(); if (matrix.MainSpec.ValidationErrors != null) { Response.error = Error.GetValidationFailure(matrix.MainSpec.ValidationErrors); return(false); } if (matrix.OtherLanguageSpec != null) { foreach (var spec in matrix.OtherLanguageSpec) { if (spec.ValidationErrors != null) { Response.error = Error.GetValidationFailure(matrix.MainSpec.ValidationErrors); return(false); } } } dynamic fileOutput = new ExpandoObject(); switch (DTO.Format.FrmType) { case Resources.Constants.C_SYSTEM_PX_NAME: List <dynamic> resultPx = new List <dynamic>(); resultPx.Add(matrix.GetPxObject(true)); Response.data = resultPx; break; case Resources.Constants.C_SYSTEM_JSON_STAT_NAME: dynamic result = new ExpandoObject(); List <JRaw> jsonData = new List <JRaw>(); jsonData.Add(new JRaw(Serialize.ToJson(matrix.GetJsonStatObject()))); if (matrix.OtherLanguageSpec != null) { foreach (Matrix.Specification s in matrix.OtherLanguageSpec) { matrix.MainSpec = s; jsonData.Add(new JRaw(Serialize.ToJson(matrix.GetJsonStatObject()))); } } Response.data = jsonData; break; default: Response.error = Label.Get("error.invalid"); return(false); } return(true); }
public override Serialize.Struct opSerialStructCSharp(Serialize.Struct i, out Serialize.Struct o, Ice.Current current) { o = i; return i; }
/// <summary> /// Bind Queries. /// </summary> private void BindQueries(Campaign objCampaign, bool IsActive) { //if (IsCampaignRunning()) //{ // Isrunning = true; //} DataSet dsQuerList; try { CampaignService objCampService = new CampaignService(); XmlDocument xDocCampaign = new XmlDocument(); xDocCampaign.LoadXml(Serialize.SerializeObject(objCampaign, "Campaign")); ActivityLogger.WriteAdminEntry(objCampaign, "Getting campaign query status, generic."); dsQuerList = objCampService.GetCampaignQueryStatus(xDocCampaign); DataView dvQueries = new DataView(); try { SetQueryStatsInPerc(objCampaign); } catch { } // Added 11/12/10 for preventing 0 available queries to be activated - enhancement DataView dvExhaustedQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1 AND Available = 0"); if (dvExhaustedQueries == null) { PageMessage = "This campaign has no queries, please create a dialing query to begin dialing."; return; } if (dvExhaustedQueries.Count > 0) { DataRowView dr = dvExhaustedQueries[0]; long campaignQueryStatusId = Convert.ToInt64(dr["CampaignQueryID"]); string queryName = dr["QueryName"].ToString(); UpdateQueryStatus(campaignQueryStatusId, false, false, false); ActivityLogger.WriteAdminEntry(objCampaign, "Getting campaign query status, exhausted queries exist."); dsQuerList = objCampService.GetCampaignQueryStatus(xDocCampaign); PageMessage = string.Format("\"{0}\" has no available numbers, it will remain on hold.", queryName, campaignQueryStatusId); ActivityLogger.WriteAdminEntry(objCampaign, "Query '{0}' has no available numbers when user attempted to activate, moving to on hold.", queryName, campaignQueryStatusId); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "QueryAlert", "alert('" + PageMessage + "');", true); } if (IsActive) { dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1"); dvQueries.Sort = "DateModified ASC"; grdActiveQueries.DataSource = dvQueries; grdActiveQueries.DataBind(); } else { dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1"); dvQueries.Sort = "DateModified ASC"; grdActiveQueries.DataSource = dvQueries; grdActiveQueries.DataBind(); dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 AND IsStandby = 1"); dvQueries.Sort = "DateModified ASC"; grdStandbyQueries.DataSource = dvQueries; grdStandbyQueries.DataBind(); dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 OR IsActive = 1"); dvQueries.Sort = "DateModified ASC"; grdAllQueries.DataSource = dvQueries; grdAllQueries.DataBind(); } if (grdActiveQueries.Items.Count < 1) { lblNoActive.Visible = true; grdActiveQueries.Visible = false; } else { lblNoActive.Visible = false; grdActiveQueries.Visible = true; } if (grdStandbyQueries.Items.Count < 1) { lblNoStanByQueries.Visible = true; grdStandbyQueries.Visible = false; } else { lblNoStanByQueries.Visible = false; grdStandbyQueries.Visible = true; } // *** Bonus add query conditions as tooltips dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1"); dvQueries.Sort = "Priority ASC"; for (int i = 0; i < grdActiveQueries.Items.Count; i++) { LinkButton lbtnQuery = (LinkButton)grdActiveQueries.Items[i].FindControl("lbtnQuery"); string strSubQueryConditions = dvQueries.Table.Rows[i]["QueryCondition"].ToString();; string strFilteredSubQueryConditions = ""; if (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } if (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } strFilteredSubQueryConditions = strFilteredSubQueryConditions.Trim(); lbtnQuery.ToolTip = strFilteredSubQueryConditions; } dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 AND IsStandby = 1"); dvQueries.Sort = "Priority ASC"; for (int i = 0; i < grdStandbyQueries.Items.Count; i++) { LinkButton lbtnQuery = (LinkButton)grdStandbyQueries.Items[i].FindControl("lbtnQuery"); string strSubQueryConditions = dvQueries.Table.Rows[i]["QueryCondition"].ToString();; string strFilteredSubQueryConditions = ""; if (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } if (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } strFilteredSubQueryConditions = strFilteredSubQueryConditions.Trim(); lbtnQuery.ToolTip = strFilteredSubQueryConditions; } dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 OR IsActive = 1"); dvQueries.Sort = "Priority ASC"; for (int i = 0; i < grdAllQueries.Items.Count; i++) { LinkButton lbtnQuery = (LinkButton)grdAllQueries.Items[i].FindControl("lbtnQuery"); string strSubQueryConditions = dvQueries.Table.Rows[i]["QueryCondition"].ToString();; string strFilteredSubQueryConditions = ""; if (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } if (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } strFilteredSubQueryConditions = strFilteredSubQueryConditions.Trim(); lbtnQuery.ToolTip = strFilteredSubQueryConditions; } } catch (Exception ex) { ActivityLogger.WriteException(ex, "Admin"); } }
public object ExecuteExpression(Serialize.Linq.Nodes.ExpressionNode expressionNode) { using (var session = SessionFactory.OpenSession()) { var query = session.Query<object>(); var expression = expressionNode.ToExpression(new NHExpressionContext(session)); var result = query.Provider.Execute(expression); IEnumerable enumerable = result as IEnumerable; if (enumerable != null) return enumerable.Cast<object>().ToArray(); else return result; } }
private Task PostEventAsync(params ExceptionRecord[] records) { string json = Serialize.ToJson(new JArray(records.Select(JObject.FromObject))); return(restClient.PostAsync(json)); }
/// <summary> /// Register a custom serializer/deserializer by the type and type code specified. /// </summary> /// <param name="typeCode"> /// The type code. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="serialize"> /// The serialize delegate. /// </param> /// <param name="deserialize"> /// The deserialize delegate. /// </param> /// <returns> /// <c>true</c> if the serializer and deserialize delegate has been registered successfully, otherwise <c>false</c>. /// </returns> public static bool Register(int typeCode, Type type, Serialize serialize, Deserialize deserialize) { return Register(typeCode, type, serialize) && Decoder.Register(typeCode, type, deserialize); }
public Lambda(Serialize <A> serialize, Deserialize <DeserializeInfo <A> > deserialize) { _serialize = serialize; _deserialize = deserialize; }
public object ExecuteExpression(Serialize.Linq.Nodes.ExpressionNode expressionNode) { return PersistenceManager.ExecuteExpression(expressionNode); }
public static ConfigFile LoadFromFile(this ConfigFile config, out bool fileEsiste, ref string testo, byte cicli, out bool encrypted, out bool inErr, Mess logMess = null) { if (logMess == null) { logMess = new Mess(LogType.Warn, Log.main.warnUserText); } byte[] byteStream; string logErrPrefix; encrypted = false; inErr = true; string fullFilePath; Util.GetPropertyOrFieldValue(config, nameof(ConfigFile.FullFilePath), out fullFilePath); logErrPrefix = "Config.fullPath=" + fullFilePath + " - "; fileEsiste = false; if (FS.ValidaPercorsoFile(fullFilePath, true, out _, verEsistenza: CheckExistenceOf.FolderAndFile) == false) { return(config); } fileEsiste = true; try { byteStream = File.ReadAllBytes(fullFilePath); //testo = IO.File.ReadAllText(config.percorsoENomeFile) } catch (Exception ex) { Log.main.Add(new Mess(LogType.ERR, "", logErrPrefix + "Eccezione in ReadAllBytes, ex.mess:<" + ex.Message + ">")); return(config); } if (byteStream.Length == 0) { Log.main.Add(new Mess(LogType.ERR, "", logErrPrefix + " the file is empty")); return(config); } if (Crypto.Decripta(byteStream, ref testo, cicli, logMess: logMess) == false) { testo = Encoding.Unicode.GetString(byteStream); if (testo.Substring(0, 3) != "{\r\n") { Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, logErrPrefix + "Lettura file fallita sia tramite Crypto.Decripta che file in chiaro, errore in Crypto.Decripta:<" + logMess.testoDaLoggare + ">")); return(config); } } else { encrypted = true; } if (Serialize.DeserializeFromText(testo, ref config) == false) { return(config); } inErr = false; return(config); }
public override void ice_response(Serialize.Small r, Serialize.Small o) { test(o == null); test(r == null); callback.called(); }
/// <summary> /// Saves area code rule /// </summary> private void SaveData() { long AreaCodeID = 0; long AgentID = 0; AreaCodeRule objAreaCodeRule = new AreaCodeRule(); Agent objAgent; if (Session["LoggedAgent"] != null) { objAgent = (Agent)Session["LoggedAgent"]; AgentID = objAgent.AgentID; } if (ViewState["AreaCodeRuleID"] != null) { objAreaCodeRule.AreaCodeRuleID = Convert.ToInt64(ViewState["AreaCodeRuleID"]); } objAreaCodeRule.AgentID = AgentID; if (hdnAreaCodeID.Value != null && hdnAreaCodeID.Value != "") { AreaCodeID = Convert.ToInt64(hdnAreaCodeID.Value); } objAreaCodeRule.AreaCodeID = AreaCodeID; objAreaCodeRule.LikeDialing = rbtnAllNumbersDial.Checked; if (rbtnElevenDigitDialing.Checked) { objAreaCodeRule.LikeDialingOption = false; } else if (rbtnTenDigitDialing.Checked) { objAreaCodeRule.LikeDialingOption = true; } objAreaCodeRule.CustomeDialing = rbtnCustomeDialing.Checked; objAreaCodeRule.IsSevenDigit = rbtnDialSevenDigits.Checked; objAreaCodeRule.IsTenDigit = rbtnDialTenDigits.Checked; if (txtAreaCode.Text != string.Empty) { objAreaCodeRule.IntraLataDialingAreaCode = txtAreaCode.Text; } objAreaCodeRule.ILDIsTenDigit = rbtnILDialTenDigit.Checked; objAreaCodeRule.ILDElevenDigit = rbtnILDialElevenDigit.Checked; if (txtReplaceAreaCode.Text != string.Empty) { objAreaCodeRule.ReplaceAreaCode = txtReplaceAreaCode.Text; } if (rbntLDDialElevenTenDigits.Checked) { objAreaCodeRule.LongDistanceDialing = false; } else if (rbntLDDialTenDigits.Checked) { objAreaCodeRule.LongDistanceDialing = true; } CampaignService objCampaignService = new CampaignService(); XmlDocument xDocAreaCodeRule = new XmlDocument(); try { xDocAreaCodeRule.LoadXml(Serialize.SerializeObject(objAreaCodeRule, "AreaCodeRule")); objAreaCodeRule = (AreaCodeRule)Serialize.DeserializeObject( objCampaignService.AreaCodeRuleInsertUpdate(xDocAreaCodeRule), "AreaCodeRule"); GetAreaCodeRuleByAgentID(); GetAreaCodes(); } catch (Exception ex) { PageMessage = ex.Message; } }
public override void ice_response(Serialize.Large r, Serialize.Large o) { test(o.d1 == 1.0); test(o.d2 == 2.0); test(o.d3 == 3.0); test(o.d4 == 4.0); test(o.d5 == 5.0); test(o.d6 == 6.0); test(o.d7 == 7.0); test(o.d8 == 8.0); test(o.d9 == 9.0); test(o.d10 == 10.0); test(r.d1 == 1.0); test(r.d2 == 2.0); test(r.d3 == 3.0); test(r.d4 == 4.0); test(r.d5 == 5.0); test(r.d6 == 6.0); test(r.d7 == 7.0); test(r.d8 == 8.0); test(r.d9 == 9.0); test(r.d10 == 10.0); callback.called(); }
//TODO: Implement NonRepeatEvents private void InsertEvents(EventLabel el) { ResetCommand(); List <Event> eventList; eventList = el.getEventList(); foreach (Event ev in eventList) { if (ev is RepeatEvent) { RepeatEvent re = (RepeatEvent)ev; //Wenn es erstellt ist, wird es einfach eingefügt if (re.ICreated) { String dayCode = generateDayCodeKurz(re.dayCode); command.CommandText = "INSERT INTO RepeatEvents (LabelId, NameOf, serialized,DayCode) VALUES (" + ev.IDatabaseID + ",'" + ev.Name + "',?,'" + dayCode + "');"; byte[] data = Serialize.GetSerializeByte(re); SQLiteParameter param = new SQLiteParameter(); command.CreateParameter(); command.Parameters.Add(param); param.Value = data; command.ExecuteNonQuery(); } //WEnn es modifiziert wurde, muss der alte Datenbank eintrag gelöscht werden bzw ersetzt werden //Hierfür ersetzen wir alles: Wenn sich das Label geändert hat, gehört es nicht mehr zu genau diesem Label else if (re.IModified) { //Anfrage String cmdGen = "UPDATE RepeatEvents SET LabelID = " + el.IDatabaseID + ", nameOf =" + re.Name + "',dayCode = '" + generateDayCodeKurz(re.dayCode) + "',serialized = ? WHERE ID = " + re.IDatabaseID + ";"; SQLiteParameter param = new SQLiteParameter(); command.CommandText = cmdGen; command.Parameters.Add(param); param.Value = Serialize.GetSerializeByte(re); command.ExecuteNonQuery(); } ResetCommand(); } else if (ev is NonRepeatingEvents) { //Schwierig - was wenn ein gleicher Name existiert? Definitiv unique id rausladen if (ev is ReferencedOneTimeEvent) { throw new NotImplementedException("Not implementd"); } else if (ev is NonReferencedOneTimeEvent) { throw new NotImplementedException("Not implementd"); } else { throw new Exception("Devs haben wieder scheise gebaut"); } } } }
internal void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { if (type != null && serializer != null && deserializer != null) { _customSerializer.Add(type, serializer); _customDeserializer.Add(type, deserializer); // reset property cache Reflection.Instance.ResetPropertyCache(); } }
public void Load() { int LoadedScore = Serialize.LoadScore(); score = LoadedScore; }