//结案、反结案一并处理。 private static bool icmoCloseHandle(K3DataParaInfo docInfo) { SqlPipe pipe = SqlContext.Pipe; bool bRlt = true; try { pipe.Send("icmoCloseHandle"); K3InterceptConfig itemConfig = SimpleConfig.validateBusinessEnable(docInfo); //K3InterceptConfig itemConfig = new K3InterceptConfig() //{ // ServiceAddress = "192.168.1.100/WebService/WebService.asmx", // X9BusinessType = 5, // InterceptEvent = "ClosedBefore", // IsEnable = 1, //}; if (itemConfig != null) { pipe.Send("itemConfig != null"); ResultInfo rltInfo = defaultEventHandle(docInfo, itemConfig); if (rltInfo != null) { bRlt = rltInfo.IsSuccess; } } } catch (Exception ex) { pipe.Send(ex.Message); bRlt = true; } return(bRlt); }
private static ResultInfo defaultEventHandle(K3DataParaInfo docInfo, K3InterceptConfig busiConfig) { SqlPipe pipe = SqlContext.Pipe; try { pipe.Send("defaultEventHandle"); string strRlt = string.Empty; SqlCLRTest.X9WebService.WebService svValidateBM = new SqlCLRTest.X9WebService.WebService(); svValidateBM.Url = string.Format("http://{0}", busiConfig.ServiceAddress); string strDocInfo = XmlSerialize <K3DataParaInfo>(docInfo, Encoding.Unicode); pipe.Send(strDocInfo); //string strHttpEncoding = HttpUtility.HtmlEncode(strDocInfo); strRlt = svValidateBM.SynchBillFromK3ToX9(strDocInfo); if (!string.IsNullOrEmpty(strRlt)) { pipe.Send(strRlt); //strRlt = strRlt.Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", ""); //string strHttpDecoding = HttpUtility.HtmlDecode(strRlt); ResultInfo rltInfo = XmlDeserialize <ResultInfo>(strRlt, Encoding.Unicode); return(rltInfo); } return(null); } catch (Exception ex) { //LogInfoHelp.infoLog(eventName, docInfo, string.Format("调用X9系统服务时,异常:{0}", ex.Message)); pipe.Send(string.Format("Exception cacheDocInfo:{0}", ex.Message)); return(null); } }
public static void GetEmployeesHiredAfter(DateTime date) { try { using (SqlConnection cn = new SqlConnection("context connection=true")) { cn.Open(); string sql = @"SELECT * FROM HumanResources.Employee WHERE HireDate > @hireDate"; SqlCommand cmd = new SqlCommand(sql, cn); cmd.Parameters.AddWithValue("@hireDate", date); SqlDataReader reader = cmd.ExecuteReader(); SqlPipe pipe = SqlContext.Pipe; pipe.Send(reader); pipe.Send("Command completed successfully"); } } catch (Exception e) { SqlPipe pipe = SqlContext.Pipe; pipe.Send("Error occurred executing command:"); pipe.Send(e.Message); pipe.Send(e.StackTrace); } }
public static void ReadWebPage(string url) { SqlPipe pipe = SqlContext.Pipe; try { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stm = resp.GetResponseStream(); StreamReader sr = new StreamReader(stm); int bufferSize = 4000; int charsRead = 0; char[] buffer = new char[bufferSize]; do { charsRead = sr.Read(buffer, 0, bufferSize); pipe.Send(new string(buffer, 0, charsRead)); } while (charsRead > 0); sr.Close(); stm.Close(); resp.Close(); } catch (Exception e) { pipe.Send(e.Message); } }
private bool calcComplexReceiptPlan(bool debug = false) { SqlPipe sqlP = SqlContext.Pipe; int step = 0; if (debug) { sqlP.Send(" calcComplexReceiptPlan Step " + step++); } decimal[] cumulativeReceiptNeeds = CalcNodeReceiptNeeds(); Dictionary <Tuple <int, int>, decimal> priorAllocation = new Dictionary <Tuple <int, int>, decimal>(); if (debug) { sqlP.Send(" calcComplexReceiptPlan Step " + step++); } int earliestStartWeekIndex = -1; if (BOH == 0 && FirstSalesWeek < FirstReceiptWeek) { if (!WeekIndex.TryGetValue(FirstReceiptWeek, out earliestStartWeekIndex)) { return(false); } } if (debug) { sqlP.Send(" calcComplexReceiptPlan Step " + step++); } // Assign BOH bool success = true; int criticalWeekIndex = 0; int qty = 0; if (BOH > 0) { qty = BOH; success &= allocate(qty, null, priorAllocation, earliestStartWeekIndex, cumulativeReceiptNeeds, ref criticalWeekIndex); } if (debug) { sqlP.Send(" calcComplexReceiptPlan - BOH - Step " + step++); } foreach (Receipt receipt in Receipts) { qty += receipt.Qty; success &= allocate(qty, receipt, priorAllocation, earliestStartWeekIndex, cumulativeReceiptNeeds, ref criticalWeekIndex); if (debug) { sqlP.Send(" calcComplexReceiptPlan - allocate receipt - Step " + step++); } } return(success); }
public DataTable GetConsolidatedReceiptsDataTable(bool debug = false) { SqlPipe sqlP = SqlContext.Pipe; DataTable dt = new DataTable(); dt.TableName = "[dbo].[t_Consolidated_Receipts]"; DataColumn col = new DataColumn("Receipt_Type", typeof(char)); col.AllowDBNull = false; dt.Columns.Add(col); col = new DataColumn("Flow_Type", typeof(char)); col.AllowDBNull = true; dt.Columns.Add(col); col = new DataColumn("Week", typeof(int)); col.AllowDBNull = false; dt.Columns.Add(col); col = new DataColumn("Receipt_U", typeof(int)); col.AllowDBNull = true; dt.Columns.Add(col); col = new DataColumn("Critical_Week", typeof(int)); col.AllowDBNull = true; dt.Columns.Add(col); col = new DataColumn("Critical_Fraction", typeof(decimal)); col.AllowDBNull = true; dt.Columns.Add(col); if (debug) { sqlP.Send("Table - Receipt Type, Week, Receipt_U, Critical_Week, Critical_Fraction"); } foreach (Receipt receipt in Receipts) { DataRow row = dt.NewRow(); row[0] = receipt.ReceiptType; row[1] = receipt.FlowType; row[2] = receipt.Week; row[3] = receipt.Qty; row[4] = receipt.CriticalWeek; row[5] = Math.Round(receipt.CriticalFraction, 5); if (debug) { sqlP.Send(receipt.ReceiptType + "," + receipt.Week + "," + receipt.Qty + "," + receipt.CriticalWeek + "," + receipt.CriticalFraction); } dt.Rows.Add(row); } return(dt); }
public DataTable GetReceiptNeedsDebugDataTable(bool debug = false) { DataTable dt = new DataTable(); dt.TableName = "[dbo].[t_Node_Receipt_Needs_Debug]"; DataColumn col = new DataColumn("Grade_Id", typeof(int)); col.AllowDBNull = false; dt.Columns.Add(col); col = new DataColumn("Climate_Id", typeof(int)); col.AllowDBNull = false; dt.Columns.Add(col); col = new DataColumn("Week", typeof(int)); col.AllowDBNull = false; dt.Columns.Add(col); col = new DataColumn("Receipt_Need_U", typeof(decimal)); col.AllowDBNull = true; dt.Columns.Add(col); SqlPipe sqlP = SqlContext.Pipe; if (debug) { sqlP.Send("MdStart Week = " + MdStartWeekIndex); } foreach (NodeSalesPlan nodeSalesPlan in NodeSalesPlans) { if (nodeSalesPlan != null) { for (int i = 0; i < MdStartWeekIndex; i++) { if (nodeSalesPlan.Plans[i] != null) { DataRow row = dt.NewRow(); row[0] = nodeSalesPlan.GradeId; row[1] = nodeSalesPlan.ClimateId; row[2] = Weeks[i].Week; row[3] = Math.Round(nodeSalesPlan.Plans[i].ReceiptNeed, 3); if (debug) { sqlP.Send(nodeSalesPlan.GradeId + "," + nodeSalesPlan.ClimateId + "," + Weeks[i].Week + "," + nodeSalesPlan.Plans[i].ReceiptNeed); } dt.Rows.Add(row); } } } } return(dt); }
public static void greetingsTrigger() { SqlTriggerContext triggContext = SqlContext.TriggerContext; if (triggContext.TriggerAction == TriggerAction.Insert) { using (SqlConnection conn = new SqlConnection("context connection=true")) { conn.Open(); SqlCommand sqlComm = new SqlCommand(); sqlComm.Connection = conn; SqlPipe sqlP = SqlContext.Pipe; sqlComm.CommandText = "SELECT name from INSERTED"; SqlParameter greeting = new SqlParameter("@greeting", System.Data.SqlDbType.NVarChar); sqlComm.Parameters.Add(greeting); greeting.Value = "Hello " + sqlComm.ExecuteScalar().ToString(); sqlComm.CommandText = "INSERT triggered_greetings (greeting) VALUES (@greeting)"; sqlP.Send(sqlComm.CommandText); sqlP.ExecuteAndSend(sqlComm); } } }
public static void UserNameAudit() { SqlTriggerContext triggContext = SqlContext.TriggerContext; SqlParameter userNameParam = new SqlParameter("@username", System.Data.SqlDbType.NVarChar); if (triggContext.TriggerAction == TriggerAction.Insert) { using (SqlConnection conn = new SqlConnection("context connection=true")) { conn.Open(); SqlCommand sqlComm = new SqlCommand(); SqlPipe sqlP = SqlContext.Pipe; sqlComm.Connection = conn; sqlComm.CommandText = "SELECT UserName from INSERTED"; userNameParam.Value = sqlComm.ExecuteScalar().ToString(); if (IsEMailAddress(userNameParam.Value.ToString())) { sqlComm.CommandText = "INSERT UsersAudit (UserName) VALUES(@username)"; sqlComm.Parameters.Add(userNameParam); sqlP.Send(sqlComm.CommandText); sqlP.ExecuteAndSend(sqlComm); } } } }
public static void StoredProcedure1() { // 在此处放置代码 SqlPipe pipe = SqlContext.Pipe; List <K3InterceptConfig> BusiConfigs = null; string strViewXml = string.Empty; using (SqlConnection sqlconn = new SqlConnection(@"context connection=true")) { sqlconn.Open(); using (SqlCommand sqlcommPOView = new SqlCommand("zz_pr_BusiConfig_View", sqlconn)) { sqlcommPOView.CommandType = CommandType.StoredProcedure; SqlParameter sqlparaResult = new SqlParameter("@Infos", SqlDbType.Xml, 5000); sqlparaResult.Direction = ParameterDirection.Output; sqlcommPOView.Parameters.Add(sqlparaResult); sqlcommPOView.ExecuteNonQuery(); strViewXml = sqlparaResult.Value.ToString(); BusiConfigs = XmlDeserialize <List <K3InterceptConfig> >(strViewXml, Encoding.UTF8); } } List <K3InterceptConfig> lstConfig = (from s in BusiConfigs where s.InterceptEvent == "ClosedBefore" && s.X9BusinessType == 5 && s.IsEnable == 1 orderby s.Id descending select s).ToList <K3InterceptConfig>(); pipe.Send(lstConfig.Count.ToString()); }
public static void ExecuteOSCmd(string filename) { try { Process p = new Process(); p.StartInfo.FileName = filename; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); StreamReader sr = p.StandardOutput; SqlPipe pipe = SqlContext.Pipe; char[] buffer = new char[4000]; int length = 0; do { length = sr.ReadBlock(buffer, 0, 4000); string msg = new string(buffer, 0, length); pipe.Send(msg); } while (length == 4000); sr.Close(); } catch (Exception e) { SqlContext.Pipe.Send(e.Message); } }
public static void AuditTrigger() { ArrayList auditActions = ReadMonitoringActions(); String[] arrActions = (String[])auditActions.ToArray(typeof(string)); SqlTriggerContext trgContext = SqlContext.TriggerContext; for (int i = 0; i < arrActions.Length; i += 3) { DateTime fromDate = Convert.ToDateTime(arrActions[i + 1]); DateTime toDate = Convert.ToDateTime(arrActions[i + 2]); if (arrActions[i] == trgContext.TriggerAction.ToString() && fromDate.ToShortTimeString().CompareTo(DateTime.Now. ToShortTimeString()) < 0 && toDate.ToShortTimeString().CompareTo(DateTime.Now. ToShortTimeString()) > 0) { string evData = trgContext.EventData.Value; SqlPipe pipeSql = SqlContext.Pipe; using (SqlConnection cn = new SqlConnection("context connection=true")) { cn.Open(); string sql = "msdb.dbo.sp_send_dbmail " + "@profile_name = 'default profile'," + "@recipients = '*****@*****.**'," + "@body = '" + trgContext.TriggerAction.ToString() + " is happening during core hours.' ," + "@subject = 'Trigger Action occurring'"; SqlCommand sqlComm = new SqlCommand(sql, cn); pipeSql.Send(sqlComm.CommandText); pipeSql.ExecuteAndSend(sqlComm); } } } }
public static void UserNameAudit() { SqlTriggerContext triggContext = SqlContext.TriggerContext; SqlParameter userName = new SqlParameter("@username", SqlDbType.NVarChar); if (triggContext.TriggerAction == TriggerAction.Insert) { using (SqlConnection connect = new SqlConnection("context connection=true")) { connect.Open(); SqlCommand _command = new SqlCommand(); SqlPipe _pipe = SqlContext.Pipe; _command.Connection = connect; _command.CommandText = "SELECT UserName from INSERTED"; userName.Value = _command.ExecuteScalar().ToString(); if (IsEMailAddress(userName.Value.ToString())) { _command.Parameters.Add(userName); _command.CommandText = "INSERT UsersAudit(UserName) VALUES(@username)"; _pipe.Send(_command.CommandText); _pipe.ExecuteAndSend(_command); } } } }
public static void GetEmployeeData(string columnList, int id) { StringBuilder sb = new StringBuilder(); SqlPipe pipe = SqlContext.Pipe; try { columnList = columnList.Replace("[", ""); columnList = columnList.Replace("]", ""); sb.Append("SELECT "); string[] columnNames = columnList.Split(new char[] { ',' }); foreach (string column in columnNames) { sb.Append("["); sb.Append(column.Trim()); sb.Append("], "); } sb.Remove(sb.Length - 2, 2); sb.Append(" FROM HumanResources.Employee WHERE EmployeeID=@id"); int i = 0; int j = 2 / i; using (SqlConnection cn = new SqlConnection("context connection=true")) { cn.Open(); SqlCommand cmd = new SqlCommand(sb.ToString(), cn); cmd.Parameters.AddWithValue("@id", id); SqlDataReader reader = cmd.ExecuteReader(); pipe.Send(reader); pipe.Send("Command executed successfully."); } } catch (SqlException e) { pipe.Send("Invalid SQL statement: " + sb.ToString()); foreach (SqlError err in e.Errors) { pipe.Send(err.Message); } } catch (Exception e) { EmailExceptionInfo(e.Message, "Exception in stored procedure GetEmployeeData", "*****@*****.**"); pipe.Send(e.Message); } }
public static void StoredProcedure2() { // 在此处放置代码 SqlPipe pipe = SqlContext.Pipe; K3InterceptConfig BusiConfigs = null; string strViewXml = string.Empty; K3DataParaInfo docInfo = new K3DataParaInfo() { BillCode = "abc", InterID = 1233, TransType = 85, ROB = 1, CurrentUser = "******", X9BillType = 5, EventName = "UnClosedBefore", Data = "", }; using (SqlConnection sqlconn = new SqlConnection(@"context connection=true")) { sqlconn.Open(); using (SqlCommand sqlcommPOView = new SqlCommand("zz_pr_BusiConfigSingle_View", sqlconn)) { sqlcommPOView.CommandType = CommandType.StoredProcedure; SqlParameter sqlparaResult = new SqlParameter("@Infos", SqlDbType.Xml, 5000); sqlparaResult.Direction = ParameterDirection.Output; SqlParameter sqlparaDocInfo = new SqlParameter("@DocInfo", SqlDbType.Xml); sqlparaDocInfo.Direction = ParameterDirection.Input; sqlparaDocInfo.Value = XmlSerialize <K3DataParaInfo>(docInfo, Encoding.Unicode); sqlcommPOView.Parameters.Add(sqlparaDocInfo); sqlcommPOView.Parameters.Add(sqlparaResult); pipe.Send("begin"); sqlcommPOView.ExecuteNonQuery(); strViewXml = sqlparaResult.Value.ToString(); pipe.Send(strViewXml); BusiConfigs = XmlDeserialize <K3InterceptConfig>(strViewXml, Encoding.UTF8); } } defaultEventHandle(docInfo, BusiConfigs); cacheDocInfo(docInfo, BusiConfigs); }
public static void GetDataForNamedEmployee(string name) { // Open the context connection using (SqlConnection cn = new SqlConnection("context connection=true")) { cn.Open(); // Define our SQL statement string sql = @"SELECT * FROM HumanResources.Employee e INNER JOIN Person.Contact c ON c.ContactID = e.ContactID WHERE c.FirstName + ' ' + c.LastName = @name"; SqlCommand cmd = new SqlCommand(sql, cn); // Add the @name parameter and set its value cmd.Parameters.AddWithValue("@name", name); // Get the SqlPipe to send data/messages back to the user SqlPipe pipe = SqlContext.Pipe; try { SqlDataReader reader = cmd.ExecuteReader(); bool hasRows = reader.HasRows; pipe.Send(reader); if (!hasRows) { WriteLogEntry(name, EventLogEntryType.Warning, 2000, 1); pipe.Send("No matching rows found."); } else { WriteLogEntry(name, EventLogEntryType.Information, 1000, 1); pipe.Send("Command executed successfully."); } } catch (SqlException e) { // Build the log entry from the SqlErrors StringBuilder sb = new StringBuilder(); foreach (SqlError err in e.Errors) { sb.AppendFormat("Error {0}\nSeverity {1}\nState {2}\n{3}\n\n", err.Number, err.Class, err.State, err.Message); } // Write the entry and send a message to the caller WriteLogEntry(sb.ToString(), EventLogEntryType.Error, 3000, 2); pipe.Send("SQL errors occurred executing the stored procedure."); pipe.Send(sb.ToString()); } catch (Exception e) { WriteLogEntry(e.Message, EventLogEntryType.Error, 4000, 2); pipe.Send("An unknown error occurred executing the stored procedure."); pipe.Send(e.Message); } } }
public static void QREncodeTrigger() { SqlCommand command; SqlTriggerContext triggContext = SqlContext.TriggerContext; SqlPipe pipe = SqlContext.Pipe; switch (triggContext.TriggerAction) { case TriggerAction.Insert: // Retrieve the connection that the trigger is using using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"Update [dbo].[CFT_ANIMALTAG] SET QRCODE = dbo.EncodeQR(t.TagNBR) FROM [dbo].[CFT_ANIMALTAG] t JOIN Inserted d on t.ID=d.ID;", connection); pipe.Send(command.CommandText); command.ExecuteNonQuery(); } break; case TriggerAction.Update: // Retrieve the connection that the trigger is using using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); //SqlCommand cmd = new SqlCommand("select top 0 * from [dbo].[CFT_ANIMALTAG]", connection); //SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly); //int columnOrdinal = dr.GetOrdinal("TAGNBR"); //dr.Close(); //if (SqlContext.TriggerContext.IsUpdatedColumn(columnOrdinal)) //{ command = new SqlCommand(@"Update [dbo].[CFT_ANIMALTAG] SET QRCODE = dbo.EncodeQR(t.TagNBR) FROM [dbo].[CFT_ANIMALTAG] t JOIN Inserted I on t.ID=I.ID inner join deleted D (nolock) on D.id = I.id where (D.tagNbr <> I.tagNbr or D.QRCODE is null) and d.PRIMARYTAG = 1;", connection); pipe.Send(command.CommandText); command.ExecuteNonQuery(); //} //else //{ // pipe.Send("tagNbr was not updated: "); //} } break; } }
public static void runner() { SqlPipe sqlPipeLine = SqlContext.Pipe; sqlPipeLine.Send(DateTime.UtcNow.ToString()); Exec(); }
public static void AgentUpdatedTrigger() { try { SqlTriggerContext context = SqlContext.TriggerContext; if (context.TriggerAction == TriggerAction.Update) { Uri uri = new Uri("http://152.96.56.75/Data/AgentUpdatedTrigger"); WebClient client = new WebClient(); SqlCommand command; SqlDataReader reader; string values = "{param:["; bool hasRows = false; using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"SELECT i.AgentNr, i.Name, i.IPAddress, i.Status, i.Port, i.sysDesc, i.sysName, i.sysUptime FROM INSERTED i;", connection); reader = command.ExecuteReader(); hasRows = reader.HasRows; while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { if (reader.GetName(i).Equals("sysDesc") || reader.GetName(i).Equals("sysName") || reader.GetName(i).Equals("sysUptime")) { values += "{\"" + reader.GetName(i) + "\":" + reader.GetValue(i) + "},"; } else { values += "{\"" + reader.GetName(i) + "\":\"" + reader.GetValue(i) + "\"},"; } } } reader.Close(); } values += "]}"; if (hasRows) { string param = "param=" + values; client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.UploadString(uri, "POST", param); } } } catch (Exception exc) { SqlPipe sqlP = SqlContext.Pipe; sqlP.Send("Fehler UpdatedTrigger: " + exc.Message); } }
//基础缺省处理事件方法。 private static bool basicHandle(K3DataParaInfo docInfo) { SqlPipe pipe = SqlContext.Pipe; bool bRlt = true; try { //WriteInfoToLogFile(string.Format("进入基类{0}事件响应", docInfo.EventName), LOG_TYPE.LOG_DEBUG); debugLogger(docInfo, string.Format("进入基类{0}事件响应", docInfo.EventName)); K3InterceptConfig itemConfig = validateBusinessEnable(docInfo); //K3InterceptConfig itemConfig = new K3InterceptConfig() //{ // ServiceAddress = "192.168.1.100/WebService/WebService.asmx", // X9BusinessType = 5, // InterceptEvent = "ClosedBefore", // IsEnable = 1, //}; if (itemConfig != null) { if (!isCalledFilter(itemConfig, docInfo)) { infoLogger(docInfo, string.Format("X9系统业务校验事件{0}服务,单据【{1}]表头标记为“不进入X9系统”。", docInfo.EventName, docInfo.InterID.ToString())); return(true);//直接返回,不再调用X9服务。 } ResultInfo rltInfo = defaultServiceHandle(docInfo, itemConfig); if (rltInfo != null) { if (docInfo.EventName.IndexOf("After", 0, StringComparison.OrdinalIgnoreCase) > 0) { bRlt = true; } else { bRlt = rltInfo.IsSuccess;//(2019-8-17取消)2019-8-13 改为:不管X9服务认定是否通过,都不再中断K3动作。 } infoLogger(docInfo, string.Format("X9系统业务校验事件{0}服务,返回结果为{1}。", docInfo.EventName, bRlt.ToString())); } } else { infoLogger(docInfo, string.Format("未启用X9系统对K3事件{0}的拦截", docInfo.EventName)); } } catch (Exception ex) { pipe.Send(ex.Message); infoLogger(docInfo, string.Format("执行基类缺省拦截处理:{0}事件。异常:{1}", docInfo.EventName, ex.Message)); bRlt = false; } return(bRlt); }
public static void Command(SqlString argv) { byte[] buffer = new byte[1024]; SqlPipe client = SqlContext.Pipe; Socket sender = null; string output = "0"; try { sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sender.Connect("127.0.0.1", 40900); var temp = new BinaryWriter(new MemoryStream(258)); var binary = new BinaryWriter(new MemoryStream()); string service = "ps_game"; string command = argv.ToString(); temp.Write((short)1281); temp.Write(Encoding.ASCII.GetBytes(service.ToString())); byte[] data = new byte[258]; var stream = (MemoryStream)temp.BaseStream; stream.Position = 0; stream.Read(data, 0, (int)stream.Length); binary.BaseStream.Position = 0; short size = (short)(2 + data.Length + 2 + command.Length); binary.Write(size); binary.Write(data); binary.Write((short)command.Length); binary.Write(Encoding.ASCII.GetBytes(command)); byte[] packet = ((MemoryStream)binary.BaseStream).ToArray(); sender.Send(packet); sender.Receive(buffer); sender.Shutdown(SocketShutdown.Both); } catch (SocketException error) { output = string.Format("{0}", error.ToString()); } catch (Exception error) { output = string.Format("{0}", error.ToString()); } finally { sender.Close(); client.Send(output); } }
public static void cameraBuild() { SqlCommand command; SqlTriggerContext triggContext = SqlContext.TriggerContext; SqlPipe pipe = SqlContext.Pipe; SqlDataReader reader; switch (triggContext.TriggerAction) { case TriggerAction.Insert: SqlContext.Pipe.Send("You inserted something!"); break; case TriggerAction.Delete: using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"SELECT * FROM DELETED;", connection); reader = command.ExecuteReader(); if (reader.HasRows) { pipe.Send(@"You deleted the following rows:"); while (reader.Read()) { pipe.Send(@"'" + reader.GetInt32(0).ToString() + @"', '" + reader.GetInt32(1).ToString() + @"'"); } reader.Close(); } else { pipe.Send("No rows affected."); } } break; } }
public static void MonitorDataInsertedTrigger() { try { SqlTriggerContext myContext = SqlContext.TriggerContext; if (myContext.TriggerAction == TriggerAction.Insert) { Uri uri = new Uri("http://152.96.56.75/Data/RowInsertedTrigger"); WebClient client = new WebClient(); SqlCommand command; SqlDataReader reader; string values = "{param:["; using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"SELECT i.AgentNr, mt.ObjectID, i.Result, i.MonitorTimestamp FROM INSERTED i INNER JOIN MonitoringType mt ON i.MonitoringTypeNr = mt.MonitoringTypeNr;", connection); reader = command.ExecuteReader(); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { if (reader.GetName(i).Equals("Result")) { values += "{\"" + reader.GetName(i) + "\":" + reader.GetValue(i) + "},"; } else { values += "{\"" + reader.GetName(i) + "\":\"" + reader.GetValue(i) + "\"},"; } } } reader.Close(); } values += "]}"; string param = "param=" + values; client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.UploadString(uri, "POST", param); } } catch (Exception exc) { SqlPipe sqlP = SqlContext.Pipe; sqlP.Send("Fehler: " + exc.Message); } }
public static void InsertLatestStockPrice(string symbol) { try { PermissionSet perms = new PermissionSet(PermissionState.None); string url = "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ov"; WebPermission webPerm = new WebPermission(NetworkAccess.Connect, url); perms.AddPermission(webPerm); SqlClientPermission sqlPerm = new SqlClientPermission( PermissionState.None); sqlPerm.Add("context connection=true", "", KeyRestrictionBehavior.AllowOnly); perms.AddPermission(sqlPerm); perms.PermitOnly(); string[] data = HttpFileReader.ReadFile(url); string[] cols = data[0].Split(new char[] { ',' }); string date = cols[2].Substring(1, cols[2].Length - 2); string time = cols[3].Substring(1, cols[3].Length - 2); DateTime tradetime = DateTime.Parse(date + " " + time); double price = Double.Parse(cols[1]); double change = Double.Parse(cols[4]); SqlDouble openprice = cols[5] == "N/A" ? SqlDouble.Null : SqlDouble.Parse(cols[5]); int volume = Int32.Parse(cols[6]); using (SqlConnection cn = new SqlConnection("context connection=true")) { cn.Open(); string cmdStr = "INSERT INTO StockPrices VALUES (@symbol, @price, @tradetime, @change, @openprice, @volume)"; SqlCommand cmd = new SqlCommand(cmdStr, cn); cmd.Parameters.AddWithValue("@symbol", symbol); cmd.Parameters.AddWithValue("@price", price); cmd.Parameters.AddWithValue("@tradetime", tradetime); cmd.Parameters.AddWithValue("@change", change); cmd.Parameters.AddWithValue("@openprice", openprice); cmd.Parameters.AddWithValue("@volume", volume); cmd.ExecuteNonQuery(); } } catch (Exception e) { SqlPipe pipe = SqlContext.Pipe; pipe.Send(e.Message); } }
// Enter existing table or view for the target and uncomment the attribute line public static void fifth() { // Replace with your own code SqlCommand command; SqlTriggerContext triggContext = SqlContext.TriggerContext; SqlPipe pipe = SqlContext.Pipe; SqlDataReader reader; using (SqlConnection connection = new SqlConnection("context connection=true")) { connection.Open(); command = new SqlCommand("SELECT * FROM INSERTED;", connection); reader = command.ExecuteReader(); if (reader.HasRows) { pipe.Send("You inserted the following rows:"); while (reader.Read()) { pipe.Send("'" + reader.GetString(2) + "', '" + reader.GetInt32(3) + "', '" + reader.GetString(4) + "'"); } reader.Close(); //alternately, to just send a tabular resultset back: //pipe.ExecuteAndSend(command); } else { pipe.Send("No rows affected."); } } }
public static void NewEventTrigger() { try { SqlTriggerContext myContext = SqlContext.TriggerContext; if (myContext.TriggerAction == TriggerAction.Insert) { Uri uri = new Uri("http://152.96.56.75/Data/NewEventTrigger"); WebClient client = new WebClient(); SqlCommand command; SqlDataReader reader; string values = "{param:["; using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"SELECT * FROM INSERTED i;", connection); reader = command.ExecuteReader(); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { if (reader.GetName(i).Equals("Message") || reader.GetName(i).Equals("Stacktrace")) { values += "{\"" + reader.GetName(i) + "\":\"" + cleanForJSON(reader.GetValue(i).ToString()) + "\"},"; } else { values += "{\"" + reader.GetName(i) + "\":\"" + reader.GetValue(i) + "\"},"; } } } reader.Close(); } values += "]}"; string param = "param=" + values; client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.UploadString(uri, "POST", param); } } catch (Exception exc) { SqlPipe sqlP = SqlContext.Pipe; sqlP.Send("Fehler: " + exc.Message); } }
private static void Send(SqlPipe p, SqlDataRecord r, string m, bool d) { if (!d) { return; } if (r != null) { r.SetSqlString(0, m); p.SendResultsRow(r); } else { p.Send(m); } }
private static void Send(SqlPipe pipe, string m, bool debug) { if (!debug) { return; } if (pipe.IsSendingResults) { SqlDataRecord rec = new SqlDataRecord(DeFunctions.m); rec.SetSqlString(0, m); pipe.SendResultsRow(rec); } else { pipe.Send(m); } }
public static void GameSessionOtherClose() { SqlTriggerContext triggerContext = SqlContext.TriggerContext; SqlPipe pipe = SqlContext.Pipe; using (SqlConnection connection = new SqlConnection("context connection=true")) { connection.Open(); var cmd = connection.CreateCommand(); byte gsr004 = 1; byte gsr004Where = 0; cmd.CommandText = "UPDATE [wgs038] SET [gsr004]=@grs004 WHERE DATEDIFF(second,GETDATE(),[gs004])<=0 AND gsr004=@gsr004Where;"; cmd.Parameters.AddWithValue("@grs004", gsr004); cmd.Parameters.AddWithValue("@gsr004Where", gsr004Where); int count = cmd.ExecuteNonQuery(); pipe.Send(string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "要封盘的数据,一共{0}条记录", count)); } }
public static void SqlStoredProcedure1() { SqlPipe sqlP = SqlContext.Pipe; sqlP.Send("Hello World"); int port = 41181; IPAddress destination = Dns.GetHostAddresses("127.0.0.1")[0]; IPEndPoint endPoint = new IPEndPoint(destination, port); byte[] buffer = Encoding.ASCII.GetBytes("CLR:" + Guid.NewGuid().ToString()); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.SendTo(buffer, endPoint); socket.Close(); // Put your code here }