locked
How to Access HttpContext in ScheduleJob related method RRS feed

  • Question

  • User82362805 posted

    Hi I am developing an automated file generator which generates file on daily basis for this purpose, I am using Hangfire background worker but the problem is when it call a method of file generator HttpContext giving me null object error this mean I cannot acesss HttpContext when there is no controller request

    Here is my complete code of file generator

    In Startup class 

     public void Configuration(IAppBuilder app)
            {
                GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireCon");
                app.UseHangfireDashboard();
                //app.UseHangfire(config=> {
    
                //    config.UseServer(1)
    
                //});
                var options = new BackgroundJobServerOptions { WorkerCount = 1 };
                RecurringJob.AddOrUpdate(() => home.GenerateFile(), Cron.Daily);
                app.UseHangfireServer(options);
            }

    Home Controller

     public void GenerateFile()
            {
    
                DataTable dt = new DataTable();
    
                List<SPParameter> plist = new List<SPParameter>();
    
                plist.Add(new SPParameter("StartDate", SqlDbType.DateTime, new DateTime(2018, 07, 31)));
                plist.Add(new SPParameter("EndDate", SqlDbType.DateTime, new DateTime(2018, 07, 31)));
    
                dt = SPs.ExecSPTableType("spRRDDetailFile", plist);
    
                StringBuilder sbd = new StringBuilder();
                foreach (DataRow row in dt.Rows)
                {
    
                    sbd.Append(row["EntityID"] + ",");
                    sbd.Append(row["EntityType"] + ",");
                    sbd.Append(row["RemittancType"] + ",");
                    sbd.Append(row["EmirateCode"].ToString() + row["CBBranchCode"] + ",");
                    sbd.Append(row["AccountNo"] + ",");
                    sbd.Append(row["MobileWallet"] + ",");
                    sbd.Append(row["TransactionConducted"] + ",");
                    sbd.Append(row["RemitterClassification"] + ",");
                    sbd.Append(ParseValidText((row["RemitterFirstName"] + " " + row["RemitterMiddleName"]).Trim() + " " + (row["RemitterLastName"]) + ",").Trim());
                    sbd.Append(row["RemitterLegalIdType"] + row["RemitterLegalIdNumber"].ToString() + ",");
                    sbd.Append(ParseCBDate(row["RemitterExpiryDate"]) + ",");
                    sbd.Append(row["RemitterNationality"] + ",");
                    sbd.Append(row["RemitterPhoneNo"] + ",");
                    sbd.Append(row["RemitterAddress"] + ",");
                    sbd.Append(row["RemitFromCountry"] + ",");
                    sbd.Append(row["FCAmount"] + ",");
                    sbd.Append(row["InstructedCurrency"] + ",");
                    sbd.Append(row["SourceOfFund"] + ",");
                    sbd.Append(ParseCBDate(row["SubmissionDate"]) + ",");
                    sbd.Append(row["TransactionID"] + ",");
                    sbd.Append(ParseCBDate(row["TransactionDate"]) + ",");
                    sbd.Append(row["PurposeCode"] + ",");
                    sbd.Append(row["ModeOfReceipt"] + ",");
                    sbd.Append(row["BeneficiaryReceiptDetails"] + ",");
                    sbd.Append(row["BeneficiaryLegalIdType"].ToString() + row["BeneficiaryLegalIdNumber"] + ",");
                    sbd.Append(ParseCBDate(row["BeneficiaryExpiryDate"]) + ",");
                    sbd.Append(row["BeneficiaryClassification"] + ",");
                    sbd.Append(ParseValidText((row["BeneficiaryFirstName"] + " " + row["BeneficiaryMiddleName"]).Trim() + " " + (row["BeneficiaryLastName"])).Trim() + ",");
                    sbd.Append(row["BeneficiaryCell"] + ",");
                    sbd.Append(row["BeneficiaryNationality"] + ",");
                    sbd.Append(row["BeneficiaryAddress"] + ",");
                    sbd.Append(row["BeneficiaryCountry"] + ",");
                    sbd.Append(row["PayModebyRemitter"] + ",");
                    sbd.Append(row["Relationship"] + ",");
                    sbd.Append(row["ProductUsed"] + ",");
                    sbd.Append(row["RemitterCharges"] + ",");
                    sbd.Append(row["BeneficiaryCharges"] + ",");
                    sbd.Append(",");
                    sbd.Append(",");
                    sbd.Append(",");
                    sbd.Append(",");
                    sbd.Append(",");
                    sbd.Append(",");
                    sbd.Append(",");
                    sbd.Append(row["AdditionalDetails"] + ",");
                    sbd.Append(row["MixedMode"] + ",");
                    sbd.Append(row["RemitterNameArabic"] + ",");
                    sbd.Append(row["BeneficiaryNameArabic"] + ",");
                    sbd.Append(row["FixedText"]);
                    sbd.AppendLine();
                }
                if (dt.Rows.Count > 0)
                {
                    DateTime filedate;
                    filedate = System.DateTime.Today;
    
                    int cbo; int cbi; int dmo; int dmi;
    
                    cbo = dt.Select("RemittancType='CBO'").Length;
                    cbi = dt.Select("RemittancType='CBI'").Length;
                    dmo = dt.Select("RemittancType='DMO'").Length;
                    dmi = dt.Select("RemittancType='DMI'").Length;
    
    
                    sbd.Append(dt.Rows[0]["RecordType"] + ",");
                    sbd.Append(dt.Rows[0]["EntityID"] + ",");
                    sbd.Append(filedate.ToString("yyyy-MM-dd") + ",");
                    sbd.Append(cbo + ",");
                    sbd.Append(cbi + ",");
                    sbd.Append(dmo + ",");
                    sbd.Append(dmi + ",");
    
                    sbd.Append(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,");
    
                    sbd.Append(dt.Rows[0]["FixedText"]);
    
                    // var filepath="";
                    // string filename;
    
                    var filename = "UAERR284SSSSSS" + filedate.ToString("yyMMddHHmmss") + ".RTD";
                    var filepath = "C:\\Users\\WS00\\source\\repos\\FileGeneratorDemo\\FileGeneratorDemo\\CBFiles\\" +filename;
    
                    string filedata = sbd.ToString();
                    StreamWriter sw = new StreamWriter(filepath);
                    sw.Write(filedata);
                    sw.Flush();
                    sw.Close();
    
                    string contentlength = System.Text.Encoding.Unicode.GetBytes(filedata).Length.ToString();
    
                    HttpContext.Response.Clear(); // here null Reference Error occur
                    HttpContext.Response.ContentType = "text/plain";
                    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
                    HttpContext.Response.AddHeader("content-length", contentlength);
                    //Response.Buffer = False;
                    HttpContext.Response.TransmitFile(filepath);
                    HttpContext.Response.Flush();
                    HttpContext.Response.Close();
    
                   
    
    
                }
            }

    Friday, August 9, 2019 11:26 AM

All replies

  • User475983607 posted

    but the problem is when it call a method of file generator HttpContext giving me null object error this mean I cannot acesss HttpContext when there is no controller request

    Correct.  Your approach will not work.  The scheduled task should save the file using System.IO.  

    Friday, August 9, 2019 11:34 AM
  • User82362805 posted

    can you please share the sample code here?

    Friday, August 9, 2019 11:42 AM
  • User475983607 posted

    AfaqRajput

    can you please share the sample code here?

    See the following which explains how to save a file.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

    Keep in mind that an HTTP request/response requires a client connection.  If there's no connection with a client then there is no place to return an Http Response.

    Friday, August 9, 2019 11:46 AM