aws sdk - listing security groups in c# - c#

Here is how I'm trying to list amazon (aws) security groups of VPC using AWSSDK in c#:
var ec2Client = new AmazonEC2Client(accessKey, secretKey, RegionEndpoint.USEast1);
var dsgRequest = new DescribeSecurityGroupsRequest();
var dsgResponse = ec2Client.DescribeSecurityGroups(dsgRequest);
List<SecurityGroup> mySGs = dsgResponse.SecurityGroups;
foreach (SecurityGroup item in mySGs)
{
Console.WriteLine("Existing security group: " + item.GroupId);
}
It only displays the default amazon security group while when I login to amazon via browser, I see lots of company security groups.
Any idea why this does not list them all?

I think it's because you didn't set a RegionEndpoint.
I modified your code slightly, and was able to enumerate my security groups:
var config = new AmazonEC2Config { RegionEndpoint = Amazon.RegionEndpoint.APSoutheast2};
var credentials = new BasicAWSCredentials(accessKey, secretKey);
using (var client = Amazon.AWSClientFactory.CreateAmazonEC2Client(credentials, config))
{
var dsgRequest = new DescribeSecurityGroupsRequest();
var dsgResponse = client.DescribeSecurityGroups(dsgRequest);
List<SecurityGroup> mySGs = dsgResponse.SecurityGroups;
foreach (SecurityGroup item in mySGs)
{
Console.WriteLine("Existing security group: " + item.GroupId);
}
}

Thanks for the help. I had actually set the end point properly. I ran the same code that I had a few days later and it worked. It must have been amazon services gone down or something like that.

Related

How to retrieve more than 3000 user details from an Active Directory group using C#?

I have an Active Directory group with more than 3000 members in it. I want to retrieve all those members from that group using the LDAP connection. I tried using the below snippet but it is providing one 1-1499 members from the group. Is there is any other way to achieve the same
LdapConnection connection = new LdapConnection(********);
NetworkCredential cred = new NetworkCredential(********, ********, ********);
connection.Credential = cred;
List<SearchResponse> results = new List<SearchResponse>();
SearchRequest request = new SearchRequest("***********", "(objectClass=group)", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] {"member" });
PageResultRequestControl prc = new PageResultRequestControl(1000);
SearchOptionsControl soc = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);
request.Controls.Add(prc);
request.Controls.Add(soc);
while (true)
{
SearchResponse response = connection.SendRequest(request) as SearchResponse;
foreach (DirectoryControl control in response.Controls)
{
if (control is PageResultResponseControl)
{
prc.Cookie = ((PageResultResponseControl)control).Cookie;
break;
}
}
foreach (var item in response.Entries[0].Attributes["member"].GetValues(typeof(String)))
{
var t = item;
}
results.Add(response);
}
Appears that you are hitting the MaxValRange limits.
MaxValRange value controls the number of values that are returned for an attribute of an object, independent of how many attributes that object has, or of how many objects were in the search result.
I do not do C# but We have a sample in Java code that may be helpful.

How to access cloudwatch logs events using C# .net core

Spent lot of time in this. But, I am not getting a way to query logs from cloud watch to c# api. I want to display those logs on UI. Any help?
Thanks in advance
You can integrate with cloudwatch and access for logs by using below code.
First and foremost you have to install awssdk with latest version and you have to provide aws accessKey and secretKey, your regionEndpoint along with loggroup name of cloudwatch.
public static void DescribeSubscriptionFilters()
{
var credentials = new BasicAWSCredentials("awskey", "secretkey"); // provide aws credentials
IAmazonCloudWatchLogs client =
new AmazonCloudWatchLogsClient(credentials, RegionEndpoint.USGovCloudWest1); // provide regionEndPoint
var describeLogStreamsRequest = new DescribeLogStreamsRequest()
{
LogGroupName = "LogGroupName" //mention your cloudwatch log group
};
var describeLogStreamsResult = client.DescribeLogStreams(describeLogStreamsRequest);
foreach (var stream in describeLogStreamsResult.LogStreams)
{
var eventsRequest = new GetLogEventsRequest()
{
LogStreamName = stream.LogStreamName,
LogGroupName = describeLogStreamsRequest.LogGroupName
};
var result = client.GetLogEvents(eventsRequest);
foreach (var events in result.Events)
{
Console.WriteLine(events.Timestamp + " - " + events.Message );
}
}
}

Getting files/folders from sharepoint via the api in c#

I'm trying to link a c# application to a sharepoint directory, so I can create folders, download and upload files. However I am strugling with connecting to the correct folder.
I can retrieve the content from allitems.aspx, but I am not sure how to actually get the content from folder.
I have tried using the ClientContext - something like this:
ClientContext cxt = new ClientContext("https://xx.sharepoint.com/sites/");
cxt.Credentials = GetCredentials();
List list = cxt.Web.Lists.GetByTitle("Kontrakter");
var test = list.Views;
var test1 = cxt.Web.Lists;
cxt.Load(test1);
cxt.Load(list);
cxt.Load(test);
var a = 4;
var fullUri = new Uri("https://xx.sharepoint.com/sites/yy/Kontrakter/AllItems.aspx");
//var folder = cxt.Web.GetFolderByServerRelativeUrl(fullUri.AbsolutePath);
using (var rootCtx = new ClientContext(fullUri.GetLeftPart(UriPartial.Authority)))
{
rootCtx.Credentials = GetCredentials();
Uri webUri = Web.WebUrlFromPageUrlDirect(rootCtx, fullUri);
using (var ctx1 = new ClientContext(webUri))
{
ctx1.Credentials = GetCredentials();
var list1 = ctx1.Web.GetList(fullUri.AbsolutePath);
ctx1.Load(list1.RootFolder.Files);
ctx1.ExecuteQuery();
Console.WriteLine(list.RootFolder.Files.Count);
}
}
or via normal api calls like this:
https://xx.sharepoint.com/_api/Web/GetFolderByServerRelativeUrl('Kontrakter/Forms')/Files
The only way I can find some data is if I look into 'Shared documents/Forms'
I'm having problems understanding the directory structure and how I can actually find the content of files/folders.
Thanks in advance :)
Turned out I was missing a /sites in one of my uris.

How to retrieve a list of subnets for launching a Fargate task?

I'm using the AWS SDK with C# in Visual Studio 2017, and have a prototype working which launches a Fargate service in ECS. As part of the setup, you instantiate a CreateServiceRequest object which requires a NetworkConfiguration.AwsVpcConfiguration setting with SecurityGroups and Subnets.
var request = new CreateServiceRequest();
request.ServiceName = "myService";
request.TaskDefinition = "myTask"; // family[:revision] of the task definition to use
request.ClientToken = Guid.NewGuid().ToString().Replace("-", ""); // max 32 characters!
request.Cluster = "default";
request.DesiredCount = 1;
request.LaunchType = LaunchType.FARGATE;
request.DeploymentConfiguration = new DeploymentConfiguration
{
MaximumPercent = 100,
MinimumHealthyPercent = 50
};
// configure the network and security groups for the task
List<string> securityGroups = new List<string>();
securityGroups.Add("sg-123456");
List<string> subnets = new List<string>();
subnets.Add("subnet-9b36aa97");
request.NetworkConfiguration = new NetworkConfiguration
{
AwsvpcConfiguration = new AwsVpcConfiguration
{
AssignPublicIp = AssignPublicIp.ENABLED,
SecurityGroups = securityGroups,
Subnets = subnets
}
};
When I configure a service manually via the AWS Console, they display a list of subnets from which to choose. So, I'm wondering how I might programmatically retrieve that list of subnets which are available in our VPC.
I'm searching their SDK documentation for possible solutions, any pointers to their docs or examples is appreciated!
Take a look at EC2Client, you'll find a lot of VPC-related APIs are associated with the EC2 service. Specifically check out AmazonEC2Client.DescribeSubnets(DescribeSubnetsRequest), method documentation here:
Request
Amazon.EC2.Model.DescribeSubnetsRequest
Response
Amazon.EC2.Model.DescribeSubnetsResponse
Response contains a list of Amazon.EC2.Model.Subnet that you will retrieve string property SubnetId from, when deciding which subnet to pass on to your Fargate request.
Example Usage (From the linked documentation):
var response = client.DescribeSubnets(new DescribeSubnetsRequest
{
Filters = new List<filter> {
new Filter {
Name = "vpc-id",
Values = new List<string> {
"vpc-a01106c2"
}
}
}
});
List<subnet> subnets = response.Subnets;
Further Reading
AWS Documentation - EC2Client - Search this document for 'DescribeSubnets' to find async variants of this SDK method.

Not All Site Collections show up in the results - Sharepoint 2013 Search through CSOM

I am working on a C# code that retrieves all site collection paths from a On-Premise Sharepoint 2013 server. I have the following Site Collections on the server:
/serverurl/
/serverurl/my
/serverurl/my/personal/site1
/serverurl/my/personal/site2
/serverurl/sites/TestSite
/serverurl/custompath/site3
when I run my code , I only get the following site collections:
/serverurl/
/serverurl/my
/serverurl/my/personal/site1
/serverurl/my/personal/site2
I was wondering why my search does not return all the site collections?
here is my code:
ClientContext context = new ClientContext(siteUrl);
var cred = new NetworkCredential(userName, password, domain);
context.Credentials = cred;
KeywordQuery query = new KeywordQuery(context);
query.QueryText = "contentclass:STS_Site";
SearchExecutor executor = new SearchExecutor(context);
query.TrimDuplicates = true;
var resultTable = executor.ExecuteQuery(query);
context.ExecuteQuery();
foreach (var row in resultTable.Value[0].ResultRows)
{
string siteName = row["siteName"] as string;
Console.WriteLine("Site Name: {0}", siteName);
}
Thanks!
I was having the same problem today. I found two solutions.
Regardless if your on-prem or on Office365 we can use Microsoft.Online.SharePoint.Client.Tenant dll. You can use this to get all the Site Collections. You do need your admins to run some power shell if your on-prem. Vesa was nice enough to write a blog about it here
Once you get that done, you can do something like the following (Note:I have not tested this method with a non Admin account) (solution taken from here) Sadly this one will not work for me as I want security trimming and this will code must be ran by a user with tenant read permissions which our users would not normal have.
var tenant = new Tenant(clientContext);
SPOSitePropertiesEnumerable spp = tenant.GetSiteProperties(0, true);
clientContext.Load(spp);
clientContext.ExecuteQuery();
foreach(SiteProperties sp in spp)
{
// you'll get your site collections here
}
I ended up doing this which gets back to using search, I still have a problem, we have well over 500 sites/webs so I'm working with our admins to see if we can increase the max rows search can return. However, the true secret here is TrimDuplicates being set to false, I don't know why SP thinks the results are dups, but it obviously does, so set it to false and you should see all your sits.
KeywordQuery query = new KeywordQuery(ctx);
query.QueryText = "contentclass:\"STS_Site\"";
query.RowLimit = 500;//max row limit is 500 for KeywordQuery
query.EnableStemming = true;
query.TrimDuplicates = false;
SearchExecutor searchExecutor = new SearchExecutor(ctx);
ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(query);
ctx.ExecuteQuery();
var data = results.Value.SelectMany(rs => rs.ResultRows.Select(r => r["Path"])).ToList();
Hope one of the two will work for you.

Categories