Calling WCF endpoint from Azure Function - azure

I have a v2 Azure function written in dotnet core. I want to call in to a legacy WCF endpoint like this:
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
var factory = new ChannelFactory<IMyWcfService>(basicHttpBinding, null);
factory.Credentials.UserName.UserName = "foo";
factory.Credentials.UserName.Password = "bar";
IMyWcfService myWcfService = factory.CreateChannel(new EndpointAddress(new Uri(endpointUri)));
ICommunicationObject communicationObject = myWcfService as ICommunicationObject;
if ( communicationObject != null)
communicationObject.Open();
try
{
return await myWcfService.GetValueAsync());
}
finally
{
if (communicationObject != null)
communicationObject.Close();
factory.Close();
}
This works when I call it from a unit test, so I know the code is fine running on Windows 10. However, when I debug in the func host, I get missing dependency exceptions. I copied two dlls : System.Private.Runtime and System.Runtime.WindowsRuntime into the in directory, but have reached the end of the line with the exception
Could not load type 'System.Threading.Tasks.AsyncCausalityTracer' from assembly 'mscorlib'
This seems like a runtime rabbit hole that I don't want to go down. Has anyone successfully called a Wcf service from an Azure function? Which dependencies should I add to get the call to work?

Related

How to reduce Azure web app temp file utilization

I have a web app developed in ASP.Net MVC 5 hosted in Azure. I am using a shared app service, not VMs. Recently Azure has started showing warnings that I need to reduce my app's usage of temporary files on workers.
Temp file utilization
After restarting the app, the problem has gone away. Seems that temporary apps were cleared by doing a restart.
How to detect and prevent unexpected growth of the temporary file usages. I am not sure what generated 20 GB of temporary files. What should I look for reduce app usage of temporary? I am not explicitly storing anything in temporary files in code, data is stored in the database, so not sure what to look for?
What are the best practices that should be followed in order to keep the Temp File usages in a healthy state and prevent any unexpected growth?
Note: I have multiple virtual path with same physical path in my Web App.
Virtual path
try
{
if (file != null && file.ContentLength > 0)
{
var fileName = uniqefilename;
CloudStorageAccount storageAccount = AzureBlobStorageModel.GetConnectionString();
if (storageAccount != null)
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
string containerName = "storagecontainer";
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
bool isContainerCreated = container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
CloudBlobDirectory folder = container.GetDirectoryReference("employee");
CloudBlockBlob blockBlob = folder.GetBlockBlobReference(fileName);
UploadDirectory = String.Format("~/upload/{0}/", "blobfloder");
physicalPath = HttpContext.Server.MapPath(UploadDirectory + fileName);
file.SaveAs(physicalPath);
isValid = IsFileValid(ext, physicalPath);
if (isValid)
{
using (var fileStream = System.IO.File.OpenRead(physicalPath))
{
blockBlob.Properties.ContentType = file.ContentType;
blockBlob.UploadFromFile(physicalPath);
if (blockBlob.Properties.Length >= 0)
{
docURL = blockBlob.SnapshotQualifiedUri.ToString();
IsExternalStorage = true;
System.Threading.Tasks.Task T = new System.Threading.Tasks.Task(() => deletefile(physicalPath));
T.Start();
}
}
}
}
}
}
catch (Exception ex)
{
}
//Delete File
public void deletefile(string filepath)
{
try
{
if (!string.IsNullOrWhiteSpace(filepath))
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(filepath);
}
}
catch(Exception e) { }
}
You problem may be caused by using temporary files to process uploads or downloads. The solution would be either to process files using memory stream instead of filestream or delete the temporary files after you are finished processing. This SO exchange has some relevant suggestions:
Azure Web App Temp file cleaning responsibility
Given your update, it looks like your file upload code lets temp files accumulate in line 39, because you are not waiting for your async call to delete the file to finish before you exit. I assume that this code block is tucked inside an MVC controller action, which means that, as soon as the code block is finished, it will abandon the un-awaited async action, leaving you with an undeleted temp file.
Consider updating your code to await your Task action. Also, you may want to update to Task.Run. E.g.,
var t = await Task.Run(async delegate
{
//perform your deletion in here
return some-value-if-you-want;
});

functions implementation

I have implemented multiple groovy methods for sending different notifications, but the code breaks-off the functions concept. So i want to rewrite/combine all groovy methods in one single methods so that i can call that one method wherever i need.
Doesn't matter success or failure and i need to pass message as parameter.
static void sendSuccessApplicationNotification(p1,p2,p3,p4) {
def x = Notify(this)
x.triggerBuild("SUCCESSFUL, application ${p1}:${p2} started properly", "${p3}")
x.triggerBuild("SUCCESSFUL, application ${p1}:${p2} started properly", "${p4")
}
Finally above above should be converted to one method.Checked many articles not getting an exact example.
you can use groovy template engine in your generalized function:
import groovy.text.SimpleTemplateEngine
void triggerBuild(a,b){
println "${a} >>>> ${b}"
}
void sendNotification(code, Map parms, List nodes) {
def templates = [
'appY': 'SUCCESSFUL, application ${app}:${ver} started properly',
'appN': 'FAILED, application ${app}:${ver} failed to start properly',
'depY': 'SUCCESSFUL deployment of ${app}:${ver} to ${node}<br>Executed by ${user}',
'depN': 'FAILED deployment of ${app}:${ver} to ${node}<br>Executed by ${user}'
]
def template = templates[code]
assert template
def message = new SimpleTemplateEngine().createTemplate(template).make(parms).toString()
nodes.each{node->
triggerBuild(message, node)
}
}
sendNotification('appY',[app:'myapp', ver:'v123'],['n1','n2'])
the code above will output:
SUCCESSFUL, application myapp:v123 started properly >>>> n1
SUCCESSFUL, application myapp:v123 started properly >>>> n2

Go + Azure: Calling a method return undefined

Am trying to use Go Azure SDK to call the notification hub api
I have installed the SDK and imported to the GO file :
package hub
import (
"fmt"
"github.com/Azure/azure-sdk-for-go/arm/notificationhubs"
)
func GetHub() {
if resourceType, err := notificationhubs.Get("sourceGroupName", "NameSpaceValue", "NameOfTheHub"); err != nil {
fmt.Println("Error occured")
return
}
fmt.Println("Success")
}
However when am trying to runt he code i got this error
undefined: notificationhubs.Get
And am not sure what it means since my IDE don't complain about importing the Azure SDK so am assuming the SDK is imported correctly.
The function you're trying to use doesn't exist (https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/notificationhubs).
You're probably trying to use the function GroupClient.Get; if that's the case, you need to get an object of type GroupClient and then call the function Get on it.
#cd1 is correct! The Get method doesn't belong directly to namespace that you've imported, but rather a client that exists in that namespace. In order to interact with NotificationsHub in this manner, instantiate a GroupClient then run a Get command.
import (
hubs "github.com/Azure/azure-sdk-for-go/arm/notificationshub"
)
func main() {
// Implementation details of your program ...
client := hubs.NewGroupClient("<YOUR SUBSCRIPTION ID>")
client.Authorizer = // Your initialized Service Principal Token
results, err := client.Get("<RESOURCE GROUP NAME>", "<NAMESPACE NAME>", "<NOTIFICATION HUB NAME>")
if err != nil {
return
}
}

Azure web job keep restarting

I've created a console application that I run as a continuous web job. It does not use the web job SDK, but it checks for the file specified in the WEBJOBS_SHUTDOWN_FILE environment variable.
I have turned the 'Always On' option on, and I'm running the job in the shared plan as a singleton using the settings.job file.
The web job keeps getting stopped by the WEBJOBS_SHUTDOWN_FILE and is restarted again after that.
I've been looking in the kudu sources, but I can't find why my web job is restarted.
Does anybody have an idea why this happens?
This is the code that initializes the FileSystemWatcher:
private void SetupExitWatcher()
{
var file = Environment.GetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE");
var dir = Path.GetDirectoryName(file);
var fileSystemWatcher = new FileSystemWatcher(dir);
FileSystemEventHandler changed = (o, e) =>
{
if (e.FullPath.Equals(Path.GetFileName(file), StringComparison.OrdinalIgnoreCase) >= 0)
{
this.Exit();
}
};
fileSystemWatcher.Created += changed;
fileSystemWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastWrite;
fileSystemWatcher.IncludeSubdirectories = false;
fileSystemWatcher.EnableRaisingEvents = true;
}

Nested IMessageQueueClient publish using Servicestack InMemoryTransientMessageService

We are using InMemoryTransientMessageService to chain several one-way notification between services. We can not use Redis provider, and we do not really need it so far. Synchronous dispatching is enough.
We are experimenting problems when using a publish inside a service that is handling another publish. In pseudo-code:
FirstService.Method()
_messageQueueClient.Publish(obj);
SecondService.Any(obj)
_messageQueueClient.Publish(obj);
ThirdService.Any(obj)
The SecondMessage is never handled. In the following code of ServiceStack TransientMessageServiceBase, when the second message is processed, the service "isRunning" so it does not try to handled the second:
public virtual void Start()
{
if (isRunning) return;
isRunning = true;
this.messageHandlers = this.handlerMap.Values.ToList().ConvertAll(
x => x.CreateMessageHandler()).ToArray();
using (var mqClient = MessageFactory.CreateMessageQueueClient())
{
foreach (var handler in messageHandlers)
{
handler.Process(mqClient);
}
}
this.Stop();
}
I'm not sure about the impact of changing this behaviour in order to be able to nest/chain message publications. Do you think it is safe to remove this check? Some other ideas?
After some tests, it seems there is no problem in removing the "isRunning" control. All nested publications are executed correctly.

Resources