I'm looking for C# SDK example to upload a Docker-Compose file while creating Azure Web App. My sole requirement is to upload a multi-container-based web app through C# SDK programmatically. I've tried exploring the Azure-Samples repository in GitHub but couldn't find any!
Turns out I was using Microsoft.Azure.Management.* SDK and there is a new Azure.ResourceManager.*
Here is the code to deploy a multi-container apps to app service
public void NewMultiContainerApps(string resourceGroupName)
{
string composeFilePath="your compose file path";
string appServicePlanName="app service plan name";
string appServiceName="app service name";
var resourceGroup = this.client.GetDefaultSubscription().GetResourceGroup(resourceGroupName).Value;
var appServicePlanData = new AppServicePlanData("centralus");
appServicePlanData.Sku = new Azure.ResourceManager.AppService.Models.SkuDescription();
appServicePlanData.Sku.Name = "S1";
appServicePlanData.Sku.Tier = "Standard";
appServicePlanData.Sku.Size = "S1";
appServicePlanData.Sku.Family = "S";
appServicePlanData.Sku.Capacity = 1;
appServicePlanData.Kind = "linux";
appServicePlanData.MaximumElasticWorkerCount = 1;
appServicePlanData.Reserved = true;
var appServicePlan = resourceGroup.GetAppServicePlans().CreateOrUpdate(Azure.WaitUntil.Completed, appServicePlanName, appServicePlanData);
var websiteData = new WebSiteData("centralus");
websiteData.ServerFarmId = appServicePlan.Value.Id;
var composeFile = File.ReadAllText(composeFilePath);
var base64ComposeFile = Convert.ToBase64String(Encoding.Default.GetBytes(composeFile));
websiteData.SiteConfig = new Azure.ResourceManager.AppService.Models.SiteConfigProperties();
websiteData.SiteConfig.LinuxFxVersion = $"COMPOSE|{base64ComposeFile}";
websiteData.SiteConfig.NetFrameworkVersion = "v4.6";
websiteData.SiteConfig.AlwaysOn = true;
websiteData.SiteConfig.LocalMySqlEnabled = false;
websiteData.SiteConfig.Http20Enabled = true;
websiteData.SiteConfig.AppSettings = new List<Azure.ResourceManager.AppService.Models.NameValuePair>();
websiteData.ScmSiteAlsoStopped = false;
websiteData.HttpsOnly = false;
websiteData.IsXenon = false;
websiteData.HyperV = false;
websiteData.Reserved = false;
var website = resourceGroup.GetWebSites().CreateOrUpdate(Azure.WaitUntil.Completed, appServiceName, websiteData);
}
Related
I'm trying to import a solution via a small c# console app. I am able to import the solution but I am not able to StageAndUpgradeRequest. I get an error "The [mysolution] solution doesn’t have an upgrade that is ready to be applied."
Here is my code:
ImportSolutionRequest importSolutionRequest = new ImportSolutionRequest()
{
CustomizationFile = data,
ImportJobId = importId,
OverwriteUnmanagedCustomizations = true,
ConvertToManaged = true,
SkipProductUpdateDependencies = false,
//SolutionParameters = new Microsoft.Xrm.Sdk.SolutionParameter
//{
// StageSolutionUploadId = Guid.NewGuid()
//}
};
var importResponse = (ImportSolutionResponse)svc.Execute(importSolutionRequest);
Console.WriteLine(importResponse.ResponseName);
var request = new DeleteAndPromoteRequest
{
UniqueName = "JEuvin",
};
var applyResponse = (DeleteAndPromoteResponse)svc.Execute(request);
Console.WriteLine(applyResponse.SolutionId);
Console.WriteLine("Imported Successfully");
What am I missing?
How to validate uploaded ARM Template using azure .net SDK or Fluent API ?
I want to validate my uploaded ARM template like azure portal do using azure .net SDK or Fluent API ?
For reference please see below image azure is showing message if ARM template not valid so same thing i want to implement using any .net API or REST API.
#Jim Below error I am getting:
If you want to validate your arm template, please refer to the following steps
Create a service principal and assign Contributor role to the sp
az ad sp create-for-rbac -n "MyApp"
Install Package
Install-Package Microsoft.Azure.Management.ResourceManager.Fluent -Version 1.34.0
Code
string clientId = "23****9c";
string clientSecret = "?s****/k";
string tenantDomain = "";
string subscription = "";
var creds= SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantDomain, AzureEnvironment.AzureGlobalCloud);
var restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(creds)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Build();
ResourceManagementClient managementClient = new ResourceManagementClient(restClient);
managementClient.SubscriptionId = subscription;
//Validates whether the specified template is syntactically correct and will be accepted by Azure Resource Manager..
DeploymentValidateResultInner res = await managementClient.Deployments.ValidateAsync("<groupName>", "<deployName>", new DeploymentInner()
{
Location = "",
Properties = new DeploymentProperties()
{
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
Console.WriteLine(res.Error.Message);
// get changes that will be made by the deployment if executed at the scope of resource group
WhatIfOperationResultInner res1 = await managementClient.Deployments.WhatIfAsync("<groupName>", "<deployName>", new DeploymentWhatIf() {
Location="",
Properties= new DeploymentWhatIfProperties() {
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
foreach (var change in res1.Changes) {
//
}
I like that the accepted answer adds the "what if" to validation. However, Microsoft.Azure.Management.ResourceManager is deprecated, and it took me a bit to figure out a way to validate an ARM template using the replacement library: Azure.ResourceManager.
Here's a code snippet that provides template validation using the new library (it doesn't include the what-if call):
var credential = new DefaultAzureCredential();
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var client = new ArmClient(credential, subscriptionId);
var deploymentContent = new ArmDeploymentContent(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
{
Template = BinaryData.FromString(templateContent),
Parameters = BinaryData.FromObjectAsJson(new
{
hostingPlanName = new
{
value = hostingPlanName
},
webSiteName = new
{
value = webAppName
},
skuName = new
{
value = webSkuName
},
skuCapacity = new
{
value = webSkuCapacity
},
})
});
var resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(SubscriptionId!, resourceGroupName);
// This ArmDeploymentResource resource may or may not exist, but it doesn't matter - it's just a placeholder for validation
var deploymentResourceId = ArmDeploymentResource.CreateResourceIdentifier(resourceGroupId, deploymentName);
var armDeployment = client.GetArmDeploymentResource(deploymentResourceId);
var validateOperation = await armDeployment.ValidateAsync(WaitUntil.Completed, toValidate, _cancellationToken);
var validateResult = validateOperation.Value;
if (validateResult.Error != null)
{
_logger.LogEndOperation(loggerOpKey, false, validateResult.Error.Message ?? "Validation errored");
_logger.LogError(JsonConvert.SerializeObject(validateResult.Error, Formatting.Indented));
return false;
}
// Log this if you want:
string deploymentDetails = $"Deployment: {deploymentName} ProvisioningState:{validateResult.Properties.ProvisioningState}\n"
+ $" started:{validateResult.Properties.Timestamp} duration:{validateResult.Properties.Duration}\n"
+ $" correlationId:{validateResult.Properties.CorrelationId}\n"
+ $" outputs:{JsonConvert.SerializeObject(validateResult.Properties.Outputs)}";
bool succeeded = validateResult.Properties.ProvisioningState == "Succeeded";
return succeeded;
I am trying to load .pem certificate file in the following SuperWebSocket code.
var config = new ServerConfig();
config.Ip = xx.xx.xx.xx;
config.Port = 2012;
config.Security = "Tls";
config.Certificate = new CertificateConfig
{
FilePath = #"C:/certificates/certificate.pem",
ClientCertificateRequired = true
};
_s = new WebSocketServer();
_s.Setup(config);
And I started server, failed to load wss://url:2012 but ws://url:2012 is working fine.
Convert pem certificate file into pfx format. It must for .NET version.
Sample code:
var config1 = new ServerConfig();
config1.Ip = brokerIP;
config1.Port = brokerPort;
config1.Security = "Tls";
config1.Certificate = new CertificateConfig
{
FilePath = #"C:\java_cer\certificate.pfx",
ClientCertificateRequired = true
};
//start user sessions listener
if (_brokerServer.Setup(config1))
{
if (!_brokerServer.Start())
{
result = "Failed to setup user listener";
}
}
else
{
result = "Failed to start user listener";
}
I have a problem with comportment of sharepoint.deployment.spimport.
I want to copy a web within the same site collection like that :
myserver/mysitecoll/website1
myserver/mysitecoll/website2
When I use the PowerShell command to execute this, it does it perfectly, the website2 is the same as the website1
Export-SPWeb -Identity http://myserver/mysitecoll/website1 -Path D:\mybackups\mytestsave\mybackup.bak
and
Import-SPWeb -Identity http://myserver/mysitecoll/website2 -Path D:\mybackups\mytestsave\mybackup.bak
But I need to do the same with c# I use
private void ExportSpWeb()
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = SPContext.Current.Web;
SPExportObject exportObject = new SPExportObject();
exportObject.Id = myWeb.ID;
exportObject.ParentId = mySite.ID;
exportObject.Type = SPDeploymentObjectType.Web;
SPExportSettings settings = new SPExportSettings();
settings.SiteUrl = mySite.Url;
settings.ExportMethod = SPExportMethodType.ExportAll;
settings.FileLocation = "D:\\mybackups\\mytestsave";
settings.BaseFileName = "test.cab";
settings.FileCompression = true;
settings.ExcludeDependencies = true;
settings.CommandLineVerbose = true;
settings.ExportObjects.Add(exportObject);
SPExport export = new SPExport(settings);
export.Run();
}
private void importSpWeb()
{
SPSite mySite = SPContext.Current.Site;
SPWeb myDestWeb = mySite.AllWebs["website2"];
SPImportSettings impsettings = new SPImportSettings();
impsettings.SiteUrl = mySite.Url;
impsettings.LogFilePath = "D:\\mybackups\\mytestsave\\test.log";
impsettings.WebUrl = myDestWeb.ServerRelativeUrl;
impsettings.FileLocation = "D:\\mybackups\\mytestsave";
impsettings.FileCompression = true;
impsettings.BaseFileName = "test.cab";
impsettings.RetainObjectIdentity = false;
SPImport import = new SPImport(impsettings);
import.Run();
}
But the comportment is not the same as PowerShell : Instead of being created using the specified WebUrl setting (http://myserver/mysitecoll/website2),
the imported website is created as a new subsite with the path
http://myserver/mysitecoll/website2/website1
How should I edit my code to obtain the same results as PowerShell?
This question got me thinking very deeply, because I hit the wall as you did, but this led me to coming up with a quesion: Where is definition of sharepoint cmdlets and How to get their implementation?
So having the knowledge where Import-SPWeb aka SPCmdletImportWeb in Microsoft.SharePoint.PowerShell.dll is I checked how it's done.
The tricky part is, that for some reason SPImportWeb has some strange logic to modify WebUrl property and always add / to the end. So in SPCmdletImportWeb they are using SPImport class Created event to reset some properties.
For your case, when you're exporting and importing one SPWeb object you need add code below to your import object:
string webUrl = "website2";
// your stuff
SPImport import = new SPImport(impsettings);
import.Started += delegate(object sender, SPDeploymentEventArgs args)
{
SPImportObjectCollection rootObjects = args.RootObjects;
if (rootObjects[0].Type == SPDeploymentObjectType.Web)
{
rootObjects[0].TargetParentUrl = site.Url;
rootObjects[0].TargetName = webUrl;
return;
}
};
To look for the full code of SPCmdletImportWeb get ILSpy and follow my mini tutorial in the first url.
Full test code:
[TestMethod]
public void Test_ExportSpWeb()
{
ExportSpWeb("http://lab/sites/custom-dev", "website1", #"C:\temp\bak\bak2.bak");
}
[TestMethod]
public void Test_ImportSpWeb()
{
ImportSpWeb("http://lab/sites/custom-dev", "website2", #"C:\temp\bak\bak2.bak");
}
private void ImportSpWeb(string siteUrl, string webUrl, string path)
{
using (SPSite site = new SPSite(siteUrl))
using (SPWeb web = site.OpenWeb(webUrl))
{
SPImportSettings impsettings = new SPImportSettings();
impsettings.SiteUrl = site.Url;
impsettings.LogFilePath = path + ".log";
impsettings.WebUrl = web.ServerRelativeUrl + "/" + webUrl;
impsettings.FileLocation = Path.GetDirectoryName(path);
impsettings.FileCompression = true;
impsettings.CommandLineVerbose = true;
impsettings.BaseFileName = Path.GetFileName(path);
impsettings.RetainObjectIdentity = false;
SPImport import = new SPImport(impsettings);
import.Started += delegate(object sender, SPDeploymentEventArgs args)
{
SPImportObjectCollection rootObjects = args.RootObjects;
if (rootObjects[0].Type == SPDeploymentObjectType.Web)
{
rootObjects[0].TargetParentUrl = site.Url;
rootObjects[0].TargetName = webUrl;
return;
}
};
import.Run();
}
}
private void ExportSpWeb(string siteUrl, string webUrl, string path)
{
using (SPSite site = new SPSite(siteUrl))
using (SPWeb web = site.OpenWeb(webUrl))
{
SPExportObject exportObject = new SPExportObject();
exportObject.Id = web.ID;
exportObject.ParentId = site.ID;
exportObject.Type = SPDeploymentObjectType.Web;
SPExportSettings settings = new SPExportSettings();
settings.SiteUrl = site.Url;
settings.ExportMethod = SPExportMethodType.ExportAll;
settings.FileLocation = Path.GetDirectoryName(path);
settings.BaseFileName = Path.GetFileName(path);
settings.LogFilePath = path + ".log";
settings.FileCompression = true;
settings.ExcludeDependencies = true;
settings.CommandLineVerbose = true;
settings.ExportObjects.Add(exportObject);
SPExport export = new SPExport(settings);
export.Run();
}
}
I am developing c# client to connect Openfire server
This is my code
User = txtUserName.Text;
Pwd = txtPassword.Text;
pnlCredentials.Enabled = false;
jabberClient1.User = User;
jabberClient1.Server = "61.182.225.189";
jabberClient1.Password = Pwd;
jabberClient1.AutoRoster = true;
jabberClient1.Port = 5222;
JID jid = new JID("kamal", "192,168,1,17", "123456");
jabberClient1.AutoLogin = true;
jabberClient1.Resource = jid.Resource;
jabberClient1.AutoStartTLS = true;
jabberClient1.NetworkHost = null;
jabberClient1.OnInvalidCertificate += new System.Net.Security.RemoteCertificateValidationCallback(jabberClient1_OnInvalidCertificate);
rm = new RosterManager();
rm.Stream = jabberClient1;
rm.AutoSubscribe = true;
rm.AutoAllow = jabber.client.AutoSubscriptionHanding.AllowAll;
rm.OnRosterBegin += new bedrock.ObjectHandler(rm_OnRosterBegin);
rm.OnRosterEnd += new bedrock.ObjectHandler(rm_OnRosterEnd);
rm.OnRosterItem += new RosterItemHandler(rm_OnRosterItem);
pm = new PresenceManager();
pm.Stream = jabberClient1;
rosterTree1.RosterManager = rm;
rosterTree1.PresenceManager = pm;
rosterTree1.DoubleClick += new EventHandler(rosterTree1_DoubleClick);
jabberClient1.OnAuthenticate += new bedrock.ObjectHandler(jabberClient1_OnAuthenticate);
lblUser.Text = jabberClient1.User;
jabberClient1.Connect();
I am not sure what I need to use in parameters for below
JID jid = new JID("kamal", "192,168,1,17", "123456");
I used user name , server IP and password for that
when I run this it returns error
Error binding resource error type="modify" code="400"bad-requestmlns="urn:ietf:params:xml:ns:xmpp-stanzas"
Could you please help me to solve this
Thank you in advance
I have edited the code using the latest Jabber.net DLL as bellows
JabberClient jabberClient = new JabberClient();
//Bind the JabberClient events to methods that handle those events.
jabberClient.OnAuthError += new IQHandler(jabberClient_OnAuthError);
jabberClient.OnError += new bedrock.ExceptionHandler(jabberClient_OnError);
jabberClient.OnConnect += new bedrock.ObjectHandler(jabberClient_OnConnect);
jabberClient.OnDisconnect += new bedrock.ObjectHandler(jabberClient_OnDisconnect);
//Set client settings
jabberClient.AutoReconnect = 3;
JID jid = new JID("kamal", "192.168,1,17", "123456");
jabberClient.User = jid.User;
jabberClient.Server = jid.Server;
jabberClient.Port =5222;
jabberClient.Resource = jid.Resource;
jabberClient.Password = "123456";
jabberClient.AutoPresence = false;
jabberClient.AutoLogin = true;
jabberClient.Connect();
Now when I try to connect it does fire disconnect event ?