示例#1
0
        public bool Get()
        {
            AppLog.Info("GET PRODUCT - Starting...");
            if (Data.OfflineMode)
            {
                AppLog.Info("GET PRODUCT - Attempting to retrieve product from local database...");

                /*try
                 * {
                 *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 *  {
                 *      AppLog.Info("GET PRODUCT - Attempting to open connection to local database...");
                 *      conn.Open();
                 *      AppLog.Info("GET PRODUCT - Connection to local database opened successfully");
                 *
                 *      SqlCommand GetProduct = new SqlCommand("SELECT * FROM Products WHERE Id = @Id;", conn);
                 *      GetProduct.Parameters.Add(new SqlParameter("Id", _Id));
                 *
                 *      GetProduct.ExecuteNonQuery();
                 *
                 *      using (SqlDataReader reader = GetProduct.ExecuteReader())
                 *      {
                 *          while (reader.Read())
                 *          {
                 *              _OrgId = new Guid(reader[1].ToString());
                 *              _Name = reader[2].ToString().Trim();
                 *          }
                 *      }
                 *  }
                 *  AppLog.Info(String.Format("GET PRODUCT - Product {0} retrieved from local database successfully",
                 *      Name));
                 * }
                 * catch (SqlException e)
                 * {
                 *  _ErrMsg = "Error while getting product from local database";
                 *  AppLog.Error(_ErrMsg + ": " + e);
                 *  return false;
                 * }*/
            }
            else
            {
                AppLog.Info("GET PRODUCT - Attempting to retrieve product from online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("GET PRODUCT - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("GET PRODUCT - Connection to online database opened successfully");

                        SqlCommand DownloadProduct = new SqlCommand("SELECT * FROM t_Products WHERE Id = @Id;", conn);
                        DownloadProduct.Parameters.Add(new SqlParameter("Id", _Id));

                        DownloadProduct.ExecuteNonQuery();

                        using (SqlDataReader reader = DownloadProduct.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                _OrgId = new Guid(reader[1].ToString());
                                _Name  = reader[2].ToString().Trim();
                            }
                        }
                    }
                    AppLog.Info(String.Format("GET PRODUCT - Product {0} retrieved fron online database successfully",
                                              Name));
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while downloading product from online database";
                    AppLog.Error(_ErrMsg + ": " + e);
                    return(false);
                }
                //Finally, check if product exists in the local database. If not, ADD THEM!!! If so, UPDATE THEM!!!
                AppLog.Info("GET PRODUCT - Checking whether product exists in local database");

                bool ExistsOnLocalDb;

                /*using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 * {
                 *  AppLog.Info("GET PRODUCT - Attempting to open connection to local database...");
                 *  conn.Open();
                 *  AppLog.Info("GET PRODUCT - Connection to local database opened successfully");
                 *
                 *
                 *
                 *  SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM Products WHERE Id = @Id;", conn);
                 *  CheckLocalDb.Parameters.Add(new SqlParameter("Id", Id));
                 *
                 *  using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
                 *  {
                 *      if (reader.Read())
                 *      {
                 *          ExistsOnLocalDb = true;
                 *          AppLog.Info("GET PRODUCT - Product already exists in the local database!");
                 *      }
                 *      else
                 *      {
                 *          ExistsOnLocalDb = false;
                 *      }
                 *  }
                 * }
                 * if (ExistsOnLocalDb)
                 * {
                 *  if (Update())
                 *  {
                 *      AppLog.Info("GET PRODUCT - Updated product on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET PRODUCT - Failed to update product: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }
                 * else
                 * {
                 *  if (Create())
                 *  {
                 *      AppLog.Info("GET PRODUCT - Created product on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET PRODUCT - Failed to create product: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }*/
            }
            AppLog.Info("GET PRODUCT - Success!");
            return(true);
        }
示例#2
0
        protected void EnsureConnection()
        {
            if (NetworkUri == null)
            {
                return;
            }

            bool      madeConnections  = false;
            bool      connected        = true;
            int       newLinkCount     = 0;
            Exception connectException = null;

            lock (this)
            {
                if (connecting)
                {
                    return;
                }
                connecting = true;
            }

            if (IsClosed)
            {
                connected = false;

                try
                {
                    AppLog.Info("Connecting to " + NetworkUri.ToString());
                    OpenConnection();
                    madeConnections = true;
                }
                catch (Exception ex)
                {
                    connectException = ex;
                    AppLog.Error(ex);
                }
            }

            if (!IsClosed)
            {
                connected = true;

                if (madeConnections)
                {
                    AppLog.Info("Connected to " + NetworkUri.ToString() + ".  Establishing Links...");
                }

                lock (this)
                {
                    foreach (AmqpLink link in links.Where(l => l.IsClosed))
                    {
                        try
                        {
                            link.CreateLink(session, this.OnMessageReceived);
                            madeConnections = true;
                            ++newLinkCount;
                        }
                        catch (Exception ex)
                        {
                            connectException = ex;
                            connected        = false;
                            AppLog.Error(ex);
                        }
                    }
                }

                if (connected && madeConnections)
                {
                    AppLog.Info($"{newLinkCount} Links established for {NetworkUri.ToString()}");
                }
            }

            lock (this)
            {
                connecting = false;
            }

            if (!connected)
            {
                AppLog.Error($"Connection Failed for {NetworkUri.ToString()}.  Will attempt again in {AmqpCFXEndpoint.ReconnectInterval?.TotalSeconds} seconds...");
                PostConnectionEvent(ConnectionEvent.ConnectionFailed, connectException);
                Task.Run(new Action(async() =>
                {
                    await Task.Delay(Convert.ToInt32(AmqpCFXEndpoint.ReconnectInterval?.TotalMilliseconds));
                    EnsureConnection();
                }));
            }
            else
            {
                if (madeConnections)
                {
                    PostConnectionEvent(ConnectionEvent.ConnectionEstablished);
                }
                if (AmqpCFXEndpoint.KeepAliveEnabled.Value)
                {
                    lock (keepAliveLock)
                    {
                        if (keepAliveTimer == null)
                        {
                            int interval = Convert.ToInt32(AmqpCFXEndpoint.KeepAliveInterval.Value.TotalMilliseconds);
                            keepAliveTimer = new Timer(new TimerCallback(KeepAliveTimer), null, 0, interval);
                        }
                    }
                }
            }
        }
示例#3
0
        private void LoadBookings()
        {
            try
            {
                //string DeletePer = Session["delete_login"].ToString();
                DateTime fromdate = Convert.ToDateTime(hfromdateL.Value);
                DateTime todate   = Convert.ToDateTime(htodateL.Value);

                lblmessage.Text = "";
                DataTable dtdetails = ObjDBAccess1.GetAllBookings(Session["companyid"].ToString(), fromdate, todate);

                if (dtdetails != null && dtdetails.Rows.Count > 0)
                {
                    String UnreadText = "";
                    foreach (DataRow drverprof in dtdetails.Rows)
                    {
                        UnreadText += "<tr>";
                        //UnreadText += "<td style='display: none;'>" + drverprof["profileid"] + "</td>";
                        UnreadText += "<td>" + drverprof["bookingId"] + "</td>";
                        UnreadText += "<td>" + Convert.ToDateTime(drverprof["bookingdate"]).ToString("dd-MMM-yyyy") + "</td>";
                        UnreadText += "<td>" + drverprof["slname"] + "</td>";
                        UnreadText += "<td>" + drverprof["customername"] + "</td>";
                        UnreadText += "<td>" + Convert.ToDateTime(drverprof["Fromdate"]).ToString("dd-MMM-yyyy") + "</td>";
                        UnreadText += "<td>" + Convert.ToDateTime(drverprof["Todate"]).ToString("dd-MMM-yyyy") + "</td>";
                        UnreadText += "<td>" + drverprof["vehsegname"] + "</td>";
                        UnreadText += "<td>" + drverprof["bookingstatus"] + "</td>";
                        UnreadText += "<td>" + drverprof["dutyclosestatus"] + "</td>";

                        //bookingid, segid, slid,vehmakeid, status, customername, bookingdate, bookedby, BookedMobileno, BookedEmail, GuestMobile, GuestName, GuestEmail, FromDate, Todate, AdvAmt, discstatus, discount, SecDepStatus,SecDepAmt, companyid
                        UnreadText += "<td style='text-align:center;'><a data-toggle='modal' data-target='.bs-example-modal-lg' href='#'  onclick= \"FillDetails('"
                                      + drverprof["bookingId"] + "','"
                                      + drverprof["vehsegid"] + "','"
                                      + drverprof["slid"] + "','"
                                      + drverprof["vehmakeid"] + "','"
                                      + drverprof["bookingstatus"] + "','"
                                      + drverprof["customername"] + "','"
                                      + Convert.ToDateTime(drverprof["bookingdate"]).ToString("dd-MMM-yyyy") + "','"
                                      + drverprof["bookedby"] + "','"
                                      + drverprof["BookedbyMobile"] + "','"
                                      + drverprof["bookedbyemail"] + "','"
                                      + drverprof["GuestMobile"] + "','"
                                      + drverprof["guest"] + "','"
                                      + drverprof["GuestEmail"] + "','"
                                      + Convert.ToDateTime(drverprof["Fromdate"]).ToString("dd-MMM-yyyy") + "','"

                                      + Convert.ToDateTime(drverprof["Todate"]).ToString("dd-MMM-yyyy") + "','"
                                      + drverprof["AdvanceAmt"] + "','"
                                      + drverprof["discstatus"] + "','"
                                      + drverprof["discount"] + "','"
                                      + drverprof["SecDepStatus"] + "','"
                                      + drverprof["SecDepAmt"] + "','"
                                      + drverprof["tariffid"] + "','"
                                      + drverprof["accessoriesStatus"] + "','"
                                      + drverprof["accsids"] + "','"
                                      + drverprof["fromtime1"] + "','"
                                      + drverprof["totime1"] + "','"

                                      + drverprof["companyid"] + "')\" > <i style='padding-right:20px;' class='fas fa-edit' aria-hidden='true'></i></a>";

                        UnreadText += "<a  href='#'  onclick= \"DeleteMe('" + drverprof["bookingId"] + "')\" > <i class='fas fa-trash-alt' aria-hidden='true'></i></a></td>";
                        //UnreadText += "<td></td>";
                        UnreadText += "		</tr>";
                    }
                    tlist.InnerHtml = UnreadText;
                    Panel1.Visible  = true;
                }
                else
                {
                    Panel1.Visible  = false;
                    lblmessage.Text = "No Records Found";
                }
                txtFromDateL.Text = hfromdateL.Value;
                txtToDateL.Text   = htodateL.Value;
            }
            catch (Exception ex)
            {
                AppLog.Error(ex);
            }
        }
示例#4
0
        public bool Get()
        {
            AppLog.Info("GET ORGMEMBER - Starting...");
            AppLog.Info("GET ORGMEMBER - OrgMember's Org's Id: " + _OrgId);
            AppLog.Info("GET ORGMEMBER - OrgMember's User's Id: " + _UserId);

            //Download from local db if offline mode is on
            if (Data.OfflineMode)
            {
                AppLog.Info("GET ORGMEMBER - Offline mode is ON. Attempting to download organisation member" +
                            " from local database...");

                /*try
                 * {
                 *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 *  {
                 *      AppLog.Info("GET ORGMEMBER - Attempting to open connection to local database...");
                 *      conn.Open();
                 *      AppLog.Info("GET ORGMEMBER - Connection to local database opened successfully");
                 *
                 *      SqlCommand GetOrgMember = new SqlCommand("SELECT * FROM OrgMembers " +
                 *          "WHERE OrgId = @OrgId AND UserId = @UserId;", conn);
                 *      GetOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                 *      GetOrgMember.Parameters.Add(new SqlParameter("UserId", _UserId));
                 *
                 *      using (SqlDataReader reader = GetOrgMember.ExecuteReader())
                 *      {
                 *          if (reader.Read())
                 *          {
                 *              _DateTimeJoined = Convert.ToDateTime(reader[2]);
                 *              _AccessLevel = Convert.ToInt32(reader[3]);
                 *          }
                 *          else
                 *          {
                 *              //If reader.Read() returns false, no data was returned
                 *              _ErrMsg = "Error while downloading organisation member from local database. " +
                 *                  "No data was returned";
                 *              AppLog.Error("GET ORGMEMBER - " + _ErrMsg);
                 *              return false;
                 *          }
                 *      }
                 *  }
                 *  AppLog.Info(String.Format("GET ORGMEMBER - Got org member from local database successfully"));
                 * }
                 * catch (SqlException e)
                 * {
                 *  _ErrMsg = "Error while getting organisation member from local database";
                 *  AppLog.Error("GET ORGMEMBER - " + _ErrMsg + ": " + e);
                 *  return false;
                 * }*/
            }
            else
            {
                AppLog.Info("GET ORGMEMBER - Offline mode is OFF. Attempting to download organisation member " +
                            "from online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("GET ORGMEMBER - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("GET ORGMEMBER - Connection to online database opened successfully");

                        SqlCommand GetOrgMember = new SqlCommand("SELECT * FROM t_OrgMembers " +
                                                                 "WHERE OrgId = @OrgId AND UserId = @UserId;", conn);
                        GetOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                        GetOrgMember.Parameters.Add(new SqlParameter("UserId", _UserId));

                        using (SqlDataReader reader = GetOrgMember.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                _DateTimeJoined = Convert.ToDateTime(reader[2]);
                                _AccessLevel    = Convert.ToInt32(reader[3]);
                            }
                            else
                            {
                                //If reader.Read() returns false, no data was returned
                                _ErrMsg = "Error while downloading organisation member from online database. " +
                                          "No data was returned";
                                AppLog.Error("GET ORGMEMBER - " + _ErrMsg);
                                return(false);
                            }
                        }
                    }
                    AppLog.Info(String.Format("GET ORGMEMBER - Got org member from online database successfully"));
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while downloading organisation member from online database";
                    AppLog.Error("GET ORGMEMBER - " + _ErrMsg + ": " + e);
                    return(false);
                }
                //Finally, check if org member exists in the local database. If not, ADD THEM!!! If so, UPDATE THEM!!!
                AppLog.Info("GET ORGMEMBER - Checking whether org member exists in local database");

                bool ExistsOnLocalDb;

                /*using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 * {
                 *  AppLog.Info("GET ORGMEMBER - Attempting to open connection to local database...");
                 *  conn.Open();
                 *  AppLog.Info("GET ORGMEMBER - Connection to local database opened successfully");
                 *
                 *
                 *
                 *  SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM OrgMembers WHERE OrgId = @OrgId AND " +
                 *      "UserId = @UserId;", conn);
                 *  CheckLocalDb.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                 *  CheckLocalDb.Parameters.Add(new SqlParameter("UserId", _UserId));
                 *
                 *  using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
                 *  {
                 *      if (reader.Read())
                 *      {
                 *          ExistsOnLocalDb = true;
                 *          AppLog.Info("GET ORGMEMBER - OrgMember already exists in the local database!");
                 *      }
                 *      else
                 *      {
                 *          ExistsOnLocalDb = false;
                 *      }
                 *  }
                 * }
                 * if (ExistsOnLocalDb)
                 * {
                 *  if (Update())
                 *  {
                 *      AppLog.Info("GET ORGMEMBER - Updated org member on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET ORGMEMBER - Failed to update org member: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }
                 * else
                 * {
                 *  if (Create())
                 *  {
                 *      AppLog.Info("GET ORGMEMBER - Created org member on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET ORGMEMBER - Failed to create org member: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }*/
            }
            AppLog.Info(String.Format("GET ORGMEMBER - Success!"));
            return(true);
        }
示例#5
0
        public bool Create()
        {
            //Print identifiers to log
            AppLog.Info("CREATE ORGMEMBER - Starting...");
            AppLog.Info("CREATE ORGMEMBER - OrgMember's Org's Id: " + _OrgId);
            AppLog.Info("CREATE ORGMEMBER - OrgMember's User's Id: " + _UserId);
            AppLog.Info("CREATE ORGMEMBER - OrgMember's User's FullName: " + MyUser.FullName);
            AppLog.Info("CREATE ORGMEMBER - OrgMember's User's Username: "******"Cannot create organisation members while in offline mode";
                AppLog.Info(String.Format("CREATE ORGMEMBER - Organisation member {0} was not created because " +
                                          "offline mode is on", MyUser.Username));
                return(false);
            }

            //Checks that data is valid before attempting upload
            AppLog.Info("CREATE ORG - Validating...");
            if (!Validate())
            {
                AppLog.Info("CREATE ORG - Organisation failed validation");
                return(false);
            }
            AppLog.Info("CREATE ORG - Organisation validated successfully");

            _DateTimeJoined = DateTime.Now;

            AppLog.Info("CREATE ORGMEMBER - Attempting to create organisation member on online database...");
            //If offline mode is on, try and create org member on online database
            try
            {
                using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                {
                    AppLog.Info("CREATE ORGMEMBER - Attempting to open connection to online database...");
                    conn.Open();
                    AppLog.Info("CREATE ORGMEMBER - Connection to online database opened successfully");

                    //This is a check to see weather the org member already exists on the database. Obviously
                    //if it's already there, it doesn't need creating again, but this might be called
                    //if for example the org member did not exist on the local database, so the Create() function
                    //needed to be able to account for that.
                    AppLog.Info("CREATE ORGMEMBER - Checking that org member doesn't already exist on online database");
                    bool OnlineOrgMemberExists;

                    SqlCommand CheckOnlineDb = new SqlCommand("SELECT * FROM t_OrgMembers WHERE OrgId = @OrgId AND " +
                                                              "UserId = @UserId;", conn);
                    CheckOnlineDb.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                    CheckOnlineDb.Parameters.Add(new SqlParameter("UserId", MyUser.Id));
                    using (SqlDataReader reader = CheckOnlineDb.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            OnlineOrgMemberExists = true;
                            AppLog.Info("CREATE ORGMEMBER - OrgMember already exists in online database!");
                        }
                        else
                        {
                            OnlineOrgMemberExists = false;
                            AppLog.Info("CREATE ORGMEMBER - OrgMember does not exist in online database. Creating org member on online database");
                        }
                    }
                    if (!OnlineOrgMemberExists)
                    {
                        SqlCommand CreateOrgMember = new SqlCommand("INSERT INTO t_OrgMembers VALUES(@OrgId," +
                                                                    "@UserId, @DateTimeJoined, @AccessLevel);", conn);
                        CreateOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                        CreateOrgMember.Parameters.Add(new SqlParameter("UserId", MyUser.Id));
                        CreateOrgMember.Parameters.Add(new SqlParameter("DateTimeJoined", _DateTimeJoined));
                        CreateOrgMember.Parameters.Add(new SqlParameter("AccessLevel", _AccessLevel));

                        CreateOrgMember.ExecuteNonQuery();

                        AppLog.Info(String.Format("CREATE ORGMEMBER - Organisation member {0} created on online " +
                                                  "database successfully", MyUser.FullName));
                    }
                }
            }
            catch (SqlException e)
            {
                //Nothing really needs to happen here, neither of the databases have been affected
                _ErrMsg = "Error while creating organisation member on online database";
                AppLog.Error("CREATE ORGMEMBER - " + _ErrMsg + ": " + e);
                return(false);
            }



            AppLog.Info("CREATE ORGMEMBER - Attempting to create organisation member on local database...");
            //If org member was created on the online database successfully, try local database

            /*try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("CREATE ORGMEMBER - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("CREATE ORGMEMBER - Connection to local database opened successfully");
             *
             *      //This is a check to see weather the org member already exists on the database. Obviously
             *      //if it's already there, it doesn't need creating again, but this might be called
             *      //if for example the org member did not exist on the local database, so the Create() function
             *      //needed to be able to account for that.
             *      AppLog.Info("CREATE ORGMEMBER - Checking that org member doesn't already exist on local database");
             *      bool LocalOrgMemberExists;
             *
             *      SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM OrgMembers WHERE OrgId = @OrgId AND " +
             *          "UserId = @UserId;", conn);
             *      CheckLocalDb.Parameters.Add(new SqlParameter("OrgId", _OrgId));
             *      CheckLocalDb.Parameters.Add(new SqlParameter("UserId", _UserId));
             *      using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
             *      {
             *          if (reader.Read())
             *          {
             *              LocalOrgMemberExists = true;
             *              AppLog.Info("CREATE ORGMEMBER - OrgMember already exists in local database!");
             *          }
             *          else
             *          {
             *              LocalOrgMemberExists = false;
             *              AppLog.Info("CREATE ORGMEMBER - OrgMember does not exist in local database. Creating org member on local database");
             *          }
             *      }
             *      if (LocalOrgMemberExists)
             *      {
             *          SqlCommand CreateOrgMember = new SqlCommand("INSERT INTO OrgMembers VALUES(@OrgId," +
             *          "@UserId, @DateTimeJoined, @AccessLevel);", conn);
             *          CreateOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
             *          CreateOrgMember.Parameters.Add(new SqlParameter("UserId", _UserId));
             *          CreateOrgMember.Parameters.Add(new SqlParameter("DateTimeJoined", _DateTimeJoined));
             *          CreateOrgMember.Parameters.Add(new SqlParameter("AccessLevel", _AccessLevel));
             *
             *          CreateOrgMember.ExecuteNonQuery();
             *
             *          AppLog.Info(String.Format("CREATE ORGMEMBER - Organisation member {0} created on local database " +
             *          "successfully.", MyUser.FullName));
             *      }
             *  }
             * }
             * catch (SqlException e)
             * {
             *
             *  //If this fails we need to reset the changes
             *  //_ErrMsg = "Error while creating organisation member on local database. Organisation member will " +
             *  //    "now be deleted.";
             *  //AppLog.Error(_ErrMsg + ": " + e);
             *  //
             *  //AppLog.Info("Attempting to resolve error by deleting organisation member...");
             *  //if (Delete())
             *  //{
             *  //    AppLog.Info("Organisation member deleted. Error resolved successfully!");
             *  //}
             *  //else
             *  //{
             *      AppLog.Info("Organisation member not deleted. FATAL ERROR!!!");
             *      throw new Exception("Fatal error while creating organisation. There was an error and " +
             *          "changes could not be reverted.");
             *  }
             *  return false;
             *
             *  _ErrMsg = "Error while creating organisation member on local database. Changes were saved " +
             *      "online so no action required. Continuing... ";
             *  AppLog.Error("CREATE ORGMEMBER - " + _ErrMsg + ": " + e);
             * }*/
            AppLog.Info(String.Format("CREATE ORGMEMBER - Success!"));
            return(true);
        }
示例#6
0
        private void LoadCompanies()
        {
            try
            {
                string DeletePer = "Required";
                //string DeletePer = Session["delete_login"].ToString();
                lblmessage.Text = "";
                DataTable dtdetails = ObjDBAccess1.GetAllCompanies();

                if (dtdetails != null && dtdetails.Rows.Count > 0)
                {
                    String UnreadText = "";
                    foreach (DataRow drverprof in dtdetails.Rows)
                    {
                        UnreadText += "<tr>";
                        //UnreadText += "<td style='display: none;'>" + drverprof["profileid"] + "</td>";
                        UnreadText += "<td>" + drverprof["companyname"] + "</td>";
                        UnreadText += "<td>" + drverprof["address1"] + "</td>";
                        UnreadText += "<td>" + drverprof["city"] + "</td>";
                        UnreadText += "<td>" + drverprof["pincode"] + "</td>";
                        UnreadText += "<td>" + drverprof["panno"] + "</td>";
                        UnreadText += "<td>" + drverprof["status"] + "</td>";

                        UnreadText += "<td style='text-align:center;'><a data-toggle='modal' data-target='.bs-example-modal-lg' href='#'  onclick= \"FillDetails('"
                                      + drverprof["companyid"] + "','"
                                      + drverprof["companyname"] + "','"
                                      + drverprof["address1"] + "','"
                                      + drverprof["address2"] + "','"
                                      + drverprof["city"] + "','"
                                      + drverprof["pincode"] + "','"
                                      + drverprof["colorlogo"] + "','"
                                      + drverprof["blacklogo"] + "','"
                                      + drverprof["panno"] + "','"
                                      + drverprof["gstno"] + "','"
                                      + drverprof["status"] + "')\" > <i style='padding-right:20px;' class='fas fa-edit' aria-hidden='true'></i></a>";

                        if (DeletePer == "Required")
                        {
                            UnreadText += "<a  href='#'  onclick= \"DeleteMe('" + drverprof["companyid"] + "')\" > <i class='fas fa-trash-alt' style='color:red;' aria-hidden='true'></i></a></td>";
                        }
                        else
                        {
                            UnreadText += "		 <a  href='#'> <i class='fas fa-ban' aria-hidden='true'></i></a></td>";
                        }
                        //UnreadText += "<td></td>";
                        UnreadText += "		</tr>";
                    }
                    tlist.InnerHtml = UnreadText;
                    Panel1.Visible  = true;
                }
                else
                {
                    Panel1.Visible  = false;
                    lblmessage.Text = "No Records Found";
                }
            }
            catch (Exception ex)
            {
                AppLog.Error(ex);
            }
        }
        /// <summary>
        /// 过滤器后 进入该方法
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        protected override void ExecuteCommand(UdpSession session, MyUdpRequestInfo requestInfo)
        {
            if (requestInfo.Key.Contains(HandleUdpUtils.C_SESSION_KEY) ||
                requestInfo.Key.Contains(HandleUdpUtils.H_SESSION_KEY) ||
                requestInfo.Key.Contains(HandleUdpUtils.T_SESSION_KEY))
            {
                if (requestInfo.TerminalCounterData.TranType == 10)
                {
                    LogHelper.WriteLog(DateTime.Now.ToString() + "  " + requestInfo.Key + ": HeartBeat success  " + session.NickName);
                    string strReaderCode = requestInfo.TerminalCounterData.ReaderID;


                    string SnDate = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now).Substring(3, 10);

                    string strHeartbeat = string.Empty;
                    strHeartbeat += "at=TDATA";                                                                           //-----1  数据类型 ---
                    strHeartbeat += ("&sn=" + (SnDate));                                                                  //-----1 通信序列号---
                    strHeartbeat += ("&ti=" + (strReaderCode));                                                           //-----1 reader id----
                    strHeartbeat += ("&lst=" + (string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now).Substring(0, 14))); //-1 最终shot 时间---
                    strHeartbeat += ("&ip=" + (VarGlobal.DeviceIP));                                                      //---1 通信接收时间--生成此命令时间
                    LogHelper.WriteLog("Heart " + requestInfo.Key + "~" + requestInfo.SessionID + "~" + strHeartbeat);
                    try
                    {
                        CounterSendMsg cntMsg = new CounterSendMsg();
                        cntMsg.bMultiFlag = false;
                        cntMsg.strSendMsg = strHeartbeat;
                        //startThreadSend(cntMsg);//Heart data
                        Task task = Task.Factory.StartNew(() => ClientPost(strHeartbeat));
                    }
                    catch (OutOfMemoryException ex)
                    {
                        LogHelper.WriteLog("OutOfMemoryException   10 Code" + ex.ToString());
                    }
                    catch (Exception ex)
                    {
                        string strex = ex.ToString();
                        AppLog.Error(requestInfo.SessionID + " 10 Code " + strex);
                        LogHelper.WriteLog("Exception   10 Code" + ex.ToString());
                    }
                }
                else if (requestInfo.TerminalCounterData.TranType == 46)
                {
                    LogHelper.WriteLog("Normal " + requestInfo.Key + "~" + requestInfo.SessionID + "~  " + session.NickName + "  ~  " + requestInfo.TerminalCounterData.allParams);
                    try
                    {
                        //strbuf46 = (m_strOneIDAllParam + "=============radio = 3  启动线程=== single ==========");
                        //showApiData(VarGlobal.TokenKey, richApiLog);
                        //showApiData(strbuf46, richApiLog);
                        CounterSendMsg cntMsg = new CounterSendMsg();
                        cntMsg.bMultiFlag = false;
                        cntMsg.strSendMsg = requestInfo.TerminalCounterData.allParams;
                        //startThreadSend(cntMsg);//Counter Data
                        Task task = Task.Factory.StartNew(() => ClientPost(requestInfo.TerminalCounterData.allParams));
                    }
                    catch (OutOfMemoryException ex)
                    {
                        LogHelper.WriteLog("OutOfMemoryException   10 Code" + ex.ToString());
                    }
                    catch (Exception ex)
                    {
                        string strex = ex.ToString();
                        AppLog.Error(requestInfo.SessionID + " 46 Code " + strex);
                        LogHelper.WriteLog("Exception   46 Code" + ex.ToString());
                        //WriteLogFileName(strex, "StartThreadToSend");
                        //return -5;
                    }
                }
                else
                {
                    LogHelper.WriteLog("Error " + requestInfo.Key + "~" + requestInfo.SessionID + "~" + requestInfo.TerminalCounterData.allParams);
                }
                //if (requestInfo.Key.Contains("0123456"))
                //{
                //    session.Send("Server receive success - " + requestInfo.Key);
                //}
                //session.Send("hello");
            }
            else
            {
                LogHelper.WriteLog(requestInfo.SessionID + "不存在该设备");
            }
        }
        public bool Update()
        {
            //Print identifiers to log
            AppLog.Info("UPDATE ORG - Starting...");
            AppLog.Info("UPDATE ORG - Organisation's Id: " + Id);
            AppLog.Info("UPDATE ORG - Organisation's Name: " + Name);

            int AffectedRows = 0;

            //Orgs can't be updated in offline mode
            if (Data.OfflineMode)
            {
                _ErrMsg = "Cannot update organisations while in offline mode";
                AppLog.Info(String.Format("UPDATE ORG - Organisation {0} was not updated because offline mode is on", _Name));
                return(false);
            }

            //try update online database
            AppLog.Info("UPDATE ORG - Attempting to update organisation on online database...");
            try
            {
                using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                {
                    AppLog.Info("UPDATE ORG - Attempting to open connection to local database...");
                    conn.Open();
                    AppLog.Info("UPDATE ORG - Connection to local database opened successfully");

                    SqlCommand UpdateOrg = new SqlCommand("UPDATE t_Organisations SET Name = @Name WHERE Id = @Id;", conn);
                    UpdateOrg.Parameters.Add(new SqlParameter("Id", _Id));
                    UpdateOrg.Parameters.Add(new SqlParameter("Name", _Name));

                    AffectedRows = UpdateOrg.ExecuteNonQuery();
                }
                AppLog.Info(String.Format("UPDATE ORG - Organisation {0} updated on online database successfully. " +
                                          "{1} row(s) affected", _Name, AffectedRows));
            }
            catch (SqlException e)
            {
                //Database has not been affected, no handling required
                _ErrMsg = "Error while updating organisation on online database";
                AppLog.Error("UPDATE ORG - " + _ErrMsg + ": " + e);
                return(false);
            }


            AffectedRows = 0;

            //If online database was updated successfully, try updating local database

            /*try
             * {
             *  AppLog.Info("UPDATE ORG - Attempting to update organisation on local database...");
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("UPDATE ORG - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("UPDATE ORG - Connection to local database opened successfully");
             *
             *      SqlCommand UpdateOrg = new SqlCommand("UPDATE Organisations SET Name = @Name WHERE Id = @Id;", conn);
             *      UpdateOrg.Parameters.Add(new SqlParameter("Id", _Id));
             *      UpdateOrg.Parameters.Add(new SqlParameter("Name", _Name));
             *
             *      AffectedRows = UpdateOrg.ExecuteNonQuery();
             *  }
             *  AppLog.Info(String.Format("UPDATE ORG - Organisation {0} updated on local database successfully. " +
             *  "{1} row(s) affected", _Name, AffectedRows));
             * }
             * catch (SqlException e)
             * {
             *  _ErrMsg = "Error while updating user on local database. Changes were saved online so " +
             *      "no action required. Continuing...";
             *  AppLog.Error("UPDATE ORG - " + _ErrMsg + ": " + e);
             * }*/
            AppLog.Info(String.Format("UPDATE ORG - Success!"));
            return(true);
        }
        public bool Get()
        {
            AppLog.Info("GET ORG - Starting...");
            AppLog.Info("GET ORG - Organisation's Id: " + Id);

            //Get from local
            if (Data.OfflineMode)
            {
                /*AppLog.Info("GET ORG - Offline mode is ON. Attempting to download organisation from local database...");
                 * try
                 * {
                 *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 *  {
                 *      //Moved to Data.Initialise
                 *
                 *  }
                 * }
                 * catch (SqlException e)
                 * {
                 *  _ErrMsg = "Error while getting organisation from local database";
                 *  AppLog.Error("GET ORG - " + _ErrMsg + ": " + e);
                 *  return false;
                 * }*/
            }
            else//Get from online
            {
                AppLog.Info("GET ORG - Offline mode is OFF. Attempting to get organisations from online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("GET ORG - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("GET ORG - Connection to online database opened successfully");

                        SqlCommand GetOrganisation = new SqlCommand("SELECT * FROM t_Organisations WHERE Id = @Id;", conn);
                        GetOrganisation.Parameters.Add(new SqlParameter("Id", _Id));

                        GetOrganisation.ExecuteNonQuery();

                        using (SqlDataReader reader = GetOrganisation.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                _Name            = reader[1].ToString().Trim();
                                _DateTimeCreated = Convert.ToDateTime(reader[2]);
                            }
                            else
                            {
                                //If reader.Read() returns false, no data was returned
                                _ErrMsg = "Error while downloading organisation from online database. No data was returned";
                                AppLog.Error("GET ORG - " + _ErrMsg);
                                return(false);
                            }
                        }

                        AppLog.Info(String.Format("GET ORG - Organisation {0} downloaded from online database successfully", _Name));
                    }
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while getting organisation from online database";
                    AppLog.Error("GET ORG - " + _ErrMsg + ": " + e);
                    return(false);
                }
                //Finally, check if organisation exists in the local database. If not, ADD THEM!!! If so, UPDATE THEM!!!
                AppLog.Info("GET ORGANISATION - Checking whether organisation exists in local database");

                /*bool ExistsOnLocalDb;
                 *
                 * using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 * {
                 *  AppLog.Info("GET ORGANISATION - Attempting to open connection to local database...");
                 *  conn.Open();
                 *  AppLog.Info("GET ORGANISATION - Connection to local database opened successfully");
                 *
                 *
                 *
                 *  SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM Organisations WHERE Id = @Id;", conn);
                 *  CheckLocalDb.Parameters.Add(new SqlParameter("Id", Id));
                 *
                 *  using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
                 *  {
                 *      if (reader.Read())
                 *      {
                 *          ExistsOnLocalDb = true;
                 *          AppLog.Info("GET ORGANISATION - Organisation already exists in the local database!");
                 *      }
                 *      else
                 *      {
                 *          ExistsOnLocalDb = false;
                 *      }
                 *  }
                 * }
                 * if (ExistsOnLocalDb)
                 * {
                 *  if (Update())
                 *  {
                 *      AppLog.Info("GET ORGANISATION - Updated organisation on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET ORGANISATION - Failed to update organisation: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }
                 * else
                 * {
                 *  if (Create())
                 *  {
                 *      AppLog.Info("GET ORGANISATION - Created organisation on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET ORGANISATION - Failed to create organisation: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }*/
            }

            AppLog.Info(String.Format("GET ORG - Success!"));

            return(true);
        }
示例#10
0
        public CFXEnvelope ExecuteRequest(string targetUri, CFXEnvelope request)
        {
            CFXEnvelope  response      = null;
            Connection   reqConn       = null;
            Session      reqSession    = null;
            ReceiverLink receiver      = null;
            SenderLink   sender        = null;
            Exception    ex            = null;
            Uri          targetAddress = new Uri(targetUri);

            try
            {
                if (string.IsNullOrWhiteSpace(request.RequestID))
                {
                    request.RequestID = "REQUEST-" + Guid.NewGuid().ToString();
                }
                Message req = AmqpUtilities.MessageFromEnvelope(request, UseCompression.Value);
                req.Properties.MessageId            = "command-request";
                req.Properties.ReplyTo              = CFXHandle;
                req.ApplicationProperties           = new ApplicationProperties();
                req.ApplicationProperties["offset"] = 1;

                Task.Run(() =>
                {
                    try
                    {
                        reqConn           = new Connection(new Address(targetAddress.ToString()));
                        reqSession        = new Session(reqConn);
                        Attach recvAttach = new Attach()
                        {
                            Source = new Source()
                            {
                                Address = CFXHandle
                            },
                            Target = new Target()
                            {
                                Address = request.Target
                            }
                        };

                        receiver = new ReceiverLink(reqSession, "request-receiver", recvAttach, null);
                        receiver.Start(300);
                        sender = new SenderLink(reqSession, CFXHandle, request.Target);

                        sender.Send(req);
                        Message resp = receiver.Receive(RequestTimeout.Value);
                        if (resp != null)
                        {
                            receiver.Accept(resp);
                            response = AmqpUtilities.EnvelopeFromMessage(resp);
                        }
                        else
                        {
                            throw new TimeoutException("A response was not received from target CFX endpoint in the alloted time.");
                        }
                    }
                    catch (Exception ex3)
                    {
                        AppLog.Error(ex3);
                        ex = ex3;
                    }
                }).Wait();
            }
            catch (Exception ex2)
            {
                AppLog.Error(ex2);
                if (ex == null)
                {
                    ex = ex2;
                }
            }
            finally
            {
                if (receiver != null && !receiver.IsClosed)
                {
                    receiver.Close();
                }
                if (sender != null && !sender.IsClosed)
                {
                    sender.Close();
                }
                if (reqSession != null && !reqSession.IsClosed)
                {
                    reqSession.Close();
                }
                if (reqConn != null && !reqConn.IsClosed)
                {
                    reqConn.Close();
                }
            }

            if (ex != null)
            {
                throw ex;
            }
            return(response);
        }
示例#11
0
        public bool Create()
        {
            //Print identifiers in log
            AppLog.Info("CREATE ORG - Starting...");
            AppLog.Info("CREATE ORG - Organisation's Id: " + Id);
            AppLog.Info("CREATE ORG - Organisation's Name: " + Name);

            int AffectedRows = 0;

            //Checks offline mode (can't create organisations in offline mode)
            if (Data.OfflineMode)
            {
                _ErrMsg = "Cannot create organisations while in offline mode";
                AppLog.Info(String.Format("CREATE ORG - Organisation {0} was not created because offline mode is on",
                                          _Name));
                return(false);
            }

            //Checks that data is valid before attempting upload
            AppLog.Info("CREATE ORG - Validating...");
            if (!Validate())
            {
                AppLog.Info("CREATE ORG - Organisation failed validation");
                return(false);
            }
            AppLog.Info("CREATE ORG - Organisation validated successfully");

            _DateTimeCreated = DateTime.Now;

            //Try creating user online first
            AppLog.Info("CREATE ORG - Attempting to create organisation on online database...");
            try
            {
                using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                {
                    AppLog.Info("CREATE ORG - Attempting to open connection to online database...");
                    conn.Open();
                    AppLog.Info("CREATE ORG - Connection to online database opened successfully");

                    //This is a check to see weather the org already exists on the database. Obviously
                    //if it's already there, it doesn't need creating again, but this might be called
                    //if for example the org did not exist on the local database, so the Create() function
                    //needed to be able to account for that.
                    AppLog.Info("CREATE ORG - Checking that org doesn't already exist on online database");
                    bool OnlineOrgExists;

                    SqlCommand CheckOnlineDb = new SqlCommand("SELECT * FROM t_Organisations WHERE Id = @Id", conn);
                    CheckOnlineDb.Parameters.Add(new SqlParameter("Id", Id));
                    using (SqlDataReader reader = CheckOnlineDb.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            OnlineOrgExists = true;
                            AppLog.Info("CREATE ORG - Org already exists in online database!");
                        }
                        else
                        {
                            OnlineOrgExists = false;
                            AppLog.Info("CREATE ORG - Org does not exist in online database. Creating org on online database");
                        }
                    }
                    if (!OnlineOrgExists)
                    {
                        SqlCommand CreateOrg = new SqlCommand("INSERT INTO t_Organisations VALUES(@Id, @Name," +
                                                              "@DateTimeCreated);", conn);
                        CreateOrg.Parameters.Add(new SqlParameter("Id", _Id));
                        CreateOrg.Parameters.Add(new SqlParameter("Name", _Name));
                        CreateOrg.Parameters.Add(new SqlParameter("DateTimeCreated", _DateTimeCreated));

                        AffectedRows = CreateOrg.ExecuteNonQuery();

                        AppLog.Info(String.Format("CREATE ORG - Organisation {0} created on online database successfully. " +
                                                  "{1} row(s) affected", _Name, AffectedRows));
                    }
                }
            }
            catch (SqlException e)
            {
                //Nothing really needs to happen here, neither of the databases have been affected
                _ErrMsg = "Error while creating organisation on online database";
                AppLog.Error("GET ORG - " + _ErrMsg + ": " + e);
                return(false);
            }

            AffectedRows = 0;

            //If the organisation was created on the online database without throwing any errors,
            //try and create it on the local database

            /*AppLog.Info("CREATE ORG - Attempting to create organisation on local database...");
             * try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("CREATE ORG - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("CREATE ORG - Connection to local database opened successfully");
             *
             *      //This is a check to see weather the organisation already exists on the database. Obviously
             *      //if it's already there, it doesn't need creating again, but this might be called
             *      //if for example the organisation did not exist on the local database, so the Create() function
             *      //needed to be able to account for that.
             *      AppLog.Info("CREATE ORG - Checking that organisation doesn't already exist on local database");
             *      bool LocalOrgExists;
             *
             *      SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM Organisations WHERE Id = @Id", conn);
             *      CheckLocalDb.Parameters.Add(new SqlParameter("Id", Id));
             *      using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
             *      {
             *          if (reader.Read())
             *          {
             *              LocalOrgExists = true;
             *              AppLog.Info("CREATE ORG - Organisation already exists in local database!");
             *          }
             *          else
             *          {
             *              LocalOrgExists = false;
             *              AppLog.Info("CREATE ORG - Organisation does not exist in local database. Creating organisation on local database");
             *          }
             *      }
             *      if (!LocalOrgExists)
             *      {
             *          SqlCommand CreateOrg = new SqlCommand("INSERT INTO Organisations VALUES(@Id, @Name, " +
             *          "@DateTimeCreated);",
             *          conn);
             *          CreateOrg.Parameters.Add(new SqlParameter("Id", _Id));
             *          CreateOrg.Parameters.Add(new SqlParameter("Name", _Name));
             *          CreateOrg.Parameters.Add(new SqlParameter("DateTimeCreated", _DateTimeCreated));
             *
             *          AffectedRows = CreateOrg.ExecuteNonQuery();
             *
             *          AppLog.Info(String.Format("CREATE ORG - Organisation {0} created on local database successfully. " +
             *              "{1} row(s) affected", _Name, AffectedRows));
             *      }
             *  }
             * }
             * catch (SqlException e)
             * {
             *  _ErrMsg = "Error while creating organisation on local database. Changes were saved online so " +
             *      "no action required. Continuing... ";
             *  AppLog.Error("CREATE ORG - " + _ErrMsg + ": " + e);
             * }*/

            AppLog.Debug("CREATE ORG - Attempting to add organisation to DATA...");

            if (Data.Organisations.GroupBy(x => x.Id).ToString() == this.Id.ToString())
            {
                AppLog.Debug("BEN!!! The organisation already exists!!!");
            }
            else
            {
                AppLog.Debug("BEN!!! The organisation does not exist!!!");
            }

            Data.Organisations.Add(this);
            AppLog.Debug("CREATE ORG - ...Success! Added organisation to DATA");

            AppLog.Info(String.Format("CREATE ORG - Success!"));
            return(true);
        }
示例#12
0
        /// <summary>
        /// 过滤器接受信息 解析byte[]
        /// Filters received data of the specific session into request info.
        /// </summary>
        /// <param name="readBuffer">待读取的缓冲数据.</param>
        /// <param name="offset">这个待读取缓冲中当前接收数据的偏移量</param>
        /// <param name="length">当前接收数据的长度</param>
        /// <param name="toBeCopied">if set to <c>true</c> [to be copied].</param>
        /// <param name="rest">没有被解析的数据的长度</param>
        /// <returns></returns>
        public MyUdpRequestInfo Filter(byte[] readBuffer, int offset, int length, bool toBeCopied, out int rest)
        {
            string result = string.Empty;

            try
            {
                string msg = Encoding.Default.GetString(readBuffer); //读出的数据为16进制

                for (int iCountRecv = 0; iCountRecv < readBuffer.Length; iCountRecv++)
                {
                    string hexOutput = System.Convert.ToString(readBuffer[iCountRecv], 16);
                    int    sLen      = Encoding.Default.GetByteCount(hexOutput);
                    if (sLen == 1)
                    {
                        hexOutput = '0' + hexOutput;
                    }
                    result += hexOutput; //Convert.ToString(byte, 16)把byte转化成十六进制string
                }
                result = result.ToUpper();
            }
            catch (Exception ex)
            {
                rest = 0;
                AppLog.Error(readBuffer + " 16 to string Err " + ex.ToString());
                return(null);
            }

            if (result.Length == 10 || result.Length == 46)
            {
                try
                {
                    rest = 0;
                    var    body       = readBuffer.Skip(offset).Take(length).ToArray();
                    string privateKey = string.Empty;
                    string sesssionId = string.Empty; //machineCode 当成sessionId

                    WrapReaderData termianlData = new WrapReaderData();
                    if (result.Length == 10)
                    {
                        termianlData.TranType = 10;
                        string str10 = result;// HandleUdpUtils.Ascii2Str(body);
                        privateKey = TermianlID_10(str10);
                        AppLog.Info(result + " T_DATA 10 Code " + privateKey);
                        termianlData.ReaderID   = privateKey;
                        sesssionId              = "Heart_ID=" + privateKey;
                        termianlData.sesssionId = sesssionId;
                    }
                    else if (result.Length == 46)
                    {
                        string str46 = result;// HandleUdpUtils.Ascii2Str(body);
                        termianlData = TermianlID_46(str46);
                        AppLog.Info(result + " C_DATA 46 Code " + termianlData.allParams);
                        termianlData.TranType = 46;
                        if (termianlData.TranResult != 0)
                        {
                            rest = 0;
                            return(null);
                        }
                        privateKey = termianlData.PID;
                        sesssionId = "Counter_ID=" + privateKey;
                        termianlData.sesssionId = sesssionId;
                    }
                    else
                    {
                        string strOther = result;// HandleUdpUtils.Ascii2Str(body);
                        termianlData.TranType = 99;
                        AppLog.Info(result + " TC_DATA  1046 Code " + termianlData);
                        if (termianlData.TranResult != 0)
                        {
                            rest = 0;
                            return(null);
                        }
                        privateKey = "Error99";
                        sesssionId = "Error_ID=" + privateKey;
                        termianlData.sesssionId = sesssionId;
                        termianlData.allParams  = strOther;
                        Reset();
                    }
                    return(new MyUdpRequestInfo(privateKey, sesssionId, termianlData)
                    {
                        TerminalCounterData = termianlData
                    });


                    ///当你在接收缓冲区中找到一条完整的请求时,你必须返回一个你的请求类型的实例.
                    ///当你在接收缓冲区中没有找到一个完整的请求时, 你需要返回 NULL.
                    ///当你在接收缓冲区中找到一条完整的请求, 但接收到的数据并不仅仅包含一个请求时,设置剩余数据的长度到输出变
                    ///量 "rest".SuperSocket 将会检查这个输出参数 "rest", 如果它大于 0, 此 Filter 方法 将会被再次执行,
                    ///参数 "offset" 和 "length" 会被调整为合适的值.
                }
                catch (Exception ex)
                {
                    rest = 0;
                    AppLog.Error(readBuffer + " 10 or 46 Code " + ex.ToString());
                    return(null);
                }
            }
            //else if(result.Length >10  && result.Length < 30)
            //{
            //    rest = 5;
            //    string msg = Encoding.Default.GetString(readBuffer);
            //    return new MyUdpRequestInfo(5.ToString(), "Test_session",null) { Parameters = msg.Split(' ') };
            //}
            else
            {
                AppLog.Error(readBuffer + " Get String turn Error not 10 or 46 " + result.ToString());
                rest = 0;
                return(null);
            }
        }
示例#13
0
 public void write()
 {
     AppLog.Error("动态实例化调用接口");
 }
示例#14
0
        public bool Create()
        {
            AppLog.Info("CREATE PRODUCT - Starting...");

            //Checks that data is valid before attempting upload
            AppLog.Info("CREATE PRODUCT - Validating...");
            if (!Validate())
            {
                AppLog.Info("CREATE PRODUCT - Product failed validation");
                return(false);
            }
            AppLog.Info("CREATE PRODUCT - Product validated successfully");

            if (!Data.OfflineMode)
            {
                AppLog.Info("CREATE PRODUCT - Attempting to create product on online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("CREATE PRODUCT - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("CREATE PRODUCT - Connection to online database opened successfully");

                        //This is a check to see weather the product already exists on the database. Obviously
                        //if it's already there, it doesn't need creating again, but this might be called
                        //if for example the product did not exist on the Online database, so the Create() function
                        //needed to be able to account for that.
                        AppLog.Info("CREATE PRODUCT - Checking that product doesn't already exist on Online database");
                        bool OnlineProductExists;

                        SqlCommand CheckOnlineDb = new SqlCommand("SELECT * FROM t_Products WHERE Id = @Id", conn);
                        CheckOnlineDb.Parameters.Add(new SqlParameter("Id", Id));
                        using (SqlDataReader reader = CheckOnlineDb.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                OnlineProductExists = true;
                                AppLog.Info("CREATE PRODUCT - Product already exists in online database!");
                            }
                            else
                            {
                                OnlineProductExists = false;
                                AppLog.Info("CREATE PRODUCT - Product does not exist in online database. Creating product on online database");
                            }
                        }
                        if (!OnlineProductExists)
                        {
                            SqlCommand CreateProduct = new SqlCommand("INSERT INTO t_Products VALUES(@Id, @OrgId, @Name);",
                                                                      conn);
                            CreateProduct.Parameters.Add(new SqlParameter("Id", _Id));
                            CreateProduct.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                            CreateProduct.Parameters.Add(new SqlParameter("Name", _Name));

                            CreateProduct.ExecuteNonQuery();

                            AppLog.Info(String.Format("CREATE PRODUCT - Product {0} created on online database successfully",
                                                      Name));
                        }
                    }
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while creating product on online database";
                    AppLog.Error(_ErrMsg + ": " + e);
                    return(false);
                }
            }
            else
            {
                AppLog.Info(String.Format("CREATE PRODUCT - Offline mode is ON. Skipping create product on" +
                                          "online database"));
            }

            /*try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("CREATE PRODUCT - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("CREATE PRODUCT - Connection to local database opened successfully");
             *
             *      //This is a check to see weather the product already exists on the database. Obviously
             *      //if it's already there, it doesn't need creating again, but this might be called
             *      //if for example the product did not exist on the local database, so the Create() function
             *      //needed to be able to account for that.
             *      AppLog.Info("CREATE PRODUCT - Checking that product doesn't already exist on local database");
             *      bool LocalProductExists;
             *
             *      SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM Products WHERE Id = @Id", conn);
             *      CheckLocalDb.Parameters.Add(new SqlParameter("Id", Id));
             *      using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
             *      {
             *          if (reader.Read())
             *          {
             *              LocalProductExists = true;
             *              AppLog.Info("CREATE PRODUCT - Product already exists in local database!");
             *          }
             *          else
             *          {
             *              LocalProductExists = false;
             *              AppLog.Info("CREATE PRODUCT - Product does not exist in local database. Creating product on local database");
             *          }
             *      }
             *      if (!LocalProductExists)
             *      {
             *          SqlCommand CreateProduct = new SqlCommand("INSERT INTO Products VALUES(@Id, @OrgId, @Name)", conn);
             *          CreateProduct.Parameters.Add(new SqlParameter("Id", _Id));
             *          CreateProduct.Parameters.Add(new SqlParameter("OrgId", _OrgId));
             *          CreateProduct.Parameters.Add(new SqlParameter("Name", _Name));
             *
             *          CreateProduct.ExecuteNonQuery();
             *
             *          Uploaded = true;
             *          AppLog.Info(String.Format("CREATE PRODUCT - Product {0} created on local database successfully",
             *              Name));
             *      }
             *  }
             * }
             * catch (SqlException e)
             * {
             *  _ErrMsg = "Error while creating product on local database";
             *  AppLog.Error(_ErrMsg + ": " + e);
             *  return false;
             * }*/


            AppLog.Debug("CREATE PRODUCT - Attempting to add product to DATA...");
            Data.Products.Add(this);
            AppLog.Debug("CREATE PRODUCT - ...Success! Added product to DATA");
            AppLog.Info("CREATE PRODUCT - Success!");
            return(true);
        }
示例#15
0
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="obj"></param>
        private void ReceiveMessage(object obj)
        {
            IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0);

            while (true)
            {
                try
                {
                    //读取报文
                    byte[] bytRecv = udpcRecv.Receive(ref remoteIpep);
                    if (bytRecv.Length > 0)
                    {
                        //byte[] message = new byte[bytRecv.Length];
                        //Array.Copy(bytRecv, message, bytRecv.Length);
                        if ((bytRecv[0]).ToString("X2") != "")
                        {
                            int    i       = 0;
                            Action action1 = () =>
                            {
                                //数据长度有效性判断
                                if (bytRecv.Length >= 13)
                                {
                                    for (int msgcount = 0; msgcount < bytRecv.Length / 13; msgcount++)
                                    {
                                        StringBuilder strbd = new StringBuilder();
                                        try {
                                            strbd.Append(bytRecv[1].ToString("X2")).Append(bytRecv[2].ToString("X2")).Append(bytRecv[3].ToString("X2")).Append(bytRecv[4].ToString("X2"));
                                            switch (strbd.ToString())
                                            {
                                            //远程控制器 EPS 命令
                                            case "1801B0C0":
                                                //异或校验
                                                byte VerifyByte = bytRecv[5];
                                                for (int msgi = 6; msgi < bytRecv.Length - 1; msgi++)
                                                {
                                                    if (bytRecv[msgi].ToString() == "0")
                                                    {
                                                        continue;
                                                    }
                                                    VerifyByte = (byte)(VerifyByte ^ bytRecv[msgi]);
                                                }
                                                //校验通过
                                                if (VerifyByte.ToString("X2") == bytRecv[bytRecv.Length - 1].ToString("X2"))
                                                {
                                                    //3.方向盘角度
                                                    if (is16Number(bytRecv[8].ToString("X2")))
                                                    {
                                                        double corner = (Convert.ToDouble(Convert.ToInt16(((bytRecv[8]).ToString("X2") + bytRecv[9].ToString("X2")), 16)) / 10) - 1080;
                                                        //3.车轮角度
                                                        if (corner >= -694.35 && corner <= 694.35)
                                                        {
                                                            double wheelcorner = Math.Round(corner / 15.43, 1);
                                                            textBlock_corner.Text = wheelcorner + "°";
                                                            double width   = imgwheeltopleft.ActualWidth;
                                                            double height  = imgwheeltopleft.ActualHeight;
                                                            double width2  = imgwheeltopright.ActualWidth;
                                                            double height2 = imgwheeltopright.ActualHeight;
                                                            imgwheelmiddle.Margin = tkwheelmiddle; imgwheeltopleft.Margin = tkwheeltopleft; imgwheeltopright.Margin = tkwheeltopright;
                                                            if (wheelcorner < -10 && tkwheelmiddle != null)
                                                            {
                                                                imgwheelmiddle.Margin = new Thickness(tkwheelmiddle.Left, tkwheelmiddle.Top + 10, tkwheelmiddle.Right, tkwheelmiddle.Bottom - 10); imgwheeltopleft.Margin = new Thickness(tkwheeltopleft.Left, tkwheeltopleft.Top + 10, tkwheeltopleft.Right, tkwheeltopleft.Bottom - 10);
                                                            }
                                                            else if (wheelcorner > 10 && tkwheeltopleft != null)
                                                            {
                                                                imgwheeltopleft.Margin = new Thickness(tkwheeltopleft.Left, tkwheeltopleft.Top - 10, tkwheeltopleft.Right, tkwheeltopleft.Bottom + 10);
                                                            }
                                                            imgwheeltopleft.LayoutTransform  = new System.Windows.Media.RotateTransform(wheelcorner, width / 2, height / 2);
                                                            imgwheeltopright.LayoutTransform = new System.Windows.Media.RotateTransform(wheelcorner, width2 / 2, height2 / 2);
                                                        }
                                                    }
                                                }
                                                break;

                                            //行车状态
                                            case "1804A0B0":
                                                //异或校验
                                                byte VerifyByte2 = bytRecv[5];
                                                for (int msgi = 6; msgi < bytRecv.Length - 1; msgi++)
                                                {
                                                    if (bytRecv[msgi].ToString() == "0")
                                                    {
                                                        continue;
                                                    }
                                                    VerifyByte2 = (byte)(VerifyByte2 ^ bytRecv[msgi]);
                                                }
                                                //校验通过
                                                if (VerifyByte2.ToString("X2") == bytRecv[bytRecv.Length - 1].ToString("X2"))
                                                {
                                                    //13.档位状态
                                                    StringBuilder sb          = new StringBuilder();
                                                    int           drivestatus = Convert.ToInt16(sb.Append(((bytRecv[5] & 32) == 32 ? 1 : 0).ToString()).Append(((bytRecv[5] & 16) == 16 ? 1 : 0).ToString()).Append(((bytRecv[5] & 8) == 8 ? 1 : 0).ToString()).Append(((bytRecv[5] & 4) == 4 ? 1 : 0).ToString()).ToString(), 2);
                                                    if (drivestatus >= 0 && drivestatus <= 3)
                                                    {
                                                        switch (drivestatus)
                                                        {
                                                        case 0:
                                                            imgdrivestatus.Source = new BitmapImage(new Uri(@"img/N.png", UriKind.Relative));
                                                            break;

                                                        case 1:
                                                            imgdrivestatus.Source = new BitmapImage(new Uri(@"img/D.png", UriKind.Relative));
                                                            break;

                                                        case 2:
                                                            imgdrivestatus.Source = new BitmapImage(new Uri(@"img/R.png", UriKind.Relative));
                                                            break;

                                                        case 3:
                                                            imgdrivestatus.Source = new BitmapImage(new Uri(@"img/P.png", UriKind.Relative));
                                                            break;

                                                        default:
                                                            imgdrivestatus.Source = null;
                                                            break;
                                                        }
                                                    }
                                                    //6.电机转速
                                                    StringBuilder sb2 = new StringBuilder();
                                                    if (is16Number(bytRecv[6].ToString("X2")) && is16Number(bytRecv[7].ToString("X2")))
                                                    {
                                                        double speed = (Convert.ToDouble(Convert.ToInt16(sb2.Append(bytRecv[6].ToString("X2")).Append(bytRecv[7].ToString("X2")).ToString(), 16) - 15000) / 1000);
                                                        if (speed > 0 && speed <= 7.0)
                                                        {
                                                            textBlock_imgenginespeed.Text = speed.ToString("f1");
                                                            progressbar_left.Value        = speed * 10;
                                                        }
                                                        else
                                                        {
                                                            textBlock_imgenginespeed.Text = speed.ToString("f1");
                                                            progressbar_left.Value        = 0;
                                                        }
                                                    }
                                                    //15.电机扭距
                                                    StringBuilder sb3 = new StringBuilder();
                                                    if (is16Number(bytRecv[8].ToString("X2")) && is16Number(bytRecv[9].ToString("X2")))
                                                    {
                                                        int mt = Convert.ToInt16(sb3.Append(bytRecv[8].ToString("X2")).Append(bytRecv[9].ToString("X2")).ToString(), 16) - 5000;
                                                        if (mt >= -5000 && mt <= 5000)
                                                        {
                                                            textBlock_MotorTorque.Text = mt.ToString() + " Nm";
                                                        }
                                                        else
                                                        {
                                                            textBlock_MotorTorque.Text = " Nm";
                                                        }
                                                    }
                                                }
                                                break;

                                            //车辆状态1
                                            case "1806A0B0":
                                                //2.自驾控制模式
                                                int sw = Convert.ToInt16(((bytRecv[5] & 2) == 2 ? 1 : 0).ToString() + ((bytRecv[5] & 0) == 0 ? 1 : 0).ToString(), 2);
                                                if (sw >= 0 && sw <= 3)
                                                {
                                                    switch (sw)
                                                    {
                                                    case 0:
                                                        label_Mode.Content       = EnumClass.description(EnumClass.ControlModel.ManualDriving);
                                                        label_ChangeMode.Content = "切换到" + EnumClass.description(EnumClass.ControlModel.AutoPilot);
                                                        break;

                                                    case 1:
                                                        label_Mode.Content       = EnumClass.description(EnumClass.ControlModel.AutoPilot);
                                                        label_ChangeMode.Content = "切换到" + EnumClass.description(EnumClass.ControlModel.ManualDriving);
                                                        break;

                                                    case 2:
                                                        label_Mode.Content       = EnumClass.description(EnumClass.ControlModel.RemoteDriving);
                                                        label_ChangeMode.Content = "切换到" + EnumClass.description(EnumClass.ControlModel.AutoPilot);
                                                        break;

                                                    case 3:
                                                        label_Mode.Content       = EnumClass.description(EnumClass.ControlModel.LongDistanceDriving);
                                                        label_ChangeMode.Content = "切换到" + EnumClass.description(EnumClass.ControlModel.ManualDriving);
                                                        break;

                                                    default:
                                                        label_Mode.Content       = EnumClass.description(EnumClass.ControlModel.AutoPilot);
                                                        label_ChangeMode.Content = "切换到" + EnumClass.description(EnumClass.ControlModel.ManualDriving);
                                                        break;
                                                    }
                                                }
                                                //14.车门状态
                                                int doorstatus = Convert.ToInt16(((bytRecv[5] & 4) == 4 ? 1 : 0).ToString(), 2);
                                                if (doorstatus == 1)
                                                {
                                                    textBlock_DoorStatus.Text = "关";
                                                }
                                                else if (doorstatus == 0)
                                                {
                                                    textBlock_DoorStatus.Text = "开";
                                                }
                                                //10.车辆速度 取绝对值
                                                if (isNumber(bytRecv[7].ToString()))
                                                {
                                                    int speed = Convert.ToInt16(bytRecv[7].ToString()) - 50;
                                                    if (speed >= -50 && speed <= 250)
                                                    {
                                                        textBlock_Speed.Text = Math.Abs(speed).ToString();
                                                    }
                                                }

                                                if (isNumber(bytRecv[8].ToString()))
                                                //7.SOC电池百分比
                                                {
                                                    double eq = Convert.ToInt16(bytRecv[8].ToString()) * 0.5;
                                                    if (eq > 0 && eq <= 100.0)
                                                    {
                                                        textBlock_imgElectricQuantity.Text = eq.ToString("f0");
                                                        progressbar_right.Value            = Math.Round(eq * 10 / 13, 2);
                                                    }
                                                    else if (eq > 100 && eq <= 125.0)
                                                    {
                                                        textBlock_imgElectricQuantity.Text = eq.ToString("f0");
                                                        progressbar_right.Value            = Math.Round(1000.0 / 13, 2);
                                                    }
                                                    else
                                                    {
                                                        textBlock_imgElectricQuantity.Text = eq.ToString("f0");
                                                        progressbar_right.Value            = 0;
                                                    }
                                                }
                                                break;

                                            //车辆状态2
                                            case "1810A0B0":
                                                //11.电池电压
                                                if (is16Number(bytRecv[5].ToString("X2") + bytRecv[6].ToString("X2")))
                                                {
                                                    int bv = Convert.ToInt16(bytRecv[5].ToString("X2") + bytRecv[6].ToString("X2"), 16);
                                                    if (bv >= 0 && bv <= 800)
                                                    {
                                                        textBlock_BatteryVoltage.Text = bv * 0.2 + " V";
                                                    }
                                                }
                                                //12.电池电流
                                                if (is16Number(bytRecv[7].ToString("X2") + bytRecv[8].ToString("X2")))
                                                {
                                                    int bc = Convert.ToInt16(bytRecv[7].ToString("X2") + bytRecv[8].ToString("X2"), 16);
                                                    if (bc >= 0 && bc <= 65000)
                                                    {
                                                        textBlock_BatteryCurrent.Text = (bc * 0.02) - 500 + " A";
                                                    }
                                                }
                                                break;

                                            //车辆状态3
                                            case "1811A0B0":
                                                //9.电池温度,取电池组最高温度
                                                if (is16Number(bytRecv[5].ToString("X2")))
                                                {
                                                    int bTEMP = Convert.ToInt16(bytRecv[5].ToString("X2"), 16) - 40;
                                                    if (bTEMP >= -40 && bTEMP <= 215)
                                                    {
                                                        textBlock_BatteryTEMP.Text = bTEMP.ToString() + " ℃";
                                                    }
                                                }
                                                //8.电机温度
                                                if (is16Number(bytRecv[10].ToString()))
                                                {
                                                    int mTEMP = Convert.ToInt16(bytRecv[10].ToString("X2"), 16) - 40;
                                                    if (mTEMP >= -40 && mTEMP <= 215)
                                                    {
                                                        textBlock_MotorTEMP.Text = mTEMP.ToString() + " ℃";
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            AppLog.Error(e.Message);
                                        }
                                    }
                                }
                            };
                            textBlock_Speed.Dispatcher.BeginInvoke(action1);
                            // 如果不设置等待,整个程序死循环
                            Thread.Sleep(20);
                            i++;
                            if (i > 100)
                            {
                                i = 0;
                            }
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    AppLog.Error(e.Message);
                    continue;
                }
            }
        }
示例#16
0
        public bool Delete()
        {
            AppLog.Info("DELETE ORG - Starting...");
            AppLog.Info("DELETE ORG - Organisation's Id: " + Id);
            AppLog.Info("DELETE ORG - Organisation's Name: " + Name);

            int AffectedRows = 0;

            if (Data.OfflineMode)
            {
                _ErrMsg = "Cannot delete organisations while in offline mode";
                AppLog.Info(String.Format("DELETE ORG - Organisation {0} was not deleted because offline mode is on", _Name));
                return(false);
            }
            //If offline mode is off, first try deleting from online database

            /*AppLog.Info("DELETE ORG - Attempting to delete organisation from local database...");
             * try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("DELETE ORG - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("DELETE ORG - Connection to local database opened successfully");
             *
             *      AppLog.Info("DELETE ORG - Attempting to delete org members from local database...");
             *      SqlCommand DeleteOrgMembers = new SqlCommand("DELETE FROM OrgMembers WHERE OrgId = @OrgId;",
             *          conn);
             *      DeleteOrgMembers.Parameters.Add(new SqlParameter("OrgId", _Id));
             *      DeleteOrgMembers.ExecuteNonQuery();
             *      AppLog.Info("DELETE ORG - Deleted org members from local database successfully");
             *
             *      AppLog.Info("DELETE ORG - Attempting to delete organisation from local database...");
             *      SqlCommand DeleteOrg = new SqlCommand("DELETE FROM Organisations WHERE Id = @Id;", conn);
             *      DeleteOrg.Parameters.Add(new SqlParameter("Id", _Id));
             *      AppLog.Info("DELETE ORG - Deleted organisation from local database successfully");
             *
             *      AffectedRows = DeleteOrg.ExecuteNonQuery();
             *  }
             *  AppLog.Info(String.Format("DELETE ORG - Organisation {0} deleted from local database successfully. " +
             *  "{1} row(s) affected", _Name, AffectedRows));
             * }
             * catch (SqlException e)
             * {
             *  _ErrMsg = "Error while deleting organisation from local database";
             *  AppLog.Error("DELETE ORG - " + _ErrMsg + ": " + e);
             *  return false;
             * }*/


            AffectedRows = 0;

            //If deleted from online database successfully, try local database
            AppLog.Info("DELETE ORG - Attempting to delete organisation from online database...");
            try
            {
                using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                {
                    AppLog.Info("DELETE ORG - Attempting to open connection to online database...");
                    conn.Open();
                    AppLog.Info("DELETE ORG - Connection to online database opened successfully");

                    AppLog.Info("DELETE ORG - Attempting to delete org members from online database...");
                    SqlCommand DeleteOrgMembers = new SqlCommand("DELETE FROM t_OrgMembers WHERE OrgId = @OrgId;",
                                                                 conn);
                    DeleteOrgMembers.Parameters.Add(new SqlParameter("OrgId", _Id));
                    DeleteOrgMembers.ExecuteNonQuery();
                    AppLog.Info("DELETE ORG - Deleted org members from online database successfully");

                    AppLog.Info("DELETE ORG - Attempting to delete organisation from online database...");
                    SqlCommand DeleteOrg = new SqlCommand("DELETE FROM t_Organisations WHERE Id = @Id;", conn);
                    DeleteOrg.Parameters.Add(new SqlParameter("Id", _Id));

                    AffectedRows = DeleteOrg.ExecuteNonQuery();
                    AppLog.Info("DELETE ORG - Deleted organisation from online database successfully");
                }
                AppLog.Info(String.Format("DELETE ORG - Organisation {0} deleted from online database successfully. " +
                                          "{1} row(s) affected", _Name, AffectedRows));
            }
            catch (SqlException e)
            {
                _ErrMsg = "Error while deleting organisation from online database";
                AppLog.Error("DELETE ORG - " + _ErrMsg + ": " + e);
                return(false);
            }
            return(true);
        }
示例#17
0
        public void init(string Messages)
        {
            try
            {
                if (!string.IsNullOrEmpty(Messages))
                {
                }
                else
                {
                    //星期显示
                    textBlock_week.Text = DateTime.Now.ToString("dddd");
                    //日期显示
                    textBlock_date.Text = DateTime.Now.ToString("D");
                    //时间显示
                    textBlock_Time.Text = DateTime.Now.ToString("t");

                    //模式
                    label_Mode.Content       = "自动模式";
                    label_ChangeMode.Content = "切换到手动模式";

                    //车轮转角
                    double corner = 155.843 / 15.43;
                    textBlock_corner.Text = corner + " °";

                    //360环视视频
                    //初始化配置,指定引用库
                    try
                    {
                        myVideo.MediaPlayer.VlcLibDirectoryNeeded += OnVlcControlNeedsLibDirectory;
                        myVideo.MediaPlayer.EndInit();
                        string[] arguments = { ":network-caching=90" };
                        myVideo.MediaPlayer.Play(new Uri("rtsp://172.16.5.168:/6"), arguments);
                        //forvideos();
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    //网络延时
                    textBlock_networkdelay.Text = "30 ms";

                    //电机转速
                    textBlock_imgenginespeed.Text = "3";

                    //SOC电池百分比
                    textBlock_imgElectricQuantity.Text = "90";

                    //电机温度
                    textBlock_MotorTEMP.Text = "30" + " ℃";

                    //电池温度
                    textBlock_BatteryTEMP.Text = "60" + " ℃";

                    //车辆速度
                    textBlock_Speed.Text = "66";

                    //档位状态
                    imgdrivestatus.Source = new BitmapImage(new Uri(@"img/D.png", UriKind.Relative));

                    //车辆速度
                    textBlock_Speed.Text = "66";

                    //行驶时间
                    textBlock_BatteryVoltage.Text = "72" + " V";

                    //行驶时间
                    textBlock_BatteryCurrent.Text = "48" + " A";

                    //车门状态
                    textBlock_DoorStatus.Text = "开";
                    //更新
                    Thread_textblockupdate();
                    //保存图片位置
                    tkwheelmiddle   = imgwheelmiddle.Margin;
                    tkwheeltopleft  = imgwheeltopleft.Margin;
                    tkwheeltopright = imgwheeltopright.Margin;
                }
            }
            catch (Exception e)
            {
                AppLog.Error(e.Message);
            }
        }
示例#18
0
        private async void Process()
        {
            while (!Queue.IsEmpty)
            {
                LogDebug("Attempting to process queued messages...");

                bool success = false;
                if (!IsClosed)
                {
                    CFXEnvelope[] messages = Queue.PeekMany(AmqpCFXEndpoint.MaxMessagesPerTransmit.Value);
                    if (messages != null && messages.Any())
                    {
                        try
                        {
                            Message msg = AmqpUtilities.MessageFromEnvelopes(messages, AmqpCFXEndpoint.Codec.Value);
                            SenderLink.Send(msg);
                            success = true;
                        }
                        catch (Exception ex)
                        {
                            LogError(ex);
                            AppLog.Error(ex);
                        }

                        if (success)
                        {
                            Queue.Dequeue(messages.Length);
                        }

                        int remainingCount = Queue.Count;
                        if (success)
                        {
                            LogDebug($"{messages.Length} messages transmitted.  {Queue.Count} messages remaining in spool.");
                        }
                        else
                        {
                            LogDebug($"Messages NOT transmitted.  {Queue.Count} messages remaining in spool.");
                        }

                        if (remainingCount > 90)
                        {
                            LogWarn(string.Format("Warning.  Spool has {0} buffered messages.", remainingCount));
                        }
                    }
                }
                else
                {
                    int remainingCount = Queue.Count;
                    if (remainingCount > 0)
                    {
                        LogWarn($"Connection Bad or Error.  {Queue.Count} messages remaining in spool.");
                    }
                    await Task.Delay(Convert.ToInt32(AmqpCFXEndpoint.ReconnectInterval.Value.TotalMilliseconds));
                }
            }

            lock (this)
            {
                isProcessing = false;
            }

            await Task.Yield();
        }
示例#19
0
 public void test()
 {
     AppLog.Error("这是第一个日志");
 }
示例#20
0
 private void LogError(Exception ex)
 {
     AppLog.Error($"sender-{Address}  {ex.Message}");
     AppLog.Error(ex);
 }
示例#21
0
        public bool Update()
        {
            AppLog.Info("UPDATE ORGMEMBER - Starting...");
            AppLog.Info("UPDATE ORGMEMBER - OrgMember's Org's Id: " + _OrgId);
            AppLog.Info("UPDATE ORGMEMBER - OrgMember's User's Id: " + _UserId);
            AppLog.Info("UPDATE ORGMEMBER - OrgMember's User's FullName: " + MyUser.FullName);
            AppLog.Info("UPDATE ORGMEMBER - OrgMember's User's Username: "******"Cannot update organisation members while in offline mode";
                AppLog.Info(String.Format("UPDATE ORGMEMBER - Organisation member {0} was not updated because " +
                                          "offline mode is on", MyUser.Username));
                return(false);
            }

            /*
             * //Creates a backup of the organisation member (from online database) before edit is attempted
             * AppLog.Info("UPDATE ORGMEMBER - Creating a backup of the current organisation member...");
             * AppLog.Break();
             * AppLog.Info(@"////////// Backup \\\\\\\\\\"); //This is just to make it display in the log
             * OrgMember BackupOrgMember = new OrgMember(_MyUser, MyOrg);               //a bit nicer
             * if (!BackupOrgMember.Get())
             * {
             *  _ErrMsg = "Error while backing up organisation member";
             *  AppLog.Error(_ErrMsg);
             *  return false;
             * }
             *
             * AppLog.Info(@"//////////////\\\\\\\\\\\\\\");
             * AppLog.Break();
             * AppLog.Info("UPDATE ORGMEMBER - Organisation member backed up successfully!");
             */

            int AffectedRows = 0;

            AppLog.Info("UPDATE ORGMEMBER - Attempting to update organisation member on online database...");
            try
            {
                using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                {
                    AppLog.Info("UPDATE ORGMEMBER - Attempting to open connection to online database...");
                    conn.Open();
                    AppLog.Info("UPDATE ORGMEMBER - Connection to online database opened successfully");

                    SqlCommand UpdateOrgMember = new SqlCommand("UPDATE t_OrgMembers SET AccessLevel = @AccessLevel " +
                                                                "WHERE OrgId = @OrgId AND UserId = @UserId;", conn);
                    UpdateOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                    UpdateOrgMember.Parameters.Add(new SqlParameter("UserId", _UserId));
                    UpdateOrgMember.Parameters.Add(new SqlParameter("AccessLevel", _AccessLevel));

                    AffectedRows = UpdateOrgMember.ExecuteNonQuery();
                }
                AppLog.Info(String.Format("UPDATE ORGMEMBER - User {0} updated on online database " +
                                          "successfully. {1} row(s) affected", MyUser.FullName, AffectedRows));
            }
            catch (SqlException e)
            {
                _ErrMsg = "Error while updating organisation member on online database";
                AppLog.Error("UPDATE ORGMEMBER - " + _ErrMsg + ": " + e);
                return(false);
            }

            AffectedRows = 0;

            AppLog.Info("UPDATE ORGMEMBER - Attempting to update organisation member on local database...");
            //If online databaase was updated successfully, try local database

            /*try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("UPDATE ORGMEMBER - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("UPDATE ORGMEMBER - Connection to local database opened successfully");
             *
             *      SqlCommand UpdateOrgMember = new SqlCommand("UPDATE OrgMembers SET AccessLevel = @AccessLevel " +
             *          "WHERE OrgId = @OrgId AND UserId = @UserId;", conn);
             *      UpdateOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
             *      UpdateOrgMember.Parameters.Add(new SqlParameter("UserId", MyUser.Id));
             *      UpdateOrgMember.Parameters.Add(new SqlParameter("AccessLevel", _AccessLevel));
             *
             *      AffectedRows = UpdateOrgMember.ExecuteNonQuery();
             *  }
             *  AppLog.Info(String.Format("UPDATE ORGMEMBER - User {0} updated on local database " +
             *  "successfully. {1} row(s) affected", MyUser.FullName, AffectedRows));
             * }
             * catch (SqlException e)
             * {
             *  //Need to revert changes here
             *
             *  //AppLog.Break();
             *  //AppLog.Info(@"////////// Restore \\\\\\\\\\");
             *  //
             *  //AppLog.Info("UPDATE ORGMEMBER - Attempting to delete organisation member...");
             *  //
             *  //if (!Delete())
             *  //{
             *  //    _ErrMsg = "UPDATE ORGMEMBER - Error while trying to delete organisation member";
             *  //    AppLog.Info(_ErrMsg);
             *  //    return false;
             *  //}
             *  //AppLog.Info("UPDATE ORGMEMBER - Organisation member deleted successfully!");
             *  //
             *  //AppLog.Info("UPDATE ORGMEMBER - Restoring values from backup...");
             *  //this._MyOrg = BackupOrgMember.MyOrg;
             *  //this._MyUser = BackupOrgMember.MyUser;
             *  //this._DateTimeJoined = BackupOrgMember.DateTimeJoined;
             *  //this._AccessLevel = BackupOrgMember.AccessLevel;
             *  //this._ErrMsg = BackupOrgMember.ErrMsg;
             *  //AppLog.Info("UPDATE ORGMEMBER - Values restored successfully!");
             *  //AppLog.Info("UPDATE ORGMEMBER - Attempting upload...");
             *  //if (!Delete())
             *  //{
             *  //    _ErrMsg = "UPDATE ORGMEMBER - Error while trying to upload organisation member";
             *  //    AppLog.Info(_ErrMsg);
             *  //    return false;
             *  //}
             *  //AppLog.Info("UPDATE ORGMEMBER - Organisation member uploaded successfully!");
             *
             *  //AppLog.Info(@"///////////////\\\\\\\\\\\\\\\");
             *
             *  //_ErrMsg = "Error while updating organisation member on local database. Changes have been reverted.";
             *  //AppLog.Error(_ErrMsg + ": " + e);
             *  //return false;
             *
             *
             *  _ErrMsg = "Error while updating organisation member on local database. Changes were saved online " +
             *      "so no action required. Continuing...";
             *  AppLog.Error("UPDATE ORGMEMBER - " + _ErrMsg + ": " + e);
             * }*/
            AppLog.Info(String.Format("UPDATE ORGMEMBER - Success!"));
            return(true);
        }
示例#22
0
        internal bool Update()
        {
            AppLog.Info("UPDATE ASSIGNEE - Starting...");

            if (!Data.OfflineMode)
            {
                AppLog.Info("UPDATE ASSIGNEE - Offline mode is OFF");

                AppLog.Info("UPDATE ASSIGNEE - Attempting to update assignee on online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("UPDATE ASSIGNEE - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("UPDATE ASSIGNEE - Connection to online database opened successfully");

                        SqlCommand UpdateAssignee = new SqlCommand("UPDATE t_Assignees SET TimeSpent = " +
                                                                   "@TimeSpent, AccessLevel = @AccessLevel WHERE BugId = @BugId AND UserId = @UserId;", conn);
                        UpdateAssignee.Parameters.Add(new SqlParameter("BugId", _BugId));
                        UpdateAssignee.Parameters.Add(new SqlParameter("UserId", _UserId));
                        UpdateAssignee.Parameters.Add(new SqlParameter("TimeSpent", _TimeSpent.Ticks));
                        UpdateAssignee.Parameters.Add(new SqlParameter("Accesslevel", _AccessLevel));

                        UpdateAssignee.ExecuteNonQuery();
                    }
                    Uploaded = true;
                    AppLog.Info(String.Format("UPDATE ASSIGNEE - Assignee {0} updated on online database " +
                                              "successfully", MyUser.Username));
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while updating assignee on online database";
                    AppLog.Error("UPDATE ASSIGNEE - " + _ErrMsg + ": " + e);;
                    return(false);
                }
            }
            else
            {
                AppLog.Info("UPDATE ASSIGNEE - Offline mode is ON. Skipping update assignee on online database");
            }

            /*AppLog.Info("UPDATE ASSIGNEE - Attempting to update assignee on local database...");
             * try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("UPDATE ASSIGNEE - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("UPDATE ASSIGNEE - Connection to local database opened successfully");
             *
             *      SqlCommand UpdateAssignee = new SqlCommand("UPDATE Assignees SET TimeSpent = @TimeSpent, " +
             *          "AccessLevel = @AccessLevel WHERE BugId = @BugId AND UserId = @UserId;", conn);
             *      UpdateAssignee.Parameters.Add(new SqlParameter("BugId", _BugId));
             *      UpdateAssignee.Parameters.Add(new SqlParameter("UserId", _UserId));
             *      UpdateAssignee.Parameters.Add(new SqlParameter("TimeSpent", _TimeSpent.Ticks));
             *      UpdateAssignee.Parameters.Add(new SqlParameter("Accesslevel", _AccessLevel));
             *
             *      UpdateAssignee.ExecuteNonQuery();
             *  }
             *  AppLog.Info(String.Format("UPDATE ASSIGNEE - Assignee {0} updated on local database successfully",
             *  MyUser.FullName));
             * }
             * catch (SqlException e)
             * {
             *  if (Data.OfflineMode)
             *  {
             *      _ErrMsg = "Error while updating assignee on local database. Changes were not saved.";
             *      AppLog.Error(_ErrMsg + ": " + e);
             *      return false;
             *  }
             * }*/
            AppLog.Info("UPDATE ASSIGNEE - Success!");
            return(true);
        }
示例#23
0
        public bool Delete()
        {
            AppLog.Info("DELETE ORGMEMBER - Starting...");
            AppLog.Info("DELETE ORGMEMBER - OrgMember's Org's Id: " + _OrgId);
            AppLog.Info("DELETE ORGMEMBER - OrgMember's User's Id: " + _UserId);
            AppLog.Info("DELETE ORGMEMBER - OrgMember's User's FullName: " + MyUser.FullName);
            AppLog.Info("DELETE ORGMEMBER - OrgMember's User's Username: "******"Cannot delete organisation members while in offline mode";
                AppLog.Info(String.Format("CREATE ORGMEMBER - Organisation member {0} was not deleted because " +
                                          "offline mode is on", MyUser.Username));
                return(false);
            }

            int AffectedRows = 0;

            //If offline mode is off, first try deleting from online database
            AppLog.Info("DELETE USER - Attempting to delete organisation member from online database...");
            try
            {
                using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                {
                    AppLog.Info("CREATE ORGMEMBER - Attempting to open connection to online database...");
                    conn.Open();
                    AppLog.Info("CREATE ORGMEMBER - Connection to online database opened successfully");

                    SqlCommand DeleteOrgMember = new SqlCommand("DELETE FROM t_OrgMembers WHERE OrgId = @OrgId " +
                                                                "AND UserId = @UserId;", conn);

                    DeleteOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
                    DeleteOrgMember.Parameters.Add(new SqlParameter("UserId", _UserId));

                    AffectedRows = DeleteOrgMember.ExecuteNonQuery();
                }
                AppLog.Info(String.Format("DELETE ORGMEMBER - Organisation member {0} deleted from online database " +
                                          "successfully. {1} row(s) affected", MyUser.FullName, AffectedRows));
            }
            catch (SqlException e)
            {
                _ErrMsg = "Error while deleting organisation member from online database";
                AppLog.Error("DELETE ORGMEMBER - " + _ErrMsg + ": " + e);
                return(false);
            }


            //If deleted from online database successfully, try local database
            AppLog.Info("DELETE USER - Attempting to delete organisation member from local database...");

            /*try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("DELETE ORGMEMBER - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("DELETE ORGMEMBER - Connection to local database opened successfully");
             *
             *      SqlCommand DeleteOrgMember = new SqlCommand("DELETE FROM OrgMembers WHERE OrgId = @OrgId " +
             *          "AND UserId = @UserId;", conn);
             *
             *      DeleteOrgMember.Parameters.Add(new SqlParameter("OrgId", _OrgId));
             *      DeleteOrgMember.Parameters.Add(new SqlParameter("UserId", _UserId));
             *
             *      AffectedRows = DeleteOrgMember.ExecuteNonQuery();
             *  }
             *  AppLog.Info(String.Format("DELETE ORGMEMBER - Organisation member {0} deleted from local database " +
             *  "successfully. {1} row(s) affected", MyUser.FullName, AffectedRows));
             * }
             * catch (SqlException e)
             * {
             *  _ErrMsg = "Error while deleting organisation member from local database";
             *  AppLog.Error("DELETE ORGMEMBER" + _ErrMsg + ": " + e);
             *  return false;
             * }*/
            //AffectedRows = 0; Why did this need resetting?? 09/10/2017 15:50
            AppLog.Info(String.Format("DELETE ORGMEMBER - Success!"));
            return(true);
        }
示例#24
0
        public bool Get()
        {
            AppLog.Info("GET ASSIGNEE - Starting...");
            if (Data.OfflineMode)
            {
                /*AppLog.Info("GET ASSIGNEE - Attempting to get assignee from local database...");
                 * try
                 * {
                 *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 *  {
                 *      AppLog.Info("GET ASSIGNEE - Attempting to open connection to local database...");
                 *      conn.Open();
                 *      AppLog.Info("GET ASSIGNEE - Connection to local database opened successfully");
                 *
                 *
                 *      SqlCommand GetAssignee = new SqlCommand("SELECT * FROM Assignees WHERE BugId = @BugId AND " +
                 *          "UserId = UserId;", conn);
                 *      GetAssignee.Parameters.Add(new SqlParameter("BugId", _BugId));
                 *      GetAssignee.Parameters.Add(new SqlParameter("UserId", _UserId));
                 *
                 *      using (SqlDataReader reader = GetAssignee.ExecuteReader())
                 *      {
                 *          while (reader.Read())
                 *          {
                 *              _TimeSpent = TimeSpan.FromTicks(Convert.ToInt64(reader[2]));
                 *              _AccessLevel = Convert.ToInt32(reader[3]);
                 *              _DateTimeCreated = Convert.ToDateTime(reader[4]);
                 *              Uploaded = Convert.ToBoolean(reader[5]);
                 *          }
                 *      }
                 *  }
                 *  AppLog.Info(String.Format("GET ASSIGNEE - Assignee {0} downloaded from local database " +
                 *      "successfully", MyUser.Username));
                 * }
                 * catch (SqlException e)
                 * {
                 *  _ErrMsg = "Error while getting assignee from local database";
                 *  AppLog.Error("GET ASSIGNEE - " + _ErrMsg + ": " + e); ;
                 *  return false;
                 * }*/
            }
            else
            {
                AppLog.Info("GET ASSIGNEE - Attempting to get assignee from online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("GET ASSIGNEE - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("GET ASSIGNEE - Connection to online database opened successfully");


                        SqlCommand GetAssignee = new SqlCommand("SELECT * FROM t_Assignees WHERE BugId = " +
                                                                "@BugId AND UserId = UserId;", conn);
                        GetAssignee.Parameters.Add(new SqlParameter("BugId", _BugId));
                        GetAssignee.Parameters.Add(new SqlParameter("UserId", _UserId));

                        using (SqlDataReader reader = GetAssignee.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                _TimeSpent       = TimeSpan.FromTicks(Convert.ToInt64(reader[2]));
                                _AccessLevel     = Convert.ToInt32(reader[3]);
                                _DateTimeCreated = Convert.ToDateTime(reader[4]);
                            }
                        }
                    }
                    AppLog.Info(String.Format("GET ASSIGNEE - Assignee {0} downloaded from online database " +
                                              "successfully", MyUser.Username));
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while getting assignee from online database";
                    AppLog.Error("GET ASSIGNEE - " + _ErrMsg + ": " + e);;
                    return(false);
                }
                //Finally, check if assignee exists in the local database. If not, ADD THEM!!! If so, UPDATE THEM!!!

                /*AppLog.Info("GET ASSIGNEE - Checking whether assignee exists in local database");
                 *
                 * bool ExistsOnLocalDb;
                 *
                 * using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
                 * {
                 *  AppLog.Info("GET ASSIGNEE - Attempting to open connection to local database...");
                 *  conn.Open();
                 *  AppLog.Info("GET ASSIGNEE - Connection to local database opened successfully");
                 *
                 *
                 *
                 *  SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM Assignees WHERE BugId = @BugId AND " +
                 *      "UserId = @UserId;", conn);
                 *  CheckLocalDb.Parameters.Add(new SqlParameter("BugId", BugId));
                 *  CheckLocalDb.Parameters.Add(new SqlParameter("UserId", MyUser.Id));
                 *
                 *  using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
                 *  {
                 *      if (reader.Read())
                 *      {
                 *          ExistsOnLocalDb = true;
                 *          AppLog.Info("GET ASSIGNEE - Assignee already exists in the local database!");
                 *      }
                 *      else
                 *      {
                 *          ExistsOnLocalDb = false;
                 *      }
                 *  }
                 * }
                 * if (ExistsOnLocalDb)
                 * {
                 *  if (Update())
                 *  {
                 *      AppLog.Info("GET ASSIGNEE - Updated assignee on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET ASSIGNEE - Failed to update assignee: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }
                 * else
                 * {
                 *  if (Create())
                 *  {
                 *      AppLog.Info("GET ASSIGNEE - Created assignee on local db successfully");
                 *  }
                 *  else
                 *  {
                 *      AppLog.Info("GET ASSIGNEE - Failed to create assignee: " + _ErrMsg);
                 *      return false;
                 *  }
                 * }*/
            }
            AppLog.Info("GET ASSIGNEE - Success!");
            return(true);
        }
示例#25
0
        /// <summary>
        /// Performs a direct, point-to-point request/response transaction with another CFX Endpoint.
        /// </summary>
        /// <param name="targetUri">The network address of the Endpoint to which the request will be sent.
        /// May use amqp:// or amqps:// topic (amqps for secure communications).
        /// May also include user information (for authentication), as well as a custom TCP port.
        /// </param>
        /// <param name="request">A CFX envelope containing the request.</param>
        /// <returns>A CFX envelope containing the response from the Endpoint.</returns>
        public async Task <CFXEnvelope> ExecuteRequestAsync(string targetUri, CFXEnvelope request)
        {
            CFXEnvelope  response      = null;
            Connection   reqConn       = null;
            Session      reqSession    = null;
            ReceiverLink receiver      = null;
            SenderLink   sender        = null;
            Exception    ex            = null;
            Uri          targetAddress = new Uri(targetUri);

            CurrentRequestTargetUri = targetAddress;

            try
            {
                if (string.IsNullOrWhiteSpace(request.RequestID))
                {
                    request.RequestID = "REQUEST-" + Guid.NewGuid().ToString();
                }
                if (string.IsNullOrWhiteSpace(request.Source))
                {
                    request.Source = CFXHandle;
                }

                Message req = AmqpUtilities.MessageFromEnvelope(request, UseCompression.Value);
                req.Properties.MessageId            = "command-request";
                req.Properties.ReplyTo              = CFXHandle;
                req.ApplicationProperties           = new ApplicationProperties();
                req.ApplicationProperties["offset"] = 1;

                await Task.Run(() =>
                {
                    try
                    {
                        ConnectionFactory factory = new ConnectionFactory();
                        if (targetAddress.Scheme.ToLower() == "amqps")
                        {
                            factory.SSL.RemoteCertificateValidationCallback = ValidateRequestServerCertificate;
                            factory.SASL.Profile = SaslProfile.External;
                        }

                        if (string.IsNullOrWhiteSpace(targetAddress.UserInfo))
                        {
                            factory.SASL.Profile = SaslProfile.Anonymous;
                        }

                        reqConn           = factory.CreateAsync(new Address(targetAddress.ToString())).Result;
                        reqSession        = new Session(reqConn);
                        Attach recvAttach = new Attach()
                        {
                            Source = new Source()
                            {
                                Address = request.Target
                            },
                            Target = new Target()
                            {
                                Address = CFXHandle
                            }
                        };

                        receiver = new ReceiverLink(reqSession, "request-receiver", recvAttach, null);
                        receiver.Start(300);
                        sender = new SenderLink(reqSession, CFXHandle, request.Target);

                        sender.Send(req);
                        Message resp = receiver.Receive(RequestTimeout.Value);
                        if (resp != null)
                        {
                            receiver.Accept(resp);
                            response = AmqpUtilities.EnvelopeFromMessage(resp);
                        }
                        else
                        {
                            throw new TimeoutException("A response was not received from target CFX endpoint in the alloted time.");
                        }
                    }
                    catch (Exception ex3)
                    {
                        AppLog.Error(ex3);
                        ex = ex3;
                    }
                });
            }
            catch (Exception ex2)
            {
                AppLog.Error(ex2);
                if (ex == null)
                {
                    ex = ex2;
                }
            }
            finally
            {
                if (receiver != null && !receiver.IsClosed)
                {
                    await receiver.CloseAsync();
                }
                if (sender != null && !sender.IsClosed)
                {
                    await sender.CloseAsync();
                }
                if (reqSession != null && !reqSession.IsClosed)
                {
                    await reqSession.CloseAsync();
                }
                if (reqConn != null && !reqConn.IsClosed)
                {
                    await reqConn.CloseAsync();
                }
            }

            if (ex != null)
            {
                if (ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                throw ex;
            }

            return(response);
        }
示例#26
0
        public bool Create()
        {
            AppLog.Info("CREATE ASSIGNEE - Starting...");

            //Checks that data is valid before attempting upload
            AppLog.Info("CREATE ASSIGNEE - Validating...");
            if (!Validate())
            {
                AppLog.Info("CREATE ASSIGNEE - Assignee failed validation");
                return(false);
            }
            AppLog.Info("CREATE ASSIGNEE - Assignee validated successfully");

            _DateTimeCreated = DateTime.Now;

            if (!Data.OfflineMode)
            {
                AppLog.Info(String.Format("CREATE ASSIGNEE - Offline mode is OFF"));

                AppLog.Info("CREATE ASSIGNEE - Attempting to create assignee on online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("CREATE ASSIGNEE - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("CREATE ASSIGNEE - Connection to online database opened successfully");

                        //This is a check to see weather the assignee already exists on the database. Obviously
                        //if it's already there, it doesn't need creating again, but this might be called
                        //if for example the assignee did not exist on the local database, so the Create() function
                        //needed to be able to account for that.
                        AppLog.Info("CREATE ASSIGNEE - Checking that assignee doesn't already exist on online database");
                        bool OnlineAssigneeExists;

                        SqlCommand CheckOnlineDb = new SqlCommand("SELECT * FROM t_Assignees WHERE BugId = @BugId AND " +
                                                                  "UserId = @UserId;", conn);
                        CheckOnlineDb.Parameters.Add(new SqlParameter("BugId", BugId));
                        CheckOnlineDb.Parameters.Add(new SqlParameter("UserId", MyUser.Id));
                        using (SqlDataReader reader = CheckOnlineDb.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                OnlineAssigneeExists = true;
                                AppLog.Info("CREATE ASSIGNEE - Assignee already exists in online database!");
                            }
                            else
                            {
                                OnlineAssigneeExists = false;
                                AppLog.Info("CREATE ASSIGNEE - Assignee does not exist in online database. Creating assignee on online database");
                            }
                        }

                        if (!OnlineAssigneeExists)
                        {
                            SqlCommand CreateAssignee = new SqlCommand("INSERT INTO t_Assignees VALUES (@BugId, " +
                                                                       "@UserId, @TimeSpent, @AccessLevel, @DateTimeCreated);", conn);

                            CreateAssignee.Parameters.Add(new SqlParameter("BugId", _BugId));
                            CreateAssignee.Parameters.Add(new SqlParameter("UserId", _UserId));
                            CreateAssignee.Parameters.Add(new SqlParameter("TimeSpent", _TimeSpent.Ticks));
                            CreateAssignee.Parameters.Add(new SqlParameter("Accesslevel", _AccessLevel));
                            CreateAssignee.Parameters.Add(new SqlParameter("DateTimeCreated", _DateTimeCreated));

                            CreateAssignee.ExecuteNonQuery();
                            Uploaded = true;
                            AppLog.Info(String.Format("CREATE ASSIGNEE - Assignee {0} created on online database successfully",
                                                      MyUser.Username));
                        }
                    }
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while creating assignee on online database";
                    AppLog.Error("CREATE ASSIGNEE - " + _ErrMsg + ": " + e);;
                    return(false);
                }
            }
            else
            {
                AppLog.Info(String.Format("CREATE ASSIGNEE - Offline mode is ON. Skipping create user on" +
                                          "online database"));
            }

            /*AppLog.Info("CREATE ASSIGNEE - Attempting to create assignee on local database...");
             * try
             * {
             *
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("CREATE ASSIGNEE - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("CREATE ASSIGNEE - Connection to local database opened successfully");
             *
             *      //This is a check to see weather the assignee already exists on the database. Obviously
             *      //if it's already there, it doesn't need creating again, but this might be called
             *      //if for example the assignee did not exist on the local database, so the Create() function
             *      //needed to be able to account for that.
             *      AppLog.Info("CREATE ASSIGNEE - Checking that assignee doesn't already exist on local database");
             *      bool LocalAssigneeExists;
             *
             *      SqlCommand CheckLocalDb = new SqlCommand("SELECT * FROM Assignees WHERE BugId = @BugId AND " +
             *          "UserId = @UserId;", conn);
             *      CheckLocalDb.Parameters.Add(new SqlParameter("BugId", BugId));
             *      CheckLocalDb.Parameters.Add(new SqlParameter("UserId", MyUser.Id));
             *      using (SqlDataReader reader = CheckLocalDb.ExecuteReader())
             *      {
             *          if (reader.Read())
             *          {
             *              LocalAssigneeExists = true;
             *              AppLog.Info("CREATE ASSIGNEE - Assignee already exists in local database!");
             *          }
             *          else
             *          {
             *              LocalAssigneeExists = false;
             *              AppLog.Info("CREATE ASSIGNEE - Assignee does not exist in local database. Creating assignee on local database");
             *          }
             *      }
             *
             *      if (!LocalAssigneeExists)
             *      {
             *          SqlCommand CreateAssignee = new SqlCommand("INSERT INTO Assignees VALUES (@BugId, @UserId, " +
             *          "@TimeSpent, @AccessLevel, @DateTimeCreated, @Uploaded);", conn);
             *
             *          CreateAssignee.Parameters.Add(new SqlParameter("BugId", _BugId));
             *          CreateAssignee.Parameters.Add(new SqlParameter("UserId", _UserId));
             *          CreateAssignee.Parameters.Add(new SqlParameter("TimeSpent", _TimeSpent.Ticks));
             *          CreateAssignee.Parameters.Add(new SqlParameter("Accesslevel", _AccessLevel));
             *          CreateAssignee.Parameters.Add(new SqlParameter("DateTimeCreated", _DateTimeCreated));
             *          CreateAssignee.Parameters.Add(new SqlParameter("Uploaded", Uploaded));
             *
             *          CreateAssignee.ExecuteNonQuery();
             *
             *          AppLog.Info(String.Format("CREATE ASSIGNEE - Assignee {0} created on local database successfully",
             *      MyUser.Username));
             *      }
             *
             *  }
             * }
             * catch (SqlException e)
             * {
             *      _ErrMsg = "Error while creating assignee on local database. Changes were not saved";
             *      AppLog.Error(_ErrMsg + ": " + e);
             *      return false;
             * }*/
            AppLog.Info(String.Format("CREATE ASSIGNEE - Success!"));
            return(true);
        }
示例#27
0
        protected void btnsave_Click(object sender, EventArgs e)
        {
            try
            {
                string   bookingid   = hbookingId.Value.ToString();
                string   customerid  = txtcustomer.Text;
                DateTime bookingdate = Convert.ToDateTime(hbookingdate.Value);
                DateTime fromdate    = Convert.ToDateTime(hfromdate.Value);
                DateTime todate      = Convert.ToDateTime(htodate.Value);
                string   Dfromtime   = txtfromtime.Text;
                TimeSpan fromtime    = TimeSpan.Parse(Dfromtime.Replace(".", ":")); //DateTime.Now.TimeOfDay;//DateTime.Now.ToString("HH:mm:ss tt");
                string   Dtotime     = txttotime.Text;
                TimeSpan totime      = TimeSpan.Parse(Dtotime.Replace(".", ":"));   //DateTime.Now.TimeOfDay;
                string   CompanyId   = Session["companyid"].ToString();

                string vehSegid     = ddlVehicleseg.SelectedValue;
                string SerLocid     = ddlLocation.SelectedValue;
                string vehmakeid    = hvehmakeid.Value;
                string secdepstatus = ddlSecDepStatus.SelectedValue;
                double SecDepAmt    = 0;
                if (secdepstatus == "required")
                {
                    if (txtSecDepAmt.Text.Length > 0)
                    {
                        SecDepAmt = Convert.ToDouble(txtSecDepAmt.Text);
                    }
                }
                string discstatus = ddlDiscStatus.SelectedValue;
                string status     = ddlstatus.SelectedValue;

                string bookedby       = txtbookedby.Text;
                string bookedbymobile = txtBookedMobileno.Text;
                string bookedbyemail  = txtBookedEmail.Text;
                string guest          = txtGuest.Text;
                string guestmobile    = txtGuestMobile.Text;
                string guestemail     = txtGuestEmail.Text;
                double AdvanceAmt     = 0;
                if (txtAdvAmt.Text.Length > 0)
                {
                    AdvanceAmt = Convert.ToDouble(txtAdvAmt.Text);
                }
                double discount = 0;
                if (txtdiscount.Text.Length > 0)
                {
                    discount = Convert.ToDouble(txtdiscount.Text);
                }

                string tariffid          = hseltariffid.Value;
                string accessoriesStatus = ddlAccessoriesStatus.SelectedValue;
                string accids            = haccids.Value;

                string Preparedby = "UP001";

                string Flag = string.Empty;
                if (bookingid != "New")
                {
                    Flag = "Edit";
                }
                else
                {
                    Flag = "Add";
                }

                //string Flag, string bookingid, DateTime bookingdate, string customerid, DateTime fromdate, DateTime Todate, TimeSpan fromtime, TimeSpan Totime, string vehsegid,string status,
                //string slid,string vehmakeid,string bookedby, string bookedbymobile,string bookedbyemail,string guest,string guestmobile,string guestEmail,
                // double AdvanceAmt,string discstatus, double discount, string SecDepStatus,double SecDepAmt, string preparedbyid, string CompanyId

                string id = ObjDBAccess1.InsertBookingData(Flag, bookingid, bookingdate, customerid, fromdate, todate, fromtime, totime, vehSegid, status,
                                                           SerLocid, vehmakeid, bookedby, bookedbymobile, bookedbyemail, guest, guestmobile, guestemail,
                                                           AdvanceAmt, discstatus, discount, secdepstatus, SecDepAmt, Preparedby, CompanyId, tariffid, accessoriesStatus, accids);

                hbookingId.Value = "New";
                if (id == "2")
                {
                    lblmessage.Text = "Sorry! Booking already exists.";
                }
                else
                {
                    lblmessage.Text = "";
                    LoadBookings();
                }
                ClearInputValues();
            }
            catch (Exception ex)
            {
                AppLog.Error(ex);
            }
        }
示例#28
0
 private void LogError(Exception ex)
 {
     AppLog.Error(string.Format("sender-{0}  {1}", Address, ex.Message));
     AppLog.Error(ex);
 }
示例#29
0
 private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
 {
     AppLog.Error(e.Exception);
 }
示例#30
0
        public bool Update()
        {
            AppLog.Info("UPDATE PRODUCT - Starting...");
            if (!Data.OfflineMode)
            {
                AppLog.Info("UPDATE PRODUCT - Offline mode is OFF");

                AppLog.Info("UPDATE PRODUCT - Attempting to update product on online database...");
                try
                {
                    using (SqlConnection conn = new SqlConnection(Data.OnlineConnStr))
                    {
                        AppLog.Info("UPDATE PRODUCT - Attempting to open connection to online database...");
                        conn.Open();
                        AppLog.Info("UPDATE PRODUCT - Connection to online database opened successfully");

                        SqlCommand UpdateProduct = new SqlCommand("UPDATE t_Products SET Name = @Name WHERE " +
                                                                  "Id = @Id;", conn);

                        UpdateProduct.Parameters.Add(new SqlParameter("Name", _Name));
                        UpdateProduct.Parameters.Add(new SqlParameter("Id", _Id));

                        UpdateProduct.ExecuteNonQuery();
                    }
                    Uploaded = true;
                    AppLog.Info(String.Format("UPDATE PRODUCT - Product {0} updated on online database successfully",
                                              Name));
                }
                catch (SqlException e)
                {
                    _ErrMsg = "Error while updating product on online database";
                    AppLog.Error(_ErrMsg + ": " + e);
                    return(false);
                }
            }
            else
            {
                AppLog.Info("UPDATE PRODUCT - Offline mode is ON. Skipping update product on online database");
            }

            AppLog.Info("UPDATE PRODUCT - Attempting to update product on local database...");

            /*try
             * {
             *  using (SqlConnection conn = new SqlConnection(Data.LocalConnStr))
             *  {
             *      AppLog.Info("UPDATE PRODUCT - Attempting to open connection to local database...");
             *      conn.Open();
             *      AppLog.Info("UPDATE PRODUCT - Connection to local database opened successfully");
             *
             *      SqlCommand UpdateProduct = new SqlCommand("UPDATE Products SET Name = @Name WHERE Id = @Id;", conn);
             *
             *      UpdateProduct.Parameters.Add(new SqlParameter("Name", _Name));
             *      UpdateProduct.Parameters.Add(new SqlParameter("Id", _Id));
             *      UpdateProduct.Parameters.Add(new SqlParameter("Uploaded", Uploaded));
             *
             *      UpdateProduct.ExecuteNonQuery();
             *  }
             *  AppLog.Info(String.Format("UPDATE PRODUCT - Product {0} created on local database successfully",
             *      Name));
             * }
             * catch (SqlException e)
             * {
             *  _ErrMsg = "Error while updating product on local database. Changes were not saved";
             *  AppLog.Error(_ErrMsg + ": " + e);
             *  return false;
             * }*/

            AppLog.Info("UPDATE PRODUCT - Success!");
            return(true);
        }