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";
}
Related
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);
}
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;
In my C# code, I want to create a Couchbase client using the ctor version that I can pass in the bucketName and password:
//
// Summary:
// Initializes a new instance of the Couchbase.CouchbaseClient class using the
// default configuration and the specified bucket.
//
// Remarks:
// The configuration is taken from the /configuration/Couchbase section.
public CouchbaseClient(string bucketName, string bucketPassword);
In my web.config file the <couchbase> section looks like this:
<couchbase>
<servers bucket="beer-sample" bucketPassword="">
<add uri="localhost:8091/pools" />
</servers>
</couchbase>
And in the code I try to create a Couchbase client by:
var cc = new CouchbaseClient("beer-sample", "ThePassword");
The above line always failing with error "cannot locate note". Can anyone help?
First, you are using an old version of the Couchbase .Net SDK.
CouchbaseClient is the old way of using Couchbase.
Please refer to the new Guide -> http://docs.couchbase.com/developer/dotnet-2.1/dotnet-intro.html
Second, you must have your bucket created with the password you want to have.
for example:
var clientConfiguration = new ClientConfiguration();
clientConfiguration.Servers = new List<Uri> { new Uri("http://localhost:8091") };
Cluster Cluster = new Cluster(clientConfiguration);
using (var bucket = Cluster.OpenBucket("bucketpwd", "1234"))
{
Console.WriteLine("Bucket Opened");
}
Hope it helps.
A little bit old topic but maybe it could help people with the same issue.
I'm currently using couchbase .net client 2.7.5
var clusterConfig = new ClientConfiguration
{
Servers = new List<Uri>{new Uri("http://couchbase0-node.io:8091")},
PoolConfiguration = new PoolConfiguration()
};
using (var cluster = new Cluster(clusterConfig))
{
var authenticator = new PasswordAuthenticator(username, password);
cluster.Authenticate(authenticator);
using (var bucket = cluster.OpenBucket(bucketName))
{
// Do something like :
var data = await bucket.GetAsync<T>(cacheKey);
// Other staff
}
}
See more on : https://docs.couchbase.com/dotnet-sdk/2.7/start-using-sdk.html
Refer this document for Couchbase Server 3.0/3.1
ClientConfiguration example
var config = new ClientConfiguration
{
Servers = new List<Uri>
{
new Uri("http://192.168.56.101:8091/pools"),
new Uri("http://192.168.56.102:8091/pools"),
new Uri("http://192.168.56.103:8091/pools"),
new Uri("http://192.168.56.104:8091/pools"),
},
UseSsl = true,
DefaultOperationLifespan = 1000,
BucketConfigs = new Dictionary<string, BucketConfiguration>
{
{"default", new BucketConfiguration
{
BucketName = "default",
UseSsl = false,
Password = "",
DefaultOperationLifespan = 2000,
PoolConfiguration = new PoolConfiguration
{
MaxSize = 10,
MinSize = 5,
SendTimeout = 12000
}
}}
}
};
using (var cluster = new Cluster(config))
{
IBucket bucket = null;
try
{
bucket = cluster.OpenBucket();
//use the bucket here
}
finally
{
if (bucket != null)
{
cluster.CloseBucket(bucket);
}
}
}
}
http://docs.couchbase.com/developer/dotnet-2.1/configuring-the-client.html
I would like to implement the Perforce command "Get Revision [Changelist Number]" using the Perforce .NET API (C#). I currently have code that will "Get Latest Revision", but I need to modify it to get a specific changelist.
To sync the data with a changelist number, what should I do?
Source
// --------Connenct----------------
Perforce.P4.Server server = new Perforce.P4.Server(
new Perforce.P4.ServerAddress("127.0.0.1:9999"));
Perforce.P4.Repository rep = new Perforce.P4.Repository(server);
Perforce.P4.Connection con = rep.Connection;
con.UserName = m_P4ID;
string password = m_P4PASS;
Perforce.P4.Options opconnect = new Perforce.P4.Options();
opconnect.Add("-p", password);
con.Connect(opconnect);
if (con.Credential == null)
con.Login(password);
//----------Download----------
string clientPath = #"C:\P4V\";
string ws_client = clientPath;
Perforce.P4.Client client = new Perforce.P4.Client();
client.Name = ws_client;
client.Initialize(con);
con.CommandTimeout = new TimeSpan(0);
IList<Perforce.P4.FileSpec> fileList = client.SyncFiles(new Perforce.P4.Options());
//----------Disconnect------------
con.Disconnect();
con.Dispose();
Edit: Attempt 1
Perforce.P4.DepotPath depot = new Perforce.P4.DepotPath("//P4V//");
Perforce.P4.LocalPath local = new Perforce.P4.LocalPath(ws_client);
Perforce.P4.FileSpec fs = new Perforce.P4.FileSpec(depot, null, local,
Perforce.P4.VersionSpec.Head);
IList<Perforce.P4.FileSpec> listFiles = new List<Perforce.P4.FileSpec>();
listFiles.Add(fs);
IList<Perforce.P4.FileSpec> foundFiles = rep.GetDepotFiles(listFiles,
new Perforce.P4.Options(1234)); // 1234 = Changelist number
client.SyncFiles(foundFiles, null);
Error Message
Usage: files/print [-o localFile -q] files...Invalid option: -c.
I do not know the problem of any argument.
Or there will not be related to this reference source?
Edit 2
I tried to solve this problem. However, it does not solve the problem yet.
Perforce.P4.Changelist changelist = rep.GetChangelist(1234);
IList<Perforce.P4.FileMetaData> fileMeta = changelist.Files;
In this case, I could get only the files in the changelist. I would like to synchronize all files of the client at the moment of changelist 1234.
SyncFiles takes an optional FileSpec arg. You can specify a file path and a revision specifier with that FileSpec arg. Here are the relevant docs:
FileSpec object docs
SyncFiles method docs
You don't need to run GetDepotFiles() to get the FileSpec object; you can just create one directly as shown in the FileSpec object docs. The error you are getting with GetDepotFiles() is because it expects the change number to be specified as part of the FileSpec object passed into as the first argument to GetDepotFiles().
To expand further, GetDepotFiles() calls the 'p4 files' command when it talks to Perforce. new Perforce.P4.Options(1234) generates an option of '-c 1234' which 'p4 files' doesn't accept. That's why the error message is 'Usage: files/print [-o localFile -q] files...Invalid option: -c.'
I struggled with the same problem as well. Finally based on Matt's answer I got it working. Please see simple example below.
using (Connection con = rep.Connection)
{
//setting up client object with viewmap
Client client = new Client();
client.Name = "p4apinet_solution_builder_sample_application_client";
client.OwnerName = "p4username";
client.Root = "c:\\clientRootPath";
client.Options = ClientOption.AllWrite;
client.LineEnd = LineEnd.Local;
client.SubmitOptions = new ClientSubmitOptions(false, SubmitType.RevertUnchanged);
client.ViewMap = new ViewMap();
client.ViewMap.Add("//depotpath/to/your/file.txt", "//" + client.Name + "/clientpath/to/your/file.txt", MapType.Include);
//connecting to p4 and creating client on p4 server
Options options = new Options();
options["Password"] = "p4password";
con.UserName = "p4username";
con.Client = new Client();
con.Connect(options);
con.Client = rep.CreateClient(client);
//syncing all files (in this case 1) defined in client's viewmap to the changelist level of 12345
Options syncFlags = new Options(SyncFilesCmdFlags.Force, 100);
VersionSpec changeListLevel = new ChangelistIdVersion(12345);
List<FileSpec> filesToBeSynced = con.Client.ViewMap.Select<MapEntry, FileSpec>(me => new FileSpec(me.Left, changeListLevel)).ToList();
IList<FileSpec> results = con.Client.SyncFiles(filesToBeSynced, syncFlags);
}
The following code should allow you to sync a depot to a particular revision (changelist number).
string uri = "...";
string user = "...";
string workspace = "...";
string pass = "...";
int id = 12345; // the actual changelist number
string depotPath = "//depot/foo/main/...";
int maxItemsToSync = 10000;
Server server = new Server(new ServerAddress(uri));
Repository rep = new Repository(server);
server = new Server(new ServerAddress(uri));
rep = new Repository(server);
Connection con = rep.Connection;
con.UserName = user;
con.Client = new Client();
con.Client.Name = workspace;
// connect
bool connected = con.Connect(null);
if (connected)
{
try
{
// attempt a login
Perforce.P4.Credential cred = con.Login(pass);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
con.Disconnect();
connected = false;
}
if (connected)
{
// get p4 info and show successful connection
ServerMetaData info = rep.GetServerMetaData(null);
Console.WriteLine("CONNECTED TO " + info.Address.Uri);
Console.WriteLine("");
try
{
Options opts = new Options();
// uncomment below lines to only get a preview of the sync w/o updating the workspace
//SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.Preview, maxItemsToSync);
SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.None, maxItemsToSync);
VersionSpec version = new ChangelistIdVersion(id);
PathSpec path = new DepotPath(depotPath);
FileSpec depotFile = new FileSpec(path, version);
IList<FileSpec> syncedFiles = rep.Connection.Client.SyncFiles(syncOpts, depotFile);
//foreach (var file in syncedFiles)
//{
// Console.WriteLine(file.ToString());
//}
Console.WriteLine($"{syncedFiles.Count} files got synced!");
}
catch (Exception ex)
{
Console.WriteLine("");
Console.WriteLine(ex.Message);
Console.WriteLine("");
}
finally
{
con.Disconnect();
}
}
}
If you are looking for other ways to build the file spec, like for example sync only a specific list of files to "head", etc, visit this link and search for "Building a FileSpec"