コード例 #1
0
        public static void Run()
        {
            var            network = new NBXplorerNetworkProvider(ChainType.Main).GetBTC();
            ExplorerClient client  = new ExplorerClient(network, new Uri(Config.Instance.NBXplorer.ServerUrl));
            Dictionary <int, GetTransactionsResponse> lastResponseDict = new Dictionary <int, GetTransactionsResponse>();

            using (Way.Lib.CLog log = new Way.Lib.CLog("runForTransactions"))
            {
                while (true)
                {
                    try
                    {
                        //程序刚启动,把所有交易拿出来检验一遍
                        checkAllTransactionForInit(network, client, log);
                        break;
                    }
                    catch (Exception ex)
                    {
                        System.Threading.Thread.Sleep(3000);
                        using (Way.Lib.CLog logErr = new Way.Lib.CLog("handleAllTransactionForInit error", false))
                        {
                            logErr.Log(ex.ToString());
                        }
                    }
                }

                while (true)
                {
                    try
                    {
                        var events = client.CreateNotificationSession();
                        events.ListenAllDerivationSchemes();
                        log.Log($"init");
                        while (true)
                        {
                            log.Log($"waiting event...");

                            var txEvent = events.NextEvent();
                            log.Log($"received event,type:{txEvent?.GetType().FullName}");
                            if (txEvent is NBXplorer.Models.NewTransactionEvent)
                            {
                                using (var db = new MainDB())
                                {
                                    var tranEvent = txEvent as NBXplorer.Models.NewTransactionEvent;
                                    checkTransaction(db, tranEvent.TransactionData.Transaction, tranEvent.TransactionData.Confirmations, log);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Threading.Thread.Sleep(2000);
                        using (Way.Lib.CLog logErr = new Way.Lib.CLog("runForTransactions error", false))
                        {
                            logErr.Log(ex.ToString());
                        }
                    }
                }
            }
        }
コード例 #2
0
 public void OnReceiveOrderSettlement(ResturantPlatformType platformType, string orderId, double settleAmount)
 {
     using (Way.Lib.CLog log = new Way.Lib.CLog("收到订单结算信息"))
     {
         log.Log("orderId:{0}", orderId);
         log.Log("settleAmount:{0}", settleAmount);
     }
 }
コード例 #3
0
 public void OnPaySuccessed(string tradeID, double?receiptAmount, double?discountAmount, string message)
 {
     using (Way.Lib.CLog log = new Way.Lib.CLog("支付成功"))
     {
         log.Log(message);
         log.Log("tradeId:{0} receiptAmount:{1} discountAmount:{2} message:{3}", tradeID, receiptAmount, discountAmount, message);
     }
 }
コード例 #4
0
 public void OnOrderFinish(ResturantPlatformType platformType, string orderId)
 {
     using (Way.Lib.CLog log = new Way.Lib.CLog("订单已完成"))
     {
         log.Log(orderId);
     }
 }
コード例 #5
0
ファイル: SystemHelper.cs プロジェクト: simpleway2016/SunRiz
 /// <summary>
 /// 如果不符合报警条件,则自动返回
 /// </summary>
 /// <param name="pointId"></param>
 /// <param name="value"></param>
 public static void AutoBackAlarm(int pointId, double value)
 {
     Task.Run(() => {
         try
         {
             using (SysDB db = new SysDB())
             {
                 var arr = db.Alarm.Where(m => m.IsConfirm == false && m.IsBack == false && m.PointId == pointId && m.Expression != null).ToArray();
                 foreach (var alarm in arr)
                 {
                     var expression = string.Format(alarm.Expression, value);
                     var result     = Convert.ToBoolean(db.Database.ExecSqlString($"select ({expression})"));
                     if (result == false)
                     {
                         //不符合报警条件,可以返回
                         alarm.IsBack = true;
                         db.Update(alarm);
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             using (Way.Lib.CLog log = new Way.Lib.CLog("AutoBackAlarm error"))
             {
                 log.Log(ex.ToString());
             }
         }
     });
 }
コード例 #6
0
ファイル: SystemHelper.cs プロジェクト: simpleway2016/SunRiz
 /// <summary>
 /// 添加报警
 /// </summary>
 public static void AddAlarm(Alarm alarm)
 {
     alarm.AlarmTime = DateTime.Now;
     Task.Run(() => {
         try
         {
             using (SysDB db = new SysDB())
             {
                 if (db.Alarm.Any(m => m.IsConfirm == false && m.IsReset == false && m.IsBack == false && m.Address == alarm.Address && m.Content == alarm.Content))
                 {
                     //有同样的报警,而且没有确认
                     return;
                 }
                 db.Insert(alarm);
             }
         }
         catch (Exception ex)
         {
             using (Way.Lib.CLog log = new Way.Lib.CLog("AddAlarm error"))
             {
                 log.Log(ex.ToString());
             }
         }
     });
 }
コード例 #7
0
ファイル: App.xaml.cs プロジェクト: simpleway2016/SunRiz
 void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     using (Way.Lib.CLog log = new Way.Lib.CLog("全局错误"))
     {
         log.Log(((Exception)e.ExceptionObject).ToString());
     }
 }
コード例 #8
0
ファイル: App.xaml.cs プロジェクト: simpleway2016/SunRiz
 void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     using (Way.Lib.CLog log = new Way.Lib.CLog("全局错误"))
     {
         log.Log(e.Exception.ToString());
     }
 }
コード例 #9
0
 public void OnPayFailed(string tradeID, string reason, string message)
 {
     using (Way.Lib.CLog log = new Way.Lib.CLog("支付失败"))
     {
         log.Log("tradeId:{0} reason:{1} message:{2}", tradeID, reason, message);
     }
 }
コード例 #10
0
 public void OnStoreMapSuccess(ResturantPlatformType platformType, StoreMapInfo mapinfo)
 {
     //门店映射成功,接收token
     using (Way.Lib.CLog log = new Way.Lib.CLog("成功映射门店"))
     {
         log.Log($"erpStoreId:{mapinfo.ErpStoreId} token:{mapinfo.Token} refresh_token:{mapinfo.Refresh_token} expires:{mapinfo.Expires}");
     }
 }
コード例 #11
0
        public static void SentNotify(DBModels.Transaction tran, string secret)
        {
            SortedDictionary <string, object> data = null;

            try
            {
                using (var db = new MainDB())
                {
                    data = Helper.SignResult(new
                    {
                        outTradeNo  = tran.OutTradeNo,
                        payedAmount = tran.PayedAmount,
                        status      = (int)tran.Status,
                        //取出比特币交易信息,并转成json字符串
                        cyptoCoinTrans = Newtonsoft.Json.JsonConvert.SerializeObject((from m in db.CyptoCoinTran
                                                                                      where m.TransactionId == tran.id
                                                                                      select new
                        {
                            cyptoCoinTransId = m.CyptoCoinTransId,
                            confirmations = m.Confirmations,
                            payedAmount = m.PayedAmount,
                            payTime = m.PayTime                                                               // 接收到款项的时间
                        }).ToArray())
                    }, secret);
                }
                var result = Helper.PostJson(tran.NotifyUrl, data, 8000);
            }
            catch (Exception ex)
            {
                using (Way.Lib.CLog log = new Way.Lib.CLog("SentNotify error", false))
                {
                    log.Log($"DBModels.Transaction.Id:{tran.id}");
                    if (data != null)
                    {
                        log.LogJson(data);
                    }
                    log.Log(ex.ToString());
                }
            }
        }
コード例 #12
0
        static void checkAllTransactionForInit(NBXplorerNetwork network, ExplorerClient client, Way.Lib.CLog log)
        {
            using (var db = new MainDB())
            {
                var allWalletInfos = db.WalletCyptoCoinInfo.Where(m => m.Currency == "BTC").ToArray();
                foreach (var walletinfo in allWalletInfos)
                {
                    var publicKey            = new ExtPubKey(walletinfo.Key2);
                    var userDerivationScheme = network.DerivationStrategyFactory.CreateDirectDerivationStrategy(publicKey, new DerivationStrategyOptions()
                    {
                        // Use non-segwit
                        Legacy = true
                    });
                    var lastResponse = client.GetTransactions(userDerivationScheme, null);

                    List <TransactionInformation> allTrans = new List <TransactionInformation>();
                    allTrans.AddRange(lastResponse.UnconfirmedTransactions.Transactions);
                    //为了防止程序关闭期间,有transaction发生,所以ConfirmedTransactions也要分析
                    allTrans.AddRange(lastResponse.ConfirmedTransactions.Transactions);

                    foreach (var payedTranInfo in allTrans)
                    {
                        var payedTranid = payedTranInfo.TransactionId.ToString();
                        if (payedTranInfo.Confirmations == 0)
                        {
                            log.Log($"received unconfirmed transaction:{payedTranid}");
                        }
                        else
                        {
                            log.Log($"received confirmed({payedTranInfo.Confirmations})");
                        }

                        checkTransaction(db, payedTranInfo.Transaction, payedTranInfo.Confirmations, log);
                    }
                }
            }
        }
コード例 #13
0
 void start()
 {
     while (true)
     {
         try
         {
             var socket = _tcpListener.AcceptSocket();
             new Thread(handleSocket).Start(socket);
         }
         catch (Exception ex)
         {
             Way.Lib.CLog log = new Way.Lib.CLog("ServerRunning Error", false);
             log.Log(ex.ToString());
         }
     }
 }
コード例 #14
0
 void handleSocket(object s)
 {
     Interlocked.Increment(ref activeHandleCount);
     try
     {
         var socket  = (Socket)s;
         var connect = new ConnectionHandler(socket);
         connect.Handle();
     }
     catch (Exception ex)
     {
         Way.Lib.CLog log = new Way.Lib.CLog("Handle Error", false);
         log.Log(ex.ToString());
     }
     Interlocked.Decrement(ref activeHandleCount);
 }
コード例 #15
0
 static HistoryAutoRec()
 {
     //检查历史记录剩余空间
     Task.Run(() =>
     {
         while (true)
         {
             try
             {
                 using (SysDB db = new SysDB())
                 {
                     var info = (from m in db.SystemSetting
                                 select new { path = m.HistoryPath, g = m.HistoryStoreAlarm }).FirstOrDefault();
                     if (info == null || string.IsNullOrEmpty(info.path) || info.path.Length < 2 || info.g == null || info.g == 0 || info.path[1] != ':')
                     {
                         continue;
                     }
                     System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
                     foreach (System.IO.DriveInfo drive in drives)
                     {
                         if (drive.Name.ToLower()[0] == info.path.ToLower()[0])
                         {
                             var gb = Math.Round(drive.TotalFreeSpace / (double)(1024 * 1024 * 1024), 2);
                             if (gb <= info.g.GetValueOrDefault())
                             {
                                 SystemHelper.AddAlarm(new Alarm()
                                 {
                                     Content = $"历史路径{info.path}剩余空间只有{gb}GB了,请尽快扩展磁盘!",
                                 });
                             }
                             break;
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 using (Way.Lib.CLog log = new Way.Lib.CLog("HistoryAutoRec 检查磁盘剩余空间 error "))
                 {
                     log.Log(ex.ToString());
                 }
             }
             Thread.Sleep(1000 * 60);
         }
     });
 }
コード例 #16
0
        /// <summary>
        /// 写历史记录
        /// </summary>
        /// <param name="point"></param>
        /// <param name="value"></param>
        static void WriteHistory(DevicePoint point, double value)
        {
            if (hisDB == null)
            {
                return;
            }
            try
            {
                lock (hisDB)
                {
                    var data = new SunRizServer.History();
                    data.PointId = point.id;
                    data.Address = point.Name;
                    data.Time    = DateTime.Now;
                    data.Value   = value;
                    hisDB.Insert(data);

                    if ((DateTime.Now - LastHisTime).TotalMinutes >= 2)
                    {
                        hisDB.CommitTransaction();
                        LastHisTime = DateTime.Now;
                        hisDB.BeginTransaction();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Way.Lib.CLog log = new Way.Lib.CLog("HistoryAutoRec WriteHistory error"))
                {
                    log.Log(ex.ToString());
                }
                hisDB.Dispose();
                hisDB = null;
                SystemHelper.AddAlarm(new Alarm()
                {
                    Content = $"记录历史时,发生错误,错误信息:{ex.Message}"
                });
            }
        }
コード例 #17
0
ファイル: SystemLog.cs プロジェクト: simpleway2016/SunRiz
 public static void Init()
 {
     try
     {
         using (SysDB db = new SysDB())
         {
             var sysSetting = db.SystemSetting.FirstOrDefault();
             if (string.IsNullOrEmpty(sysSetting.LogPath))
             {
                 return;
             }
             try
             {
                 //目录不存在,创建目录
                 if (System.IO.Directory.Exists(sysSetting.LogPath) == false)
                 {
                     System.IO.Directory.CreateDirectory(sysSetting.LogPath);
                 }
                 LogDataPath = $"data source=\"{sysSetting.LogPath.Replace("\\", "/")}/log_data.db\"";
                 using (logDB = new DB.SunRiz(LogDataPath, Way.EntityDB.DatabaseType.Sqlite))
                 {
                 }
             }
             catch
             {
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         using (Way.Lib.CLog log = new Way.Lib.CLog("SystemLog error "))
         {
             log.Log(ex.ToString());
         }
     }
 }
コード例 #18
0
        static void checkTransaction(MainDB db, NBitcoin.Transaction cyptoCoinTransaction, int confirmations, Way.Lib.CLog log)
        {
            var payedTranid = cyptoCoinTransaction.GetHash().ToString();

            log.Log($"transactionid:{payedTranid}");

            foreach (var txOut in cyptoCoinTransaction.Outputs)
            {
                var addr = txOut.ScriptPubKey.GetDestinationAddress(NBitcoin.Network.Main).ToString();
                log.Log($"txOut:{addr} value:{txOut.Value}");

                //如果支付地址和钱包交易里的地址一致,那么,进行处理
                var transaction = db.Transaction.FirstOrDefault(m => m.Status != DBModels.Transaction_StatusEnum.Invalided && m.CyptoCoinAddress == addr);
                if (transaction != null)
                {
                    var cyptoCoinTranItem = db.CyptoCoinTran.FirstOrDefault(m => m.TransactionId == transaction.id && m.CyptoCoinTransId == payedTranid);
                    if (cyptoCoinTranItem == null)
                    {
                        log.Log($"belong to Transaction {transaction.id},increase Transaction's PayedAmount");

                        var amount = Convert.ToDouble(txOut.Value.ToDecimal(NBitcoin.MoneyUnit.BTC));
                        transaction.PayedAmount += amount;
                        if (transaction.PayedAmount >= transaction.Amount)
                        {
                            transaction.Status = DBModels.Transaction_StatusEnum.AllPayed;
                        }
                        else
                        {
                            transaction.Status = DBModels.Transaction_StatusEnum.PartialPayed;
                        }
                        db.Update(transaction);

                        var secret = db.Wallet.Where(m => m.id == transaction.WalletId).Select(m => m.Secret).FirstOrDefault();

                        //发送通知
                        if (!string.IsNullOrEmpty(transaction.NotifyUrl))
                        {
                            Task.Run(() => NotifyTask.SentNotify(transaction, secret));
                        }

                        cyptoCoinTranItem = new DBModels.CyptoCoinTran()
                        {
                            CyptoCoinTransId = payedTranid,
                            TransactionId    = transaction.id,
                            PayedAmount      = amount,
                            PayTime          = DateTime.Now
                        };
                        db.Insert(cyptoCoinTranItem);
                    }
                    else
                    {
                        cyptoCoinTranItem.Confirmations = confirmations;
                        db.Update(cyptoCoinTranItem);


                        //发送通知
                        if (!string.IsNullOrEmpty(transaction.NotifyUrl) && confirmations <= 6)
                        {
                            var secret = db.Wallet.Where(m => m.id == transaction.WalletId).Select(m => m.Secret).FirstOrDefault();
                            Task.Run(() => NotifyTask.SentNotify(transaction, secret));
                        }
                    }
                }
            }
        }
コード例 #19
0
        /// <summary>
        /// 发起btc支付交易
        /// </summary>
        /// <returns></returns>
        public object Pay([FromBody] NullableSortedDict <string, object> postData)
        {
            using (var db = new MainDB())
                using (Way.Lib.CLog log = new Way.Lib.CLog("Pay"))
                {
                    try
                    {
                        double?amount     = postData.GetValue <double?>("amount");
                        string account    = postData.GetValue <string>("account");
                        string sign       = postData.GetValue <string>("sign");
                        string outTradeNo = postData.GetValue <string>("outTradeNo");
                        string notifyUrl  = postData.GetValue <string>("notifyUrl");
                        string currency   = postData.GetValue <string>("currency");

                        if (amount <= 0)
                        {
                            throw new Exception("金额无效");
                        }

                        var wallet = db.Wallet.FirstOrDefault(m => m.Account == account);
                        if (wallet == null)
                        {
                            throw new Exception($"账户“{account}”不存在");
                        }

                        log.LogJson(postData);
                        currency = currency.ToUpper();

                        var signResult = Helper.Sign(postData, wallet.Secret);
                        if (signResult != sign)
                        {
                            throw new Exception("签名校验失败");
                        }

                        var newTran = new DBModels.Transaction {
                            Amount     = amount,
                            NotifyUrl  = notifyUrl,
                            OutTradeNo = outTradeNo
                        };

                        //根据币种创建ICyptoCoinClient
                        var client = Activator.CreateInstance(typeof(ApiController).Assembly.GetType($"Cailutong.CyptoCoinGateway.CyptoCoinPlatform.Impls.{currency}.{currency}_Client")) as CyptoCoinPlatform.ICyptoCoinClient;
                        if (client == null)
                        {
                            throw new Exception("不支持" + currency);
                        }

                        //填充交易里面的付款地址
                        transactionGetCyptoCoinAddress(db, account, currency, client, newTran);
                        newTran.WalletId = wallet.id;
                        db.Insert(newTran);

                        return(Helper.SignResult(new
                        {
                            status = "success",
                            outTradeNo = outTradeNo,
                            targetAddress = newTran.CyptoCoinAddress
                        }, wallet.Secret));
                    }
                    catch (Exception ex)
                    {
                        log.Log(ex.ToString());
                        return(new
                        {
                            status = "error",
                            errMsg = ex.Message
                        });
                    }
                }
        }
コード例 #20
0
        static void start()
        {
            try
            {
                if (hisDB != null)
                {
                    lock (hisDB)
                    {
                        hisDB.CommitTransaction();
                        hisDB.Dispose();
                    }
                    hisDB = null;
                }
                using (SysDB db = new SysDB())
                {
                    var sysSetting = db.SystemSetting.FirstOrDefault();
                    if (string.IsNullOrEmpty(sysSetting.HistoryPath))
                    {
                        return;
                    }
                    try
                    {
                        //目录不存在,创建目录
                        if (System.IO.Directory.Exists(sysSetting.HistoryPath) == false)
                        {
                            System.IO.Directory.CreateDirectory(sysSetting.HistoryPath);
                        }
                        HistoryDataPath = $"data source=\"{sysSetting.HistoryPath.Replace("\\", "/")}/history_data.db\"";
                        hisDB           = new DB.SunRiz(HistoryDataPath, Way.EntityDB.DatabaseType.Sqlite);
                        LastHisTime     = DateTime.Now;
                        hisDB.BeginTransaction();
                    }
                    catch
                    {
                        return;
                    }


                    var pointGroups = from m in db.DevicePoint
                                      where m.ValueRelativeChange == true || m.ValueAbsoluteChange == true || m.ValueOnTimeChange == true || m.IsAlarm == true
                                      group m by m.DeviceId into g
                                      select g;
                    foreach (var pointArr in pointGroups)
                    {
                        var deviceId = pointArr.Key.GetValueOrDefault();
                        var device   = db.Device.AsTracking().FirstOrDefault(m => m.id == deviceId);
                        var driver   = db.CommunicationDriver.AsTracking().FirstOrDefault(m => m.id == device.DriverID);

                        MyDriverClient client = new MyDriverClient(driver.Address, driver.Port.Value);
                        client.Points = (from m in pointArr
                                         select new MyDevicePoint(m)).ToArray();
                        AllClients.Add(client);
                        string[] pointAddrs = new string[client.Points.Length];
                        for (int i = 0; i < client.Points.Length; i++)
                        {
                            pointAddrs[i] = client.Points[i].DevicePoint.Address;
                            if (client.Points[i].DevicePoint.ValueOnTimeChange == true)
                            {
                                client.SaveOnTimeInfos.Add(new SaveOnTimeInfo()
                                {
                                    PointObj = client.Points[i],
                                    PointId  = client.Points[i].DevicePoint.id.Value,
                                    Interval = client.Points[i].DevicePoint.ValueOnTimeChangeSetting.GetValueOrDefault(),
                                });
                            }
                        }
                        watchClient(client, device, pointAddrs);
                        //启动定时保存的线程
                        saveValueOnTime_Thread(client, device);
                    }
                }
            }
            catch (Exception ex)
            {
                using (Way.Lib.CLog log = new Way.Lib.CLog("HistoryAutoRec error "))
                {
                    log.Log(ex.ToString());
                }
            }
        }