I use Perforce Api (.net c#) works.
source...
//--------Connect--------
Perforce.P4.Server server = new Perforce.P4.Server(new Perforce.P4.ServerAddress("111.222.333.444"));
Perforce.P4.Repository rep = new Perforce.P4.Repository(server);
Perforce.P4.Connection con = rep.Connection;
con.UserName = "PSY";
string password = "gangnamstyle";
con.Client = new Perforce.P4.Client();
Perforce.P4.Options opconnect = new Perforce.P4.Options();
opconnect.Add("-p", password);
con.Connect(opconnect);
con.Login(password);
//--------How to ?--------
string ws_client = #"C:\ClientPath\";
string depot = "//depot/";
Perforce.P4.P4Server p4Server = new Perforce.P4.P4Server(server.Address.Uri, con.UserName, password, ws_client);
Perforce.P4.P4Command com = new Perforce.P4.P4Command(p4Server);
//--------Disconnect---------
con.Disconnect();
Perforce commands of this "Get Latest Revision"
If you already have the workspace for c:\clientPath setup on your machine and assuming it has the name myWorkspace (as in the "Workspace" column in the "Workspaces" tab in p4v), then:
client.Name = "myWorkspace";
client.Initialize(con);
con.Client = client; // otherwise later things fail somewhat mysteriously
con.CommandTimeout = new TimeSpan(0); // otherwise the sync is likely to time out
client.SyncFiles(new Perforce.P4.Options()); // sync everything
Related
How do I set ECS_CLUSTER=my_cluster_name in user-data when launching a new EC2 instance using the AWS .NET SDK?
I've found info on doing this manually by running a bash script on the machine. But I'm specifically interested in learning how to do this programmatically, using the SDK.
Found it in the RunInstancesRequest class. The key for me was not only in finding the UserData field, but also in including the IamInstanceProfile. Here's an example:
string userDataString = $"#!/bin/bash \necho ECS_CLUSTER=my_cluster_name >> /etc/ecs/ecs.config";
string userData = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userDataString));
var response = client.RunInstances(new RunInstancesRequest
{
ImageId = "ami-abc12345",
InstanceType = "t2.micro",
KeyName = "my-key-pair",
MaxCount = 1,
MinCount = 1,
SecurityGroupIds = new List<string> { "sg-1a2b3c4d"},
SubnetId = "subnet-6e7f829e",
UserData = userData,
IamInstanceProfile = new IamInstanceProfileSpecification { Name = "ecsInstanceRole" }
});
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_container_instance.html
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesRequest.html
All of the documentation for SpeechClient that I've found involves either running a command line after downloading the SDK, or awkwardly setting up a "GOOGLE_APPLICATION_CREDENTIALS" environment variable to point to a local credential file.
I hate the environment variable approach, and instead want a solution that loads a shared, source-controlled dev account file from the application root. Something like this:
var credential = GoogleCredential.FromStream(/*load shared file from app root*/);
var client = SpeechClient.Create(/*I wish I could pass credential in here*/);
Is there a way to do this so that I don't have to rely on the environment variable?
Yes, by converting the GoogleCredential into a ChannelCredentials, and using that to initialize a Channel, which you then wrap in a SpeechClient:
using Grpc.Auth;
//...
GoogleCredential googleCredential;
using (Stream m = new FileStream(credentialsFilePath, FileMode.Open))
googleCredential = GoogleCredential.FromStream(m);
var channel = new Grpc.Core.Channel(SpeechClient.DefaultEndpoint.Host,
googleCredential.ToChannelCredentials());
var speech = SpeechClient.Create(channel);
Update 2018-02-02 https://cloud.google.com/docs/authentication/production now shows all they possible ways to authenticate to a Google Cloud Service, including a sample like this one.
In latest version SpeechClient.Create does not have any parameters.
Now it is possible to do it using SpeechClientBuilder:
var client = new SpeechClientBuilder { ChannelCredentials = credentials.ToChannelCredentials() }.Build();
'Install-Package Google.Cloud.Speech.V1 -Version 3.0.0
Imports Google.Cloud.Speech.V1
'Dim sCredentialsPath As String = "C:\google_keys\deft.json"
'Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", sCredentialsPath)
'Dim oSpeechClient As SpeechClient = Google.Cloud.Speech.V1.SpeechClient.Create()
Dim oSpeechSettings As New SpeechSettings()
Dim oSpeechClient = New SpeechClientBuilder With {
.CredentialsPath = sCredentialsPath
}.Build()
Dim oRecognitionAudio As RecognitionAudio = RecognitionAudio.FromFile("C:\Temp\test.weba")
Dim oRecognitionConfig As New RecognitionConfig
'oRecognitionConfig.SampleRateHertz = 44100
oRecognitionConfig.LanguageCode = LanguageCodes.English.UnitedStates '"en-US"
oRecognitionConfig.Encoding = RecognitionConfig.Types.AudioEncoding.WebmOpus
Dim oRecognizeResponse As RecognizeResponse = oSpeechClient.Recognize(oRecognitionConfig, oRecognitionAudio)
Dim sRet As String = ""
For Each oResult As Google.Cloud.Speech.V1.SpeechRecognitionResult In oRecognizeResponse.Results
For Each oAlternative As Google.Cloud.Speech.V1.SpeechRecognitionAlternative In oResult.Alternatives
sRet += oAlternative.Transcript
Next
Next
I am detecting whether or not I'm attempting a connection against localhost, and creating (or not) the WMI connection options as follows:
if (NetworkUtils.IsLocalIpAddress(machineName))
{
_scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", machineName));
}
else
{
_connectionOptions = new ConnectionOptions
{
Username = username,
Password = password,
Impersonation = ImpersonationLevel.Impersonate
};
_scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", machineName), _connectionOptions);
}
When I call _scope.Connect() in either case, it works. That is, no exception and IsConnected is true.
However, when I attempt to invoke a method in the local case, such as Win32_Share.Create I get errors. The following code always works for remote connections for me:
var winSharePath = new ManagementPath("Win32_Share");
var winShareClass = new ManagementClass(_scope, winSharePath, null);
var shareParams = winShareClass.GetMethodParameters("Create");
shareParams["Path"] = pathName.TrimEnd('\\');
shareParams["Name"] = shareName;
shareParams["Type"] = 0;
shareParams["Description"] = "CMC Bootstrap Share";
var outParams = winShareClass.InvokeMethod("Create", shareParams, null);
if ((uint) (outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " +
outParams.Properties["ReturnValue"].Value);
}
I create the pathName directory just prior to invoking this method, so I guarantee pathName exists in all cases.
When executing locally ONLY on Windows Server 2008 & 2012, the above code throws the exception with error code 24. Executing against localhost on Windows 8 works just fine.
What is the correct way to specify "blank credentials" when invoking WMI methods against localhost, as I believe this is the underlying issue?
I tried the code below on my local PC and this works (shares my temp folder). Could you try the same please? Also, which is the patch & share name you're using?
string pathName = #"c:\temp\";
string shareName = "tempFolder";
var scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", "localhost"));
// your code below
var winSharePath = new ManagementPath("Win32_Share");
var winShareClass = new ManagementClass(scope, winSharePath, null);
var shareParams = winShareClass.GetMethodParameters("Create");
shareParams["Path"] = pathName.TrimEnd('\\');
shareParams["Name"] = shareName;
shareParams["Type"] = 0;
shareParams["Description"] = "CMC Bootstrap Share";
var outParams = winShareClass.InvokeMethod("Create", shareParams, null);
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " +
outParams.Properties["ReturnValue"].Value);
}
the above code throws the exception with error code 24
That doesn't have anything to do with the error you mention in the title of your question. Error codes for Win32_Share.Create method are documented in this MSDN article. Return value 24 means "Unknown Device or Directory".
In other words, your pathName variable is wrong.
I am using SharpSVN dll with my Visual Studio 2010 to get the latest revision number so I can version my project using this number. I tried this piece of code below but it gives me error saying:
Can't determine the user's config path
I don't even understand what that means. All I want to do is provide the svn link, my credentials like username and password and get the latest revision number.
Here is the code I tried so far:
using(SvnClient client = new SvnClient())
{
//client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "Svn"), true);
Collection<SvnLogEventArgs> list;
client.Authentication.DefaultCredentials = new NetworkCredential("john.locke", "s7y5543a!!");
SvnLogArgs la = new SvnLogArgs();
client.GetLog(new Uri("https://100.10.20.12/svn/P2713888/trunk/src/"), la, out list);
string sRevisionNumber = string.Empty;
int iRevisionNumber = 0;
foreach(SvnLogEventArgs a in list)
{
if (Convert.ToInt32(a.Revision) > iRevisionNumber)
{
iRevisionNumber = Convert.ToInt32(a.Revision);
}
}
RevisionNumber.Text = iRevisionNumber.ToString();
}
other ways to get the revision number may also be selected as answer.
I had this problem as well-- needing to find/set properties on the SvnClient before use. Here's what I ended up using. Try using this method instead of just instantiating your client object-- it will auto-create a config folder if it doesn't already exist:
private SvnClient GetClient()
{
SvnClient client = new SvnClient();
// Note: Settings creds up here is optional
// client.Authentication.DefaultCredentials = _creds;
string configPath = Path.Combine(Path.GetTempPath(), "sharpsvn");
if (!Directory.Exists(configPath))
{
Directory.CreateDirectory(configPath);
}
client.LoadConfiguration(configPath, true);
return client;
}
Alternately, if you want to minimize File IO checking to see if the directory exists, you can try LoadConfiguration, and only create and reassign the directory if that call failed, but just checking each time is simpler.
At any rate, you can then get the latest revision number for a location using the following code:
public long GetLatestRevisionNumber(Uri svnPath)
{
using (SvnClient client = GetClient())
{
SvnInfoEventArgs info;
client.GetInfo(svnPath, out info);
return info.LastChangeRevision;
}
}
I want to use SPExport (which is working OK) and SPImport to copy one web to another location. I am using Application Page in Sharepoint Foundation 2010. This code is executed on a Button click event.
using (SPWeb web = site.OpenWeb(sourceWebUrl))
{
SPExportSettings exportSettings = new SPExportSettings();
exportSettings.FileLocation = exportPath;
exportSettings.BaseFileName = exportFileName;
exportSettings.SiteUrl = site.Url;
exportSettings.ExportMethod = SPExportMethodType.ExportAll;
exportSettings.FileCompression = true;
exportSettings.IncludeVersions = SPIncludeVersions.All;
exportSettings.IncludeSecurity = SPIncludeSecurity.All;
exportSettings.ExcludeDependencies = false;
exportSettings.ExportFrontEndFileStreams = true;
exportSettings.OverwriteExistingDataFile = true;
SPExportObject expObj = new SPExportObject();
expObj.IncludeDescendants = SPIncludeDescendants.All;
expObj.Id = web.ID;
expObj.Type = SPDeploymentObjectType.Web;
exportSettings.ExportObjects.Add(expObj);
SPExport export = new SPExport(exportSettings);
export.Run();
}
using (SPWeb web = site.OpenWeb(destinationWebUrl))
{
web.AllowUnsafeUpdates = true;
SPImportSettings importSettings = new SPImportSettings();
web.FileLocation = exportPath;
web.BaseFileName = exportFileName;
web.IncludeSecurity = SPIncludeSecurity.All;
web.UpdateVersions = SPUpdateVersions.Overwrite;
web.RetainObjectIdentity = false;
web.SiteUrl = site.Url;
web.WebUrl = web.Url;
web.Validate();
SPImport import = new SPImport(importSettings);
import.Run();
web.AllowUnsafeUpdates = false;
}
Exception "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. " is thrown when SPImport.Run() is called.
I haven't been able to find a solution for this problem neither adding FormDigest control on application page nor Allowing Unsafe Updates on the destination web.
Also, running this code from Console Application works OK, but if code runs from Application Page it is not working (even with elevated security).
Any help would be appreciated. Thanks.
Managed to do this by adding
SPUtility.ValidateFormDigest();
at line 1.