Error in Webjob microsoft.azure.webjobs.host could not load phb

Occasional Visitor

Hi Guys,

 

I am facing one issue.

 

I am running a web job in Azure app service which is reading events from IoTHub.

 

After running for sometimes the web job throws an error:

 

Microsoft.WindowsAzure.Storage.StorageException occurred
  HResult=0x80131500
  Message=The client could not finish the operation within the specified timeout.
  Source=Microsoft.WindowsAzure.Storage
  StackTrace:
   at Microsoft.WindowsAzure.Storage.Core.Util.StorageAsyncResult`1.End() in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\StorageAsyncResult.cs:line 77
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.EndUploadFromStream(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlockBlob.cs:line 774
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.EndUploadFromByteArray(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlockBlob.cs:line 1162
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.EndUploadText(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlockBlob.cs:line 1285
   at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass4.<CreateCallbackVoid>b__3(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 114
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 184
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 156
   at Microsoft.Azure.WebJobs.Host.Loggers.UpdateOutputLogCommand.<UpdateOutputBlob>d__18.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 184
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 156
   at Microsoft.Azure.WebJobs.Host.Loggers.UpdateOutputLogCommand.<TryExecuteAsync>d__14.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 184
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 156
   at Microsoft.Azure.WebJobs.Host.Timers.RecurrentTaskSeriesCommand.<ExecuteAsync>d__3.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 184
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\clr\src\BCL\system\runtime\compilerservices\TaskAwaiter.cs:line 156
   at Microsoft.Azure.WebJobs.Host.Timers.TaskSeriesTimer.<RunAsync>d__14.MoveNext()
   at Microsoft.Azure.WebJobs.Host.Timers.WebJobsExceptionHandler.<>c__DisplayClass3_0.<OnUnhandledExceptionAsync>b__0()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state) in f:\dd\ndp\clr\src\BCL\system\threading\thread.cs:line 68
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) in f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs:line 954
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) in f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs:line 901
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) in f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs:line 890
   at System.Threading.ThreadHelper.ThreadStart() in f:\dd\ndp\clr\src\BCL\system\threading\thread.cs:line 105

Inner Exception 1:
TimeoutException: The client could not finish the operation within the specified timeout.

 

 

I tried to fix the problem by adding lines in Program.cs

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.ServiceBus;
using System;

namespace RoomDetails.WebJob
{
    // To learn more about Microsoft Azure WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976
    class Program
    {
        static string eventHubName = "interelcloud-ehout";
        static string connectionString = "Endpoint=sb://interelcloud.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXXXX";

        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var config = new JobHostConfiguration();
         
            config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(60);
            config.Queues.VisibilityTimeout = TimeSpan.FromSeconds(60);
            var eventHubConfig = new EventHubConfiguration();
      
            eventHubConfig.AddReceiver(eventHubName, connectionString);
            config.UseEventHub(eventHubConfig);

            JobHost host = new JobHost(config);
         
            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
    }
}


functions.cs is

 

 

namespace RoomDetails.WebJob
{
    /// <summary>
    /// Class Functions.
    /// </summary>
    public class Functions
    {
        static HttpClient client = new HttpClient();

        /// <summary>
        /// The container
        /// </summary>
        private static readonly IContainer Container;

        /// <summary>
        /// The room logic
        /// </summary>
        private static IRoomLogic _roomLogic;

        /// <summary>
        /// Initializes static members of the <see cref="Functions"/> class.
        /// </summary>
        static Functions()
        {
            //  client.BaseAddress = new Uri("http://interelrc.azurewebsites.net/");
            client.BaseAddress = new Uri("http://localhost:65224/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          
            var builder = new ContainerBuilder();
            builder.RegisterModule(new WebAutofacModule());
            builder.RegisterType<ConfigurationProvider>().As<IConfigurationProvider>();
            Container = builder.Build();
        }


        static async Task UpdateFanMode(string fanMode, string roomNumber, string eventDate)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync($"rooms/updatefanmode?roomNumber={roomNumber}&fanmode={fanMode}&eventDate={eventDate}", "");
            response.EnsureSuccessStatusCode();

            // Return the URI of the created resource.
            //return response.Headers.Location;
        }

        static async Task UpdateSetPoint(string setPoint, string roomNumber, string eventDate)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync($"rooms/updatesetpoint?roomNumber={roomNumber}&setpoint={setPoint}&eventDate={eventDate}", "");
            response.EnsureSuccessStatusCode();

            // Return the URI of the created resource.
            //return response.Headers.Location;
        }

        static async Task UpdateUpgradeStatus(string status, string roomNumber)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync($"rooms/updateupgradestatus?roomNumber={roomNumber}&status={status}", "");
            response.EnsureSuccessStatusCode();

            // Return the URI of the created resource.
            //return response.Headers.Location;
        }

        static async Task UpdateDndMurStatus(string status, string roomNumber, string eventDate)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync($"rooms/updateDndMurStatus?roomNumber={roomNumber}&status={status}&eventDate={eventDate}", "");
            response.EnsureSuccessStatusCode();
        }

        static async Task UpdateUserPresenceStatus(string status, string roomNumber, string eventDate)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync($"rooms/updateUserPresenceStatus?roomNumber={roomNumber}&status={status}&eventDate={eventDate}", "");
            response.EnsureSuccessStatusCode();
        }



        /// <summary>
        /// Triggers the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>Task.</returns>
        public static async Task Trigger([EventHubTrigger("interelcloud-ehout")] string message)
        {
            try
            {
                string data = message;
                _roomLogic = Container.Resolve<IRoomLogic>();
                if (data.Contains("category") && data.Contains("Connections"))
                {
                    try
                    {
                        DeviceConnectionMessage[] deviceConnectionMessage = JsonConvert.DeserializeObject<DeviceConnectionMessage[]>(data);
                        foreach (var item in deviceConnectionMessage)
                        {
                            var hotelRoom = await _roomLogic.GetRoomByDeviceIdAsync(item.deviceId);
                            hotelRoom.IsRoomOnline = (item.operationName == "deviceConnect");
                            await _roomLogic.UpdateRoomAsync(hotelRoom);
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
                else if (data.Contains("operation") && data.Contains("UPGRADE"))
                {
                    var payload = JsonConvert.DeserializeObject<UpgradPayload>(data);
                    var hotelRoom = await _roomLogic.GetHotelRoomAsync(payload.RoomNumber, payload.HotelName);

                    hotelRoom.RoomRCUs[0].Status = payload.Status;

                    if (!string.IsNullOrEmpty(payload.Version))
                    {
                    hotelRoom.RoomRCUs[0].InstalledDate= payload.UpgradeDate;
                        hotelRoom.RoomRCUs[0].FirmwareVersion = payload.Version;

                    }

                    await _roomLogic.UpdateRoomAsync(hotelRoom);

                    await UpdateUpgradeStatus(payload.Status, payload.RoomNumber);
                }


                else
                {
                    DeviceTelemetry deviceTelemetry = JsonConvert.DeserializeObject<DeviceTelemetry>(data);
                    var hotelRoom = await _roomLogic.GetHotelRoomAsync(deviceTelemetry.roomNumber.ToString(), deviceTelemetry.hotelname);
                   
                    string eventDate = hotelRoom._tsUpd?.ToString("dd-MM-yyyy hh:mm:ss");
                    if (data.Contains("fanSpeed"))
                    {
                        hotelRoom.FanMode = GetFanModeText(deviceTelemetry.fanSpeed);
                        await UpdateFanMode(hotelRoom.FanMode, hotelRoom.RoomNumber, eventDate);
                    }
                    if (data.Contains("roomTemperature"))
                    {
                        hotelRoom.ActualTemperature = (float)deviceTelemetry.roomTemperature;
                    }
                    if (data.Contains("setPoint"))
                    {
                        hotelRoom.SetPoint = (float)deviceTelemetry.setPoint;
                        await UpdateSetPoint(hotelRoom.SetPoint.ToString(), hotelRoom.RoomNumber, eventDate);

                    }
                    else if (data.Contains("dnd"))
                    {
                        await UpdateDndMurStatus($"{deviceTelemetry.dnd.ToString()}-{deviceTelemetry.mur.ToString()}", hotelRoom.RoomNumber, eventDate);

                        hotelRoom.DndState = deviceTelemetry.dnd;
                        hotelRoom.MurState = deviceTelemetry.mur;
                    }
                    else if (data.Contains("presence"))
                    {
                        hotelRoom.PresenceStatus = deviceTelemetry.presence;
                        await UpdateUserPresenceStatus($"{deviceTelemetry.presence.ToString()}", hotelRoom.RoomNumber, eventDate);
                    }

                    await _roomLogic.UpdateRoomAsync(hotelRoom);
                }
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"At {DateTime.Now} Message received. Data: '{data}'");
                Console.ResetColor();
            }
            catch (Exception ex)
            {
                 throw ex.InnerException;
            }
        }

        /// <summary>
        /// Gets the fan mode text.
        /// </summary>
        /// <param name="fanMode">The fan mode.</param>
        /// <returns>System.String.</returns>
        private static string GetFanModeText(int fanMode)
        {
            switch (fanMode)
            {
                case 1:
                    return "Low";

                case 2:
                    return "Medium";

                case 3:
                    return "High";

                case 4:
                    return "Auto";

                case 5:
                    return "Eco";

                case 6:
                    return "Off";
            }

            return "";
        }
    }

    public class UpgradPayload
    {
        [JsonProperty("deviceId")]
        public string DeviceId { get; set; }

        [JsonProperty("operation")]
        public string Operation { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("hotelName")]
        public string HotelName { get; set; }

        [JsonProperty("roomNumber")]
        public string RoomNumber { get; set; }

        [JsonProperty("upgradeDate")]
        public DateTime UpgradeDate { get; set; }


        [JsonProperty("version")]
        public string Version { get; set; }
    }


}


         


 

IoTHub Subscription ID: a11bf993-e71f-43ff-b512-647cee60e4c6

 

I would be grateful if you provide me with a solution.

 

Thanks and best regards,

0 Replies