public bool addTransaction(TransactionData transaction)
 {
     bool bRet = false;
     string sql = string.Empty;
     sql += "INSERT INTO " + Table_of_Transaction;
     sql += " (`UUID`,`sender`,`receiver`,`amount`,`objectUUID`,`regionHandle`,`type`,`time`,`secure`,`status`,`description`) VALUES";
     sql += " (?transID,?sender,?receiver,?amount,?objID,?regionHandle,?type,?time,?secure,?status,?desc)";
     MySqlCommand cmd = new MySqlCommand(sql, dbcon);
     cmd.Parameters.AddWithValue("?transID", transaction.TransUUID.ToString());
     cmd.Parameters.AddWithValue("?sender", transaction.Sender);
     cmd.Parameters.AddWithValue("?receiver", transaction.Receiver);
     cmd.Parameters.AddWithValue("?amount", transaction.Amount);
     cmd.Parameters.AddWithValue("?objID", transaction.ObjectUUID);
     cmd.Parameters.AddWithValue("?regionHandle", transaction.RegionHandle);
     cmd.Parameters.AddWithValue("?type", transaction.Type);
     cmd.Parameters.AddWithValue("?time", transaction.Time);
     cmd.Parameters.AddWithValue("?secure", transaction.SecureCode);
     cmd.Parameters.AddWithValue("status", transaction.Status);
     cmd.Parameters.AddWithValue("?desc", transaction.Description);
     try
     {
         if (cmd.ExecuteNonQuery() > 0)
             bRet = true;
         cmd.Dispose();
     }
     catch (Exception e)
     {
         m_log.Error("Error adding transation to DB: " + e.ToString());
         return false;
     }
     return bRet;
 }
 public bool addTransaction(TransactionData transaction)
 {
     MySQLSuperManager dbm = GetLockedConnection();
     try
     {
         return dbm.Manager.addTransaction(transaction);
     }
     catch (Exception e)
     {
         dbm.Manager.Reconnect();
         m_log.Error(e.ToString());
         return false;
     }
     finally
     {
         dbm.Release();
     }
 }
        public TransactionData FetchTransaction(UUID transactionID)
        {
            TransactionData transactionData = new TransactionData();

            transactionData.TransUUID = transactionID;
            string sql = string.Empty;

            sql += "SELECT * from " + Table_of_Transaction + " where UUID = ?transID;";
            MySqlCommand cmd = new MySqlCommand(sql, dbcon);

            cmd.Parameters.AddWithValue("?transID", transactionID.ToString());

            using (MySqlDataReader r = cmd.ExecuteReader())
            {
                if (r.Read())
                {
                    try
                    {
                        transactionData.Sender       = (string)r["sender"];
                        transactionData.Receiver     = (string)r["receiver"];
                        transactionData.Amount       = Convert.ToInt32(r["amount"]);
                        transactionData.ObjectUUID   = (string)r["objectUUID"];
                        transactionData.RegionHandle = (string)r["regionHandle"];
                        transactionData.Type         = Convert.ToInt32(r["type"]);
                        transactionData.Time         = Convert.ToInt32(r["time"]);
                        transactionData.Status       = Convert.ToInt32(r["status"]);
                        transactionData.CommonName   = (string)r["commonName"];
                        transactionData.Description  = (string)r["description"];
                    }
                    catch (Exception e)
                    {
                        m_log.Error("[MONEY DB]: Fetching transaction failed: " + e.ToString());
                        return(null);
                    }
                }
                r.Close();
            }

            return(transactionData);
        }
        ///////////////////////////////////////////////////////////////////////
        //
        // transaction
        //
        public bool addTransaction(TransactionData transaction)
        {
            bool   bRet = false;
            string sql  = string.Empty;

            sql += "INSERT INTO " + Table_of_Transaction;
            sql += " (`UUID`,`sender`,`receiver`,`amount`,`objectUUID`,`regionHandle`,`type`,`time`,`secure`,`status`,`commonName`,`description`) VALUES";
            sql += " (?transID,?sender,?receiver,?amount,?objID,?regionHandle,?type,?time,?secure,?status,?cname,?desc)";

            MySqlCommand cmd = new MySqlCommand(sql, dbcon);

            cmd.Parameters.AddWithValue("?transID", transaction.TransUUID.ToString());
            cmd.Parameters.AddWithValue("?sender", transaction.Sender);
            cmd.Parameters.AddWithValue("?receiver", transaction.Receiver);
            cmd.Parameters.AddWithValue("?amount", transaction.Amount);
            cmd.Parameters.AddWithValue("?objID", transaction.ObjectUUID);
            cmd.Parameters.AddWithValue("?regionHandle", transaction.RegionHandle);
            cmd.Parameters.AddWithValue("?type", transaction.Type);
            cmd.Parameters.AddWithValue("?time", transaction.Time);
            cmd.Parameters.AddWithValue("?secure", transaction.SecureCode);
            cmd.Parameters.AddWithValue("?status", transaction.Status);
            cmd.Parameters.AddWithValue("?cname", transaction.CommonName);
            cmd.Parameters.AddWithValue("?desc", transaction.Description);

            try
            {
                if (cmd.ExecuteNonQuery() > 0)
                {
                    bRet = true;
                }
                cmd.Dispose();
            }
            catch (Exception e)
            {
                m_log.Error("[MONEY DB]: Error adding transation to DB: " + e.ToString());
                return(false);
            }
            return(bRet);
        }
        public TransactionData[] FetchTransaction(string userID, int startTime, int endTime, uint index,uint retNum)
        {
            List<TransactionData> rows = new List<TransactionData>();
            string sql = string.Empty;
            sql += "SELECT * from " + Table_of_Transaction + " where time>=?start AND time<=?end ";
            sql += "AND (sender=?user or receiver=?user) order by time asc limit ?index,?num;";
            MySqlCommand cmd = new MySqlCommand(sql, dbcon);
            cmd.Parameters.AddWithValue("?start", startTime);
            cmd.Parameters.AddWithValue("?end", endTime);
            cmd.Parameters.AddWithValue("?user", userID);
            cmd.Parameters.AddWithValue("?index", index);
            cmd.Parameters.AddWithValue("?num", retNum);
            using (MySqlDataReader r = cmd.ExecuteReader())
            {
                for (int i = 0; i < retNum; i++)
                {
                    if (r.Read())
                    {
                        try
                        {
                            TransactionData transactionData = new TransactionData();
                            string uuid = (string)r["UUID"];
                            UUID transUUID;
                            UUID.TryParse(uuid,out transUUID);

                            transactionData.TransUUID = transUUID;
                            transactionData.Sender = (string)r["sender"];
                            transactionData.Receiver = (string)r["receiver"];
                            transactionData.Amount = Convert.ToInt32(r["amount"]);
                            if (r["objectUUID"] is System.DBNull)
                            {
                                transactionData.ObjectUUID = "null";
                            }
                            else
                            {
                                transactionData.ObjectUUID = (string)r["objectUUID"];
                            }
                            transactionData.Type = Convert.ToInt32(r["type"]);
                            transactionData.Time = Convert.ToInt32(r["time"]);
                            transactionData.Status = Convert.ToInt32(r["status"]);
                            transactionData.Description = (string)r["description"];
                            rows.Add(transactionData);
                        }

                        catch (Exception e)
                        {
                            m_log.Error("[MySQL] Fetching transaction failed: " + e.ToString());
                            return null;
                        }

                    }
                }
                r.Close();
            }

            cmd.Dispose();
            return rows.ToArray();
        }
        public TransactionData FetchTransaction(UUID transactionID)
        {
            TransactionData transactionData = new TransactionData();
            transactionData.TransUUID = transactionID;
            string sql = string.Empty;
            sql += "SELECT * from " + Table_of_Transaction + " where UUID = ?transID;";
            MySqlCommand cmd = new MySqlCommand(sql, dbcon);
            cmd.Parameters.AddWithValue("?transID", transactionID.ToString());
            using (MySqlDataReader r = cmd.ExecuteReader())
            {
                if (r.Read())
                {
                    try
                    {
                        transactionData.Sender = (string)r["sender"];
                        transactionData.Receiver = (string)r["receiver"];
                        transactionData.Amount = Convert.ToInt32(r["amount"]);
                        transactionData.ObjectUUID = (string)r["objectUUID"];
                        transactionData.RegionHandle = (string)r["regionHandle"];
                        transactionData.Type = Convert.ToInt32(r["type"]);
                        transactionData.Time = Convert.ToInt32(r["time"]);
                        transactionData.Status = Convert.ToInt32(r["status"]);
                        transactionData.Description = (string)r["description"];
                    }
                    catch (Exception e)
                    {
                        m_log.Error("[MySQL] Fetching transaction failed: " + e.ToString());
                        return null;
                    }

                }
                r.Close();
            }

            return transactionData;
        }
        //
        // deleted using ASP.NET  by Fumi.Iseki
        //
        /// <summary>
        /// handle incoming transaction
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public XmlRpcResponse handleTransaction(XmlRpcRequest request, IPEndPoint remoteClient)
        {
            //m_log.InfoFormat("[MONEY RPC] handleTransaction:");

            Hashtable requestData = (Hashtable)request.Params[0];
            XmlRpcResponse response = new XmlRpcResponse();
            Hashtable responseData  = new Hashtable();
            response.Value = responseData;

            int	   amount = 0;
            int	   transactionType = 0;
            string senderID = string.Empty;
            string receiverID = string.Empty;
            string senderSessionID = string.Empty;
            string senderSecureSessionID = string.Empty;
            string objectID = string.Empty;
            string regionHandle = string.Empty;
            string description  = "Newly added on";
            string senderUserServIP = string.Empty;
            string receiverUserServIP = string.Empty;

            string fmID = string.Empty;
            string toID = string.Empty;
            UUID transactionUUID = UUID.Random();

            if (requestData.ContainsKey("senderID")) 			  senderID = (string)requestData["senderID"];
            if (requestData.ContainsKey("receiverID")) 			  receiverID = (string)requestData["receiverID"];
            if (requestData.ContainsKey("senderSessionID")) 	  senderSessionID = (string)requestData["senderSessionID"];
            if (requestData.ContainsKey("senderSecureSessionID")) senderSecureSessionID = (string)requestData["senderSecureSessionID"];
            if (requestData.ContainsKey("amount")) 				  amount = (Int32)requestData["amount"];
            if (requestData.ContainsKey("objectID")) 			  objectID = (string)requestData["objectID"];
            if (requestData.ContainsKey("regionHandle")) 		  regionHandle = (string)requestData["regionHandle"];
            if (requestData.ContainsKey("transactionType")) 	  transactionType = (Int32)requestData["transactionType"];
            if (requestData.ContainsKey("description")) 		  description = (string)requestData["description"];
            if (requestData.ContainsKey("senderUserServIP")) 	  senderUserServIP = (string)requestData["senderUserServIP"];
            if (requestData.ContainsKey("receiverUserServIP"))	  receiverUserServIP = (string)requestData["receiverUserServIP"];

            fmID = senderID   + "@" + senderUserServIP;
            toID = receiverID + "@" + receiverUserServIP;

            if (m_sessionDic.ContainsKey(fmID) && m_secureSessionDic.ContainsKey(fmID))
            {
                if (m_sessionDic[fmID]==senderSessionID && m_secureSessionDic[fmID]==senderSecureSessionID)
                {
                    m_log.InfoFormat("[MONEY RPC] handleTransaction: Transfering money from {0} to {1}", fmID, toID);
                    int time = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);
                    try
                    {
                        TransactionData transaction = new TransactionData();
                        transaction.TransUUID = transactionUUID;
                        transaction.Sender   = fmID;
                        transaction.Receiver = toID;
                        transaction.Amount = amount;
                        transaction.ObjectUUID = objectID;
                        transaction.RegionHandle = regionHandle;
                        transaction.Type = transactionType;
                        transaction.Time = time;
                        transaction.SecureCode = UUID.Random().ToString();
                        transaction.Status = (int)Status.PENDING_STATUS;
                        transaction.Description = description + " " + DateTime.Now.ToString();

                        UserInfo rcvr = m_moneyDBService.FetchUserInfo(toID);
                        if (rcvr==null)
                        {
                            m_log.ErrorFormat("[MONEY RPC] handleTransaction: Receive User is not yet in DB {0}", toID);
                            responseData["success"] = false;
                            return response;
                        }

                        bool result = m_moneyDBService.addTransaction(transaction);
                        if (result)
                        {
                            UserInfo user = m_moneyDBService.FetchUserInfo(fmID);
                            if (user!=null)
                            {
                                if (amount!=0)
                                {
                                    string snd_message = "";
                                    string rcv_message = "";

                                    if (transaction.Type==(int)TransactionType.Gift) {
                                        snd_message = m_BalanceMessageSendGift;
                                        rcv_message = m_BalanceMessageReceiveGift;
                                    }
                                    else if (transaction.Type==(int)TransactionType.LandSale) {
                                        snd_message = m_BalanceMessageLandSale;
                                        rcv_message = m_BalanceMessageRcvLandSale;
                                    }
                                    else if (transaction.Type==(int)TransactionType.PayObject) {
                                        snd_message = m_BalanceMessageBuyObject;
                                    }
                                    else if (transaction.Type==(int)TransactionType.ObjectPays) {		// ObjectGiveMoney
                                        rcv_message = m_BalanceMessageGetMoney;
                                    }

                                    responseData["success"] = NotifyTransfer(transactionUUID, snd_message, rcv_message);
                                }
                                else
                                {
                                    responseData["success"] = true;		// No messages for L$0 object. by Fumi.Iseki
                                }
                                return response;
                            }
                        }
                        else // add transaction failed
                        {
                            m_log.ErrorFormat("[MONEY RPC] handleTransaction: Add transaction for user {0} failed", fmID);
                        }

                        responseData["success"] = false;
                        return response;
                    }
                    catch (Exception e)
                    {
                        m_log.Error("[MONEY RPC] handleTransaction: Exception occurred while adding transaction " + e.ToString());
                        responseData["success"] = false;
                        return response;
                    }

                }

            }

            m_log.Error("[MONEY RPC] handleTransaction: Session authentication failure for sender " + fmID);
            responseData["success"] = false;
            responseData["message"] = "Session check failure, please re-login later!";
            return response;
        }
        //
        // added by Fumi.Iseki
        //
        /// <summary>
        /// handle sending money transaction.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public XmlRpcResponse handleSendMoneyBalance(XmlRpcRequest request, IPEndPoint remoteClient)
        {
            //m_log.InfoFormat("[MONEY RPC] handleSendMoneyBalance:");

            Hashtable requestData = (Hashtable)request.Params[0];
            XmlRpcResponse response = new XmlRpcResponse();
            Hashtable responseData  = new Hashtable();
            response.Value = responseData;

            int	   amount = 0;
            int	   transactionType = 0;
            string senderID = UUID.Zero.ToString();
            string avatarID = string.Empty;
            string description  = "Send Money to Avatar on";
            string avatarUserServIP = string.Empty;
            string clientIP   = remoteClient.Address.ToString();
            string secretCode = string.Empty;

            string fmID = string.Empty;
            string toID = string.Empty;
            UUID transactionUUID = UUID.Random();

            responseData["success"] = false;

            if (!m_scriptSendMoney || m_scriptAccessKey=="")
            {
                m_log.Error("[MONEY RPC] handleSendMoneyBalance: Not allowed send money to avatar!!");
                m_log.Error("[MONEY RPC] handleSendMoneyBalance: Set enableScriptSendMoney and MoneyScriptAccessKey at [MoneyServer] in MoneyServer.ini");
                responseData["message"] = "not allowed set money to avatar!";
                return response;
            }

            if (requestData.ContainsKey("avatarID")) 		 avatarID = (string)requestData["avatarID"];
            if (requestData.ContainsKey("amount")) 			 amount = (Int32)requestData["amount"];
            if (requestData.ContainsKey("transactionType"))  transactionType = (Int32)requestData["transactionType"];
            if (requestData.ContainsKey("description")) 	 description = (string)requestData["description"];
            if (requestData.ContainsKey("avatarUserServIP")) avatarUserServIP = (string)requestData["avatarUserServIP"];
            if (requestData.ContainsKey("secretAccessCode")) secretCode = (string)requestData["secretAccessCode"];

            MD5 md5 = MD5.Create();
            byte[] code = md5.ComputeHash(ASCIIEncoding.Default.GetBytes(m_scriptAccessKey + "_" + clientIP));
            string hash = BitConverter.ToString(code).ToLower().Replace("-", "");
            code = md5.ComputeHash(ASCIIEncoding.Default.GetBytes(hash + "_" + m_scriptIPaddress));
            hash = BitConverter.ToString(code).ToLower().Replace("-", "");

            if (secretCode.ToLower()!=hash)
            {
                m_log.Error("[MONEY RPC] handleSendMoneyBalance: Not allowed send money to avatar!!");
                m_log.Error("[MONEY RPC] handleSendMoneyBalance: Not match Script Key");
                responseData["message"] = "not allowed send money to avatar! not match Script Key";
                return response;
            }

            fmID = senderID + "@" + avatarUserServIP;
            toID = avatarID + "@" + avatarUserServIP;

            m_log.InfoFormat("[MONEY RPC] handleSendMoneyBalance: Send money to avatar {0}", toID);
            int time = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);

            try
            {
                TransactionData transaction = new TransactionData();
                transaction.TransUUID = transactionUUID;
                transaction.Sender   = fmID;
                transaction.Receiver = toID;
                transaction.Amount = amount;
                transaction.ObjectUUID   = UUID.Zero.ToString();
                transaction.RegionHandle = "0";
                transaction.Type = transactionType;
                transaction.Time = time;
                transaction.SecureCode = UUID.Random().ToString();
                transaction.Status = (int)Status.PENDING_STATUS;
                transaction.Description = description + " " + DateTime.Now.ToString();

                UserInfo rcvr = m_moneyDBService.FetchUserInfo(toID);
                if (rcvr==null)
                {
                    m_log.ErrorFormat("[MONEY RPC] handleSendMoneyBalance: Avatar is not yet in DB: {0}", toID);
                    return response;
                }

                bool result = m_moneyDBService.addTransaction(transaction);
                if (result)
                {
                    if (amount!=0)
                    {
                        if (m_moneyDBService.DoAddMoney(transactionUUID))
                        {
                            transaction = m_moneyDBService.FetchTransaction(transactionUUID);
                            if (transaction!=null && transaction.Status==(int)Status.SUCCESS_STATUS)
                            {
                                m_log.InfoFormat("[MONEY RPC] handleSendMoneyBalance: Sending money finished successfully, now update balance {0}",
                                                 transactionUUID.ToString());
                                string message = string.Format(m_BalanceMessageReceiveMoney, amount, "SYSTEM");
                                UpdateBalance(transaction.Receiver, message);
                                responseData["success"] = true;
                            }
                        }
                    }
                    else
                    {
                        responseData["success"] = true;		// No messages for L$0 add
                    }
                    return response;
                }
                else // add transaction failed
                {
                    m_log.ErrorFormat("[MONEY RPC] handleSendMoneyBalance: Add force transaction for user {0} failed", fmID);
                }

                return response;
            }
            catch (Exception e)
            {
                m_log.Error("[MONEY RPC] handleSendMoneyBalance: Exception occurred while adding money transaction " + e.ToString());
                return response;
            }
        }
        //
        // added by Fumi.Iseki
        //
        /// <summary>
        /// handle pay charge transaction. no check receiver information.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public XmlRpcResponse handlePayMoneyCharge(XmlRpcRequest request, IPEndPoint remoteClient)
        {
            //m_log.InfoFormat("[MONEY RPC] handlePayMoneyCharge:");

            Hashtable requestData = (Hashtable)request.Params[0];
            XmlRpcResponse response = new XmlRpcResponse();
            Hashtable responseData  = new Hashtable();
            response.Value = responseData;

            int	   amount = 0;
            int	   transactionType = 0;
            string senderID = string.Empty;
            string receiverID = UUID.Zero.ToString();
            string senderSessionID = string.Empty;
            string senderSecureSessionID = string.Empty;
            string objectID = UUID.Zero.ToString();
            string regionHandle = string.Empty;
            string description  = "Pay Charge on";
            string senderUserServIP = string.Empty;
            string receiverUserServIP = "0.0.0.0";

            string fmID = string.Empty;
            string toID = string.Empty;
            UUID transactionUUID = UUID.Random();

            if (requestData.ContainsKey("senderID")) 			  senderID = (string)requestData["senderID"];
            if (requestData.ContainsKey("senderSessionID")) 	  senderSessionID = (string)requestData["senderSessionID"];
            if (requestData.ContainsKey("senderSecureSessionID")) senderSecureSessionID = (string)requestData["senderSecureSessionID"];
            if (requestData.ContainsKey("amount")) 				  amount = (Int32)requestData["amount"];
            if (requestData.ContainsKey("regionHandle")) 		  regionHandle = (string)requestData["regionHandle"];
            if (requestData.ContainsKey("transactionType")) 	  transactionType = (Int32)requestData["transactionType"];
            if (requestData.ContainsKey("description")) 		  description = (string)requestData["description"];
            if (requestData.ContainsKey("senderUserServIP")) 	  senderUserServIP = (string)requestData["senderUserServIP"];

            fmID = senderID   + "@" + senderUserServIP;
            toID = receiverID + "@" + receiverUserServIP;

            if (m_sessionDic.ContainsKey(fmID) && m_secureSessionDic.ContainsKey(fmID))
            {
                if (m_sessionDic[fmID]==senderSessionID && m_secureSessionDic[fmID]==senderSecureSessionID)
                {
                    m_log.InfoFormat("[MONEY RPC] handlePayMoneyCharge: Pay from {0}", fmID);
                    int time = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);
                    try
                    {
                        TransactionData transaction = new TransactionData();
                        transaction.TransUUID = transactionUUID;
                        transaction.Sender   = fmID;
                        transaction.Receiver = toID;
                        transaction.Amount = amount;
                        transaction.ObjectUUID = objectID;
                        transaction.RegionHandle = regionHandle;
                        transaction.Type = transactionType;
                        transaction.Time = time;
                        transaction.SecureCode = UUID.Random().ToString();
                        transaction.Status = (int)Status.PENDING_STATUS;
                        transaction.Description = description + " " + DateTime.Now.ToString();

                        bool result = m_moneyDBService.addTransaction(transaction);
                        if (result)
                        {
                            UserInfo user = m_moneyDBService.FetchUserInfo(fmID);
                            if (user!=null)
                            {
                                if (amount!=0)
                                {
                                    string message = string.Format(m_BalanceMessagePayCharge, amount, "SYSTEM");
                                    responseData["success"] = NotifyTransfer(transactionUUID, message, "");
                                }
                                else
                                {
                                    responseData["success"] = true;		// No messages for L$0 object. by Fumi.Iseki
                                }
                                return response;
                            }
                        }
                        else // add transaction failed
                        {
                            m_log.ErrorFormat("[MONEY RPC] handlePayMoneyCharge: Pay money transaction for user {0} failed", fmID);
                        }

                        responseData["success"] = false;
                        return response;
                    }
                    catch (Exception e)
                    {
                        m_log.Error("[MONEY RPC] handlePayMoneyCharge: Exception occurred while pay money transaction " + e.ToString());
                        responseData["success"] = false;
                        return response;
                    }

                }

            }

            m_log.Error("[MONEY RPC] handlePayMoneyCharge: Session authentication failure for sender " + fmID);
            responseData["success"] = false;
            responseData["message"] = "Session check failure, please re-login later!";
            return response;
        }
        /// <summary>
        /// RollBack the transaction if user failed to get the object paid
        /// </summary>
        /// <param name="transaction"></param>
        /// <returns></returns>
        protected bool RollBackTransaction(TransactionData transaction)
        {
            //m_log.InfoFormat("[MONEY RPC] RollBackTransaction:");

            if(m_moneyDBService.withdrawMoney(transaction.TransUUID, transaction.Receiver, transaction.Amount))
            {
                if(m_moneyDBService.giveMoney(transaction.TransUUID, transaction.Sender, transaction.Amount))
                {
                    m_log.InfoFormat("[MONEY RPC] RollBackTransaction: Transaction {0} successfully", transaction.TransUUID.ToString());
                    m_moneyDBService.updateTransactionStatus(transaction.TransUUID, (int)Status.FAILED_STATUS,
                                                             "The buyer failed to get the object, roll back the transaction");

                    UserInfo senderInfo   = m_moneyDBService.FetchUserInfo(transaction.Sender);
                    UserInfo receiverInfo = m_moneyDBService.FetchUserInfo(transaction.Receiver);
                    string senderName 	= "unknown user";
                    string receiverName = "unknown user";
                    if (senderInfo!=null)   senderName   = senderInfo.Avatar;
                    if (receiverInfo!=null) receiverName = receiverInfo.Avatar;

                    string snd_message = string.Format(m_BalanceMessageRollBack, transaction.Amount, receiverName);
                    string rcv_message = string.Format(m_BalanceMessageRollBack, transaction.Amount, senderName);

                    if (transaction.Sender!=transaction.Receiver) UpdateBalance(transaction.Sender, snd_message);
                    UpdateBalance(transaction.Receiver, rcv_message);
                    return true;
                }
            }
            return false;
        }
        //
        // added by Fumi.Iseki
        //
        /// <summary>
        /// handle adding money transaction.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public XmlRpcResponse handleAddBankerMoney(XmlRpcRequest request, IPEndPoint remoteClient)
        {
            //m_log.InfoFormat("[MONEY RPC] handleAddBankerMoney:");

            Hashtable requestData = (Hashtable)request.Params[0];
            XmlRpcResponse response = new XmlRpcResponse();
            Hashtable responseData  = new Hashtable();
            response.Value = responseData;

            int	   amount = 0;
            int	   transactionType = 0;
            string senderID = UUID.Zero.ToString();
            string bankerID = string.Empty;
            string regionHandle = "0";
            string description  = "Add Money to Avatar on";
            string bankerUserServIP = string.Empty;

            string fmID = string.Empty;
            string toID = string.Empty;
            UUID transactionUUID = UUID.Random();

            responseData["success"] = false;

            if (requestData.ContainsKey("bankerID")) 			bankerID = (string)requestData["bankerID"];
            if (requestData.ContainsKey("amount")) 				amount = (Int32)requestData["amount"];
            if (requestData.ContainsKey("regionHandle")) 		regionHandle = (string)requestData["regionHandle"];
            if (requestData.ContainsKey("transactionType")) 	transactionType = (Int32)requestData["transactionType"];
            if (requestData.ContainsKey("description")) 		description = (string)requestData["description"];
            if (requestData.ContainsKey("bankerUserServIP"))	bankerUserServIP = (string)requestData["bankerUserServIP"];

            // Check Banker Avatar
            if (m_bankerAvatar!=UUID.Zero.ToString() && m_bankerAvatar!=bankerID)
            {
                m_log.Error("[MONEY RPC] handleAddBankerMoney: Not allowed add money to avatar!!");
                m_log.Error("[MONEY RPC] handleAddBankerMoney: Set BankerAvatar at [MoneyServer] in MoneyServer.ini");
                responseData["message"] = "not allowed add money to avatar!";
                responseData["banker"]  = false;
                return response;
            }

            responseData["banker"] = true;
            fmID = senderID + "@" + bankerUserServIP;
            toID = bankerID + "@" + bankerUserServIP;

            m_log.InfoFormat("[MONEY RPC] handleAddBankerMoney: Add money to avatar {0}", toID);
            int time = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);

            try
            {
                TransactionData transaction = new TransactionData();
                transaction.TransUUID = transactionUUID;
                transaction.Sender   = fmID;
                transaction.Receiver = toID;
                transaction.Amount = amount;
                transaction.ObjectUUID   = UUID.Zero.ToString();
                transaction.RegionHandle = regionHandle;
                transaction.Type = transactionType;
                transaction.Time = time;
                transaction.SecureCode = UUID.Random().ToString();
                transaction.Status = (int)Status.PENDING_STATUS;
                transaction.Description = description + " " + DateTime.Now.ToString();

                UserInfo rcvr = m_moneyDBService.FetchUserInfo(toID);
                if (rcvr==null)
                {
                    m_log.ErrorFormat("[MONEY RPC] handleAddBankerMoney: Avatar is not yet in DB {0}", toID);
                    return response;
                }

                bool result = m_moneyDBService.addTransaction(transaction);
                if (result)
                {
                    if (amount!=0)
                    {
                        if (m_moneyDBService.DoAddMoney(transactionUUID))
                        {
                            transaction = m_moneyDBService.FetchTransaction(transactionUUID);
                            if (transaction!=null && transaction.Status==(int)Status.SUCCESS_STATUS)
                            {
                                m_log.InfoFormat("[MONEY RPC] handleAddBankerMoney: Adding money finished successfully, now update balance: {0}",
                                                 transactionUUID.ToString());
                                string message = string.Format(m_BalanceMessageBuyMoney, amount, "SYSTEM");
                                UpdateBalance(transaction.Receiver, message);
                                responseData["success"] = true;
                            }
                        }
                    }
                    else
                    {
                        responseData["success"] = true;		// No messages for L$0 add
                    }
                    return response;
                }
                else // add transaction failed
                {
                    m_log.ErrorFormat("[MONEY RPC] handleAddBankerMoney: Add force transaction for user {0} failed", fmID);
                }

                return response;
            }
            catch (Exception e)
            {
                m_log.Error("[MONEY RPC] handleAddBankerMoney: Exception occurred while adding money transaction " + e.ToString());
                return response;
            }
        }
 public bool DoTransfer(UUID transactionUUID)
 {
     TransactionData transaction = new TransactionData();
     transaction = FetchTransaction(transactionUUID);
     if (transaction != null && transaction.Status == (int)Status.PENDING_STATUS)
     {
         int balance = getBalance(transaction.Sender);
         //check the amount
         if (transaction.Amount >= 0 && balance >= transaction.Amount)
         {
             if (withdrawMoney(transactionUUID, transaction.Sender, transaction.Amount))
             {
                 //If receiver not found, add it to DB.
                 if (getBalance(transaction.Receiver) == -1)
                 {
                     addUser(transaction.Receiver, 0, (int)Status.SUCCESS_STATUS);
                 }
                 if (giveMoney(transactionUUID, transaction.Receiver, transaction.Amount))
                     return true;
                 else // give money to receiver failed.
                 {
                     m_log.ErrorFormat("[Money DB] Give money to receiver {0} failed", transaction.Receiver);
                     //Return money to sender
                     if (giveMoney(transactionUUID, transaction.Sender, transaction.Amount))
                     {
                         m_log.ErrorFormat("[Money DB] give money to receiver {0} failed but return it to sender {1} successfully",
                             transaction.Receiver,
                             transaction.Sender);
                         updateTransactionStatus(transactionUUID,
                             (int)Status.FAILED_STATUS,
                             "give money to receiver failed but return it to sender successfully");
                     }
                     else
                     {
                         m_log.ErrorFormat("[Money DB] FATAL ERROR: Money withdrawn from sender: {0}, but failed to be given to receiver {1}",
                             transaction.Sender, transaction.Receiver);
                     }
                 }
             }
             else // withdraw money failed
             {
                 m_log.ErrorFormat("[Money DB] Withdraw money from sender {0} failed", transaction.Sender);
             }
         }
         else // not enough balance to finish the transaction
         {
             m_log.ErrorFormat("[Money DB] Not enough balance for user: {0} to apply the transaction.", transaction.Sender);
         }
     }
     else // Can not fetch the transaction or it has expired
     {
         m_log.ErrorFormat("[Money DB] The transaction:{0} has expired", transactionUUID.ToString());
     }
     return false;
 }
        // by Fumi.Iseki
        public bool DoAddMoney(UUID transactionUUID)
        {
            TransactionData transaction = new TransactionData();
            transaction = FetchTransaction(transactionUUID);

            if (transaction != null && transaction.Status == (int)Status.PENDING_STATUS)
            {
                //If receiver not found, add it to DB.
                if (getBalance(transaction.Receiver)==-1)
                {
                    addUser(transaction.Receiver, 0, (int)Status.SUCCESS_STATUS);
                }

                if (giveMoney(transactionUUID, transaction.Receiver, transaction.Amount)) return true;
                else // give money to receiver failed.
                {
                    m_log.ErrorFormat("[Money DB] Add money to receiver {0} failed", transaction.Receiver);
                    updateTransactionStatus(transactionUUID, (int)Status.FAILED_STATUS, "add money to receiver failed");
                }
            }
            else // Can not fetch the transaction or it has expired
            {
                m_log.ErrorFormat("[Money DB] The transaction:{0} has expired", transactionUUID.ToString());
            }
            return false;
        }
		//
		// added by Fumi.Iseki
		//
		/// <summary>
		/// handle incoming force transaction. no check senderSessionID and senderSecureSessionID
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		public XmlRpcResponse handleForceTransaction(XmlRpcRequest request, IPEndPoint remoteClient)
		{
			//Console.WriteLine("[MONEY RPC]: handleForceTransaction:");

			GetSSLCommonName(request);

			Hashtable requestData = (Hashtable)request.Params[0];
			XmlRpcResponse response = new XmlRpcResponse();
			Hashtable responseData  = new Hashtable();
			response.Value = responseData;

			int	   amount = 0;
			int	   transactionType = 0;
			string senderID = string.Empty;
			string receiverID = string.Empty;
			string objectID = string.Empty;
			string regionHandle = string.Empty;
			string description  = "Newly added on";

			UUID transactionUUID = UUID.Random();

			//
			if (!m_forceTransfer)
			{
				Console.WriteLine("[MONEY RPC]: handleForceTransaction: Not allowed force transfer of Money. Set enableForceTransfer at [MoneyServer] to true in MoneyServer.ini");
				responseData["success"] = false;
				responseData["message"] = "not allowed force transfer of Money!";
				return response;
			}

			if (requestData.ContainsKey("senderID")) 			senderID = (string)requestData["senderID"];
			if (requestData.ContainsKey("receiverID")) 			receiverID = (string)requestData["receiverID"];
			if (requestData.ContainsKey("amount")) 				amount = (Int32)requestData["amount"];
			if (requestData.ContainsKey("objectID")) 			objectID = (string)requestData["objectID"];
			if (requestData.ContainsKey("regionHandle")) 		regionHandle = (string)requestData["regionHandle"];
			if (requestData.ContainsKey("transactionType")) 	transactionType = (Int32)requestData["transactionType"];
			if (requestData.ContainsKey("description")) 		description = (string)requestData["description"];

			Console.WriteLine("[MONEY RPC]: handleForceTransaction: Force transfering money from {0} to {1}", senderID, receiverID);
			int time = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);

			try
			{
				TransactionData transaction = new TransactionData();
				transaction.TransUUID = transactionUUID;
				transaction.Sender   = senderID;
				transaction.Receiver = receiverID;
				transaction.Amount = amount;
				transaction.ObjectUUID = objectID;
				transaction.RegionHandle = regionHandle;
				transaction.Type = transactionType;
				transaction.Time = time;
				transaction.SecureCode = UUID.Random().ToString();
				transaction.Status = (int)Status.PENDING_STATUS;
				transaction.CommonName  = GetSSLCommonName();
				transaction.Description = description + " " + DateTime.Now.ToString();

				UserInfo rcvr = m_moneyDBService.FetchUserInfo(receiverID);
				if (rcvr==null) 
				{
					Console.WriteLine("[MONEY RPC]: handleForceTransaction: Force receive User is not yet in DB {0}", receiverID);
					responseData["success"] = false;
					return response;
				}

				bool result = m_moneyDBService.addTransaction(transaction);
				if (result) 
				{
					UserInfo user = m_moneyDBService.FetchUserInfo(senderID);
					if (user!=null) 
					{
						if (amount!=0)
						{
							string snd_message = "";
							string rcv_message = "";

							if (transaction.Type==(int)TransactionType.Gift) {
								snd_message = m_BalanceMessageSendGift;
								rcv_message = m_BalanceMessageReceiveGift;
							}
							else if (transaction.Type==(int)TransactionType.LandSale) {
								snd_message = m_BalanceMessageLandSale;
								snd_message = m_BalanceMessageRcvLandSale;
							}
							else if (transaction.Type==(int)TransactionType.PayObject) {
								snd_message = m_BalanceMessageBuyObject;
							}
							else if (transaction.Type==(int)TransactionType.ObjectPays) {		// ObjectGiveMoney
								rcv_message = m_BalanceMessageGetMoney;
							}
						
							responseData["success"] = NotifyTransfer(transactionUUID, snd_message, rcv_message);
						}
						else
						{
							responseData["success"] = true;		// No messages for L$0 object. by Fumi.Iseki
						}
						return response;
					}
				}
				else // add transaction failed
				{
					Console.WriteLine("[MONEY RPC]: handleForceTransaction: Add force transaction for user {0} failed", senderID);
				}

				responseData["success"] = false;
				return response;
			}
			catch (Exception e)
			{
				Console.WriteLine("[MONEY RPC]: handleForceTransaction: Exception occurred while adding force transaction " + e.ToString());
				responseData["success"] = false;
				return response;
			}
		}
		//
		// added by Fumi.Iseki
		//
		/// <summary>
		/// handle incoming force transaction. no check senderSessionID and senderSecureSessionID
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		public XmlRpcResponse handleForceTransaction(XmlRpcRequest request, IPEndPoint remoteClient)
		{
			Hashtable requestData = (Hashtable)request.Params[0];
			XmlRpcResponse response = new XmlRpcResponse();
			Hashtable responseData  = new Hashtable();
			response.Value = responseData;

			int	   amount = 0;
			int	   transactionType = 0;
			string senderID = string.Empty;
			string receiverID = string.Empty;
			string objectID = string.Empty;
			string regionHandle = string.Empty;
			string description  = "Newly added on";
			string senderUserServIP = string.Empty;
			string receiverUserServIP = string.Empty;

			string fmID = string.Empty;
			string toID = string.Empty;
			UUID transactionUUID = UUID.Random();

			//m_log.InfoFormat("[Money RPC] in handleForceTransaction");
			//
			if (!m_forceTransfer)
			{
				m_log.Error("[Money RPC] Not allowed force transfer of Money. Set enableForceTransfer at [MoneyServer] to true in MoneyServer.ini");
				responseData["success"] = false;
				responseData["message"] = "not allowed force transfer of Money!";
				return response;
			}

			if (requestData.ContainsKey("senderID")) 			senderID = (string)requestData["senderID"];
			if (requestData.ContainsKey("receiverID")) 			receiverID = (string)requestData["receiverID"];
			if (requestData.ContainsKey("amount")) 				amount = (Int32)requestData["amount"];
			if (requestData.ContainsKey("objectID")) 			objectID = (string)requestData["objectID"];
			if (requestData.ContainsKey("regionHandle")) 		regionHandle = (string)requestData["regionHandle"];
			if (requestData.ContainsKey("transactionType")) 	transactionType = (Int32)requestData["transactionType"];
			if (requestData.ContainsKey("description")) 		description = (string)requestData["description"];
			if (requestData.ContainsKey("senderUserServIP")) 	senderUserServIP = (string)requestData["senderUserServIP"];
			if (requestData.ContainsKey("receiverUserServIP"))	receiverUserServIP = (string)requestData["receiverUserServIP"];

			fmID = senderID   + "@" + senderUserServIP;
			toID = receiverID + "@" + receiverUserServIP;

			m_log.InfoFormat("[Money RPC] Force transfering money from {0} to {1}", fmID, toID);
			int time = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000);

			try
			{
				TransactionData transaction = new TransactionData();
				transaction.TransUUID = transactionUUID;
				transaction.Sender   = fmID;
				transaction.Receiver = toID;
				transaction.Amount = amount;
				transaction.ObjectUUID = objectID;
				transaction.RegionHandle = regionHandle;
				transaction.Type = transactionType;
				transaction.Time = time;
				transaction.SecureCode = UUID.Random().ToString();
				transaction.Status = (int)Status.PENDING_STATUS;
				transaction.Description = description + " " + DateTime.Now.ToString();

				UserInfo rcvr = m_moneyDBService.FetchUserInfo(toID);
				if (rcvr == null) 
				{
					m_log.ErrorFormat("[Money RPC] Force receive User is not yet in DB:{0}", toID);
					responseData["success"] = false;
					return response;
				}

				bool result = m_moneyDBService.addTransaction(transaction);
				if (result) 
				{
					UserInfo user = m_moneyDBService.FetchUserInfo(fmID);
					if (user != null) 
					{
						if (amount!=0)
						{
							string snd_message = "";
							string rcv_message = "";

							if (transaction.Type==5001) {			// Gift
								snd_message = m_BalanceMessageSendGift;
								rcv_message = m_BalanceMessageReceiveGift;
							}
							else if (transaction.Type==5002) {		// LandSale
								snd_message = m_BalanceMessageLandSale;
							}
							else if (transaction.Type==5008) {		// PayObject
								snd_message = m_BalanceMessageBuyObject;
							}
							else if (transaction.Type==5009) {		// ObjectGiveMoney
								rcv_message = m_BalanceMessageGetMoney;
							}
						
							responseData["success"] = NotifyTransfer(transactionUUID, snd_message, rcv_message);
						}
						else
						{
							responseData["success"] = true;		// No messages for L$0 object. by Fumi.Iseki
						}
						return response;
					}
				}
				else // add transaction failed
				{
					m_log.ErrorFormat("[Money RPC] Add force transaction for user:{0} failed", fmID);
				}

				responseData["success"] = false;
				return response;
			}
			catch (Exception e)
			{
				m_log.Error("[Money RPC] Exception occurred while adding force transaction " + e.ToString());
				responseData["success"] = false;
				return response;
			}
		}
		//
		public XmlRpcResponse handleGetTransaction(XmlRpcRequest request, IPEndPoint remoteClient)
		{
			//m_log.InfoFormat("[Money RPC] in handleGetTransaction");

			Hashtable requestData = (Hashtable)request.Params[0];
			XmlRpcResponse response = new XmlRpcResponse();
			Hashtable responseData = new Hashtable();
			TransactionData transaction = new TransactionData();
			response.Value = responseData;
			string secureCode = string.Empty;
			string transactionID = string.Empty;
			UUID transactionUUID = UUID.Zero;

			if (requestData.ContainsKey("transactionID"))
			{
				transactionID = (string)requestData["transactionID"];
				UUID.TryParse(transactionID, out transactionUUID);
			}

			//if (string.IsNullOrEmpty(transactionID))
			if (string.IsNullOrEmpty(secureCode) || string.IsNullOrEmpty(transactionID))
			{
				responseData["success"] = false;
				responseData["description"] = "TransactionID can`t be empty";
				m_log.Error("[Money RPC] TransactionID can't be empty");
				return response;
			}

			transaction = m_moneyDBService.FetchTransaction(transactionUUID);
			if (transaction!=null)
			{
				UserInfo senderInfo = m_moneyDBService.FetchUserInfo(transaction.Sender);
				UserInfo receiverInfo = m_moneyDBService.FetchUserInfo(transaction.Receiver);
				if (senderInfo != null && receiverInfo != null)
				{
					responseData["success"] = true;
					responseData["sender"] = senderInfo.Avatar;
					responseData["receiver"] = receiverInfo.Avatar;
				}
				else
				{
					responseData["success"] = false;
					responseData["sender"] = "Query failed";
					responseData["receiver"] = "Query failed";
				}
				responseData["amount"] = transaction.Amount;
				responseData["time"] = transaction.Time;
			}
			return response;

		}
        public TransactionData[] FetchTransaction(string userID, int startTime, int endTime, uint index, uint retNum)
        {
            List <TransactionData> rows = new List <TransactionData>();
            string sql = string.Empty;

            sql += "SELECT * from " + Table_of_Transaction + " where time>=?start AND time<=?end ";
            sql += "AND (sender=?user or receiver=?user) order by time asc limit ?index,?num;";
            MySqlCommand cmd = new MySqlCommand(sql, dbcon);

            cmd.Parameters.AddWithValue("?start", startTime);
            cmd.Parameters.AddWithValue("?end", endTime);
            cmd.Parameters.AddWithValue("?user", userID);
            cmd.Parameters.AddWithValue("?index", index);
            cmd.Parameters.AddWithValue("?num", retNum);

            using (MySqlDataReader r = cmd.ExecuteReader())
            {
                for (int i = 0; i < retNum; i++)
                {
                    if (r.Read())
                    {
                        try
                        {
                            TransactionData transactionData = new TransactionData();
                            string          uuid            = (string)r["UUID"];
                            UUID            transUUID;
                            UUID.TryParse(uuid, out transUUID);

                            transactionData.TransUUID = transUUID;
                            transactionData.Sender    = (string)r["sender"];
                            transactionData.Receiver  = (string)r["receiver"];
                            transactionData.Amount    = Convert.ToInt32(r["amount"]);
                            if (r["objectUUID"] is System.DBNull)
                            {
                                transactionData.ObjectUUID = "null";
                            }
                            else
                            {
                                transactionData.ObjectUUID = (string)r["objectUUID"];
                            }
                            transactionData.Type        = Convert.ToInt32(r["type"]);
                            transactionData.Time        = Convert.ToInt32(r["time"]);
                            transactionData.Status      = Convert.ToInt32(r["status"]);
                            transactionData.CommonName  = (string)r["commonName"];
                            transactionData.Description = (string)r["description"];
                            rows.Add(transactionData);
                        }

                        catch (Exception e)
                        {
                            m_log.Error("[MONEY DB]: Fetching transaction failed: " + e.ToString());
                            return(null);
                        }
                    }
                }
                r.Close();
            }

            cmd.Dispose();
            return(rows.ToArray());
        }