Launch AWS EC2 Instance with User-data using the .NET SDK - c#

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

Related

C# - First step with Amazon MWS

I'm an Amazon FBA seller and I would like to begin to upload data regarding my sales in a more automated process using Amazon MWS. I just made an amazon MWS account and received my different IDs (Access Key Id, secret Access Key, ...).
I have the impression that most MWS developers use C#. I have a lot of Excel VBA experience but not in C#. Therefore, I'm not sure of the steps I have to follow.
On the webpage below, you can find a C# code that I would like to run:
http://www.samswiches.com/2011/02/how-to-use-amazon-mws-to-download-unshipped-order-reports/
Could you confirm the steps below are correct? :
1) Download Visual Studio => Do I need to download any extra package from Amazon?
2) In Visual Studio: File => New Project => C# console application
3) Erase all code and replace it by a copy-paste of the code found on above website => Do I need to put the code Inside something like "Sub - end Sub" in VBA?
4) Change "YourSecretKey", "YourSecretAccessKey", "YourSecretAccessKey", "YourMerchantID", "YourMarketplaceID" by my IDs.
5) Hit the run button
If it works, what will be the output like: An array inside Visual studio? A text file? A csv file? Where will it be stored?
I realize this is a very newbie question. However, I think that once I have a first code running correctly, my VBA experience will allow me to start efficiently from there.
Thanks in advance,
Diego.
After looking the code from http://www.samswiches.com/2011/02/how-to-use-amazon-mws-to-download-unshipped-order-reports/
I tried and changed something, and it works. Here is my solution:
Download the C# MWS Reports API Client Library: https://developer.amazonservices.com/doc/bde/reports/v20090101/cSharp.html
Use Visual Studio to create a project to get reports using MWS Reports API Client Library
Here is the code.
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using MarketplaceWebService;
using MarketplaceWebService.Mock;
using MarketplaceWebService.Model;
using System.IO;
using System.Threading;
public void testReport()
{
String accessKeyId = "Your Access Key ID";
String secretAccessKey = "Your Secret Access Key";
const string merchantId = "Merchant ID";
const string marketplaceId = "Marketplace ID";
MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
config.ServiceURL = "https://mws.amazonservices.com";
const string applicationName = "ApplicationName";
const string applicationVersion = "0.01";
MarketplaceWebServiceClient service =
new MarketplaceWebServiceClient(
accessKeyId,
secretAccessKey,
applicationName,
applicationVersion,
config);
RequestReportRequest reportRequestRequest = new RequestReportRequest();
reportRequestRequest.Merchant = merchantId;
// you can change ReportType here:
//http://docs.developer.amazonservices.com/en_IN/reports/Reports_ReportType.html
reportRequestRequest.ReportType = “_GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_";
RequestReportResponse requestResponse = service.RequestReport(reportRequestRequest);
IdList lstRequestID = new IdList();
lstRequestID.Id.Add
(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);
GetReportRequestListRequest reportRequestListRequest = new
GetReportRequestListRequest();
reportRequestListRequest.Merchant = merchantId;
reportRequestListRequest.ReportRequestIdList = lstRequestID;
List<ReportRequestInfo> myListzz = new List<ReportRequestInfo>();
GetReportRequestListResponse reportRequestListResponse = new
GetReportRequestListResponse();
reportRequestListResponse =
service.GetReportRequestList(reportRequestListRequest);
GetReportRequestListResult reportRequestListResult = new
GetReportRequestListResult();
reportRequestListResult =
reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
if (myListzz.Count > 0)
{
while (myListzz[0].ReportProcessingStatus.ToString() != "_DONE_")
{
Console.WriteLine("Waiting for Report");
Thread.Sleep(61000);
reportRequestListResponse =
service.GetReportRequestList(reportRequestListRequest);
reportRequestListResult =
reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
}
if (myListzz[0].GeneratedReportId !=null)
{
GetReportRequest reportRequest = new GetReportRequest();
reportRequest.Merchant = merchantId;
String source = "C:\\myreport.txt";
reportRequest.ReportId = myListzz[0].GeneratedReportId;
reportRequest.Report = File.Open(source, FileMode.Create,
FileAccess.ReadWrite);
service.GetReport(reportRequest);
}
}
}
You are missing step 1b) Download the C# MWS Reports API Client Library. You may need other libraries to access other parts of the MWS API, but from a quick glance at that code above library is the main one.
Note that it refers to a lblStatus, which seems to be a label on a form, but nowhere in that post does it say anything else about that form. So step 2) probably is not a "console" style application, but a form based one, which also means, you shouldn't erase all code in step 3, but paste the code into whatever is the equivalent of a main() function (I've only ever used C and C++, but not C#, so I have no clue)

Is It Possible To Manually Supply a GoogleCredential To SpeechClient (In .NET API)?

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

How to list all the users with One Drive in one Office365 domain?

We're using the SharePoint Client Object Model SDK to access Office 365, there's no API to get all the users who has one drive. How can we do that?
There'r is a PowerShell script solution on MSDN, can we implement it with only C# code?
Based on the PowerShell Script from MSDN, I figured it out how to do it in C#:
On command line, run WSDL.exe to generate the proxy code for the user profiler service:
wsdl https://xxxx-admin.sharepoint.com/_vti_bin/UserProfileService.asmx?wsdl /username:aaaaa /password:ppppp
Add the generated file "UserProfileService.cs" to the project
The following code will list all the users with OneDrive:
UserProfileService uprofService = new UserProfileService();
uprofService.Url = adminPortalUrl + "/_vti_bin/UserProfileService.asmx";
uprofService.UseDefaultCredentials = false;
Uri targetSite = new Uri(url);
uprofService.CookieContainer = new CookieContainer();
string authCookieValue = spCredentials.GetAuthenticationCookie();
uprofService.CookieContainer.SetCookies(targetSite, authCookieValue);
var userProfileResult = uprofService.GetUserProfileByIndex(-1);
long numProfiles = uprofService.GetUserProfileCount();
while (userProfileResult.NextValue != "-1")
{
string personalUrl = null;
foreach(var u in userProfileResult.UserProfile)
{
/* (PersonalSpace is the name of the path to a user's OneDrive for Business site. Users who have not yet created a OneDrive for Business site might not have this property set.)*/
if (u.Values.Length != 0 && u.Values[0].Value != null && u.Name == "PersonalSpace" )
{ personalUrl = u.Values[0].Value as string;
break;
}
}
int nextIndex = -1;
nextIndex = Int32.Parse(userProfileResult.NextValue);
userProfileResult = uprofService.GetUserProfileByIndex(nextIndex);
}

WMI Win32_Share.Create method on localhost via WMI on Server OSes gives Error Code 24

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.

Perforce api - How to Command "Get Latest Revision"

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

Categories

Resources