Member 10236682 Ответов: 2

Windows coludnt запускает службу на локальном компьютере ошибка:1053


Сервис должен быть запущен мануллаем.Я перепробовал все способы, найденные в Google search, не получая никакого решения, пожалуйста, предложите любое решение
protected override void OnStart(string[] args)
        {
            Logger.WriteInfoLog("Service Started");
            Thread.Sleep(31000);
            ProceesXMlFiles();
        }

        public void ProceesXMlFiles()
        {
            try
            {

                //To check whether zip enabled or not
                string strIsZipEnable = ConfigurationManager.AppSettings["IsZipEnable"].ToString();


                if (!Directory.Exists(strArchiveFolderPath))
                    Directory.CreateDirectory(strArchiveFolderPath);

                //to check whether data from zip Url or folder path
                if (Convert.ToInt32(strIsZipEnable) == 1)
                {
                    Logger.WriteInfoLog("XML files from Zip URL path");

                    System.Net.WebClient client = new System.Net.WebClient();
                    //Folder path of downloaded Zip files
                    string Zippath = ConfigurationManager.AppSettings["ZipDownloadPath"].ToString();
                    if (!File.Exists(Zippath))
                    {
                        File.Delete(Zippath);
                    }
                    //Zip Download Url
                    client.DownloadFile(ConfigurationManager.AppSettings["ZipDownloadUrl"].ToString(), Zippath);

                    Logger.WriteInfoLog("Downloaded XML files from Zip URL path");

                    //Zip Files extracted path
                    string StrExtractPath = ConfigurationManager.AppSettings["ZipExtarctedPath"].ToString();

                    //To crete Extracted File Folder
                    if (!Directory.Exists(StrExtractPath))
                        Directory.CreateDirectory(StrExtractPath);

                    if (Directory.Exists(StrExtractPath + "\\New folder"))
                        Directory.Delete(StrExtractPath + "\\New folder", true);

                    //to extract zip file XMLs
                    ZipFile.ExtractToDirectory(Zippath, StrExtractPath);

                    Logger.WriteInfoLog("Downloaded Zip Files Extracted");

                    strArrayXMLfiles = Directory.GetFiles(StrExtractPath + "\\New folder", "*.xml");
                    StrAllFiles = Directory.GetFiles(StrExtractPath + "\\New folder");
                }
                else
                {
                    if (Directory.Exists(ConfigurationManager.AppSettings["XMLsFolderPath"].ToString()))
                    {
                        //folder path to Xml Files
                        strArrayXMLfiles = Directory.GetFiles(ConfigurationManager.AppSettings["XMLsFolderPath"].ToString(), "*.xml");
                        StrAllFiles = Directory.GetFiles(ConfigurationManager.AppSettings["XMLsFolderPath"].ToString());
                    }
                    else
                        Logger.WriteInfoLog("Xml Folder not found at given path");
                }
                foreach (string strFilepath in StrAllFiles)
                {
                    string StrFileExtension = Path.GetExtension(strFilepath);
                    if (StrFileExtension != "xml")
                    {
                        Logger.WriteInfoLog(Path.GetFileName(strFilepath) + " is not an Xml File");
                    }
                }

                for (int i = 0; i < strArrayXMLfiles.Count(); i++)
                {
                    Logger.WriteInfoLog("Processing XML files one after another");

                    //To get Xml File path to process
                    strXMLFilePath = strArrayXMLfiles[i].ToString();

                    Logger.WriteInfoLog("Getting file name whether it is started with aceds  or acfcs");

                    //to get the file name to check whether aceds or acfcs files
                    strFileName = Path.GetFileName(strXMLFilePath);

                    DataSet dsXMLData = new DataSet();
                    //to read XML file to Dataset 
                    dsXMLData.ReadXml(strXMLFilePath, XmlReadMode.InferSchema);
                    Logger.WriteInfoLog("XML Files converted as Dateset");

                    //To send prospect_id to aother json payloads also
                    string prospect_id = dsXMLData.Tables["prospect"].Rows[0][0].ToString();
                    //to process ParadotProspect JsonPayload
                    ProcessParadotProspect(dsXMLData, strFileName);
                    //to process VistorActivity JsonPayload
                    ProcessVistorActivity(dsXMLData, prospect_id, strFileName);
                    //to process VistorActivity JsonPayload
                    ProcessListSubscription(dsXMLData, prospect_id, strFileName);
                    //To move files from source to Archive Folder
                    MovefilesFromSourceToDestination(strXMLFilePath, strArchiveFolderPath);

                }
                Logger.WriteInfoLog("Service Stoped");
            }
            catch (Exception ex)
            {
                Logger.WriteErrorLog(ex, "", "");
            }
        }

        /// <summary>
        /// Paradot Prospect json Paylod Processed
        /// </summary>
        /// <param name="dsXMLData"></param>
        /// <param name="strFileName"></param>
        public void ProcessParadotProspect(DataSet dsXMLData, string strFileName)
        {
            try
            {
                #region ParadotProspect
                DataTable dtparodot = dsXMLData.Tables["prospect"];

                Logger.WriteInfoLog("If any column in paradot doesnt exist then need to add");
                //if column doesnt exist then add to send to json paylod
                if (dtparodot.Columns.Contains("campaign_id") == false)
                    dtparodot.Columns.Add("campaign_id", typeof(String));

                if (dtparodot.Columns.Contains("salutation") == false)
                    dtparodot.Columns.Add("salutation", typeof(String));

                if (dtparodot.Columns.Contains("first_name") == false)
                    dtparodot.Columns.Add("first_name", typeof(String));

                if (dtparodot.Columns.Contains("last_name") == false)
                    dtparodot.Columns.Add("last_name", typeof(String));

                if (dtparodot.Columns.Contains("email") == false)
                    dtparodot.Columns.Add("email", typeof(String));

                if (dtparodot.Columns.Contains("password") == false)
                    dtparodot.Columns.Add("password", typeof(String));

                if (dtparodot.Columns.Contains("company") == false)
                    dtparodot.Columns.Add("company", typeof(String));

                if (dtparodot.Columns.Contains("website") == false)
                    dtparodot.Columns.Add("website", typeof(String));

                if (dtparodot.Columns.Contains("job_title") == false)
                    dtparodot.Columns.Add("job_title", typeof(String));

                if (dtparodot.Columns.Contains("department") == false)
                    dtparodot.Columns.Add("department", typeof(String));

                if (dtparodot.Columns.Contains("country") == false)
                    dtparodot.Columns.Add("country", typeof(String));

                if (dtparodot.Columns.Contains("address_one") == false)
                    dtparodot.Columns.Add("address_one", typeof(String));

                if (dtparodot.Columns.Contains("address_two") == false)
                    dtparodot.Columns.Add("address_two", typeof(String));

                if (dtparodot.Columns.Contains("city") == false)
                    dtparodot.Columns.Add("city", typeof(String));

                if (dtparodot.Columns.Contains("state") == false)
                    dtparodot.Columns.Add("state", typeof(String));

                if (dtparodot.Columns.Contains("territory") == false)
                    dtparodot.Columns.Add("territory", typeof(String));

                if (dtparodot.Columns.Contains("zip") == false)
                    dtparodot.Columns.Add("zip", typeof(String));

                if (dtparodot.Columns.Contains("phone") == false)
                    dtparodot.Columns.Add("phone", typeof(String));

                if (dtparodot.Columns.Contains("fax") == false)
                    dtparodot.Columns.Add("fax", typeof(String));

                if (dtparodot.Columns.Contains("source") == false)
                    dtparodot.Columns.Add("source", typeof(String));

                if (dtparodot.Columns.Contains("annual_revenue") == false)
                    dtparodot.Columns.Add("annual_revenue", typeof(String));

                if (dtparodot.Columns.Contains("employees") == false)
                    dtparodot.Columns.Add("employees", typeof(String));

                if (dtparodot.Columns.Contains("industry") == false)
                    dtparodot.Columns.Add("industry", typeof(String));

                if (dtparodot.Columns.Contains("years_in_business") == false)
                    dtparodot.Columns.Add("years_in_business", typeof(String));

                if (dtparodot.Columns.Contains("comments") == false)
                    dtparodot.Columns.Add("comments", typeof(String));

                if (dtparodot.Columns.Contains("notes") == false)
                    dtparodot.Columns.Add("notes", typeof(String));

                if (dtparodot.Columns.Contains("score") == false)
                    dtparodot.Columns.Add("score", typeof(String));

                if (dtparodot.Columns.Contains("grade") == false)
                    dtparodot.Columns.Add("grade", typeof(String));

                if (dtparodot.Columns.Contains("last_activity_at") == false)
                    dtparodot.Columns.Add("last_activity_at", typeof(String));

                if (dtparodot.Columns.Contains("recent_interaction") == false)
                    dtparodot.Columns.Add("recent_interaction", typeof(String));

                if (dtparodot.Columns.Contains("crm_lead_fid") == false)
                    dtparodot.Columns.Add("crm_lead_fid", typeof(String));

                if (dtparodot.Columns.Contains("crm_contact_fid") == false)
                    dtparodot.Columns.Add("crm_contact_fid", typeof(String));

                if (dtparodot.Columns.Contains("crm_owner_fid") == false)
                    dtparodot.Columns.Add("crm_owner_fid", typeof(String));

                if (dtparodot.Columns.Contains("crm_account_fid") == false)
                    dtparodot.Columns.Add("crm_account_fid", typeof(String));

                if (dtparodot.Columns.Contains("crm_last_sync") == false)
                    dtparodot.Columns.Add("crm_last_sync", typeof(String));

                if (dtparodot.Columns.Contains("crm_url") == false)
                    dtparodot.Columns.Add("crm_url", typeof(String));

                if (dtparodot.Columns.Contains("is_do_not_email") == false)
                    dtparodot.Columns.Add("is_do_not_email", typeof(String));

                if (dtparodot.Columns.Contains("is_do_not_call") == false)
                    dtparodot.Columns.Add("is_do_not_call", typeof(String));

                if (dtparodot.Columns.Contains("opted_out") == false)
                    dtparodot.Columns.Add("opted_out", typeof(String));

                if (dtparodot.Columns.Contains("is_reviewed") == false)
                    dtparodot.Columns.Add("is_reviewed", typeof(String));

                if (dtparodot.Columns.Contains("is_starred") == false)
                    dtparodot.Columns.Add("is_starred", typeof(String));

                if (dtparodot.Columns.Contains("created_at") == false)
                    dtparodot.Columns.Add("created_at", typeof(String));

                if (dtparodot.Columns.Contains("updated_at") == false)
                    dtparodot.Columns.Add("updated_at", typeof(String));

                if (dtparodot.Columns.Contains("type") == false)
                    dtparodot.Columns.Add("type", typeof(String));


                if (strFileName.StartsWith("acfcs-"))
                {
                    Logger.WriteInfoLog("processing file starts with acfcs");

                    if (dtparodot.Columns.Contains("ACFCS_2015_Conference_request_for_info") == false)
                        dtparodot.Columns.Add("ACFCS_2015_Conference_request_for_info", typeof(String));

                    if (dtparodot.Columns.Contains("ACFCS_2015_Conference_at_a_Glance_Download") == false)
                        dtparodot.Columns.Add("ACFCS_2015_Conference_at_a_Glance_Download", typeof(String));

                    if (dtparodot.Columns.Contains("ACFCS_2015_Conference_Prospectus") == false)
                        dtparodot.Columns.Add("ACFCS_2015_Conference_Prospectus", typeof(String));

                    if (dtparodot.Columns.Contains("ACFCS_2015_Summit_Agenda_Download") == false)
                        dtparodot.Columns.Add("ACFCS_2015_Summit_Agenda_Download", typeof(String));

                    if (dtparodot.Columns.Contains("ACFCS_2015_Summit_Prospectus") == false)
                        dtparodot.Columns.Add("ACFCS_2015_Summit_Prospectus", typeof(String));

                    if (dtparodot.Columns.Contains("ACFCS_Candidate_Handbook_Download") == false)
                        dtparodot.Columns.Add("ACFCS_Candidate_Handbook_Download", typeof(String));

                    if (dtparodot.Columns.Contains("CFCS_Brochure") == false)
                        dtparodot.Columns.Add("CFCS_Brochure", typeof(String));

                }
                else if (strFileName.StartsWith("aceds-"))
                {
                    Logger.WriteInfoLog("processing file starts with aceds");

                    if (dtparodot.Columns.Contains("ACEDS_2015_Conference_request_for_info") == false)
                        dtparodot.Columns.Add("ACEDS_2015_Conference_request_for_info", typeof(String));

                    if (dtparodot.Columns.Contains("ACEDS_2015_Conference_at_a_Glance_Download") == false)
                        dtparodot.Columns.Add("ACEDS_2015_Conference_at_a_Glance_Download", typeof(String));

                    if (dtparodot.Columns.Contains("ACEDS_2015_Conference_Prospectus") == false)
                        dtparodot.Columns.Add("ACEDS_2015_Conference_Prospectus", typeof(String));

                    if (dtparodot.Columns.Contains("ACEDS_2015_Summit_Agenda_Download") == false)
                        dtparodot.Columns.Add("ACEDS_2015_Summit_Agenda_Download", typeof(String));

                    if (dtparodot.Columns.Contains("ACEDS_2015_Summit_Prospectus") == false)
                        dtparodot.Columns.Add("ACEDS_2015_Summit_Prospectus", typeof(String));

                    if (dtparodot.Columns.Contains("ACEDS_Candidate_Handbook_Download") == false)
                        dtparodot.Columns.Add("ACEDS_Candidate_Handbook_Download", typeof(String));

                    if (dtparodot.Columns.Contains("CEDS_Brochure") == false)
                        dtparodot.Columns.Add("CEDS_Brochure", typeof(String));

                }

                if (dtparodot.Columns.Contains("Colombian_Seminar_Program_at_a_Glance") == false)
                    dtparodot.Columns.Add("Colombian_Seminar_Program_at_a_Glance", typeof(String));

                if (dtparodot.Columns.Contains("FinCrime_Jobs") == false)
                    dtparodot.Columns.Add("FinCrime_Jobs", typeof(String));

                if (dtparodot.Columns.Contains("Lat_Am_2014_Conference_at_a_Glance_Download") == false)
                    dtparodot.Columns.Add("Lat_Am_2014_Conference_at_a_Glance_Download", typeof(String));

                if (dtparodot.Columns.Contains("Lat_Am_2015_Conference___request_info") == false)
                    dtparodot.Columns.Add("Lat_Am_2015_Conference___request_info", typeof(String));

                if (dtparodot.Columns.Contains("Lat_Am_2015_Conference_at_a_Glance") == false)
                    dtparodot.Columns.Add("Lat_Am_2015_Conference_at_a_Glance", typeof(String));

                if (dtparodot.Columns.Contains("Lat_Am_2015_Conference_Prospectus") == false)
                    dtparodot.Columns.Add("Lat_Am_2015_Conference_Prospectus", typeof(String));

                if (dtparodot.Columns.Contains("Lat_Am_Candidate_Handbook_Download") == false)
                    dtparodot.Columns.Add("Lat_Am_Candidate_Handbook_Download", typeof(String));

                if (dtparodot.Columns.Contains("Management_Level") == false)
                    dtparodot.Columns.Add("Management_Level", typeof(String));

                if (dtparodot.Columns.Contains("Spanish") == false)
                    dtparodot.Columns.Add("Spanish", typeof(String));


                if (strFileName.StartsWith("acfcs-"))
                {
                    Logger.WriteInfoLog(strFileName + " paradot Datatable process started");

                    var lstACFCSParodotProspect = (from Tableparodot in dtparodot.AsEnumerable()
                                                   select new
                                                   {
                                                       Id = Tableparodot["id"],
                                                       Campaign_id = Tableparodot["campaign_id"],
                                                       Salutation = Tableparodot["salutation"],
                                                       First_name = Tableparodot["first_name"],
                                                       Last_name = Tableparodot["last_name"],
                                                       Email = Tableparodot["email"],
                                                       Password = Tableparodot["password"],
                                                       Company = Tableparodot["company"],
                                                       Website = Tableparodot["website"],
                                                       Job_title = Tableparodot["job_title"],
                                                       Department = Tableparodot["department"],
                                                       Country = Tableparodot["country"],
                                                       Address_one = Tableparodot["address_one"],
                                                       Address_two = Tableparodot["address_two"],
                                                       City = Tableparodot["city"],
                                                       State = Tableparodot["state"],
                                                       Territory = Tableparodot["territory"],
                                                       Zip = Tableparodot["zip"],
                                                       Phone = Tableparodot["phone"],
                                                       Fax = Tableparodot["fax"],
                                                       Source = Tableparodot["source"],
                                                       Annual_revenue = Tableparodot["annual_revenue"],
                                                       Employees = Tableparodot["employees"],
                                                       Industry = Tableparodot["industry"],
                                                       Years_in_business = Tableparodot["years_in_business"],
                                                       Comments = Tableparodot["comments"],
                                                       Notes = Tableparodot["notes"],
                                                       Score = Tableparodot["score"],
                                                       Grade = Tableparodot["grade"],
                                                       Last_activity_at = Tableparodot["last_activity_at"],
                                                       Recent_interaction = Tableparodot["recent_interaction"],
                                                       Crm_lead_fid = Tableparodot["crm_lead_fid"],
                                                       Crm_contact_fid = Tableparodot["crm_contact_fid"],
                                                       Crm_owner_fid = Tableparodot["crm_owner_fid"],
                                                       Crm_account_fid = Tableparodot["crm_account_fid"],
                                                       Crm_last_sync = Tableparodot["crm_last_sync"],
                                                       Crm_url = Tableparodot["crm_url"],
                                                       Is_do_not_email = Tableparodot["is_do_not_email"],
                                                       Is_do_not_call = Tableparodot["is_do_not_call"],
                                                       Opted_out = Tableparodot["opted_out"],
                                                       Is_reviewed = Tableparodot["is_reviewed"],
                                                       Is_starred = Tableparodot["is_starred"],
                                                       Created_at = Tableparodot["created_at"],
                                                       Updated_at = Tableparodot["updated_at"],
                                                       ACFCS_2015_Conference_request_for_info = Tableparodot["ACFCS_2015_Conference_request_for_info"],
                                                       ACFCS_2015_Conference_at_a_Glance_Download = Tableparodot["ACFCS_2015_Conference_at_a_Glance_Download"],
                                                       ACFCS_2015_Conference_Prospectus = Tableparodot["ACFCS_2015_Conference_Prospectus"],
                                                       ACFCS_2015_Summit_Agenda_Download_ = Tableparodot["ACFCS_2015_Summit_Agenda_Download"],
                                                       ACFCS_2015_Summit_Prospectus = Tableparodot["ACFCS_2015_Summit_Prospectus"],
                                                       ACFCS_Candidate_Handbook_Download = Tableparodot["ACFCS_Candidate_Handbook_Download"],
                                                       CFCS_Brochure = Tableparodot["CFCS_Brochure"],
                                                       Colombian_Seminar_Program_at_a_Glance = Tableparodot["Colombian_Seminar_Program_at_a_Glance"],
                                                       FinCrime_Jobs = Tableparodot["FinCrime_Jobs"],
                                                       Lat_Am_2014_Conference_at_a_Glance_Download = Tableparodot["Lat_Am_2014_Conference_at_a_Glance_Download"],
                                                       Lat_Am_2015_Conference___request_info = Tableparodot["Lat_Am_2015_Conference___request_info"],
                                                       Lat_Am_2015_Conference_at_a_Glance = Tableparodot["Lat_Am_2015_Conference_at_a_Glance"],
                                                       Lat_Am_2015_Conference_Prospectus = Tableparodot["Lat_Am_2015_Conference_Prospectus"],
                                                       Lat_Am_Candidate_Handbook_Download = Tableparodot["Lat_Am_Candidate_Handbook_Download"],
                                                       Management_Level = Tableparodot["Management_Level"],
                                                       Spanish = Tableparodot["Spanish"],
                                                   }).ToList();
                    //to make list as datatable
                    DataTable dtLstparodot = ToDataTable(lstACFCSParodotProspect);
                    //to make data as json payload
                    DataTableToJSONWithStringBuilder(dtLstparodot, "pardotprospect", strFileName, "Paradot json Payload");
                }
                else if (strFileName.StartsWith("aceds-"))
                {
                    var lstACEDSParodotProspect = (from Tableparodot in dtparodot.AsEnumerable()
                                                   select new
                                                   {
                                                       Id = Tableparodot["id"],
                                                       Campaign_id = Tableparodot["campaign_id"],
                                                       Salutation = Tableparodot["salutation"],
                                                       First_name = Tableparodot["first_name"],
                                                       Last_name = Tableparodot["last_name"],
                                                       Email = Tableparodot["email"],
                                                       Password = Tableparodot["password"],
                                                       Company = Tableparodot["company"],
                                                       Website = Tableparodot["website"],
                                                       Job_title = Tableparodot["job_title"],
                                                       Department = Tableparodot["department"],
                                                       Country = Tableparodot["country"],
                                                       Address_one = Tableparodot["address_one"],
                                                       Address_two = Tableparodot["address_two"],
                                                       City = Tableparodot["city"],
                                                       State = Tableparodot["state"],
                                                       Territory = Tableparodot["territory"],
                                                       Zip = Tableparodot["zip"],
                                                       Phone = Tableparodot["phone"],
                                                       Fax = Tableparodot["fax"],
                                                       Source = Tableparodot["source"],
                                                       Annual_revenue = Tableparodot["annual_revenue"],
                                                       Employees = Tableparodot["employees"],
                                                       Industry = Tableparodot["industry"],
                                                       Years_in_business = Tableparodot["years_in_business"],
                                                       Comments = Tableparodot["comments"],
                                                       Notes = Tableparodot["notes"],
                                                       Score = Tableparodot["score"],
                                                       Grade = Tableparodot["grade"],
                                                       Last_activity_at = Tableparodot["last_activity_at"],
                                                       Recent_interaction = Tableparodot["recent_interaction"],
                                                       Crm_lead_fid = Tableparodot["crm_lead_fid"],
                                                       Crm_contact_fid = Tableparodot["crm_contact_fid"],
                                                       Crm_owner_fid = Tableparodot["crm_owner_fid"],
                                                       Crm_account_fid = Tableparodot["crm_account_fid"],
                                                       Crm_last_sync = Tableparodot["crm_last_sync"],
                                                       Crm_url = Tableparodot["crm_url"],
                                                       Is_do_not_email = Tableparodot["is_do_not_email"],
                                                       Is_do_not_call = Tableparodot["is_do_not_call"],
                                                       Opted_out = Tableparodot["opted_out"],
                                                       Is_reviewed = Tableparodot["is_reviewed"],
                                                       Is_starred = Tableparodot["is_starred"],
                                                       Created_at = Tableparodot["created_at"],
                                                       Updated_at = Tableparodot["updated_at"],
                                                       ACFCS_2015_Conference_request_for_info = Tableparodot["ACEDS_2015_Conference_request_for_info"],
                                                       ACFCS_2015_Conference_at_a_Glance_Download = Tableparodot["ACEDS_2015_Conference_at_a_Glance_Download"],
                                                       ACFCS_2015_Conference_Prospectus = Tableparodot["ACEDS_2015_Conference_Prospectus"],
                                                       ACFCS_2015_Summit_Agenda_Download_ = Tableparodot["ACEDS_2015_Summit_Agenda_Download"],
                                                       ACFCS_2015_Summit_Prospectus = Tableparodot["ACEDS_2015_Summit_Prospectus"],
                                                       ACFCS_Candidate_Handbook_Download = Tableparodot["ACEDS_Candidate_Handbook_Download"],
                                                       CFCS_Brochure = Tableparodot["CEDS_Brochure"],
                                                       Colombian_Seminar_Program_at_a_Glance = Tableparodot["Colombian_Seminar_Program_at_a_Glance"],
                                                       FinCrime_Jobs = Tableparodot["FinCrime_Jobs"],
                                                       Lat_Am_2014_Conference_at_a_Glance_Download = Tableparodot["Lat_Am_2014_Conference_at_a_Glance_Download"],
                                                       Lat_Am_2015_Conference___request_info = Tableparodot["Lat_Am_2015_Conference___request_info"],
                                                       Lat_Am_2015_Conference_at_a_Glance = Tableparodot["Lat_Am_2015_Conference_at_a_Glance"],
                                                       Lat_Am_2015_Conference_Prospectus = Tableparodot["Lat_Am_2015_Conference_Prospectus"],
                                                       Lat_Am_Candidate_Handbook_Download = Tableparodot["Lat_Am_Candidate_Handbook_Download"],
                                                       Management_Level = Tableparodot["Management_Level"],
                                                       Spanish = Tableparodot["Spanish"],
                                                   }).ToList();
                    DataTable dtLstparodot = ToDataTable(lstACEDSParodotProspect);
                    DataTableToJSONWithStringBuilder(dtLstparodot, "pardotprospect", strFileName, "Paradot json Payload");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteErrorLog(ex, "", "");
            }
                #endregion

        }

/// <summary>
        /// Generic List Converted to Data Table
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name);
            }
            foreach (T item in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }
            //put a breakpoint here and check datatable
            return dataTable;
        }

        /// <summary>
        /// Data Table converted to Json payload and sent to http Url
        /// </summary>
        /// <param name="table"></param>
        /// <param name="ExportType"></param>
        /// <param name="FileName"></param>
        public  void DataTableToJSONWithStringBuilder(DataTable table, string ExportType, string FileName, string JsonName)
        {
            try
            {
                Logger.WriteInfoLog("Datatable converted to Json format");

                var JSONString = new StringBuilder();
                if (table.Rows.Count > 0)
                {
                    JSONString.Append("{");
                    JSONString.Append("\"" + "ExportType" + "\":" + "\"" + ExportType + "\"," + "\"" + System.Environment.NewLine + "BodyJson [");
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        JSONString.Append("{");
                        for (int j = 0; j < table.Columns.Count; j++)
                        {
                            if (j < table.Columns.Count - 1)
                            {
                                JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
                            }
                            else if (j == table.Columns.Count - 1)
                            {
                                JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
                            }
                            JSONString.Append(System.Environment.NewLine);
                        }
                        if (i == table.Rows.Count - 1)
                        {
                            JSONString.Append("}]");
                        }
                        else
                        {
                            JSONString.Append("},");
                        }
                        JSONString.Append(System.Environment.NewLine);
                    }
                    JSONString.Append("}");
                }
                Logger.WriteInfoLog("sending JSON Payload to URL");
                var stringPayload = JSONString.ToString();

                byte[] byteRequestData;
                byteRequestData = Encoding.UTF8.GetBytes(stringPayload.ToString());


                WebRequest request = WebRequest.Create(ConfigurationManager.AppSettings["JsonPayloadPostUrl"].ToString());
                //set the content type to JSON
                request.Method = "POST";
                request.ContentType = "";
                // "application/json";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteRequestData.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteRequestData, 0, byteRequestData.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
                Logger.WriteInfoLog("Getting Response..");
                //
                WebResponse response = request.GetResponse();
                Logger.WriteInfoLog("Response stream started");
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                //// Open the stream using a StreamReader for easy access.
                Logger.WriteInfoLog("Response stream started");
                StreamReader reader = new StreamReader(dataStream);
               string  strResponseFromServer = reader.ReadToEnd();

                HttpWebResponse httpResponse = (HttpWebResponse)response;
                string strStatusCode = httpResponse.StatusCode.ToString();
                Logger.WriteInfoLog("http Response code for- " + FileName + "----" + JsonName + "-------:" + httpResponse.StatusCode);

                //var httpContent = new StringContent(stringPayload);

                //using (var httpClient = new HttpClient())
                //{
                //    httpClient.DefaultRequestHeaders.ExpectContinue = false; 

                //    // Do the actual request and await the response
                //    var httpResponse = await httpClient.PostAsync(ConfigurationManager.AppSettings["JsonPayloadPostUrl"].ToString(), httpContent);

                //    Logger.WriteInfoLog("http Response code for- " + FileName + "----" + JsonName + "-------:" + httpResponse.StatusCode);

                //    if (httpResponse.IsSuccessStatusCode == false)
                //    {
                //        Logger.WriteInfoLog(httpResponse.Content.ToString());
                //    }
                //}

            }
            catch (Exception ex)
            {
                Logger.WriteErrorLog(ex,FileName,JsonName);
            }
        }

        /// <summary>
        /// After json Payloads Sent to url XML files moved to url
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="destinationDirectorypath"></param>
        public void MovefilesFromSourceToDestination(string sourceFilePath, string destinationDirectorypath)
        {
            try
            {
                Logger.WriteInfoLog("To move XML Files to Archive Folder");

                //if file already existed Need to replace
                if (File.Exists(destinationDirectorypath + "\\" + Path.GetFileName(sourceFilePath)))
                {
                 File.Delete(destinationDirectorypath + "\\" + Path.GetFileName(sourceFilePath));
                }
                //To move file from source to destination folder
                File.Move(sourceFilePath, destinationDirectorypath + "\\" + Path.GetFileName(sourceFilePath));
            }
            catch (Exception ex)
            {
                Logger.WriteErrorLog(ex,"","");
            }
        }


Что я уже пробовал:

развертывание папки выпуска
Тайм-аут сервисного канала Regedit
тайм-аут requestdelay
Нить Сна

phil.o

Если вы не уделяете времени описанию вашей проблемы с помощью актуальной контекстуальной информации, вам может быть трудно найти кого-то, кто захочет потратить время на анализ вашей проблемы.
Пожалуйста, используйте зеленую кнопку "улучшить вопрос" и дайте нам подробную информацию о вашей проблеме.

F-ES Sitecore

Ваша служба начинается слишком долго, возможно, более 30 секунд. Вы не опубликовали никакого кода, так что невозможно сказать почему, но, скорее всего, вы не написали его соответствующим образом и ожидаете, что вся "работа" будет выполнена в событии OnStart (то есть вы делаете цикл внутри этого события, ожидая, что что-то будет сделано).

2 Ответов

Рейтинг:
2

Bernhard Hiller

Thread.Sleep(31000);
Таким образом, у вас есть исполняющий поток, спящий 31 секунду во время OnStart, в то время как Windows ожидает, что этот метод вернется в течение 30 секунд (если не указано, что это займет больше времени)? Этот призыв не только бесполезен, он разрушителен.
Кроме того, выполните всю эту обработку файлов в другом потоке/задаче.
protected override void OnStart(string[] args)
{
    Logger.WriteInfoLog("Service Started");
    System.Threading.Tasks.Task.Run(() => ProceesXMlFiles());
}


Jochen Arndt

О, МОЙ БОГ

Моя пятерка

Maciej Los

5ед!

Рейтинг:
2

Garth J Lancaster

в зависимости от того, как вы написали свой сервис, вы можете использовать Например.Метод RequestAdditionalTime (Int32) (System.Сервисный процесс)[^]

- вы гораздо лучше регистрируете и профилируете свой сервис, чтобы увидеть, что/где находится "задержка", прежде чем сделать это, хотя, если вы не можете ускорить запуск, то примените RequestAdditionalTime


Member 10236682

уже пробовал для RequestAdditionalTime даже
на самом деле у меня есть 300xML файлов для обработки .после получения этого ежедневного окна даже процесс был сделан фоном .но всплывающее окно тайм-аута приближается

Garth J Lancaster

вы не предоставили никакого кода, поэтому мы не знаем, как написан ваш сервис - у меня есть это тайное подозрение из того, что вы сказали, что вы пытаетесь сделать waaaaaay слишком много в OnStart() - я бы рекомендовал найти хороший справочный источник для сервисов - может быть https://www.syncfusion.com/resources/techportal/details/ebooks/windowsservices и начать с этого

Member 10236682

спасибо за предложение я отпустил его на старт слишком долго так что я поместил поток и весь процесс переместился в фоновый режим он работает нормально