Esempio n. 1
0
 //Button Add click handler
 private void btnAdd_Click(object sender, EventArgs e)
 {
     if (CheckUpCount() == true)
     {
         try
         {
             //show Editor dialog
             frmEditor EditorForm = new frmEditor();
             EditorForm.ShowDialog();
             //add new data to data-collection
             if (EditorForm.IsCanceled == false)
             {
                 Note NewNote = new Note(EditorForm.TextName, EditorForm.TextArray);
                 EncryptedData.AddNote(NewNote);
             }
         }
         catch (OutOfMemoryException Exc)
         {
             MessageBox.Show(Exc.ToString());
         }
         catch (ArgumentException Exc)
         {
             MessageBox.Show(Exc.ToString());
         }
         //add new record to grid
         UpdateGrid();
     }
 }
Esempio n. 2
0
        private Bitmap GetImage(string Url)
        {
            try
            {
                WebRequest request        = WebRequest.Create(Url);
                Stream     responseStream = request.GetResponse().GetResponseStream();
                return(new Bitmap(responseStream));
            }
            catch (WebException WebExc)
            {
                DialogResult result = MessageBox.Show(WebExc.Message + "\nWould you like to try Get the image again??", "Web Exception!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

                if (result == DialogResult.Yes)
                {
                    return(GetImage(Url));
                }
                else
                {
                    return(null);
                }
            }
            catch (ArgumentException AExc)
            {
                //  Add code later
                MessageBox.Show(AExc.ToString(), "===:GetImage ArgumentException:===");
                return(null);
            }
            catch (Exception Exc)
            {
                MessageBox.Show(Exc.ToString(), "===:Get Image:===");
                MessageBox.Show(Exc.GetType().ToString());

                return(null);
            }
        }
Esempio n. 3
0
    // Returns true if successful
    bool CreateFile(string path, string content = "")
    {
        try
        {
            // Check if file already exists
            if (!File.Exists(path))
            {
                // Create a new file
                using (FileStream fs = File.Create(path))
                {
                    // Write text to file
                    Byte[] file_content = new UTF8Encoding(true).GetBytes(content);
                    fs.Write(file_content, 0, file_content.Length);
                }
                Debug.Log(path + " was created!");
                return(true);
            }
            else
            {
                Debug.Log(path + " exists already!");
                return(false);
            }
        }

        catch (Exception Exc)
        {
            Debug.Log(Exc.ToString());
            return(false);
        }
    }
Esempio n. 4
0
        public async Task ProcessDailyChange()
        {
            try
            {
                var processDate = DateTime.Now;

                ////var ListToProcess = await BR.LoadCandles(8736);
                //var ListToProcess = await BR.LoadPercentChangeList(8736);
                //var percentChange = new PercentChange(ListToProcess, processDate);
                //percentChange.CalculateChange();
                ////var result = percentChange.CalculatedData;
                //await BR.BulkPercentChangeInsert(percentChange.CalculatedData);



                var stockList = await BR.FindProcessedStocks();

                foreach (var stock in stockList)
                {
                    var ListToProcess = await BR.LoadPercentChangeList(stock.Id);

                    //var ListToProcess = await BR.LoadCandles(stock.Id);
                    var percentChange = new PercentChange(ListToProcess, processDate);
                    percentChange.CalculateChange();
                    //var result = percentChange.CalculatedData;
                    await BR.BulkPercentChangeInsert(percentChange.CalculatedData);
                }
            }
            catch (Exception Exc)
            {
                Logger.Info(Exc.ToString());
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Adds an entry to the 'User Account Activity Log' table (s_user_account_activity).
        /// </summary>
        /// <param name="AUserID">UserID of the user to add the User Account Activity for.</param>
        /// <param name="AActivityType">Type of the User Account Activity.</param>
        /// <param name="AActivityDetails">Details/description of the User Account Activity.</param>
        /// <param name="ATransaction">Instantiated DB Transaction.</param>
        public static void AddUserAccountActivityLogEntry(String AUserID,
                                                          String AActivityType,
                                                          String AActivityDetails,
                                                          TDBTransaction ATransaction)
        {
            SUserAccountActivityTable ActivityTable  = new SUserAccountActivityTable();
            SUserAccountActivityRow   NewActivityRow = ActivityTable.NewRowTyped(false);
            DateTime ActivityDateTime = DateTime.Now;

            // Set DataRow values
            NewActivityRow.UserId          = AUserID.ToUpper();
            NewActivityRow.ActivityDate    = ActivityDateTime.Date;
            NewActivityRow.ActivityTime    = Conversions.DateTimeToInt32Time(ActivityDateTime);
            NewActivityRow.ActivityType    = AActivityType;
            NewActivityRow.ActivityDetails = AActivityDetails;

            ActivityTable.Rows.Add(NewActivityRow);

            try
            {
                SUserAccountActivityAccess.SubmitChanges(ActivityTable, ATransaction);

                // Also log this to the server log
                TLogging.Log(AActivityDetails);
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the saving of a User Account Activity Log entry:" +
                             Environment.NewLine + Exc.ToString());

                throw;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Returns the translation of <paramref name="msgid"/> and
        /// <paramref name="msgidPlural"/>, choosing the right plural form
        /// depending on the number <paramref name="n"/>.
        /// </summary>
        /// <param name="msgid">the key string to be translated, an ASCII
        ///                     string</param>
        /// <param name="msgidPlural">the English plural of <paramref name="msgid"/>,
        ///                           an ASCII string</param>
        /// <param name="n">the number, should be &gt;= 0</param>
        /// <param name="treatZeroAsPlural">if set to true then the number 0 is considered being plural
        /// (for situations like where strings like "0 records" are to be displayed).</param>
        /// <returns>the translation, or <c>null</c> if none is found</returns>
        public static string GetPluralString(String msgid, String msgidPlural, long n, bool treatZeroAsPlural = false)
        {
            bool Plural = treatZeroAsPlural ? ((n != 1) && (n != -1)) : (((n != 1) && (n != -1)) && (n != 0));

            if (catalog == null)
            {
                return(Plural ? msgidPlural : msgid);
            }
            else
            {
                string result = msgid;

                if ((n == 0))
                {
                    // Calling 'catalog.GetPluralString' does not know about our 'treatZeroAsPlural = false' and would return plural in case of n = 0
                    // so we call 'catalog.GetPluralString' in case 'treatZeroAsPlural = false' ...
                    if (treatZeroAsPlural)
                    {
                        try
                        {
                            result = catalog.GetPluralString(msgid, msgidPlural, n);
                        }
                        catch (Exception Exc)
                        {
                            TLogging.Log(
                                "GetText: Catalog.GetPluralString: problem for getting text for \"" + msgid + "\" and/or \"" + msgidPlural + "\"");
                            TLogging.Log(Exc.ToString());
                        }

                        return(result);
                    }
                    else
                    {
                        // ...and we make n 1 to get the call to 'catalog.GetPluralString' (further below) to return the singular string!
                        n = 1;
                    }
                }

                // Calling 'catalog.GetPluralString' does not work with negative numbers...
                if (n < 0)
                {
                    // ...so we make them positive
                    n = n * -1;
                }

                try
                {
                    result = catalog.GetPluralString(msgid, msgidPlural, n);
                }
                catch (Exception Exc)
                {
                    TLogging.Log("GetText: Catalog.GetPluralString: problem for getting text for \"" + msgid + "\" and/or \"" + msgidPlural + "\"");
                    TLogging.Log(Exc.ToString());
                }

                return(result);
            }
        }
Esempio n. 7
0
        /// roll back the transaction
        public void Rollback()
        {
            string         TransactionIdentifier     = null;
            bool           TransactionValid          = false;
            IsolationLevel TransactionIsolationLevel = IsolationLevel.Unspecified;

            // Attempt to roll back the DB Transaction.
            try
            {
                // 'Sanity Check': Check that TheTransaction hasn't been committed or rolled back yet.
                if (!Valid)
                {
                    var Exc1 =
                        new EDBAttemptingToUseTransactionThatIsInvalidException(
                            "TDataBase.RollbackTransaction called on DB Transaction that isn't valid",
                            ThreadingHelper.GetThreadIdentifier(ThreadThatTransactionWasStartedOn),
                            ThreadingHelper.GetCurrentThreadIdentifier());

                    TLogging.Log(Exc1.ToString());

                    throw Exc1;
                }

                if (TLogging.DL >= DBAccess.DB_DEBUGLEVEL_TRANSACTION_DETAIL)
                {
                    // Gather information for logging
                    TransactionIdentifier     = GetDBTransactionIdentifier();
                    TransactionValid          = Valid;
                    TransactionIsolationLevel = IsolationLevel;
                }

                WrappedTransaction.Rollback();

                TLogging.LogAtLevel(DBAccess.DB_DEBUGLEVEL_TRANSACTION, "       Transaction " + FTransactionName + " in Connection " + FTDataBaseInstanceThatTransactionBelongsTo.ConnectionName + " rolled back");

                // Rollback was OK, now clean up.
                Dispose();

                TLogging.LogAtLevel(DBAccess.DB_DEBUGLEVEL_TRANSACTION_DETAIL, String.Format(
                                        "DB Transaction{0} got rolled back.  Before that, its DB Transaction Properties were: Valid: {1}, " +
                                        "IsolationLevel: {2} (it got started on Thread {3} in AppDomain '{4}').", TransactionIdentifier,
                                        TransactionValid, TransactionIsolationLevel, ThreadThatTransactionWasStartedOn,
                                        AppDomainNameThatTransactionWasStartedIn)
                                    );
            }
            catch (Exception Exc)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                //
                // MSDN says: "Try/Catch exception handling should always be used when rolling back a
                // transaction. A Rollback generates an InvalidOperationException if the connection is
                // terminated or if the transaction has already been rolled back on the server."
                TLogging.Log("Exception while attempting Transaction rollback: " + Exc.ToString());
            }
        }
Esempio n. 8
0
        private async void SearchButton_Click(object sender, EventArgs e)
        {
            FlowLayoutPanelSong.Controls.Clear();

            try
            {
                Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "fxjPUENH-tGJthT1vzpZtH4EcdZAOTfj_zIDA1xicETAQXc7xhuBVs1j1sr3yb68");

                var response = await Client.GetAsync("search?q=" + SearchTextBox.Text);

                string value = await response.Content.ReadAsStringAsync();

                dynamic Answer = JsonConvert.DeserializeObject(value);

                try
                {
                    for (int i = 0; i < 4;)
                    {
                        if (Answer.response.hits[i].type == "song")
                        {
                            int    id    = Answer.response.hits[i].result.id;
                            string url   = Answer.response.hits[i].result.song_art_image_thumbnail_url;
                            Bitmap Cover = GetImage(url);

                            if (Cover == null)
                            {
                                Cover = (Bitmap) new PictureBox().Image;
                            }

                            string Title  = Answer.response.hits[i].result.title_with_featured;
                            string Artist = Answer.response.hits[i].result.primary_artist.name;

                            FlowLayoutPanelSong.Controls.Add(CreateSongCard(id, Cover, Title, Artist));
                            i++;
                        }
                        else
                        {
                            i--;
                        }
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    //  Add Code Later
                }
                catch (Exception Exc)
                {
                    MessageBox.Show(Exc.ToString(), "===:Answer Response Hits:===");
                    MessageBox.Show(Exc.GetType().ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "===:Search Button Click -Answer-:===");
                MessageBox.Show(ex.GetType().ToString());
            }
        }
Esempio n. 9
0
        // This function will save the measurements in memory to a
        // txt Log file.
        private void SaveLog(object sender, EventArgs e)
        {
            // Make sure that there are items in the list
            if (lstCurrentInfo.Items.Count < 1)
            {
                MessageBox.Show("Log is empty.");
                return;
            }

            // Stop the timer for saving
            bool RestartTimer = false;

            if (timer1.Enabled == true)
            {
                RestartTimer   = true;
                timer1.Enabled = false;
            }

            // find the next available filename of form PowerLogXXX format
            string folder       = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            string BaseTextName = folder + "/PowerLog";
            int    FileNum      = 0;

            for (; FileNum < 100; FileNum++)
            {
                bool exists = System.IO.File.Exists(BaseTextName + FileNum.ToString() + ".txt");
                if (!exists)
                {
                    break;
                }
            }
            BaseTextName += FileNum.ToString() + ".txt";

            // open the text file for saving
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(BaseTextName))
            {
                try
                {
                    foreach (Measurement line in Measurements)
                    {
                        sw.WriteLine(line.Current.ToString() + ", " + line.Temperature.ToString() + ", " + line.Life.ToString());
                    }
                    MessageBox.Show("Done saving log.");
                }
                catch (Exception Exc)
                {
                    // display the exception in the list box
                    lstCurrentInfo.Items.Add(Exc.ToString());
                }
            }

            // restart the timer if necessary
            if (RestartTimer)
            {
                timer1.Enabled = true;
            }
        }
    public static string ReplaceIDWithValues(object id, string TableName, string TableID, string TableValue)
    {
        // Checks that text is not null.
        if (id == null || id == DBNull.Value || TableName == "" || TableID == "" || TableValue == "")    //id == DBNull.Value ||
        {
            return("Error");
        }
        else
        {
            string        ReplacedId = id.ToString();
            string        value      = "";
            string        ConnectionStringFromWebConfig = ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString;//Gets the CMSConnection string dynamically
            string        sqlConnectString = @"" + ConnectionStringFromWebConfig + "";
            string        sqlSelect        = "SELECT " + TableID + "," + TableValue + " FROM " + TableName + ";";
            SqlConnection sqlConnection    = new SqlConnection(sqlConnectString);
            sqlConnection.Open();
            SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
            sqlCommand.CommandTimeout = 0;    //won’t timeout yourqueries
            var reader = sqlCommand.ExecuteReader();
            //By writing this we see if it gets any exceptions or not while closing
            try
            {
                if (reader.Read())    //Checks if the reader has any value
                {
                    //Starts code - Only for the 1st record/row
                    var IntegerValueFirstRow = reader.GetInt32(reader.GetOrdinal("" + TableID + ""));
                    var NameFirstRow         = reader.GetString(reader.GetOrdinal("" + TableValue + ""));

                    if (id.ToString().Contains(IntegerValueFirstRow.ToString()))
                    {
                        ReplacedId = ReplacedId.Replace(IntegerValueFirstRow.ToString(), NameFirstRow.ToString());
                    }
                    //Ends code - Only for the 1st record/row

                    while (reader.Read())    //Creates a loop from the second row and shows all the results from then onwards (doesn't show first record)
                    {
                        var IntegerValue = reader.GetInt32(reader.GetOrdinal("" + TableID + ""));
                        var Name         = reader.GetString(reader.GetOrdinal("" + TableValue + ""));

                        if (id.ToString().Contains(IntegerValue.ToString()))
                        {
                            ReplacedId = ReplacedId.Replace(IntegerValue.ToString(), Name.ToString());
                        }
                    }
                }
            }
            catch (Exception Exc)
            {
                Console.WriteLine(Exc.ToString());
            }

            sqlConnection.Close();
            value = ReplacedId.ToString();
            return(value);
        }
    }
Esempio n. 11
0
        public override string ToString()
        {
            if (Exc != null)
            {
                return(Exc.ToString());
            }
            string res = string.Format("Code:{0} Result:{1}", Code, Result);

            return(res);
        }
Esempio n. 12
0
 public void Send(byte[] Bytes)
 {
     try
     {
         UdpSend.Send(Bytes, Bytes.Length, SendEndPoint);
     }
     catch (Exception Exc)
     {
         MessageBox.Show(Exc.ToString());
     }
 }
Esempio n. 13
0
        public ActionResult SaveDistributionContract(ViewDistributionContract model)
        {
            ViewBase b = new ViewBase();

            try
            {
                if (model.IsSignAgreement == false)
                {
                    b.Code    = 0;
                    b.Message = ConstantHelper.Failure;
                    return(Json(b, JsonRequestBehavior.AllowGet));
                }


                using (var db = new EFContext())
                {
                    var shopdistribution = db.selshopdistribution.FirstOrDefault(x => x.ShopID == ShopId);

                    if (shopdistribution == null)
                    {
                        shopdistribution = new selshopdistribution()
                        {
                            ShopID            = ShopId,
                            IsSignAgreement   = true,
                            SignAgreementTime = DateTime.Now,
                            IsOpen            = false,
                            IsSetPercentage   = false,
                            OperatorDateTime  = DateTime.Now,
                            Percentage        = 0,
                            SetPercentageTime = DateTime.Now
                        };
                        db.selshopdistribution.Add(shopdistribution);
                    }
                    else
                    {
                        shopdistribution.IsSignAgreement   = true;
                        shopdistribution.SignAgreementTime = DateTime.Now;
                    }

                    db.SaveChanges();
                    b.Code    = 1;
                    b.Message = "协议签署成功";
                    b.Url     = "/DistributionBank/DistributionContract";
                }
            }
            catch (Exception Exc)
            {
                b.Code        = 0;
                b.Message     = ConstantHelper.Failure;
                b.Description = Exc.ToString();
            }

            return(Json(b, JsonRequestBehavior.AllowGet));
        }
Esempio n. 14
0
        private void listView1_ItemActivate(object sender, EventArgs e)
        {
            var sFileName = listView1.FocusedItem.Text;

            try
            {
                var sPath = treeView1.SelectedNode.FullPath;
                Process.Start(sPath + "" + sFileName);
            }
            catch (Exception Exc) { MessageBox.Show(Exc.ToString()); }
        }
Esempio n. 15
0
    /// <summary>
    /// 异步发送邮件
    /// </summary>
    /// <param name="toAddress"></param>
    /// <param name="subject"></param>
    /// <param name="content"></param>
    public static Base SendSmtpAsyncToUser(string toAddress, string subject, string content)
    {
        Base b = new Base();

        try
        {
            #region 异步发送邮件
            //实例化一个smtp客户端
            SmtpClient client = new SmtpClient();
            //smtp服务器 qq:smtp.qq.com,端口:25 smtp服务器需要身份验证
            client.Host = host;
            client.Port = port;
            //指定如何处理待发的电子邮件
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            //指定超时时间
            client.Timeout = timeout;
            //实例化发件人地址
            MailAddress from = new MailAddress(fromAddress, fromNickName, Encoding.UTF8);
            MailAddress to   = new MailAddress(toAddress);

            //  MailMessage mail = new MailMessage(from, to);
            MailMessage mail = new MailMessage();
            mail.From = from;
            mail.To.Add(to);
            //主题
            mail.Subject         = subject;
            mail.SubjectEncoding = Encoding.UTF8;
            mail.IsBodyHtml      = true;
            //正文
            mail.Body = content;

            mail.Priority     = MailPriority.High;
            mail.BodyEncoding = Encoding.GetEncoding("utf-8");
            //指定发件人信息  包括邮箱地址和邮箱密码
            client.Credentials = new NetworkCredential(fromAddress, fromPassword);
            //默认的身份凭据,这个最好不要设置,无论设置真假,发邮件都会出问题
            //client.UseDefaultCredentials = false;
            string userState = string.Format("toAddress:{0},subject:{1},content:{2}", toAddress, subject, content);
            client.SendCompleted += client_SendCompleted;
            client.SendAsync(mail, userState);
            b.Code    = 1;
            b.Message = ConstantHelper.Success;
            #endregion
        }
        catch (Exception Exc)
        {
            b.Code        = 0;
            b.Description = Exc.ToString();
            b.Message     = ConstantHelper.Failure;
        }
        b.Code    = 1;
        b.Message = "ok";
        return(b);
    }
Esempio n. 16
0
 public UdpConnection(string ListenIp, int ListenPort, string SendIp, int SendPort)
 {
     try
     {
         ListenEndpoint = new IPEndPoint(IPAddress.Parse(ListenIp), ListenPort);
         SendEndPoint   = new IPEndPoint(IPAddress.Parse(SendIp), SendPort);
     }
     catch (Exception Exc)
     {
         MessageBox.Show(Exc.ToString());
     }
 }
Esempio n. 17
0
 public void Send(string Message)
 {
     try
     {
         byte[] Bytes = Encoding.ASCII.GetBytes(Message);
         UdpSend.Send(Bytes, Bytes.Length, SendEndPoint);
     }
     catch (Exception Exc)
     {
         MessageBox.Show(Exc.ToString());
     }
 }
Esempio n. 18
0
 public void Unbind()
 {
     try
     {
         ListenThread.Suspend(); //Deprecated
         UdpListen.Close();
     }
     catch (Exception Exc)
     {
         MessageBox.Show(Exc.ToString());
     }
 }
Esempio n. 19
0
        /// <summary>
        /// 添加充值记录
        /// </summary>
        /// <param name="uguid"></param>
        /// <param name="data"></param>
        /// <param name="paymode">支付方式</param>
        /// <param name="origin"></param>
        /// <returns></returns>
        public NewBase <ExAddRecharge> AddRecharge(string shopid, string managerid, decimal data, int paymode, int origin)
        {
            NewBase <ExAddRecharge> b = new NewBase <ExAddRecharge>();

            b.Data = new ExAddRecharge();
            try
            {
                DateTime now = DateTime.Now;
                using (var db = new EFContext())
                {
                    selshopjinbirecharge recharge = new selshopjinbirecharge();
                    recharge.ID          = WebTools.getGUID();
                    recharge.ShopID      = shopid;
                    recharge.ManagerID   = managerid;
                    recharge.Data        = data;
                    recharge.DT          = now;
                    recharge.Status      = 0;
                    recharge.Mode        = paymode;
                    recharge.Origin      = origin;
                    recharge.IsAvailable = true;

                    recharge.BatchId  = BatchHelper.GetBatchId;
                    recharge.Contents = data.ToString();

                    db.selshopjinbirecharge.Add(recharge);

                    syspayhistory payhistory = new syspayhistory()
                    {
                        OrderMode   = 1,
                        OrderNumber = recharge.ID,
                        CreateTime  = now,
                        Status      = 0,
                        BatchId     = recharge.BatchId,
                        Price       = data
                    };
                    db.syspayhistory.Add(payhistory);

                    db.SaveChanges();
                    b.Code         = 1;
                    b.Message      = "充值订单已提交,请确认后进行付款操作";
                    b.Data.Id      = recharge.ID;
                    b.Data.BatchId = recharge.BatchId;
                }
            }
            catch (Exception Exc)
            {
                b.Code        = 0;
                b.Message     = ConstantHelper.Failure;
                b.Description = Exc.ToString();
            }
            return(b);
        }
Esempio n. 20
0
        /// <summary>
        /// 确认支付成功 支付宝支付回调使用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Base ConfirmShopVersionByBatchId(string batchid)
        {
            Base b = new Base();

            try
            {
                using (var db = new EFContext())
                {
                    selshopsmschange recharge = db.selshopsmschange.FirstOrDefault(a => a.BatchId == batchid);

                    if (recharge == null)
                    {
                        b.Code    = 0;
                        b.Message = "无效的支付记录!";
                        return(b);
                    }
                    selshop selshopmodel = db.selshop.FirstOrDefault(a => a.ID == recharge.ShopID);

                    if (selshopmodel == null)
                    {
                        b.Code    = 0;
                        b.Message = "无效的帐户,请联系管理员!";
                        return(b);
                    }

                    if (recharge.Status == 1)
                    {
                        b.Code    = 1;
                        b.Message = "支付成功!";
                        return(b);
                    }
                    var      ordernumber = recharge.ID.ToString();
                    DateTime now         = DateTime.Now;


                    //升级成功
                    recharge.Status    = 1;
                    recharge.ConfirmDT = now;

                    db.SaveChanges();
                    b.Code    = 1;
                    b.Message = ConstantHelper.Success;
                }
            }
            catch (Exception Exc)
            {
                b.Code        = 0;
                b.Message     = ConstantHelper.Failure;
                b.Description = Exc.ToString();
            }
            return(b);
        }
Esempio n. 21
0
        /// <summary>
        /// modified version taken from Ict.Petra.Server.App.Main::TServerManager
        /// </summary>
        private TDataBase EstablishDBConnectionAndReturnIt(string AConnectionName = null, bool ALogNumberOfConnections = false)
        {
            TDataBase ReturnValue;

            if (ALogNumberOfConnections)
            {
                if (FDBType == TDBType.PostgreSQL)
                {
                    TLogging.Log("  EstablishDBConnectionAndReturnIt: Number of open DB Connections on PostgreSQL BEFORE Connecting to Database: " +
                                 TDataBase.GetNumberOfDBConnections(FDBType) + TDataBase.GetDBConnectionName(AConnectionName));
                }
            }

            TLogging.Log("  EstablishDBConnectionAndReturnIt: Establishing connection to Database..." + TDataBase.GetDBConnectionName(AConnectionName));

            ReturnValue = new TDataBase();

            TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 10);

            try
            {
                ReturnValue.EstablishDBConnection(FDBType,
                                                  TAppSettingsManager.GetValue("Server.DBHostOrFile"),
                                                  TAppSettingsManager.GetValue("Server.DBPort"),
                                                  TAppSettingsManager.GetValue("Server.DBName"),
                                                  TAppSettingsManager.GetValue("Server.DBUserName"),
                                                  TAppSettingsManager.GetValue("Server.DBPassword"),
                                                  "", AConnectionName);
            }
            catch (Exception Exc)
            {
                TLogging.Log("  EstablishDBConnectionAndReturnIt: Encountered Exception while trying to establish connection to Database " +
                             TDataBase.GetDBConnectionName(AConnectionName) + Environment.NewLine +
                             Exc.ToString());

                throw;
            }

            TLogging.Log("  EstablishDBConnectionAndReturnIt: Connected to Database." + ReturnValue.GetDBConnectionIdentifier());

            if (ALogNumberOfConnections)
            {
                if (FDBType == TDBType.PostgreSQL)
                {
                    TLogging.Log("  EstablishDBConnectionAndReturnIt: Number of open DB Connections on PostgreSQL AFTER  Connecting to Database: " +
                                 TDataBase.GetNumberOfDBConnections(FDBType) + ReturnValue.GetDBConnectionIdentifier());
                }
            }

            return(ReturnValue);
        }
Esempio n. 22
0
        public void Bind()
        {
            try
            {
                UdpListen.Client.Bind(ListenEndpoint);
                ListenThread = new Thread(StartListening);
                ListenThread.Start();
            }

            catch (Exception Exc)
            {
                MessageBox.Show(Exc.ToString());
            }
        }
 public ListEntryInfo this[int index]
 {
     get
     {
         try
         {
             return((ListEntryInfo)base.List[index]);
         }
         catch (System.Exception Exc)
         {
             Exc.ToString();
             return(null);
         }
     }
 }
Esempio n. 24
0
 private void EmergencyStopClick(object sender, EventArgs e)
 {
     try
     {
         Packet EmergencyStopPacket = new Packet(PacketType.EMERGENCY_STOP, false, Scarlet.Science.Constants.CLIENT_NAME);
         EmergencyStopPacket.AppendData(UtilData.ToBytes("Homura"));
         Server.SendNow(EmergencyStopPacket);
     }
     catch (Exception Exc)
     {
         Log.Output(Log.Severity.FATAL, Log.Source.GUI, "FAILED TO SEND EMERGENCY STOP!");
         Log.Exception(Log.Source.GUI, Exc);
         DarkMessageBox.ShowError("Failed to send emergency stop!\n\n" + Exc.ToString(), "Science");
     }
 }
Esempio n. 25
0
        /// <summary>
        /// connect the client
        /// </summary>
        /// <param name="AUserName"></param>
        /// <param name="APassword"></param>
        /// <param name="AProcessID"></param>
        /// <param name="AWelcomeMessage"></param>
        /// <param name="ASystemEnabled"></param>
        /// <param name="AError"></param>
        /// <param name="AUserInfo"></param>
        /// <returns></returns>
        virtual protected eLoginEnum ConnectClient(String AUserName,
                                                   String APassword,
                                                   out Int32 AProcessID,
                                                   out String AWelcomeMessage,
                                                   out Boolean ASystemEnabled,
                                                   out String AError,
                                                   out IPrincipal AUserInfo)
        {
            AError          = "";
            ASystemEnabled  = false;
            AWelcomeMessage = "";
            AProcessID      = -1;
            AUserInfo       = null;

            try
            {
                eLoginEnum result = FClientManager.ConnectClient(AUserName, APassword,
                                                                 TClientInfo.ClientComputerName,
                                                                 TClientInfo.ClientIPAddress,
                                                                 new Version(TClientInfo.ClientAssemblyVersion),
                                                                 DetermineClientServerConnectionType(),
                                                                 out FClientID,
                                                                 out AWelcomeMessage,
                                                                 out ASystemEnabled,
                                                                 out AUserInfo);

                if (result != eLoginEnum.eLoginSucceeded)
                {
                    AError = result.ToString();
                }

                return(result);
            }
            catch (Exception Exc)
            {
                if (TExceptionHelper.IsExceptionCausedByUnavailableDBConnectionClientSide(Exc))
                {
                    TExceptionHelper.ShowExceptionCausedByUnavailableDBConnectionMessage(true);

                    AError = Exc.Message;
                    return(eLoginEnum.eLoginFailedForUnspecifiedError);
                }

                TLogging.Log(Exc.ToString() + Environment.NewLine + Exc.StackTrace, TLoggingType.ToLogfile);
                AError = Exc.Message;
                return(eLoginEnum.eLoginFailedForUnspecifiedError);
            }
        }
Esempio n. 26
0
        private void AddFiles(string strPath, string filter = null)
        {
            this.path = strPath;

            listView1.BeginUpdate();

            listView1.Items.Clear();
            iFiles = 0;

            if (String.IsNullOrEmpty(filter))
            {
                filter = this.Filter;
            }

            if (String.IsNullOrEmpty(filter))
            {
                filter = "*.*";
            }


            if (String.IsNullOrWhiteSpace(Path.GetExtension(filter)))
            {
                if (!filter.EndsWith("*"))
                {
                    filter = string.Concat(filter, "*");
                }
                filter = string.Concat(filter, ".*");
            }


            try
            {
                DirectoryInfo di       = new DirectoryInfo(strPath + "\\");
                FileInfo[]    theFiles = di.GetFiles(filter);
                foreach (FileInfo theFile in theFiles)
                {
                    iFiles++;
                    ListViewItem lvItem = new ListViewItem(theFile.Name);
                    lvItem.SubItems.Add(theFile.Length.ToString());
                    lvItem.SubItems.Add(theFile.LastWriteTime.ToShortDateString());
                    lvItem.SubItems.Add(theFile.LastWriteTime.ToShortTimeString());
                    listView1.Items.Add(lvItem);
                }
            }
            catch (Exception Exc) { statusBar1.Text = Exc.ToString(); }

            listView1.EndUpdate();
        }
Esempio n. 27
0
        public bool SignUpSelfServiceConfirm(string AUserID, string AToken)
        {
            try
            {
                TServerAdminWebConnector.LoginServerAdmin("SELFSERVICE");
                bool Result = TMaintenanceWebConnector.SignUpSelfServiceConfirm(AUserID, AToken);
                Logout();
                return(Result);
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during SignUpSelfServiceConfirm:" + Environment.NewLine +
                             Exc.ToString());

                throw;
            }
        }
Esempio n. 28
0
 // -- Timers for handling Meteor connection and status --
 #region StatusHandlers
 /// <summary>
 /// Called periodically to (a) connect to Meteor (if the connection is
 /// not already open); (b) retrieve the status from Meteor; (c) update
 /// the temperature set points if required.
 /// </summary>
 private void timerMeteorStatus_Tick(object sender, EventArgs e)
 {
     if (inTimer)
     {
         return;
     }
     inTimer = true;
     try {
         HandleMeteorStatus();
     }
     // If an exception is thrown above, display it to assist trouble shooting
     catch (Exception Exc) {
         string Msg = "Exception thrown:\r\n\r\n" + Exc.ToString();
         MessageBox.Show(Msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
         Application.Exit();
     }
     inTimer = false;
 }
Esempio n. 29
0
        private DataTable GetReportDataTable(string AReportName, Dictionary <String, TVariant> AParamsDictionary, ref bool AThreadFinished)
        {
            DataTable ReturnTable = null;

            try
            {
                ReturnTable = TRemote.MReporting.WebConnectors.GetReportDataTable(AReportName, AParamsDictionary);
            }
            catch (System.OutOfMemoryException Exc)
            {
                TExceptionHelper.ShowExceptionCausedByOutOfMemoryMessage(true);

                TLogging.Log(Exc.ToString());
            }

            AThreadFinished = true;
            return(ReturnTable);
        }
Esempio n. 30
0
        private void updateUser()
        {
            MySqlCommand cmd = new MySqlCommand("call updateUser(@email, @frstn, @ln, @fthn, @pnum);", cn);

            MySqlParameter email = new MySqlParameter();

            email           = cmd.Parameters.Add("@email", MySqlDbType.VarChar);
            email.Direction = ParameterDirection.Input;
            email.Value     = textBoxEmail.Text;

            MySqlParameter firstN = new MySqlParameter();

            firstN           = cmd.Parameters.Add("@frstn", MySqlDbType.VarChar);
            firstN.Direction = ParameterDirection.Input;
            firstN.Value     = textBoxName.Text;

            MySqlParameter ln = new MySqlParameter();

            ln           = cmd.Parameters.Add("@ln", MySqlDbType.VarChar);
            ln.Direction = ParameterDirection.Input;
            ln.Value     = textBoxLastName.Text;

            MySqlParameter fatN = new MySqlParameter();

            fatN           = cmd.Parameters.Add("@fthn", MySqlDbType.VarChar);
            fatN.Direction = ParameterDirection.Input;
            fatN.Value     = textBoxFatherName.Text;

            MySqlParameter pN = new MySqlParameter();

            pN           = cmd.Parameters.Add("@pnum", MySqlDbType.VarChar);
            pN.Direction = ParameterDirection.Input;
            pN.Value     = textBoxCallNum.Text;

            try
            {
                var result = cmd.ExecuteNonQuery();
                // MessageBox.Show("Данные обновлены", "Редактирование данных", MessageBoxButtons.OK);
            }
            catch (Exception Exc)
            {
                MessageBox.Show(Exc.ToString(), "Редактирование данных", MessageBoxButtons.OK);
            }
        }