Hangfire Discussion

Setting environment variable fail in production

recurring
aspnetcore
Tags: #<Tag:0x00007f84f9678f88> #<Tag:0x00007f84f9678d58>

#1

I am using google text to speech and everything works in debug. when I push to production, if the method is called by a user using web frontend, everything works but if the method is called under HangFIre scheduler, I get an error saying object reference is not set to an instance of an object on any line. Does anybody know which account Hangfire scheduler run under and if it has something to do with it, how to fix it. Here is the code that fails on first line if scheduler does the scheduling.

 public static void TextToVoice(string text, Guid guid)
        {
           //Fails right here asp.net object reference not set to an instance of an object
            string path1 = @"C:\inetpub\Email\files\tcx1-d73434edb97e.json"; //HttpContext.Current.Server.MapPath("~/app_data/tcx1-d73434edb97e.json");
            if (Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") == null)
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",path1);
            var client = TextToSpeechClient.Create();
            var input = new SynthesisInput
            { Text = text };

            var voiceSelection = new VoiceSelectionParams
            {
                LanguageCode = "en-US",
                SsmlGender = SsmlVoiceGender.Female
            };

            var audioConfig = new AudioConfig
            {
                AudioEncoding = AudioEncoding.Mp3
            };

            var response = client.SynthesizeSpeech(input, voiceSelection, audioConfig);
            using (var output = File.Create(HttpContext.Current.Server.MapPath("~/files/" + guid.ToString() + ".mp3"))) 
            {
                response.AudioContent.WriteTo(output);
            }
        }

#2

First, you shouldn’t really be using a static method for your job as hangfire has an activator to handle instantiation. Also, you are accessing HttpContext which is NOT something you will have access to at this point because a hangfire job runs outside of the scope of your request on a separate thread not managed by IIS. As for your exception, that’s just a standard null reference exception you’ll need to put breakpoints in and debug it.


#3

Thank you for your reply. Very helpful. A couple of comments

  1. this method is within a class and HangFire calls another method which does some work and then calls this method. So this method is not called directly by HangFire
  2. As you can see I commented HttpContext and hard coded the directory. still have the same problem
  3. When I call this method from the front end client, It works fine
  4. I get the exception as soon as I reach this method before any line is called

Do you have any example of how this method can be configured to avoid this issue? That would be most helpful.