Hot questions for Using Azure in cloud

Question:

I'm using the Azure table storage from java, following the tutorial here. I'm successfully able to create a table, add an entity, retrieve an entity and delete an entity. However, I've got this method to delete a table:

public void deleteTable(String tableName) {
    try {
        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
        CloudTableClient tableClient = storageAccount.createCloudTableClient();

        // Delete the table and all its data if it exists.
        CloudTable cloudTable = new CloudTable(tableName, tableClient);

        cloudTable.deleteIfExists();
    } catch (Exception e) {
        System.out.println("Error in deleting");
        e.printStackTrace();
    }
}

In this method I am getting an error on this line

CloudTable cloudTable = new CloudTable(tableName, tableClient);

which has no suggestions available within eclipse only the following markers:

Multiple markers at this line

  • The constructor CloudTable(String, CloudTableClient) is not visible
  • The constructor CloudTable(String, CloudTableClient) is not visible

Any help would be greatly appreciated.


Answer:

If you look at CloudTable constructors here, you will notice that the code you're using is not a valid one. It is possible that the SDK got upgraded however the code sample isn't. I would suggest using getTableReference method on CloudTableClient to get an instance of CloudTable:

try
{
    // Retrieve storage account from connection-string.
    CloudStorageAccount storageAccount =
        CloudStorageAccount.parse(storageConnectionString);

    // Create the table client.
    CloudTableClient tableClient = storageAccount.createCloudTableClient();

    // Delete the table and all its data if it exists.
    CloudTable cloudTable = tableClient.getTableReference("people");
    cloudTable.deleteIfExists();
}
catch (Exception e)
{
    // Output the stack trace.
    e.printStackTrace();
}

Question:

I'm currently testing the MS Azure Storage API for Android I found here: github: azure-storage-android.

I tried the sample code and it is working fine. Assume the setup of the CloudStorageAccount, the CloudBlobClient and the CloudBlobContainer is already done as showcased by the sample (also found in the same git repo)

Following code works fine:

CloudBlockBlob blockBlob = container.getBlockBlobReference("blockblob");
blockBlob.uploadText("foobar");

When I run this code and look at the Blob Container using e.g. the Azure Storage Explorer everything is fine. Here is the result:

Now the error-case:

Switching from

container.getBlockBlobReference("...")

to

container.getAppendBlobReference("...")

and working with CloudAppendBlob instead of CloudBlockBlob as seen in this snippet:

CloudAppendBlob appendBlob = container.getAppendBlobReference("appendblob");
appendBlob.createOrReplace();
appendBlob.appendText("foobar");

leaves me with following error every time I try to read container data:

Error retrieving blob list: 409 Conflict

Does anyone have any idea why this is happening and how to fix it? I tried using Leases but it didn't change the result.

Thanks in advance!


Answer:

As Emily mentioned in her comments, the issue is with Azure Storage Explorer tool. Append Blobs are supported in the latest version of Storage API and unfortunately the tool is not updated to make use of the latest version.

You can make use of other tools that support the latest version of Storage API and thus Append Blobs. A few of them I can recommend are: Cloud Portam [Full Disclosure: I am building this tool], Cerebrata Azure Explorer, Cerebrata Azure Management Studio and ClumsyLeaf CloudXplorer.

Question:

I am new to IoTHub. I have successfully sent messages to IOT hub (D2C) using python.The protocol we used is mqtt.We are trying to retrieve data from cloud(IOT hub) using java,but could not able to find out a proper way to recieve message from the cloud..My doubt is whether we can read messages from IOT Hub directly or we need to redirect the incoming messages to an event hub to retrieve the message.

Also I tried to read messages from iothub in java simultaneously while sending data to cloud,but I got the error as follows..(Lost connection to the server. Reconnecting 0 time.)

I use this code to read data from iothub,

import com.microsoft.azure.sdk.iot.device.DeviceClient;
import com.microsoft.azure.sdk.iot.device.IotHubMessageResult;
import com.microsoft.azure.sdk.iot.device.Message;
import com.microsoft.azure.sdk.iot.device.MessageCallback;
import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol;
import com.microsoft.azure.sdk.iot.service.sdk.IotHubServiceClientProtocol;
import java.io.IOException;
import java.net.URISyntaxException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Kafkareception {

    public static void main(String[] args) throws IOException {
        try {
            String connString = "HostName=";
            IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
            DeviceClient client = new DeviceClient(connString, protocol);

            MessageCallback callback = new AppMessageCallback();
            client.setMessageCallback(callback, null);
            client.open();
        } catch (URISyntaxException ex) {
            Logger.getLogger(Kafkareception.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static class AppMessageCallback implements MessageCallback {

        public IotHubMessageResult execute(Message msg, Object context) {
            System.out.println(new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET) + "Received message from hub: ");

            return IotHubMessageResult.COMPLETE;
        }
    }
}

Answer:

From information you provided, you may tried to setup two active connections of one device to Azure IoT Hub using DeviceClient: one is sending D2C messages and one is "reading data from iothub". You get the error maybe because:

IoT Hub only supports one active MQTT connection per device. Any new MQTT connection on behalf of the same device ID causes IoT Hub to drop the existing connection.

Ref:Communicate with your IoT hub using the MQTT protocol.

If you want to receive D2C message that sent to Azure IoT Hub you can use Event Hub-compatible endpoint(Java). No need to redirect the incoming messages to an event hub by yourself.

IoT Hub exposes the messages/events built-in endpoint for your back-end services to read the device-to-cloud messages received by your hub. This endpoint is Event Hub-compatible, which enables you to use any of the mechanisms the Event Hubs service supports for reading messages.

Ref: Understand Azure IoT Hub messaging and IoT Hub endpoints.

Question:

Using Jclouds and jclouds-labs azurecompute I have the following code snip-it which is working as expected

ContextBuilder contextBuilder = ContextBuilder.newBuilder(cloudProvider);

AzureComputeApi api = contextBuilder
     .credentials(keyStoreLocation, keyStorePassword)
     .endpoint(uri + subscriptionId)
     .buildApi(AzureComputeApi.class);

List<Location> locations = api.getLocationApi().list();
for(Location l : locations)
     System.out.println(l);

AzureComputeApi is connecting and printing expected output

Location{name=West Europe, displayName=West Europe, availableServices=[Compute, Storage, PersistentVMRole, HighMemory]}
Location{name=North Europe, displayName=North Europe, availableServices=[Compute, Storage, PersistentVMRole, HighMemory]}
...

However my existing jclouds code base is working with an ComputeService type e.g. this approach is working of the cloudProvider's AWS and GCE

ContextBuilder contextBuilder = newContextBuilder(cloudProvider);

ComputeService cs =  contextBuilder
    .credentials(identity, credential)
    .buildView(ComputeServiceContext.class)
    .getComputeService();

How can i get AzureComputeApi to return a ComputeService (or some thing to this effect), so that I don't have to change my existing code base ? is this is possible.

If I try this code snip-it, using cloudPprovider=azurecompute

ContextBuilder contextBuilder = ContextBuilder.newBuilder(cloudProvider);
ComputeService cs  = contextBuilder
    .credentials(keyStoreLocation, keyStorePassword)
    .endpoint(uri + subscriptionId)
    .buildView(ComputeServiceContext.class)
    .getComputeService();

I get this exception thrown

Exception in thread "main" java.lang.IllegalArgumentException: api {id=azurecompute, name=Microsoft Azure Service Management Service API, views=[], endpointName=Service Management Endpoint ending in your Subscription Id, identityName=Path to Management Certificate .p12 file, or PEM string, credentialName=Optional.of(Password to Management Certificate), documentation=http://msdn.microsoft.com/en-us/library/ee460799, api=interface org.jclouds.azurecompute.AzureComputeApi} not wrappable as org.jclouds.compute.ComputeServiceContext; context: org.jclouds.rest.ApiContext<org.jclouds.azurecompute.AzureComputeApi>, views: []
    at org.jclouds.ContextBuilder.buildView(ContextBuilder.java:604)
    at org.jclouds.ContextBuilder.buildView(ContextBuilder.java:588)
    at com.hazelcast.stabilizer.provisioner.ComputeServiceBuilder.main(ComputeServiceBuilder.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

I know all my keyStoreLocation, keyStorePassword, uri + subscriptionId variables are ok as they work If i am handle the AzureComputeApi direct


Answer:

Azure compute is still under development and the ComputeService abstraction is still a work in progress, so you can't use it yet; you have to use directly the AzureComputeApi. You can track JCLOUDS-664 if you want to stay up to date.

Question:

I found quite a few documents advertising or explaining how to enable geo-redundant (or geo-replicated) MS Azure storage accounts. Finding some document explaining how to access the secondary storage turned out more difficult.

From the little (potentially outdated) information I found, my understanding is that in order to access the secondary location for geo-redundant storage accounts I just set the location mode to LocationMode.SECONDARY_ONLY and then proceed as usual. If I do that however (in Java, using the SDK vs 0.6.0 and azure-storage-1.2.0.jar library), a StorageException is thrown, caused by a java.net.UnknownHostException.

I also found, that the hostname for the secondary location should be -secondary..core.windows.net. And while .cloud.core.windows.net resolves for my (geo redundant) storage account, -secondary.cloud.core.windows.net does not.

So, where do I err and how do I access the secondary location (it's also my understanding that I must access the secondary location in order to use the getServiceStats() method of a CloudBlobClient object)?


Answer:

Make sure the storage account type is Read-only Access to Geo Redundant Storage (RA-GRS), not just Geo Redundant Storage (GRS). Otherwise you won't be able to access the secondary directly.

Question:

I am trying to have a POC running, with which I can use Azure Service Bus relay with Java as backend.

Azure Service Bus relay allow .NET libraries to integrate. There is no Java library available.

If it is not possible with Java, is there any other alternative with java for relay functionality.


Answer:

I searched an answer for your question from MSDN thread How to relay on premises java web service through service bus?.

This isn't available in Java. Only WCF Services are able to use Service Bus Relay feature currently.

Some options to workaround this might be:

  1. Create a wrapper WCF service in front of the existing Java Service and register it with Service Bus Relay this way making it available.

  2. Making this into a Loosely coupled architecture by leveraging the Service Bus features that are available currently for Java, like Queues and Topics.

Hope it helps. Best Regards.

Question:

I am well aware of the reasons behind app:dexDebug error in Android. Going through many similar question in stackoverflow and trying every possible solution, I finally traced out the cause of the error. Below are my dependencies:

If the two compiles

compile 'com.google.android.gms:play-services:+'
compile 'com.microsoft.azure:azure-mobile-services-android-sdk:2.0.3'

are compiled together, the error is caused. Removing either of the compiles removes the error, but I don't understand why? Google Play is required for cloud messaging while Azure services is required for registering the device to the Azure push notification hub. I don't see any possibility that they share common jar files or have repeated/duplicate class anywhere.

The libs folder is empty.

Any suggestion for the problem?


Answer:

There is no conflict of Google play service and azure mobile service compiles. I have a test project with dependencies: compile 'com.android.support:appcompat-v7:23.1.0' compile 'com.microsoft.azure:azure-mobile-services-android-sdk:2.0.3' compile 'com.google.android.gms:play-services:+' And sync project with gradle files, it works fine on my side.

To integrate Notification Hubs in Azure Mobile Service, we can refer to official guide of Azure Notification Hubs which was updated at 10/15/2015. In this article, it uses gms dependency in: compile 'com.google.android.gms:play-services-base:6.5.87'

By the way, I found the a thread with the same issue you met, maybe it will give you some help.

Question:

I'm just trying to set up my springcloud with azure functions test to play with the environment. When I ran as just a SpringBoot/Cloud app it worked fine. When I add the Azure adapter, it had me add a class with a bunch of annotations like below.

I'm trying to get it to run in junit before I try promoting to Azure itself.

public class AzureReverseAdapter extends AzureSpringBootRequestHandler<String, String> {

    public AzureReverseAdapter() {
        super();
        // TODO Auto-generated constructor stub
    }

    public AzureReverseAdapter(Class<?> configurationClass) {
        super(configurationClass);
        // TODO Auto-generated constructor stub
    }

    @FunctionName("reverseString")
    public String execute(
            @HttpTrigger(name = "request", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            ExecutionContext context) {

        context.getLogger().info("Input: " + request.getBody().get());
        return handleRequest(request.getBody().get(), context);
    }

}

But the following test:

    @Test
    public void start() throws Exception {
//        AzureSpringBootRequestHandler<String, String> handler = new AzureSpringBootRequestHandler<String, String>(CloudFunctionApplication.class);
        AzureReverseAdapter handler = new AzureReverseAdapter(CloudFunctionApplication.class);
        String result = handler.handleRequest("Hello World", null);
        handler.close();
        Assert.assertEquals(result, "dlroW olleH");
    }

throws this exception:

java.lang.AbstractMethodError: org.springframework.boot.context.config.ConfigFileApplicationListener.supportsSourceType(Ljava/lang/Class;)Z
    at org.springframework.context.event.GenericApplicationListenerAdapter.supportsSourceType(GenericApplicationListenerAdapter.java:79)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.supportsEvent(AbstractApplicationEventMulticaster.java:289)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:221)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:192)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:347)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:306)
    at org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.initialize(AbstractSpringFunctionAdapterInitializer.java:117)
    at org.springframework.cloud.function.adapter.azure.AzureSpringBootRequestHandler.handleRequest(AzureSpringBootRequestHandler.java:58)
    at test.TestCloud.start(TestCloud.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:628)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:117)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:127)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

I think I reproduced the example I was working on pretty well. So I'm not sure what I'm missing. The error seems to complain about a lack of application.properties when I look up that listener class' Javadoc. I added the application.properties in the root of my classpath. Same error. I'm not sure what properties I need to define if any.


Answer:

Problem comes from pom.xml. java.lang.AbstractMethodError is thrown when an app tries to call an abstract method. Your code can works with earlier version but the later version that is setted in pom.xml makes the method abstract. Solution is try earlier versions in the setting of pom.xml.

setting like this(under the modelVersion):

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository --></relativePath>
</parent>

try earlier version than what you used know.

Question:

I deployed a new version of my Azure Functions based on Java. Now there is following error toast in the Azure portal under my Azure Function resource in a specific function:

Error: The function runtime is unable to start. Microsoft.Azure.WebJobs.ServiceBus: Could not load type 'Microsoft.Azure.ServiceBus.Management.ManagementClient' from assembly 'Microsoft.Azure.ServiceBus, Version=3.0.2.0, Culture=neutral, PublicKeyToken=7e34167dcc6d6d8c'. Session Id: a9f3c42dbb524ceca2c5158df9460c97 Timestamp: 2019-12-02T18:21:46.680Z

It sounds for me a bit like that: https://github.com/Azure/azure-functions-host/issues/3363

The interesting thing is that I changed nothing except some minor Java code changes till the last deployment. Is the Function App Version automatically updated?

I also checked the logs via kudu and log stream (application logs).

logs:

2019-12-02T11:08:04.412 [Information] Starting JobHost 2019-12-02T11:08:04.415 [Information] Starting Host (HostId=functionapp-dtw-worker-dp-master, InstanceId=aaab65a2-acef-4e4c-a8be-c3a1b13a795c, Version=2.0.12888.0, ProcessId=6860, AppDomainId=1, InDebugMode=True, InDiagnosticMode=False, FunctionsExtensionVersion=~2) 2019-12-02T11:08:04.467 [Information] Loading functions metadata 2019-12-02T11:08:04.495 [Information] 3 functions loaded 2019-12-02T11:08:04.812 [Information] Generating 3 job function(s) 2019-12-02T11:08:05.126 [Information] Found the following functions: Host.Functions.lastWillCronJobProcessor Host.Functions.serviceBusDeadLetterProcessor Host.Functions.serviceBusProcessor 2019-12-02T11:08:05.351 [Error] A host error has occurred during startup operation '7c3d76bc-730c-401a-86cb-27d04231d515'. System.TypeLoadException : Could not load type 'Microsoft.Azure.ServiceBus.Management.ManagementClient' from assembly 'Microsoft.Azure.ServiceBus, Version=3.0.2.0, Culture=neutral, PublicKeyToken=7e34167dcc6d6d8c'. at Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusScaleMonitor..ctor(String functionId,EntityType entityType,String entityPath,String connectionString,Lazy1 receiver,ILoggerFactory loggerFactory)
at Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener.<.ctor>b__18_0()
at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication,Boolean useDefaultConstructor)
at System.Lazy1.CreateValue() at Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener.GetMonitor() at Microsoft.Azure.WebJobs.Host.Listeners.HostListenerFactory.RegisterScaleMonitor(IListener listener,IScaleMonitorManager monitorManager) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Listeners\HostListenerFactory.cs : 107 at async Microsoft.Azure.WebJobs.Host.Listeners.HostListenerFactory.CreateAsync(CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Listeners\HostListenerFactory.cs : 69 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at async Microsoft.Azure.WebJobs.Host.Listeners.ListenerFactoryListener.StartAsyncCore(CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Listeners\ListenerFactoryListener.cs : 45 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at async Microsoft.Azure.WebJobs.Host.Listeners.ShutdownListener.StartAsync(CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Listeners\ShutdownListener.cs : 29 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at async Microsoft.Azure.WebJobs.JobHost.StartAsyncCore(CancellationToken cancellationToken) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\JobHost.cs : 101 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at async Microsoft.Azure.WebJobs.Script.ScriptHost.StartAsyncCore(CancellationToken cancellationToken) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Host\ScriptHost.cs : 249 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at async Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken) at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at async Microsoft.Azure.WebJobs.Script.WebHost.WebJobsScriptHostService.UnsynchronizedStartHostAsync(ScriptHostStartupOperation activeOperation,Int32 attemptCount,JobHostStartupMode startupMode) at C:\azure-webjobs-sdk-script\src\WebJobs.Script.WebHost\WebJobsScriptHostService.cs : 235

Log streaming:

Same logs as in the log file via kudu

Do you know why it stopped working? I have no plan to be honest. Did any configuration for the service bus trigger changes?

Check for a solution in the Azure portal For issues in production, please check for a solution to common issues in the Azure portal before opening a bug. In the Azure portal, navigate to your function app => Platform features => Diagnose and solve problems and the relevant dashboards before opening your issue.

Investigative information Please provide the following:

Timestamp: 2019-12-02T18:21:46.680Z Function App version (1.0 or 2.0): 2.0.12888.0 (~2) Function App name: functionapp-dtw-worker-dp-master Application Setting: FUNCTIONS_WORKER_RUNTIME: java Function name(s) (as appropriate): serviceBusProcessor Session Id: a9f3c42dbb524ceca2c5158df9460c97 Region: West Europe Related information Provide any related information

Programming language used: Java with Spring Boot, Spring Cloud Functions Links to source Bindings used: ServiceBusTrigger, TimeTrigger

SUPPLEMENT: I updated the local dependencies like .NET Core Version to the newest v2.2.8 from here: https://dotnet.microsoft.com/download/dotnet-core/2.2

The update does not change the error message. I get the same error exception when I locally start the function with the maven plugin "azure-functions-maven-plugin" version 1.3.4, as you can see below:

[12/2/2019 10:44:26 PM] Starting JobHost [12/2/2019 10:44:26 PM] Starting Host (HostId=n900b368-1683948780, InstanceId=889e113f-9129-4a24-8fbf-9b560addd68e, Version=2.0.12888.0, ProcessId=2368, AppDomainId=1, InDebugMode=False, InDiagnosticMode=False, FunctionsExtensionVersion=(null)) [12/2/2019 10:44:26 PM] Loading functions metadata [12/2/2019 10:44:26 PM] 3 functions loaded [12/2/2019 10:44:26 PM] Generating 3 job function(s) [12/2/2019 10:44:26 PM] Found the following functions: [12/2/2019 10:44:26 PM] Host.Functions.lastWillCronJobProcessor [12/2/2019 10:44:26 PM] Host.Functions.serviceBusDeadLetterProcessor [12/2/2019 10:44:26 PM] Host.Functions.serviceBusProcessor [12/2/2019 10:44:26 PM] [12/2/2019 10:44:26 PM] A host error has occurred during startup operation '03187631-f70a-45f5-9c3e-008568c4c6a4'. [12/2/2019 10:44:26 PM] Microsoft.Azure.WebJobs.ServiceBus: Could not load type 'Microsoft.Azure.ServiceBus.Management.ManagementClient' from assembly 'Microsoft.Azure.ServiceBus, Version=3.0.2.0, Culture=neutral, PublicKeyToken=7e34167dcc6d6d8c'. [12/2/2019 10:44:26 PM] Stopping JobHost

GitHub Issue Report: https://github.com/Azure/azure-functions-host/issues/5317

Do you have any suggestion to solve that problems?


Answer:

it seems that the deployment somehow removes the installed extensions. I just had the same error with a TS function after deployment from VSCode. As a workaround I started the creation of a new function in the same function app using the same template as I used for the other functions in the app (e. g. Azure Service Bus Topic trigger). In my case this triggered a new installation of the required extensions and the error was gone.

Question:

I develop a high load enterprise application. There are 2 services which should be scaled in specific way. They use Azure EventHubs for messaging. When load increase we need to create one more instance of a service and create one more topic (Event Hub) for communication with other services.

Is there a way to create event hub dynamically from java code? For example if I use Kafka I can just pass name of topic that doesn't exist and it will create it by itself. When I try to do it with Azure EventHubs I have such error:

The messaging entity 'sb://eventhubdev.servicebus.windows.net/newTopic' could not be found.

So... is it possible to create and delete it programmatically? Google didn't help me with this question clearly enough.


Answer:

There might be a solution to scale via java, but I would challenge that. Scaling should be handled by your infrastructure (e.g. kubernetes) and not your code. Furthermore, I don't know if the eventhub is dynamically enough to be scaled in the first place.

Providing the eventhub could be done via terraform. See Link for further details: https://www.terraform.io/docs/providers/azurerm/r/eventhub.html

Question:

I have a board that sends jsons with telemetry to Azure IoT hub (using http). I want to read telemetry data with my android device. I looked some examples of reading messages from IoT hub for android, but I found only how to read them from "Cloud to device feedback" endpoint. So now my application looks like:

Json from the board ----> "Events" endpoint ---> Function application that resending json to "Cloud to device feedback" endpoint -----> "Cloud to device feedback" endpoint ----> Android device.

I'm a beginner in Azure, so I'm sure that exists smarter way to do that. (Json from the board ----> "Events" endpoint ---> Android device). I did it on my desktop, but looks like android doesn't work with some libraries from desktop project.

Does anybody know how can I do it? (maybe some guides or lessons)

Desktop version

Part of android code:

public void btnReceiveOnClick(View v) throws URISyntaxException, IOException
{
    System.out.println("Receiving:");
    Button button = (Button) v;

    // Comment/uncomment from lines below to use HTTPS or MQTT protocol
    //IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
    IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;

    DeviceClient client = new DeviceClient(connString, protocol);

    if (protocol == IotHubClientProtocol.MQTT)
    {
        MessageCallbackMqtt callback = new MessageCallbackMqtt();
        Counter counter = new Counter(0);
        client.setMessageCallback(callback, counter);
    } else
    {
        MessageCallback callback = new MessageCallback();
        Counter counter = new Counter(0);
        client.setMessageCallback(callback, counter);
    }

    try
    {
        client.open();
    } catch (Exception e2)
    {
        System.out.println("Exception while opening IoTHub connection: " + e2.toString());
    }

    try
    {
        Thread.sleep(1000);
    } catch (InterruptedException e)
    {
        e.printStackTrace();
    }

    client.closeNow();

    try {
        ....

    }catch (JSONException je){
        ....
    }
}



// Our MQTT doesn't support abandon/reject, so we will only display the messaged received
// from IoTHub and return COMPLETE
static class MessageCallbackMqtt implements com.microsoft.azure.sdk.iot.device.MessageCallback
{
    public IotHubMessageResult execute(Message msg, Object context)
    {
        responce = new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET);
        Counter counter = (Counter) context;
        System.out.println(
                "[from MessageCallbackMqtt] Received message " + counter.toString()
                        + " with content: " + responce);

        counter.increment();
        return IotHubMessageResult.COMPLETE;
    }
}

static class EventCallback implements IotHubEventCallback
{
    public void execute(IotHubStatusCode status, Object context)
    {
        Integer i = (Integer) context;
        System.out.println("[from EventCallback]  IoT Hub responded to message " + i.toString()
                + " with status " + status.name());
    }
}

static class MessageCallback implements com.microsoft.azure.sdk.iot.device.MessageCallback
{
    public IotHubMessageResult execute(Message msg, Object context)
    {
        Counter counter = (Counter) context;
        System.out.println(
                "Received message " + counter.toString()
                        + " with content: " + new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET));

        int switchVal = counter.get() % 3;
        IotHubMessageResult res;
        switch (switchVal)
        {
            case 0:
                res = IotHubMessageResult.COMPLETE;
                break;
            case 1:
                res = IotHubMessageResult.ABANDON;
                break;
            case 2:
                res = IotHubMessageResult.REJECT;
                break;
            default:
                // should never happen.
                throw new IllegalStateException("Invalid message result specified.");
        }

        System.out.println("Responding to message " + counter.toString() + " with " + res.name());
        counter.increment();
        return res;
    }
}

Answer:

You can refer to this document.It shows how to read the telemetry from you IoT Hub with Java.In the ReadDeviceToCloudMessages.java sample, it connects to the service-side Events endpoint on your IoT Hub and receives the device-to-cloud messages.

BTW, you can get the eventHubsCompatibleEndpoint, eventHubsCompatiblePath and iotHubSasKey from Azure Portal simply. The eventHubsCompatibleEndpoint is in this format:

sb://xxxxxxxxxxxxxx.servicebus.windows.net/

Question:

I'm trying to integrate azure's app service with my app. In particular, I'm trying to store data on the database hosted by Azure. I can insert data fine, but whenever I try to retrieve it, my app freezes.

MainActivity- starts the activity and initializes the azure connection and table.

public class MainActivity extends ActionBarActivity {

    /**
     * TODO: view data, put data in ordered lists, rate data, scheduler
     * **/

    Toolbar toolbar;
    ViewPager pager;
    ViewPageAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[]={"New","Trending","Famous"};
    int Numboftabs =3;
    MobileServiceClient client;
    MobileServiceTable<Post> postTable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Creating The Toolbar and setting it as the Toolbar for the activity

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);

        //manually set action bar color since not happening before
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));

        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPageAdapter(getSupportFragmentManager(),Titles,Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.colorAccent);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);



        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                postPrompt();
            }
        });

        //initialize azure
        try {
            client = new MobileServiceClient("https://firechat.azurewebsites.net", this);
            postTable = client.getTable(Post.class);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        //testing
        //Post post = new Post("haha, so funny :p");
        //postTable.insert(post);

    }


    private String makePost(String input){
        Post post = new Post(input);
        postTable.insert(post);
        return post.text;
    }
}
        return post.text;
    }
}

Tab1- a fragment that populates a list with data retrieved from the server. I believe my error is here when I try to query azure for the data.

public class Tab1 extends Fragment {
    MainActivity mainActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab_1,container,false);

        return v;
    }

    @Override
    public void onStart() {
        super.onStart();

        try {
            //get data from azure
            mainActivity = (MainActivity) getActivity();
            List<Post> postList= mainActivity.postTable.execute().get();
            //List<Post> postList = new ArrayList<Post>();

            //set lists
            ListView newListView = (ListView) mainActivity.findViewById(R.id.newListView);
            NewAdapter newAdapter = new NewAdapter(mainActivity, postList);
            newListView.setAdapter(newAdapter);
        }catch(Exception e){

        }
    }
}

Answer:

I found out I was having the error because you must retrieve data from Azure using an async task. I left an example of one down below.

private void retrievePosts(){
        AsyncTask<Void,Void,Void> task = new AsyncTask<Void,Void,Void>(){
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    postList= mainActivity.postTable.execute().get();
                    Log.e("TAG",postList.get(0).text);
                    newAdapter.updateList(postList);
                } catch (final Exception e) {
                }
                return null;
            }
        };

        runAsyncTask(task);
    }