Ankur
Ankur

Reputation: 1021

Windows service time out expired

 protected override void OnStart(string[] args)
        {
            try
            {
                t.Enabled = true;
                t.Interval = 10000; //60 * 24;
                t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
            }
            catch (Exception ex)
            {
                writeErrorToFile(ex.Message + " -- (OnStart) --");
            }
        }

this is my onstart method. I am new to making the windows service. Can you explain me what the code inside the instart method does.? I am not able to get the right answer when i googled.

Following is the method that is called from the onstart method

private void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                // Read Data from Excel
                OleDbConnection conn = new OleDbConnection();
                OleDbCommand cmd = new OleDbCommand();
                OleDbDataAdapter da = new OleDbDataAdapter();

                SqlCommand sm = new SqlCommand();
                string connString = "";
                string query = "";

                string strDt = DateTime.Now.ToString("dd_MM_yyyy");
                string strNewPath = @"E:\E-Cata_Stock_Report\ALL_INDIA_STOCK_REPORT_" + strDt + ".xls";    //Server.MapPath(@"C:\E-Cata_Stock_Report\ALL_INDIA_STOCK_REPORT.xls");  // ///" + strFileName + strFileType);


                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath +
                             ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";


                query = "SELECT * FROM [SPARE_LIST$]";
                conn = new OleDbConnection(connString);
                //Open connection
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                conn.Open();
                //Create the command object
                cmd = new OleDbCommand(query, conn);
                da = new OleDbDataAdapter(cmd);
                dsExcel = new DataSet();

                try
                {
                    da.Fill(dsExcel);
                }
                catch (Exception ex)
                {
                    writeErrorToFile(ex.Message + " -- (t_Elapsed -> Keep valid excel file which you want to upload..) --");
                    //lblMsg.Text = "Keep valid excel file which you want to upload..";
                    return;
                }

                //lblMsg.Text = "Data retrieved successfully! Total Records:" + dsExcel.Tables[0].Rows.Count;
                da.Dispose();
                conn.Close();
                conn.Dispose();

                if (dsExcel.Tables[0].Columns.Count != 32)
                {
                    writeErrorToFile("Please check the Excel Sheet.. It contains more or less columns..");
                    return;
                }

                if (dsExcel.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < dsExcel.Tables[0].Rows.Count; i++)
                        File.AppendAllText(@"C:\E-Cata_Itms.txt", dsExcel.Tables[0].Rows[i][0].ToString() + "  \n\r"+i+i);
                }

                //======================================================================================================

                string con = getConn_string();
                SqlConnection sn = new SqlConnection(con);

                if (sn.State == ConnectionState.Open)
                    sn.Close();
                sn.Open();
                SqlTransaction transaction = sn.BeginTransaction();

                try
                {
                    for (int j = 4; j < dsExcel.Tables[0].Rows.Count; j++) // for rows
                    {
                        for (int i = 2; i < 32; i++) //for coloumns
                        {
                            sm = new SqlCommand();
                            sm.Transaction = transaction;
                            sm.CommandText = "whItmItemwise_upload_update";
                            sm.Connection = sn;

                            sm.CommandType = CommandType.StoredProcedure;
                            sm.Parameters.AddWithValue("@whItm_wh_code", dsExcel.Tables[0].Rows[3][i].ToString().Trim());
                            sm.Parameters.AddWithValue("@whItm_item_code", dsExcel.Tables[0].Rows[j][0].ToString().Trim());

                            try
                            {
                                // open stock quantity
                                decimal op_qty = (dsExcel.Tables[0].Rows[j][i].ToString().Trim() ==
                                                                 "")
                                                                    ? Convert.ToDecimal(0.0)
                                                                    : Convert.ToDecimal(
                                                                        dsExcel.Tables[0].Rows[j][i].ToString().Trim
                                                                            ());

                                sm.Parameters.AddWithValue("@whItm_OP_STK_Qty", op_qty);
                            }
                            catch (Exception ex)
                            {
                                writeErrorToFile(ex.Message + " -- (t_Elapsed -> Enter valid Open stock quantity..) --"+i);
                                return;
                            }

                            sm.Parameters.AddWithValue("@whItm_Creation_DT", DateTime.Now.ToString("yyyy/MM/dd"));
                            //sm.Parameters.AddWithValue("@whItm_Created_By", "");
                            //sm.Parameters.AddWithValue("@His_whItm_Modify_Del_DT", DateTime.Now.ToString("yyyy/MM/dd"));
                            //sm.Parameters.AddWithValue("@His_whItm_Modify_Del_By", "");

                            try
                            {
                                int x = sm.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                System.Text.StringBuilder str_Upload = new System.Text.StringBuilder();
                                str_Upload.Append(dsExcel.Tables[0].Rows[3][i].ToString().Trim() + ",");
                                str_Upload.Append(dsExcel.Tables[0].Rows[j][0].ToString().Trim() + ",");
                                str_Upload.Append(ex.Message.Replace(',', '-') + ",");
                                str_Upload.Append(DateTime.Now.ToString("dd/MM/yyyy") + ",");

                                File.AppendAllText(@"C:\E-Cata_Error" + ".csv", str_Upload.ToString());
                            }

                            sm.Parameters.Clear();
                        }
                    }

                    // Update stock from WH master to Item Master
                    SqlCommand sm2 = new SqlCommand();
                    sm2.Transaction = transaction;
                    sm2.CommandText = "Stock_Update_from_WH_to_Item_master";
                    sm2.Connection = sn;
                    sm2.CommandType = CommandType.StoredProcedure;
                    sm2.Parameters.AddWithValue("@Item_Code", "");
                    sm2.ExecuteNonQuery();

                    transaction.Commit();
                    sm2.Dispose();
                    MyNewService iyu = new MyNewService();
                    iyu.Stop();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();

                    writeErrorToFile(ex.Message+"abcd");
                    return;
                }
                finally
                {
                    sm.Dispose();
                    transaction.Dispose();
                    sn.Close();
                    sn.Dispose();
                }

                //try
                //{
                //    // delete uploaded file
                //    File.Delete(strNewPath);
                //}
                //catch (Exception)
                //{
                //}
            }
            catch (Exception ex)
            {
                writeErrorToFile(ex.Message + " -- (t_Elapsed) --"+"xyz");
            }
        }

Upvotes: 0

Views: 730

Answers (1)

user2323308
user2323308

Reputation: 769

Windows service has to inherit from ServiceBase class. It has OnStart and OnStop virtual methods that we need to override in the service class. In your code, when the windows service is started, OnStart method is invoked. In this method the timer is enabled and set the interval to 10 sec. Timer interval always sets in milliseconds, that’s why value is 10000. When 10 sec elapsed the method subscribed in the Elapsed event is fired, in this case the t_Elapsed method in fired.
See the following article for hosting the wcf service in a managed windows service. http://msdn.microsoft.com/en-us/library/ms733069.aspx

Upvotes: 1

Related Questions