Como detectar se o ambiente está em teste ou produção na função de trabalhador de serviço hospedado do azure?
-
29-10-2019 - |
Pergunta
Tenho uma função de trabalho em meu serviço hospedado. O trabalhador está enviando e-mail bases diárias. Mas no serviço hospedado, existem 2 ambientes, Preparação e Produção. Portanto, minha função de trabalho envia e-mail 2 vezes ao dia. Gostaria de saber como detectar se o operário está em encenação ou produção. Agradecemos antecipadamente.
Solução
De acordo com minha pergunta aqui , você verá que não existe uma maneira rápida de fazer isso.Além disso, a menos que você realmente saiba o que está fazendo, sugiro fortemente que não faça isso .
No entanto, se quiser, você pode usar uma biblioteca muito boa (Azure Service Management via C # ), embora tivéssemos alguns problemas com o WCF ao usá-lo.
Aqui está um exemplo rápido de como fazer isso (observe que você precisa incluir o certificado de gerenciamento como um recurso em seu código e implantá-lo no Azure):
private static bool IsStaging()
{
try
{
if (!CloudEnvironment.IsAvailable)
return false;
const string certName = "AzureManagement.pfx";
const string password = "Pa$$w0rd";
// load certificate
var manifestResourceStream = typeof(ProjectContext).Assembly.GetManifestResourceStream(certName);
if (manifestResourceStream == null)
{
// should we panic?
return true;
}
var bytes = new byte[manifestResourceStream.Length];
manifestResourceStream.Read(bytes, 0, bytes.Length);
var cert = new X509Certificate2(bytes, password);
var serviceManagementChannel = Microsoft.Toolkit.WindowsAzure.ServiceManagement.ServiceManagementHelper.
CreateServiceManagementChannel("WindowsAzureServiceManagement", cert);
using (new OperationContextScope((IContextChannel)serviceManagementChannel))
{
var hostedServices =
serviceManagementChannel.ListHostedServices(WellKnownConfiguration.General.SubscriptionId);
// because we don't know the name of the hosted service, we'll do something really wasteful
// and iterate
foreach (var hostedService in hostedServices)
{
var ad =
serviceManagementChannel.GetHostedServiceWithDetails(
WellKnownConfiguration.General.SubscriptionId,
hostedService.ServiceName, true);
var deployment =
ad.Deployments.Where(
x => x.PrivateID == Zebra.Framework.Azure.CloudEnvironment.CurrentRoleInstanceId).
FirstOrDefault
();
if (deployment != null)
{
return deployment.DeploymentSlot.ToLower().Equals("staging");
}
}
}
return false;
}
catch (Exception e)
{
// if something went wrong, let's not panic
TraceManager.AzureFrameworkTraceSource.TraceData(System.Diagnostics.TraceEventType.Error, "Exception", e);
return false;
}
}
Outras dicas
Se você estiver usando um servidor SQL (Azure SQL ou SQL Server hospedado na VM), poderá interromper a função de trabalho de teste, permitindo apenas que o IP público da instância de produção acesse o servidor de banco de dados.