public void WriteSession(TheSessionState pSession) { if (pSession == null || pSession.HasExpired) //we should never write an expired Session { return; } try { pSession.LastAccess = DateTimeOffset.Now; pSession.cdeCTIM = DateTimeOffset.Now; pSession.PageHits++; MySessionStates.UpdateItem(pSession, null); #if CDE_LOGSESSIONS if (TheCDEngines.MyStorageService != null) { //LogSession(pSession.cdeMID, pSession.CurrentURL, pSession.Browser, pSession.BrowserDesc, pSession.InitReferer, pSession.CustomData); TheBaseAssets.MySYSLOG.WriteToLog(1236, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("SSM", "WriteRession: Writing ", eMsgLevel.l6_Debug, pSession.ToString())); } #endif } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(1237, new TSM("SSM", "WriteRession: Exception occured:", eMsgLevel.l2_Warning, e.ToString())); } }
/// <summary> /// Requests the capabilities of the Server /// </summary> /// <param name="pMagicID">MagicID to be used for back-publish</param> /// <param name="pCallBack">If set, and the call came from a local service, the sevices calls back without using the communication system</param> public void EdgeStorageServerRequestCaps(string pMagicID, Action <TSM> pCallBack) { if (TheCDEngines.MyIStorageService == null || TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService) { return; } string serializedXML = TheCommonUtils.SerializeObjectToJSONString(TheCDEngines.MyIStorageService.GetStorageCaps()); string post = "CDE_GETEDGECAPS"; if (pMagicID.Length > 0 && pCallBack != null) { MyTimedCallbacks.AddAnItem(new TheTimedCallback() { cdeMID = TheCommonUtils.CGuid(pMagicID), MyCallback = pCallBack }); post += ":" + pMagicID; } TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), post, serializedXML); if (TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService) { ProcessStorageServiceCommands(tTSM, pCallBack, true); } //else //Later for Remote Storage //{ // tTSM.SetToServiceOnly(true); // TheCommCore.PublishCentral(tTSM); //} }
static TimeSpan MaxTimeOut = new TimeSpan(1, 0, 0); // TODO Add to TheBaseAssets and make configurable? private static TSM PrepareRequestMessage(TheMessageAddress originator, TheMessageAddress target, string messageName, Guid correlationToken, string[] txtParameters, string PLS, byte[] PLB) { var parameterText = CreateParameterText(txtParameters); if (parameterText == null) { return(null); } TSM msg = new TSM(target.EngineName, String.Format("{0}:{1}:{2}", messageName, TheCommonUtils.cdeGuidToString(correlationToken), parameterText), PLS); if (PLB != null) { msg.PLB = PLB; } if (originator.ThingMID != Guid.Empty) { msg.SetOriginatorThing(originator.ThingMID); } if (target.ThingMID != Guid.Empty) { msg.OWN = TheCommonUtils.cdeGuidToString(target.ThingMID); } if (!string.IsNullOrEmpty(target.Route)) { msg.GRO = target.Route; } return(msg); }
private static void SetCookies(TheInternalRequestState myRequestState) { myRequestState.MyRequestData.TempCookies = new CookieContainer(); if (myRequestState.MyRequestData.RequestCookies != null && myRequestState.MyRequestData.RequestCookies.Count > 0) { foreach (string nam in myRequestState.MyRequestData.RequestCookies.Keys) { try { string tVal = myRequestState.MyRequestData.RequestCookies[nam]; if (string.IsNullOrEmpty(tVal)) { continue; } string[] co = tVal.Split(';'); string val = co[0]; string pat = "/"; //if (co.Length > 1) pat = co[1]; //string dom = ""; if (co.Length > 2) dom = co[2]; string dom = myRequestState.MyRequestData.RequestUri.Host.Trim(); //if (string.IsNullOrEmpty(dom)) //TheSystemMessageLog.ToCo(string.Format("GetREST: Cookie: ({0}) ({1}) ({2}) ({3})", nam,val,pat,dom)); myRequestState.MyRequestData.TempCookies.Add(myRequestState.MyRequestData.RequestUri, new Cookie(nam.Trim(), val.Trim(), pat, dom)); } catch (Exception e) { if (TheBaseAssets.MySYSLOG != null) { TheBaseAssets.MySYSLOG.WriteToLog(254, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheREST", "SetCookies Exception: " + myRequestState.MyRequestData.RequestUri, eMsgLevel.l1_Error, e.Message)); } } } //TheSystemMessageLog.ToCo(string.Format("GetREST: CookieCont: ({0})", myRequestState.MyRequestData.TempCookies.GetCookieHeader(myRequestState.MyRequestData.RequestUri))); } }
public RemoteSubscriber(TSM tsm, IList <string> patterns, RegistrySubscriptionRequest request) { Tsm = tsm; _registryRequest = request; _patterns = new HashSet <string>(patterns.Distinct()); IsLocalHost = tsm.IsLocalHost(); }
/// <summary> /// Sets a client Certificate on TheRequestData /// </summary> /// <param name="pData"></param> /// <param name="pThumbPrint"></param> /// <returns></returns> internal static bool SetClientCert(TheRequestData pData, string pThumbPrint) { if (!string.IsNullOrEmpty(pThumbPrint)) { try { X509Certificate2Collection certs = null; if (pThumbPrint == TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb) { certs = TheBaseAssets.MyServiceHostInfo.ClientCerts; //Use cached value if master cache } else { certs = GetClientCertificatesByThumbprint(pThumbPrint); //load a custom cert for ISB Connect and other client cert scenarios } if (certs?.Count > 0) { pData.ClientCert = certs[0]; return(true); //Client cert could be set to TheRequestData } } catch (Exception certex) { TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", "Error setting Client Certificate", eMsgLevel.l1_Error, certex.ToString())); } return(false); //ClientThumb is set but could not be added to TheRequestData...let caller know } return(true); //Not set..all is good }
/// <summary> /// Sets a new client Certificate. If it contains a scopeid and ApplyScope is true, the node will be scoped with that ScopeID /// </summary> /// <param name="pCertThumb">Thumbprint of the new client certificate</param> /// <param name="ApplyScope">if true, the scope in the certificate will be used to scope the node</param> /// <returns></returns> public static string SetClientCertificate(string pCertThumb, bool ApplyScope = false) { if (!string.IsNullOrEmpty(pCertThumb)) { TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb = pCertThumb; TheBaseAssets.MyServiceHostInfo.ClientCerts = GetClientCertificatesByThumbprint(pCertThumb); if (TheBaseAssets.MyServiceHostInfo.ClientCerts == null || TheBaseAssets.MyServiceHostInfo.ClientCerts?.Count == 0) //No valid client certifcate found { TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb = null; TheBaseAssets.MyServiceHostInfo.ClientCerts = null; TheBaseAssets.MySYSLOG.WriteToLog(4151, new TSM("TheBaseAssets", $"Client Certificate with Thumbprint {pCertThumb} required but not found! Connection to Cloud not possible", eMsgLevel.l1_Error)); } else { string error = ""; var tScopes = GetScopesFromCertificate(TheBaseAssets.MyServiceHostInfo.ClientCerts[0], ref error); if (tScopes?.Count > 0) { TheBaseAssets.MySYSLOG.WriteToLog(2821, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", $"Scope {tScopes[0]} found in Certificate {(ApplyScope ? "and applied" : "")}", eMsgLevel.l3_ImportantMessage)); if (ApplyScope) { TheBaseAssets.MyScopeManager.SetScopeIDFromEasyID(tScopes[0]); } return(tScopes[0]); } else { TheBaseAssets.MySYSLOG.WriteToLog(4151, new TSM("TheBaseAssets", $"Client Certificate with Thumbprint {pCertThumb} found and will be applied as soon as cloud is connected")); } } } return(null); }
internal static List <string> GetScopesFromCertificate(X509Certificate2 x509cert, ref string error) { string extensions = ""; List <string> scopeIds = new List <string>(); foreach (X509Extension extension in x509cert.Extensions) { // Create an AsnEncodedData object using the extensions information. AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData); extensions += $"{extension.Oid.FriendlyName} {asndata.Oid.Value} {asndata.RawData.Length} {asndata.Format(false)}"; try { if (extension.Oid.Value == "2.5.29.17") // SAN { string strSANEntry = asndata.Format(true); var lines = strSANEntry.Split(new[] { "\r\n", "\n\r", "\n", "\r" }, StringSplitOptions.None); foreach (var line in lines) { try { if (line.StartsWith("URL=")) { var scopeidUriStr = line.Substring("URL=".Length); var scopeidUri = TheCommonUtils.CUri(scopeidUriStr, true); if (scopeidUri.Scheme.ToLowerInvariant() == "com.c-labs.cdescope") { var scopeid = scopeidUri.Host; scopeIds.Add(scopeid); } } else if (line.StartsWith("URI:")) // TODO check why .Net Core on Linux returns a different prefix (openssl?) - are there platform agnostic ways of doing this? Are there other platforms with different behavior? { var scopeidUriStr = line.Substring("URI:".Length); var scopeidUri = TheCommonUtils.CUri(scopeidUriStr, true); if (scopeidUri.Scheme.ToLowerInvariant() == "com.c-labs.cdescope") { var scopeid = scopeidUri.Host; scopeIds.Add(scopeid); } } } catch (Exception e) { error += e.ToString(); } } } } catch (Exception e) { error += e.ToString(); } //Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName); //Console.WriteLine("Oid value: {0}", asndata.Oid.Value); //Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine); //Console.WriteLine(asndata.Format(true)); } TheBaseAssets.MySYSLOG.WriteToLog(2351, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("HttpService", $"{DateTimeOffset.Now}: {x509cert?.Subject} ScopeIds: {TheCommonUtils.CListToString(scopeIds, ",")} {error} [ Raw: {extensions} ] [Cert: {Convert.ToBase64String(x509cert.RawData)}]")); return(scopeIds); }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_Product model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into CK_Product("); strSql.Append("CK_ProductTypeID,CK_ProductName,CK_ProductPrice)"); strSql.Append(" values ("); strSql.Append("@CK_ProductTypeID,@CK_ProductName,@CK_ProductPrice)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@CK_ProductTypeID", SqlDbType.Int,4), new SqlParameter("@CK_ProductName", SqlDbType.VarChar,100), new SqlParameter("@CK_ProductPrice", SqlDbType.Decimal,9)}; parameters[0].Value = model.CK_ProductTypeID; parameters[1].Value = model.CK_ProductName; parameters[2].Value = model.CK_ProductPrice; object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 1; } else { return Convert.ToInt32(obj); } }
public void LogChanges(bool IsConsumer, cdeP[] changedProperties = null) { string logMessage = ""; if (IsConsumer) { List <TheThingStore> history = testThing.GetThingHistory(historyToken, 1, false); logMessage = "Aggregated - "; foreach (TheThingStore snapShot in history) { foreach (string property in properties) { if (snapShot.PB.TryGetValue(property, out var propValue)) { logMessage += $"{property}: {propValue} | "; } } } } else { logMessage = $"{testThing.FriendlyName} - "; if (changedProperties != null) { foreach (cdeP property in changedProperties) { logMessage += $"{property.Name}: {property.Value} | "; } } } // Log the message to SYSLOG TheBaseAssets.MySYSLOG.WriteToLog( 2020, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), logMessage, IsConsumer ? eMsgLevel.l3_ImportantMessage : eMsgLevel.l4_Message)); }
internal void Startup() { TheDiagnostics.SetThreadName("WSStartup"); if (TheBaseAssets.MyServiceHostInfo.MyStationWSPort == 0) return; Uri tUri = new Uri(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); MyHttpUrl = tUri.Scheme + "://*"; // +tUri.Host; MyHttpUrl += ":" + TheBaseAssets.MyServiceHostInfo.MyStationWSPort; MyHttpUrl += "/"; appServer = new WebSocketServer(); //Setup the appServer if (!appServer.Setup(new ServerConfig() { Port = TheBaseAssets.MyServiceHostInfo.MyStationWSPort, MaxRequestLength = 400000 })) //Setup with listening port { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Error During Startup", eMsgLevel.l1_Error)); return; } appServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(appServer_NewMessageReceived); appServer.NewDataReceived += appServer_NewDataReceived; appServer.NewSessionConnected += appServer_NewSessionConnected; appServer.SessionClosed += appServer_SessionClosed; //Try to start the appServer if (!appServer.Start()) { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Failed to start Super-Web-Socket Server", eMsgLevel.l1_Error)); IsActive = false; return; } IsActive = true; TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheWSServer", "New Super-Web-Socket Server started ", eMsgLevel.l4_Message)); }
protected void Page_Load(object sender, EventArgs e) { TSM oTSM = new TSM(0, dsn); if (Request.QueryString["u"] != null && Request.QueryString["u"] == "GET") { XmlDocument oDoc = new XmlDocument(); oDoc.Load(Request.InputStream); Response.ContentType = "application/xml"; StringBuilder sb = new StringBuilder("<values>"); string strValue = Server.UrlDecode(oDoc.FirstChild.InnerXml); int intParent = Int32.Parse(strValue); DataSet ds = oTSM.GetDomains(intParent, 1); foreach (DataRow dr in ds.Tables[0].Rows) { sb.Append("<value>"); sb.Append(dr["id"].ToString()); sb.Append("</value><text>"); sb.Append(dr["name"].ToString()); sb.Append("</text>"); } sb.Append("</values>"); Response.Write(sb.ToString()); Response.End(); } }
protected void Page_Load(object sender, EventArgs e) { if (Request.Cookies["adminid"] != null && Request.Cookies["adminid"].Value != "") { intProfile = Int32.Parse(Request.Cookies["adminid"].Value); } else { Reload(); } oTSM = new TSM(intProfile, dsn); if (Request.QueryString["id"] != null && Request.QueryString["id"] != "") { lblId.Text = Request.QueryString["id"]; } string strControl = ""; string strControlText = ""; if (Request.QueryString["control"] != null) { strControl = Request.QueryString["control"]; } if (Request.QueryString["controltext"] != null) { strControlText = Request.QueryString["controltext"]; } btnNone.Attributes.Add("onclick", "return Reset(0,'" + hdnId.ClientID + "','None','" + txtName.ClientID + "');"); btnSave.Attributes.Add("onclick", "return Update('" + hdnId.ClientID + "','" + strControl + "','" + txtName.ClientID + "','" + strControlText + "');"); btnClose.Attributes.Add("onclick", "return HidePanel();"); LoadTree(); }
bool ProcessCDEngine(TheUPnPDeviceInfo tHistory, Uri tLocationUrl) { if ((tLocationUrl.Host.Equals(TheBaseAssets.MyServiceHostInfo.MyStationIP) && tLocationUrl.Port == TheBaseAssets.MyServiceHostInfo.MyStationPort) || !tHistory.PacketString.Contains(TheBaseAssets.MyServiceHostInfo.ApplicationName) || tLocationUrl.Host.Contains("127.0.0.1")) { return(true); } TheBaseAssets.MySYSLOG.WriteToLog(111, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", string.Format("C-DEngine Root Device Found: {0}", tHistory), eMsgLevel.l7_HostDebugMessage)); if (!TheBaseAssets.MyServiceHostInfo.DisableUPnPAutoConnect && TheBaseAssets.MyServiceHostInfo.ApplicationName.Equals(tHistory.ModelName)) { if (!string.IsNullOrEmpty(tHistory.CDEContextID)) { if (!string.IsNullOrEmpty(tHistory.CDEProvisionUrl)) { TheBaseAssets.MySettings.SetSetting("AutoProvisioningUrl", tHistory.CDEProvisionUrl); } if (!TheBaseAssets.MyScopeManager.IsScopingEnabled || (TheBaseAssets.MyScopeManager.IsScopingEnabled && !TheBaseAssets.MyScopeManager.ScopeID.Equals(TheBaseAssets.MyScopeManager.GetRealScopeID(tHistory.CDEContextID)))) //GRSI: rare { return(false); } } else { if (TheBaseAssets.MyScopeManager.IsScopingEnabled || !TheBaseAssets.MyServiceHostInfo.AllowUnscopedMesh) { return(false); } } if (!TheCommonUtils.DoesContainLocalhost(tHistory.CDEConnectUrl) && !TheCommonUtils.DoesContainLocalhost(tHistory.CDEConnectWsUrl)) { string strStationRoles = tHistory.FriendlyName; int pos = strStationRoles.LastIndexOf(':') + 1; if (!string.IsNullOrEmpty(strStationRoles) && pos >= 0) { strStationRoles = strStationRoles.Substring(pos, strStationRoles.Length - pos); string[] sRoles = strStationRoles.Split(';'); List <string> discoveredStationRoles = new List <string>(); foreach (string gt in sRoles) { discoveredStationRoles.Add(TheBaseAssets.MyScopeManager.AddScopeID(gt)); } string[] apps = TheCommonUtils.cdeSplit(tHistory.FriendlyName, " at:", false, false); string appName = "Unknown App"; if (apps != null && apps.Length > 0) { appName = apps[0].Trim(); } string tConnectUrl = tHistory.CDEConnectUrl; if (!string.IsNullOrEmpty(tHistory.CDEConnectWsUrl)) { tConnectUrl = tHistory.CDEConnectWsUrl; } TheBaseAssets.MySYSLOG.WriteToLog(112, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", $"Compatible Service Found: {tHistory.FriendlyName} {tHistory.Manufacturer} {tHistory.ModelName} {tHistory.ModelNumber} {tHistory.SerialNumber} {tConnectUrl}", eMsgLevel.l7_HostDebugMessage)); eventWSDMatchFound?.Invoke(tHistory.CDENodeID, tConnectUrl, discoveredStationRoles); TheBaseAssets.MySYSLOG.WriteToLog(113, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("UPnP", "New " + appName + " Station found at: " + tConnectUrl, eMsgLevel.l3_ImportantMessage)); } } } return(true); }
private async void OnWatchDogTimer(object state) { try { OnSendAttempt(null); var timeSinceLastAttempt = DateTimeOffset.Now - LastSendAttemptTime; if (timeSinceLastAttempt > new TimeSpan(0, 0, WatchDogIdleRecycleIntervalInMinutes, 0)) { TheBaseAssets.MySYSLOG.WriteToLog(95014, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: No activity since {LastSendAttemptTime}. Disconnecting Sender and waiting 5 seconds to reconnect.", eMsgLevel.l4_Message)); Disconnect(true); try { await TheCommonUtils.TaskDelayOneEye(5000, 100); } catch (TaskCanceledException) { } if (TheBaseAssets.MasterSwitch) { TheBaseAssets.MySYSLOG.WriteToLog(95015, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: Reconnecting Sender.", eMsgLevel.l4_Message)); Connect(); } } } catch (Exception ex) { TheBaseAssets.MySYSLOG.WriteToLog(95302, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: Internal error.", eMsgLevel.l1_Error, ex.ToString())); } }
/// <summary> /// Main call to store values in the StorageService /// </summary> /// <typeparam name="T">Type of class to be stored</typeparam> /// <param name="MyValue">Dictionary of Values of the class to be stored</param> /// <param name="pCMD">Command for the store process</param> /// <param name="pMagicID">MagicID to be used for back-publish</param> /// <param name="pCallBack">If set, and the call came from a local service, the sevices calls back without using the communication system</param> public void EdgeDataStore <T>(Dictionary <string, T> MyValue, eSCMD pCMD, string pMagicID, Action <TSM> pCallBack, string pTableName) { if (TheCDEngines.MyIStorageService != null) { string serializedXML = TheStorageUtilities.SerializeDataToStore(MyValue, pMagicID, pCMD, typeof(T).Equals(typeof(cdeP)) ? null : pTableName); string post = "CDE_EDGESTORE"; post += ":"; if (!string.IsNullOrEmpty(pMagicID) && pCallBack != null) { MyTimedCallbacks.AddAnItem(new TheTimedCallback() { cdeMID = TheCommonUtils.CGuid(pMagicID), MyCallback = pCallBack }); post += pMagicID; } if (typeof(T).Equals(typeof(cdeP))) { post += ":" + TheStorageUtilities.GenerateUniqueIDFromType(typeof(TheThing), pTableName); } TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), post, serializedXML); if (TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService) { ProcessStorageServiceCommands(tTSM, pCallBack, true); } //else //Later for Remote Storage //{ // tTSM.SetToServiceOnly(true); // TheCommCore.PublishCentral(tTSM); //} } }
void appServer_NewSessionConnected(WebSocketSession session) { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheSWSServer", string.Format("New Session: {0} ID:{1}", session.RemoteEndPoint.ToString(), session.SessionID))); try { TheWSProcessor tProcessor = new TheWSProcessor(session); mSessionList.TryAdd(session.SessionID, tProcessor); TheRequestData tRequestData = new TheRequestData(); tRequestData.RequestUri = new Uri(session.UriScheme + "://" + session.Host + session.Path); // pContext.Request.Url; tRequestData.Header = new cdeConcurrentDictionary<string, string>(); foreach (var tKey in session.Items) { switch (tKey.Key.ToString().ToLower()) { case "user-agent": //tRequestData.UserAgent = pContext.Request.UserAgent; tRequestData.UserAgent = tKey.Value.ToString(); break; case "content-type": //tRequestData.ResponseMimeType = pContext.Request.ContentType; tRequestData.ResponseMimeType = tKey.Value.ToString(); break; } tRequestData.Header.TryAdd(tKey.Key.ToString(), tKey.Value.ToString()); } tRequestData.ServerTags = null; tProcessor.SetRequest(tRequestData); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheSWSServer", "Error during new Session-Connect", eMsgLevel.l1_Error,e.ToString())); } }
bool Connect(TheProcessMessage pMsg) { bool bSuccess = false; try { MyBaseThing.StatusLevel = 4; // ReaderThread will set statuslevel to 1 foreach (var field in MyModFieldStore.TheValues) { var p = MyBaseThing.GetProperty(field.PropertyName, true); p.cdeM = "MODPROP"; p.UnregisterEvent(eThingEvents.PropertyChangedByUX, null); p.RegisterEvent(eThingEvents.PropertyChangedByUX, sinkPChanged); } SetupModbusProperties(true, pMsg); IsConnected = true; MyBaseThing.LastMessage = $"{DateTime.Now} - Device Connecting"; TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, MyBaseThing.LastMessage, eMsgLevel.l4_Message)); TheCommonUtils.cdeRunAsync($"ModRunThread{MyBaseThing.FriendlyName}", true, (o) => { ReaderThread(); }); bSuccess = true; } catch (Exception e) { MyBaseThing.StatusLevel = 3; string error = $"Error connecting: {e.Message}"; MyBaseThing.LastMessage = $"{DateTimeOffset.Now}: {error}"; TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, error, eMsgLevel.l1_Error, e.ToString())); IsConnected = false; } return(bSuccess); }
/// <summary> /// Copies the in-memory configuration to the stored configuration file. /// </summary> /// <param name="pin">The personal identification number (PIN) to use as an encryption key.</param> public static void Save(int pin) => TSM.RunSafe(() => { using (var s = Application.Context.OpenFileOutput(FILE_NAME, FileCreationMode.Private)) using (var w = new BinaryWriter(s)) { w.Write(FILE_VERSION); w.Write(Address); w.Write(ConnectionTargets.Length); foreach (var t in ConnectionTargets) { w.Write(t.Serialize()); } w.Write(Contacts.Length); foreach (var c in Contacts) { w.Write(c.Address); w.WriteString472(c.Name); } w.Write(Recents.Length); foreach (var r in Recents) { w.Write(r.Address); w.Write(r.Timestamp.Ticks); } var aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7); var sha = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha512); var bk = sha.HashData(BitConverter.GetBytes(pin)); using (var ms = new MemoryStream()) { /*using (var es = new EncryptedStream(ms, key)) * using (var ws = new WrapperStream(ms)) * using (var cs = new CryptoStream(ws, WinRTCrypto.CryptographicEngine.CreateEncryptor(aes.CreateSymmetricKey(key)), CryptoStreamMode.Write))*/ using (var cw = new BinaryWriter(ms)) { cw.Write(bk); cw.Write(VerificationKeys.Length); foreach (var k in VerificationKeys) { w.Write(k.Address); w.Write(k.PrivateKey.Length); w.Write(k.PrivateKey); w.Write(k.PublicKey.Length); w.Write(k.PublicKey); } } var key = bk; var data = ms.ToArray(); for (int i = 0; i < data.Length / 64 + 1; ++i) { key = sha.HashData(key); for (int j = 0; j < 64 && (i < data.Length / 64 || j < data.Length % 64); ++j) { data[i * 64 + j] ^= key[j]; } } w.Write(data.Length); w.Write(data); } } });
void sinkThingWasUpdated(ICDEThing sender, object pPara) { if (TheBaseAssets.MyServiceHostInfo.IsCloudService) { return; //TODO: Allow Cloud Rules } TheThing pThing = sender as TheThing; if (pThing != null && TheThing.GetSafePropertyString(pThing, "DeviceType") == eKnownDeviceTypes.TheThingRule) { TheRule tRule = pThing.GetObject() as TheRule; if (tRule == null) { tRule = new TheRule(pThing, this); tRule.RegisterEvent(eEngineEvents.ThingUpdated, sinkUpdated); RegisterRule(tRule); } { tRule.IsRuleWaiting = true; tRule.IsRuleRunning = false; TheSystemMessageLog.WriteLog(4445, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(eKnownDeviceTypes.TheThingRule, $"Rule {tRule.FriendlyName} stopped on Rule Update"), false); TheThingRegistry.UpdateThing(tRule, false); } ActivateRules(); } }
private void StorageHasStarted(ICDEThing sender, object pReady) { if (pReady != null) { if (MyServiceHealthDataStore == null) { MyServiceHealthDataStore = new TheStorageMirror <TheThingStore>(TheCDEngines.MyIStorageService) { IsRAMStore = "RAM".Equals(pReady.ToString()), IsCachePersistent = "RAM".Equals(pReady.ToString()) && !TheBaseAssets.MyServiceHostInfo.IsCloudService, CacheTableName = "TheHealthHistory" }; if (MyServiceHealthDataStore.IsRAMStore) { MyServiceHealthDataStore.SetRecordExpiration(86400, null); //RAM stores for 1 day MyServiceHealthDataStore.InitializeStore(true, false); } else { MyServiceHealthDataStore.SetRecordExpiration(604800, null); //Storage stores for 7 days MyServiceHealthDataStore.CreateStore("C-DMyComputer: DeviceHealthData", "All health Data of a Device/Service", null, true, false); } TheBaseAssets.MySYSLOG.WriteToLog(8002, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("jcHealth", "Health Storage Started", eMsgLevel.l3_ImportantMessage)); } } }
internal static void ParseUnsubscribe(string pTopics, TheQueuedSender pQSender) { TheBaseAssets.MySYSLOG.WriteToLog(301, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"ParseUnsubscribe for Topics={pTopics} of {pQSender.MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l7_HostDebugMessage)); if (string.IsNullOrEmpty(pTopics) || pQSender == null) { return; } bool WasSubscribed = pQSender.Unsubscribe(pTopics); TheBaseAssets.MySYSLOG.WriteToLog(302, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"ParseUnsubscribe: Removing Topic Topics={pTopics} of {pQSender.MyTargetNodeChannel?.ToMLString()} Was Sub'ed: {WasSubscribed}", eMsgLevel.l7_HostDebugMessage)); #region DebugInfo if (TheBaseAssets.MyServiceHostInfo.DebugLevel > eDEBUG_LEVELS.FULLVERBOSE) { string tContent = "ParseUnsubscribe - Unsubscribed from: " + pTopics; eMsgLevel tLev = eMsgLevel.l4_Message; if (WasSubscribed) { tLev = eMsgLevel.l2_Warning; tContent = "A Subscription was not Found for: " + pTopics; } TheBaseAssets.MySYSLOG.WriteToLog(304, new TSM("CoreComm", tContent, tLev)); } #endregion }
/// <summary> /// Construtor for network related events /// </summary> /// <param name="onNewInterfaceSink"></param> /// <param name="onDeletedInterfaceSink"></param> public TheNetworkInfo(Action <object, TheIPDef> onNewInterfaceSink, Action <object, TheIPDef> onDeletedInterfaceSink) { TheBaseAssets.MySYSLOG.WriteToLog(138, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("UPnP", "Enter NetworkInfo")); TheQueuedSenderRegistry.RegisterHealthTimer(PollInterface); MyHostName = cdeGetHostName(); TheBaseAssets.MySYSLOG.WriteToLog(139, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("UPnP", "NetworkInfo - HostName :" + MyHostName)); GetLocalIPs(true); if (onNewInterfaceSink != null) { OnNewInterfaceEvent += onNewInterfaceSink; foreach (TheIPDef address in AddressTable.Values) { if (address.IsDnsEnabled) { TheBaseAssets.MySYSLOG.WriteToLog(141, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("UPnP", string.Format("NetworkInfo - Init-Address: {0} of {1}", address, AddressTable.Count), eMsgLevel.l3_ImportantMessage)); OnNewInterfaceEvent?.Invoke(this, address); } } } if (OnInterfaceDisabledEvent != null) { OnInterfaceDisabledEvent += onDeletedInterfaceSink; } TheBaseAssets.MySYSLOG.WriteToLog(144, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("UPnP", "NetworkInfo - All Interfaces Initialized")); }
internal bool Startup() { if (TheBaseAssets.MyServiceHostInfo.MyStationWSPort == 0 || TheBaseAssets.MyServiceHostInfo.MyStationWSPort == TheBaseAssets.MyServiceHostInfo.MyStationPort) return false; mHttpListener = new HttpListener(); Uri tUri = new Uri(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); MyHttpUrl = tUri.Scheme + "://*"; // +tUri.Host; MyHttpUrl += ":" + TheBaseAssets.MyServiceHostInfo.MyStationWSPort; MyHttpUrl += "/"; try { mHttpListener.Prefixes.Add(MyHttpUrl); mHttpListener.Start(); TheBaseAssets.MySYSLOG.WriteToLog(4370, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheWSServer", "New WebSockets8 HttpListener started ", eMsgLevel.l4_Message, $"Port: {TheBaseAssets.MyServiceHostInfo.MyStationWSPort}")); IsActive = true; TheCommonUtils.cdeRunAsync("WebSocketServer - Processing Thread", true, async o => { while (IsActive && TheBaseAssets.MasterSwitch) { try { if (mHttpListener != null) { HttpListenerContext context = await mHttpListener.GetContextAsync(); if (!context.Request.IsWebSocketRequest) { context.Response.StatusCode = 400; context.Response.Close(); continue; } TheCommonUtils.cdeRunAsync("WSWait4AcceptThread", false, async oo => { try { await WaitForWSAccept(context); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4371, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Error During WSAccept", eMsgLevel.l1_Error, e.ToString())); IsActive = false; } }); } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4372, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "WebSocketServer:Failed - Will Stop!", eMsgLevel.l1_Error, e.ToString())); IsActive = false; } } ShutDown(); }); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4373, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Error During Startup", eMsgLevel.l1_Error, $"Port: {TheBaseAssets.MyServiceHostInfo?.MyStationWSPort} {e.ToString()}")); IsActive = false; } return IsActive; }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_People model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into CK_People("); strSql.Append("CK_PeopleName,CK_PhoneNo,CK_Comment)"); strSql.Append(" values ("); strSql.Append("@CK_PeopleName,@CK_PhoneNo,@CK_Comment)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32), new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32), new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)}; parameters[0].Value = model.CK_PeopleName; parameters[1].Value = model.CK_PhoneNo; parameters[2].Value = model.CK_Comment; object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 1; } else { return Convert.ToInt32(obj); } }
private void OnDownloadClick(ICDEThing pThing, object pPara) { TheProcessMessage pMSG = pPara as TheProcessMessage; if (pMSG == null || pMSG.Message == null) { return; } string[] cmd = pMSG.Message.PLS.Split(':'); if (cmd.Length > 2) { TheThing tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(cmd[2]), true); if (tThing == null) { return; } TSM tFilePush = new TSM(eEngineName.ContentService, string.Format("CDE_FILE:{0}.JSON:application/zip", tThing.FriendlyName)) { SID = pMSG.Message.SID, PLS = "bin", PLB = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(tThing)) }; TheCommCore.PublishToOriginator(pMSG.Message, tFilePush); } }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_Payment model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into CK_Payment("); strSql.Append("CK_PeopleID,CK_PayDate,CK_PayMoney,CK_PayComment)"); strSql.Append(" values ("); strSql.Append("@CK_PeopleID,@CK_PayDate,@CK_PayMoney,@CK_PayComment)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleID", SqlDbType.Int,4), new SqlParameter("@CK_PayDate", SqlDbType.DateTime), new SqlParameter("@CK_PayMoney", SqlDbType.Decimal,9), new SqlParameter("@CK_PayComment", SqlDbType.VarChar,100)}; parameters[0].Value = model.CK_PeopleID; parameters[1].Value = model.CK_PayDate; parameters[2].Value = model.CK_PayMoney; parameters[3].Value = model.CK_PayComment; object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 1; } else { return Convert.ToInt32(obj); } }
public bool RegisterRule(TheThingRule pRule) { if (pRule == null || TheBaseAssets.MyServiceHostInfo.IsCloudService) { return(false); } pRule.GetBaseThing().EngineName = MyBaseEngine.GetEngineName(); if (pRule.TriggerCondition == eRuleTrigger.Set) { pRule.ActionValue = null; } pRule.IsRuleRunning = false; pRule.IsRuleWaiting = true; pRule.IsIllegal = false; pRule.IsTriggerObjectAlive = false; pRule.Parent = MyBaseThing.ID; pRule.GetBaseThing().EngineName = MyBaseEngine.GetEngineName(); TheSystemMessageLog.WriteLog(4445, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(eKnownDeviceTypes.TheThingRule, $"Rule {pRule.FriendlyName} stopped during Register Rule - waiting for startup"), false); TheThing.SetSafePropertyDate(pRule.GetBaseThing(), "LastTriggered", DateTimeOffset.MinValue); TheThing.SetSafePropertyDate(pRule.GetBaseThing(), "LastAction", DateTimeOffset.MinValue); TheThingRegistry.RegisterThing(pRule); return(true); }
/// <summary> /// Set the first request to the WS-Processor. It will be used to handle all WebSocket data for the session of the related node /// </summary> /// <param name="pRequest">If null, the Processor will create a new empty TheRequestData to handle all traffic</param> public void SetRequest(TheRequestData pRequest) { if (pRequest == null) { MySessionRequestData = new TheRequestData(); } else { MySessionRequestData = pRequest; } MySessionRequestData.WebSocket = this; mre = new ManualResetEventSlim(true); IsActive = true; CloseFired = false; try { if (TheCommCore.MyHttpService != null && MySessionRequestData.RequestUri != null) { TheCommCore.MyHttpService.cdeProcessPost(MySessionRequestData); } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4360, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor", "cdeProcssPost Error", eMsgLevel.l1_Error, e.ToString())); } }
void SendRuleTSM(bool serviceOnly) { string engine = TheCommonUtils.CStr(GetProperty("TSMEngine", false)); string text = TheCommonUtils.CStr(GetProperty("TSMText", false)); string payload = TheCommonUtils.CStr(GetProperty("TSMPayload", false)); //payload = payload.Replace("%DTO%", TheCommonUtils.CStr(DateTimeOffset.Now)); //text = text.Replace("%DTO%", TheCommonUtils.CStr(DateTimeOffset.Now)); ICDEThing triggerThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(TriggerObject)) as ICDEThing; string escPayload = TheCommonUtils.GenerateFinalStr(payload, triggerThing); escPayload = TheCommonUtils.GenerateFinalStr(escPayload, MyBaseThing); string escText = TheCommonUtils.GenerateFinalStr(text, triggerThing); escText = TheCommonUtils.GenerateFinalStr(escText, MyBaseThing); if (!string.IsNullOrEmpty(engine) && !string.IsNullOrEmpty(text)) { TSM customTSM = new TSM(engine, escText, escPayload); if (serviceOnly) { customTSM.SetToServiceOnly(true); } TheCommCore.PublishCentral(customTSM, true); } if (IsRuleLogged) { LogEvent(escPayload); } if (TheThing.GetSafePropertyBool(MyBaseThing, "IsEVTLogged")) { TheLoggerFactory.LogEvent(eLoggerCategory.RuleEvent, TheCommonUtils.GenerateFinalStr(MyBaseThing.FriendlyName, MyBaseThing), eMsgLevel.l4_Message, TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false), escText, escPayload); } }
public void IncomingMessageEventTest() { var contentServiceThing = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService); var contentServiceEng = contentServiceThing.GetBaseEngine(); int numberOfMessages = 0; string txt = "TEST_TXT"; string payload = "TestPayload"; TSM testMsg = new TSM(eEngineName.ContentService, txt, payload); contentServiceEng?.RegisterEvent(eEngineEvents.IncomingMessage, (t, o) => { numberOfMessages++; if (o is TheProcessMessage msg) { Assert.AreEqual(msg.Message.TXT, txt); Assert.AreEqual(msg.Message.PLS, payload); Assert.AreEqual(msg.Message.ENG, contentServiceEng.GetEngineName()); testMsg.PLS = "TestPayload2"; //Assert.AreNotEqual(msg.Message.PLS, testMsg.PLS); // This fails } if (t is ICDEThing thing) { Assert.AreEqual(thing.GetBaseThing().cdeMID, contentServiceThing.cdeMID); } }); TheCommCore.PublishCentral(testMsg, true); TheCommonUtils.SleepOneEye(5000, 1000); Assert.AreEqual(numberOfMessages, 1); }
private static void SendGlobalThings(Guid targetNodeId) { // Do not send more often than every 60 seconds if (lastGlobalThingSendPerNode.TryGetValue(targetNodeId, out thingSendStatus timeAndPending)) { if (DateTimeOffset.Now.Subtract(timeAndPending.lastSend).TotalSeconds < 59) // && !timeAndPending.Pending) { return; } } var globalThings = TheThingRegistry.GetThingsByFunc("*", (t) => TheThing.GetSafePropertyBool(t, "IsRegisteredGlobally") && t.IsOnLocalNode()); if (globalThings != null) { TSM tTSM = new TSM(eEngineName.ContentService, "CDE_SYNC_THINGS", TheCommonUtils.SerializeObjectToJSONString(globalThings)); tTSM.SetToServiceOnly(true); if (targetNodeId == Guid.Empty) { TheCommCore.PublishCentral(tTSM); } else { TheCommCore.PublishToNode(targetNodeId, tTSM); } lastGlobalThingSendPerNode[targetNodeId] = new thingSendStatus { lastSend = DateTimeOffset.Now, Pending = false }; } }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_SendGoods model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into CK_SendGoods("); strSql.Append("CK_PeopleID,CK_ProductID,CK_SendGoodsNo,CK_SendGoodsAmount,CK_SendGoodsDate)"); strSql.Append(" values ("); strSql.Append("@CK_PeopleID,@CK_ProductID,@CK_SendGoodsNo,@CK_SendGoodsAmount,@CK_SendGoodsDate)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleID", SqlDbType.Int,4), new SqlParameter("@CK_ProductID", SqlDbType.Int,4), new SqlParameter("@CK_SendGoodsNo", SqlDbType.VarChar,32), new SqlParameter("@CK_SendGoodsAmount", SqlDbType.Int,4), new SqlParameter("@CK_SendGoodsDate", SqlDbType.DateTime)}; parameters[0].Value = model.CK_PeopleID; parameters[1].Value = model.CK_ProductID; parameters[2].Value = model.CK_SendGoodsNo; parameters[3].Value = model.CK_SendGoodsAmount; parameters[4].Value = model.CK_SendGoodsDate; object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 1; } else { return Convert.ToInt32(obj); } }
/// <summary> /// Handles Messages sent from a host sub-engine to its clients /// </summary> public void HandleMessage(ICDEThing sender, object pIncoming) { if (!(pIncoming is TheProcessMessage pMsg)) { return; } switch (pMsg.Message.TXT) { case "CDE_INITIALIZED": TheBaseAssets.MySYSLOG.WriteToLog(888, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("MiniRelayService", $"BackChannel Updated - ORG:{TheCommonUtils.GetDeviceIDML(pMsg.Message.GetLastRelay())}", eMsgLevel.l3_ImportantMessage)); break; default: if (pMsg.Message.TXT.Equals("CDE_INITIALIZE")) { TSM tRelayMsg = new TSM(MyBaseEngine.GetEngineName(), "CDE_INITIALIZED") { QDX = 3, SID = pMsg.Message.SID }; tRelayMsg.SetNoDuplicates(true); TheBaseAssets.MySYSLOG.WriteToLog(888, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("MiniRelayService", $"Message Text {tRelayMsg.TXT} relayed - ORG:{TheCommonUtils.GetDeviceIDML(tRelayMsg.ORG)}", eMsgLevel.l3_ImportantMessage)); //ORG-OK TheCommCore.PublishCentral(MyBaseEngine.GetEngineName() + pMsg.Message?.AddScopeIDFromTSM(), tRelayMsg); } break; } }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_ProductType model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into CK_ProductType("); strSql.Append("CK_ProductTypeName)"); strSql.Append(" values ("); strSql.Append("@CK_ProductTypeName)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@CK_ProductTypeName", SqlDbType.VarChar,64)}; parameters[0].Value = model.CK_ProductTypeName; object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 1; } else { return Convert.ToInt32(obj); } }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_Product model) { dal.Update(model); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_Payment model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update CK_Payment set "); strSql.Append("CK_PeopleID=@CK_PeopleID,"); strSql.Append("CK_PayDate=@CK_PayDate,"); strSql.Append("CK_PayMoney=@CK_PayMoney,"); strSql.Append("CK_PayComment=@CK_PayComment"); strSql.Append(" where CK_PaymentID=@CK_PaymentID "); SqlParameter[] parameters = { new SqlParameter("@CK_PaymentID", SqlDbType.Int,4), new SqlParameter("@CK_PeopleID", SqlDbType.Int,4), new SqlParameter("@CK_PayDate", SqlDbType.DateTime), new SqlParameter("@CK_PayMoney", SqlDbType.Decimal,9), new SqlParameter("@CK_PayComment", SqlDbType.VarChar,100)}; parameters[0].Value = model.CK_PaymentID; parameters[1].Value = model.CK_PeopleID; parameters[2].Value = model.CK_PayDate; parameters[3].Value = model.CK_PayMoney; parameters[4].Value = model.CK_PayComment; DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_People model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update CK_People set "); strSql.Append("CK_PeopleName=@CK_PeopleName,"); strSql.Append("CK_PhoneNo=@CK_PhoneNo,"); strSql.Append("CK_Comment=@CK_Comment"); strSql.Append(" where CK_PeopleID=@CK_PeopleID "); SqlParameter[] parameters = { new SqlParameter("@CK_PeopleID", SqlDbType.Int,4), new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32), new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32), new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)}; parameters[0].Value = model.CK_PeopleID; parameters[1].Value = model.CK_PeopleName; parameters[2].Value = model.CK_PhoneNo; parameters[3].Value = model.CK_Comment; DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_Product model) { return dal.Add(model); }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_People model) { return dal.Add(model); }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_Payment model) { return dal.Add(model); }
/// <summary> /// ����һ������ /// </summary> public int Add(TSM.Model.CK_TakeGoods model) { return dal.Add(model); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_TakeGoods model) { dal.Update(model); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_SendGoods model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update CK_SendGoods set "); strSql.Append("CK_PeopleID=@CK_PeopleID,"); strSql.Append("CK_ProductID=@CK_ProductID,"); strSql.Append("CK_SendGoodsNo=@CK_SendGoodsNo,"); strSql.Append("CK_SendGoodsAmount=@CK_SendGoodsAmount,"); strSql.Append("CK_SendGoodsDate=@CK_SendGoodsDate"); strSql.Append(" where CK_SendGoodsID=@CK_SendGoodsID "); SqlParameter[] parameters = { new SqlParameter("@CK_SendGoodsID", SqlDbType.Int,4), new SqlParameter("@CK_PeopleID", SqlDbType.Int,4), new SqlParameter("@CK_ProductID", SqlDbType.Int,4), new SqlParameter("@CK_SendGoodsNo", SqlDbType.VarChar,32), new SqlParameter("@CK_SendGoodsAmount", SqlDbType.Int,4), new SqlParameter("@CK_SendGoodsDate", SqlDbType.DateTime)}; parameters[0].Value = model.CK_SendGoodsID; parameters[1].Value = model.CK_PeopleID; parameters[2].Value = model.CK_ProductID; parameters[3].Value = model.CK_SendGoodsNo; parameters[4].Value = model.CK_SendGoodsAmount; parameters[5].Value = model.CK_SendGoodsDate; DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_Payment model) { dal.Update(model); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_ProductType model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update CK_ProductType set "); strSql.Append("CK_ProductTypeName=@CK_ProductTypeName"); strSql.Append(" where CK_ProductTypeID=@CK_ProductTypeID "); SqlParameter[] parameters = { new SqlParameter("@CK_ProductTypeID", SqlDbType.Int,4), new SqlParameter("@CK_ProductTypeName", SqlDbType.VarChar,64)}; parameters[0].Value = model.CK_ProductTypeID; parameters[1].Value = model.CK_ProductTypeName; DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_SendGoods model) { dal.Update(model); }
/// <summary> /// ����һ������ /// </summary> public void Update(TSM.Model.CK_People model) { dal.Update(model); }