RallyApi.Net Getting Workspaces from a Subscription Version 2.0 - c#

Following this link How to obtain a list of workspaces using Rally REST .NET
I tried the example however when I try to query against sub["Workspaces"] I get the error
RuntimeBinderException was unhandled;
The best overloaded method match for 'Rally.RestApi.RallyRestApi.Query(Rally.RestApi.Request)' has some invalid arguments
I cannot find any other ways to gather a list of workspaces from the subscription using the RallyApi dll for .Net which I obtained from the link provided.
Any help will be much appreciated.

Try to modify that code as follows:
Request wRequest = new Request(sub["Workspaces"]);
QueryResult queryResult = restApi.Query(wRequest);
Here is an entire app:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace Rest_v2._0_test
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//get the current subscription
DynamicJsonObject sub = restApi.GetSubscription("Workspaces");
Request wRequest = new Request(sub["Workspaces"]);
//query the Workspaces collection
QueryResult queryResult = restApi.Query(wRequest);
foreach (var result in queryResult.Results)
{
var workspaceReference = result["_ref"];
var workspaceName = result["Name"];
Console.WriteLine( workspaceName + " " + workspaceReference);
}
}
}
}

Related

Get Azure VM PowerState in C#/dotnet using Azure.ResourceManager

I want to get the PowerState (on/off/restarting, etc.) of a known Azure VM instance in a C#/dotnet application using Azure.ResourceManager (not PowerShell, not CLI, not REST, not using any deprecated Fluent approach).
I can do it successfully with REST so I know the underlying VM InstanceView data exists, but for this application REST will not pass muster.
I am using the following code; vm.Data.Name comes back as expected, but am getting null responses from InstanceView.Statuses.
I haven't been able to find any helpful MSFT documentation, except for old, deprecated approaches.
Does anyone know how to get PowerState via Azure.ResourceManager, or why I am getting NULL back?
Thanks!!
[code sample updated below on 1/16/23, changed auth approach, InstanceView still returning NULL]
using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Resources;
namespace Test
{
public class Program
{
public static async Task ListAllVms()
{
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
string rgName = "redacted";
ResourceGroupResource resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName);
VirtualMachineCollection vmCollection = resourceGroup.GetVirtualMachines();
AsyncPageable<VirtualMachineResource> response = vmCollection.GetAllAsync();
await foreach (VirtualMachineResource vm in response)
{
Console.WriteLine(vm.Data.Name);
foreach (InstanceViewStatus istat in vm.Data.InstanceView.Statuses)
{
Console.WriteLine("\n code: " + istat.Code);
Console.WriteLine(" level: " + istat.Level);
Console.WriteLine(" displayStatus: " + istat.DisplayStatus);
}
}
}
public static async Task Main(string[] args)
{
await ListAllVms();
}
}
}
After reproducing from my end, I could able to achieve this using vm.Get().Value.InstanceView().Value.Statuses[1].DisplayStatus. Below is the complete code that worked for me where I list all the vm present in my resource group and get the statuses of it.
using System;
using System.Threading.Tasks;
using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Resources;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
ArmClient armClient = new ArmClient(new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions() { TenantId = "<YOUR_TENAT_ID>" }));
SubscriptionResource subscriptionResource = await armClient.GetDefaultSubscriptionAsync();
string rgName = "<YOUR_RESOURCE_GROUP>";
ResourceGroupResource resourceGroupResource = await subscriptionResource.GetResourceGroups().GetAsync(rgName);
VirtualMachineCollection vmCollection = resourceGroupResource.GetVirtualMachines();
// Lists all virtual machines
AsyncPageable<VirtualMachineResource> vmList = vmCollection.GetAllAsync();
Console.WriteLine("Listing");
await foreach (VirtualMachineResource vm in vmList)
{
Console.WriteLine(vm.Data.Name);
Console.WriteLine(vm.Get().Value.InstanceView().Value.Statuses[1].DisplayStatus);
}
}
}
}
output:

Getting Distance between 2 points returns Error

I am trying to get the distance between 2 points using the Longitude and Latitude in c# now i stumbled into some good codes and using them in my code i am getting this as an exception error :
System.Net.WebException: 'Request Not Authorized or Over QueryLimit'
My code is looking thus :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GoogleMaps.LocationServices;
using System.Device.Location;
namespace DistanceCalcConsole
{
class Program
{
static void Main(string[] args)
{
getDistancebetween2Points();
}
private static void getDistancebetween2Points()
{
var originAddress = "Lagos, Nigeria";
var locationService = new GoogleLocationService();
var point = locationService.GetLatLongFromAddress(originAddress);
var latitude1 = point.Latitude;
var longitude1 = point.Longitude;
var destinationAddress = "Ibadan, Nigeria";
var locationService2 = new GoogleLocationService();
var point2 = locationService2.GetLatLongFromAddress(destinationAddress);
var latitude2 = point.Latitude;
var longitude2 = point.Longitude;
var locA = new GeoCoordinate(latitude1, longitude1);
var locB = new GeoCoordinate(latitude2, longitude2);
double distance = locA.GetDistanceTo(locB);
double finalDistance = distance / 1000;
Console.Write(finalDistance +" Kilometers");
Console.Read();
}
}
}
Does it look like i am missing something? was made to understand that using Googlemaps.Locationservice is free so i should not be expecting this error...
There are few possible reasons for having unauthorized or over query limit error:
Billing not enabled
Keyless Implementation
Self-Imposed usage cap
If above solutions didn't work or are already done on your end, kindly file a support case via https://console.cloud.google.com/google/maps-apis/support in order to open personalized communication channel as this will need further investigation to address the issue properly.

How to send a simple message using a twilio number with an ASP.NET MVC project?

I am trying to change and edit the code but it returns with exceptions errors in regards authentication errors. The username cannot be null as well as the category is not able to load the code. Another exception that is running on it is the Twilio.Exceptions.ApiExecution that requires a phone number.
The documentation is here: https://www.twilio.com/docs/sms/tutorials/server-notifications-csharp-mvc?code-sample=code-csv-list-of-phone-numbers-to-notify&code-language=csv&code-sdk-version=default
The video to build the code for integrating Twilio in an ASP.net MVC project is here: https://www.youtube.com/watch?v=ndxQXnoDIj8
The code excerpt is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
using Twilio.TwiML;
using Twilio.AspNet.Mvc;
namespace SendandReceiveSms.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS
public ActionResult SendSms()
{
var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
var authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];
TwilioClient.Init("ACa4XXXXXXXXXX","77XXXXXXXXXX");
var to = new PhoneNumber(ConfigurationManager.AppSettings["+65XXXXXXXX"]);
var from = new PhoneNumber("+12053016835");
var message = MessageResource.Create(
to: to,
from: from,
body: "Conserve with us and save the Wolrd ");
return Content(message.Sid);
}
public ActionResult ReceiveSms()
{
var response = new MessagingResponse();
response.Message(" We turn waste into environmental assets");
return TwiML(response);
}
}
}
You can try this also.
using DocGen.Notifications.Contract;
using DocGen.Notifications.Models;
using System;
using System.Configuration;
using System.Linq;
using System.Text;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace DocGen.Notifications.Providers
{
public class SmsNotificationProvider : INotificationProtocolContract
{
NotificationResponseModel notificationResponseModel = new NotificationResponseModel();
public NotificationResponseModel SendNotification(NotificationRequestModel notificationRequestModel)
{
if (notificationRequestModel.SmsTo == null || notificationRequestModel.SmsTo.Count() == 0)
throw new ArgumentNullException(nameof(notificationRequestModel.SmsTo));
TwilioClient.Init(ConfigurationManager.AppSettings["accountSid"], ConfigurationManager.AppSettings["authToken"]);
foreach (var Sms_to in notificationRequestModel.SmsTo)
{
var to = new PhoneNumber(Sms_to);
var message = MessageResource.Create(
to,
from: new PhoneNumber(ConfigurationManager.AppSettings["senderNumber"]),//"+12563054795"
body: Encoding.UTF8.GetString(notificationRequestModel.Message));
notificationResponseModel.ResponseMessage = message.Status.ToString();
}
//notificationResponseModel.ResponseMessage = "Message Successfully sent.";
return notificationResponseModel;
}
}
}

How to Generate Text File from API Source?

I have a small problem. I just recently started using Twilio's API to generate a record of messages that was sent to my assigned SID and Auth Token. However my question is how can I generate a text file, based off of what the console writes from the source its addressed to?
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Twilio;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "X";
string AuthToken = "X";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
// Build the parameters
var options = new MessageListRequest();
options.From = "2015-07-01";
options.To = "2015-07-13";
var messages = twilio.ListMessages(options);
foreach (var message in messages.Messages)
{
Console.WriteLine(message.Body);
Console.Read();
}
}
}
}
Writing to a text file is pretty much boilerplate. The methods are shown here:
https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

.NET HBase REST API client library - calling from MVC5 Controller

Looking at the sample code given on https://azure.microsoft.com/en-us/documentation/articles/hdinsight-hbase-tutorial-get-started/#use-the-net-hbase-rest-api-client-library,
I'm trying to connect to HBase from an MVC Controller as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace MyHBaseTest.Controllers
{
[RoutePrefix("api/myhbasetestcontroller")]
public class MyHBaseTestController : ApiController
{
HBaseReader hbase = new HBaseReader();
[HttpGet]
[Route("")]
public IHttpActionResult Index()
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername = "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
return Ok();
}
}
}
When I try to view the URL /api/myhbasetestcontroller in my browser when it is run in debug mode, it keeps loading the page forever without throwing any exception or anything in Visual Studio. I have waited for 15-20 minutes but nothing changes.
When I put try to do the same in a console application, it gets the version information in a matter of seconds though:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername= "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
}
}
}
I just don't understand how it makes a difference really.
Could you please advice?
Many thanks.
As of today, you need to run your calls on a background thread. I ran into this same exact issue. My calls are consolidated under a single function. I run that function on a background thread and everything works great.
// POST: api/Vizzini
[ResponseType(typeof(string))]
public async Task<IHttpActionResult> GetResponse(string tweet)
{
string s = await Task.Run(() =>
{
return ResponseEngine.GetBestResponse(tweet);
});
return Ok(s);
}
You are using blocking synchronous APIs, which won't work in the context of MVC/Web app (due to using wrong async context by default). You need to use async version of the methods. E.g. for GetVersion use GetVersionAsync.

Categories

Resources