Why are the print capabilities always empty? - c#

I'm getting a print queue for various printers installed locally by doing:
var queueName = "Myprinterqueue";
using (var ps = new PrintServer())
using (var pq = ps.GetPrintQueue(queueName))
{
pq.Refresh();
var status = pq.QueueStatus;
var jobs = pq.NumberOfJobs;
var averagePagesPerMinute = pq.AveragePagesPerMinute;
}
Status and NumberOfJobs are retrieved correctly. But many other print capabilities, eg. AveragePagesPerMinute, are always empty or 0.
Why is this?

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.

Saving multiple responses from foreach c#

Creating C#/.net application that gets services names from AWS using the cluster name. With the AWS .net SDK
Able to retrieve cluster names and save them in a list of strings:
AmazonECSClient client = new AmazonECSClient();
ListClustersRequest listClusterREquest = new ListClustersRequest();
var responseClusterList = await client.ListClustersAsync(listClusterREquest);
List<string> clusterArns = responseClusterList.ClusterArns;
Now trying to retrieve the list of services using the cluster names. I am having issues saving each response back to a list named serviceArns. It only saves the last response to the list called serviceArns. There should be about 20 responses saved to the list.
ListServicesRequest listRequest = new ListServicesRequest();
List<string> serviceArns = null;
ListServicesResponse responsethree = new ListServicesResponse();
foreach (var item in clusterArns)
{
listRequest.Cluster = item;
ListServicesResponse listResponse = await client.ListServicesAsync(listRequest);
serviceArns = listResponse.ServiceArns;
};
You should intialise the list at the start and add elements as needed be. Currently with each iteration, the list gets set, where it should be adding it instead.
ListServicesRequest listRequest = new ListServicesRequest();
List<string> serviceArns = new();
ListServicesResponse responsethree = new ListServicesResponse();
foreach (var item in clusterArns)
{
listRequest.Cluster = item;
ListServicesResponse listResponse = await client.ListServicesAsync(listRequest);
serviceArns.AddRange(listResponse.ServiceArns);
};

AWS Kinesis .NET Consumer

I am experimenting with producer and consumer using AWS Kinesis and the issue is the consumer keeps receiving the first message (or record) that we produced though we have changed the data object sent multiple times . Additionally we have tried multiple ShardIteratorType and none have worked. Latest produces no results, all others produce the same original record.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.Internal;
using Amazon.Kinesis;
using Amazon.Kinesis.Model;
using BenchmarkRuleSetModel.Models;
using MongoDB.Driver;
using Newtonsoft.Json;
namespace ConsoleApp7
{
internal class Program
{
private static AmazonKinesisClient _client;
private static string _streamName;
static async Task ReadFromStream()
{
var kinesisStreamName = _streamName;
var describeRequest = new DescribeStreamRequest
{
StreamName = kinesisStreamName,
};
var describeResponse = await _client.DescribeStreamAsync(describeRequest);
var shards = describeResponse.StreamDescription.Shards;
foreach (var shard in shards)
{
var iteratorRequest = new GetShardIteratorRequest
{
StreamName = kinesisStreamName,
ShardId = shard.ShardId,
ShardIteratorType = ShardIteratorType.AT_TIMESTAMP,
Timestamp = DateTime.MinValue
};
var iteratorResponse = await _client.GetShardIteratorAsync(iteratorRequest);
var iteratorId = iteratorResponse.ShardIterator;
while (!string.IsNullOrEmpty(iteratorId))
{
var getRequest = new GetRecordsRequest
{
ShardIterator = iteratorId, Limit = 10000
};
var getResponse = await _client.GetRecordsAsync(getRequest);
var nextIterator = getResponse.NextShardIterator;
var records = getResponse.Records;
if (records.Count > 0)
{
Console.WriteLine("Received {0} records. ", records.Count);
foreach (var record in records)
{
var json = Encoding.UTF8.GetString(record.Data.ToArray());
Console.WriteLine("Json string: " + json);
}
}
iteratorId = nextIterator;
}
}
}
private static async Task<string> Produce()
{
var data = new
{
Message = "Hello world!",
Author = "Amir"
};
//convert to byte array in prep for adding to stream
var oByte = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
using (var ms = new MemoryStream(oByte))
{
//create put request
var requestRecord = new PutRecordRequest
{
StreamName = _streamName,
PartitionKey = Guid.NewGuid().ToString(),
Data = ms
};
//list name of Kinesis stream
//give partition key that is used to place record in particular shard
//add record as memorystream
//PUT the record to Kinesis
var response = await _client.PutRecordAsync(requestRecord);
return response.SequenceNumber;
}
}
static void Main(string[] args)
{
_client = new AmazonKinesisClient("ExampleKey", "ExampleSecret", RegionEndpoint.EUWest2);
_streamName = "SomeStream";
Produce().Wait();
ReadFromStream().Wait();
}
}
}
First of all, as I have debugged your code, I noticed that it loops infinitely in the inner loop (while (!string.IsNullOrEmpty(iteratorId))) and never loops over all the shards in your stream (assuming you have >1). The reason is explained in https://docs.aws.amazon.com/streams/latest/dev/troubleshooting-consumers.html#getrecords-returns-empty - because the producer never called MergeShards or SplitShards, they remain open, thus NextShardIterator will never be NULL.
This is why you only ever see records put on the first shard (or at least I did when running your code) - you must read from shards in parallel.
As far as your usage pattern goes, you're using:
ShardIteratorType = ShardIteratorType.AT_TIMESTAMP,
Timestamp = DateTime.MinValue
By this, you're essentially telling Kinesis "give me all the records in the stream from the beginning of time" (or at least as far as the retention period reaches). That's why you keep seeing the same old records in addition to new ones (again, that's what I saw when I ran your code).
A GetRecords[Async] call does not actually remove records from the stream (see https://stackoverflow.com/a/25741304/4940707). The correct way of using Kinesis is to move checkpoint-to-checkpoint. If the consumer was to persist the SequenceNumber from the last record read and then restart as such:
ShardIteratorType = ShardIteratorType.AT_SEQUENCE_NUMBER,
StartingSequenceNumber = lastSeenSequenceNumber
Then you'd see only newer records.

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.

How to add/update individual result to each test step in testcase of VSTS/TFS programatically

I'm able to update test result to testcase in VSTS through program.
Test Case Result Updation
Now, i want to update the result of each test step in test case. Couldn't find any related info. Please help
The simple way is using client API:
Simple sample:
int testpointid = 176;
var u = new Uri("https://[account].visualstudio.com");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, "[pat]"));
TfsTeamProjectCollection _tfs = new TfsTeamProjectCollection(u, c);
ITestManagementService test_service = (ITestManagementService)_tfs.GetService(typeof(ITestManagementService));
ITestManagementTeamProject _testproject = test_service.GetTeamProject("scrum2015");
ITestPlan _plan = _testproject.TestPlans.Find(115);
ITestRun testRun = _plan.CreateTestRun(false);
testRun.Title = "apiTest";
ITestPoint point = _plan.FindTestPoint(testpointid);
testRun.AddTestPoint(point, test_service.AuthorizedIdentity);
testRun.Save();
testRun.Refresh();
ITestCaseResultCollection results = testRun.QueryResults();
ITestIterationResult iterationResult;
foreach (ITestCaseResult result in results)
{
iterationResult = result.CreateIteration(1);
foreach (Microsoft.TeamFoundation.TestManagement.Client.ITestStep testStep in result.GetTestCase().Actions)
{
ITestStepResult stepResult = iterationResult.CreateStepResult(testStep.Id);
stepResult.Outcome = Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Passed; //you can assign different states here
iterationResult.Actions.Add(stepResult);
}
iterationResult.Outcome = Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Passed;
result.Iterations.Add(iterationResult);
result.Outcome = Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Passed;
result.State = TestResultState.Completed;
result.Save(true);
}
testRun.State = Microsoft.TeamFoundation.TestManagement.Client.TestRunState.Completed;
results.Save(true);
Regarding REST api, the necessary information is stored in actionResults of iterationDetails (TestCaseResult.IterationDetails), you can try specify IterationDetails to TestCaseResult and update test result.
You can check the details of a test result by using Get a Test Result with DetailInclude (detailsToInclude=Iterations)

Categories