Google compute engine .NET API examples/samples/tutorials - google-compute-engine

I haven't been able to find anything that will clearly explain how to use google compute engine through the .net API (specifically c#). Is there anyone that can point me to anything?
P.S. I know about the API reference (https://developers.google.com/resources/api-libraries/documentation/compute/v1/csharp/latest/annotated.html)

I could not find any detailed tutorial with code samples, but official documentation is available at [1] includes a code sample.
There is a tutorial with C# sample specific for Google Drive at [2].
For your reference APIs documentation is available at [3] and the annotated library reference is available at [4].
Link:
[1] - https://developers.google.com/api-client-library/dotnet/get_started#examples
[2] - http://conficient.wordpress.com/2014/06/18/using-google-drive-api-with-c-part-1/
[3] - https://developers.google.com/compute/docs/reference/latest/
[4] - https://developers.google.com/resources/api-libraries/documentation/compute/v1/csharp/latest/annotated.html

A list of steps you need to follow:
Specifically you can modify and use the following code to Create the vmInstance of Google Compute Engine
Here is the c# (using Google api SDK) functions that can create instances
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "ClientId",
ClientSecret = "ClientSecret"
},
new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform },
"user",
CancellationToken.None, null);
`ComputeService service = new ComputeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ApplicationName",
ApiKey = "ApiKey"
});
public IEnumerable<CreateInstanceResult> CreateInstances(params CreateInstanceRequest[] instances)
{
IList<Instance> vmInstances = new List<Instance>();
ComputeService service = assign GoogleComputeServiceObject;
if (instances != null)
{
foreach (CreateInstanceRequest requestInstance in instances)
{
#region Meatadata Setting
Metadata metaData = new Metadata();
metaData.Items = new List<Metadata.ItemsData>();
Metadata.ItemsData itemData = new Metadata.ItemsData();
itemData.Key = "Expiration";
itemData.Value = requestInstance.Expiration.ToString();
metaData.Items.Add(itemData);
itemData = new Metadata.ItemsData();
itemData.Key = "AccountId";
itemData.Value = requestInstance.AccountId;
metaData.Items.Add(itemData);
if (requestInstance.Data != null)
{
foreach (KeyValuePair<string, string> keyValue in requestInstance.Data)
{
Metadata.ItemsData otherItemData = new Metadata.ItemsData();
otherItemData.Key = keyValue.Key;
otherItemData.Value = keyValue.Value;
metaData.Items.Add(otherItemData);
}
}
#endregion Meatadata Setting
#region DiskSetting
IList<AttachedDisk> attachedDisks = new List<AttachedDisk>();
AttachedDisk attachedDisk = new AttachedDisk();
AttachedDiskInitializeParams attachedDiskInitializeParams = new AttachedDiskInitializeParams();
attachedDiskInitializeParams.DiskSizeGb = googleCloudServerSetting.DiskSize;
attachedDiskInitializeParams.DiskType = service.BaseUri + "Your_ProjectId" + "/zones/" + "specifyZone" + "/diskTypes/" + "specify_DiskType";
// for example
attachedDiskInitializeParams.SourceImage = service.BaseUri + "/debian-cloud/global/images/specify_imagesourceImage";
attachedDisk.AutoDelete = true;
attachedDisk.Boot = true;
attachedDisk.Interface__ = "SCSI";//for example
attachedDisk.InitializeParams = attachedDiskInitializeParams;
attachedDisks.Add(attachedDisk);
IList<NetworkInterface> networkInterfaces = new List<NetworkInterface>();
NetworkInterface networkInterface = new NetworkInterface();
networkInterface.Network = service.BaseUri + ProjectId + "/global/networks/default";
networkInterfaces.Add(networkInterface);
Tags tags = new Tags();
IList<string> stringList = new List<string>();
tags.Items = new List<string>();
tags.Items.Add("http-server");
tags.Items.Add("https-server");
#endregion DiskSetting
#region Creating Instance object
Instance instance = new Instance()
{
MachineType = requestInstance.SizeId ?? service.BaseUri + "ProjectId" + "/zones/" + "specify_Zone" + "/machineTypes/" + "specify_machineType",
Metadata = metaData,
Name = "InstanceName",
Tags = tags,
NetworkInterfaces = networkInterfaces,
Disks = attachedDisks
};
#endregion Creating Instance object
vmInstances.Add(instance);
}
var batchRequest = new BatchRequest(service);
foreach (Instance instance in instances)
{
batchRequest.Queue<Instance>(service.Instances.Insert(instance, ProjectId, Zone),
(content, error, i, message) =>
{
});
}
await batchRequest.ExecuteAsync();
}
else
{
throw new Exception("null");
}
}

Related

How can I get the Json Response of create chat from Microsoft Graph Api

I'm trying to get the response of create chat function with Microsoft Graph Api in my c# Application and show it in a textbox, to let my c# system be able to sent message with the chatID. I was be able to get the response of getallchat with following the steps in How can I parse the JSON response from Microsoft Graph Api List Chat into the textbox, bt I was nt unable to use the following steps to get the response of create chat any ideas?Documentation of create chat https://learn.microsoft.com/en-us/graph/api/chat-post?view=graph-rest-1.0&tabs=http
Coding Part of create chat
private async void button5_Click(object sender, EventArgs e)
{
var scopes = new[] { "Directory.Read.All", "Directory.ReadWrite.All", "User.Read", "User.Read.All", "User.ReadBasic.All", "User.ReadWrite", "Chat.Create", "Chat.ReadWrite" };
{
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "5xxxxxxx3-3xxx6a-xxx1-9xxxc-exxxxxxxxx0";
// Value from app registration
var clientId = "3xxxx04-5c92-42xxx-8500-6xxxxxxxaf";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var userName = "xx.yxxxx#xxxxxxi.com";
var password = "Aaxxxxxxxxxxx#";
// https://learn.microsoft.com/dotnet/api/azure.identity.usernamepasswordcredential
var userNamePasswordCredential = new UsernamePasswordCredential(
userName, password, tenantId, clientId, options);
GraphServiceClient graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);
var chat = new Chat
{
ChatType = ChatType.OneOnOne,
Members = new ChatMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users[comboBox1.Text]"}
}
},
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users/[comboBox2.Text]"}
}
}
}
};
await graphClient.Chats
.Request()
.AddAsync(chat);
}
}
here's the sample from the api document.
pls try to give the application api permission and try code below.
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var chat = new Chat
{
ChatType = ChatType.OneOnOne,
Members = new ChatMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users('8b081ef6-4792-4def-b2c9-c363a1bf41d5')"}
}
},
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", "https://graph.microsoft.com/v1.0/users('82af01c5-f7cc-4a2e-a728-3a5df21afd9d')"}
}
}
}
};
var res = await graphClient.Chats.Request().AddAsync(chat);

Schema Extension Value is always NULL when updating through Microsoft Graph SDK

Step 1:
Created GraphServiceClient using Microsoft.Graph 4.9.0 and Microsoft.Graph.Core 2.0.5 SDK
var scopes = new[] { "https://graph.microsoft.com/.default" };
ClientSecretCredential clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, new ClientSecretCredentialOptions()
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
});`
GraphServiceClient graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
Step 2:
And created a custom schema extension like below.
SchemaExtension schemaExtension = new SchemaExtension()
{
Id = "data1",
Description = "creating test schema extn",
TargetTypes = new List<string>()
{
"User"
},
Properties = new List<ExtensionSchemaProperty>()
{
new ExtensionSchemaProperty()
{
Name ="prop1",
Type ="String"
}
}
};
Step 3:
Updated the Schema extension status to "Available"
var updatedExtn = await graphServiceClient
.SchemaExtensions[schemaExtension.Id].Request()
.UpdateAsync(new SchemaExtension()
{
Status = "Available"
});
Step 4:
Create Class for extension data
public class data1
{
// You must serialize your property names to camelCase if your SchemaExtension describes as such.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "prop1", Required = Newtonsoft.Json.Required.Default)]
public string Prop1 { get; set; }
}
Step 5:
Find the User and add the created schema extension to the user
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
// The below line is not working. but doesn't throw error
extensionInstance.Add(schemaExtension.Id, new data1 { prop1 = "testing" });
var usrCollection = await graphServiceClient.Users
.Request()
.Filter($"userPrincipalNames eq '{adelev_Mail}'")
.GetAsync();
var usr = usrCollection.FirstOrDefault();
if(usr != null)
{
usr.AdditionalData.Add(extensionInstance);
var updatedUser = await graphServiceClient.Users[usr.Id]
.Request()
.UpdateAsync(usr);
}
Step 6:
When you try to retrieve the extension the value is NULL.
User updatedUser = await graphServiceClient.Users[usr.Id].Request()
.Select($"id, {schemaExtension.Id}")
.GetAsync();
But it works with API using Graph Explorer.
PATCH https://graph.microsoft.com/v1.0/users/{userId}
{
"extXXXXXXXX_data1":
{
"prop1" : "testing"
}
}
Please let me know if I'm missing anything here. Any help here is much appreciated.
You should accessing the data on AdditionalData property. Try looking at user.AdditionalData in your result. Here is a screenshot with my example.
Getting User with Schema extension from Graph explorer.
While using the SDK, i access my custom data in user.AdditionalData
Check this thread - Graph SDK and SchemaExtensions for details.

MaxLength not available in MVC Core json result

I have developed web API with this method and I test it with Advanced Rest Client in my machine and everything is alright, but after deploy to server the result is omitted by the server and not recognize as valid JSON text and not parse correctly.
[Route("[action]")]
[HttpGet]
public async Task<JsonResult> GetAllCityEvent(string apiKey)
{
List<CityMapMarker> availableMapMarkers = new List<CityMapMarker>();
PersianUtilCore.Api.MethodResult result = new PersianUtilCore.Api.MethodResult();
List<PersianUtilCore.Api.MethodError> errors = new List<PersianUtilCore.Api.MethodError>();
ApiBO apiBO = new ApiBO(AggregateService);
bool isValidKey = apiBO.IsValidKey(apiKey);
if (!isValidKey)
{
result.IsSuccess = false;
errors.Add(new PersianUtilCore.Api.MethodError(300, "your key is not valid!"));
}
else
{
JunctionBO junctionBO = new JunctionBO(AggregateService);
StreetBO streetBO = new StreetBO(AggregateService);
HighwayBO highwayBO = new HighwayBO(AggregateService);
SightBO sightBO = new SightBO(AggregateService);
TrafficLightBO trafficLightBO = new TrafficLightBO(AggregateService);
CameraBO cameraBO = new CameraBO(AggregateService);
TransportationStationBO bussStationBO = new TransportationStationBO(AggregateService);
TrafficBO trafficBO = new TrafficBO(AggregateService);
CityEventBO cityEventBO = new CityEventBO(AggregateService);
//availableMapMarkers.AddRange(junctionBO.CityMapMarkers());
//availableMapMarkers.AddRange(streetBO.CityMapMarkers());
//availableMapMarkers.AddRange(highwayBO.CityMapMarkers());
//availableMapMarkers.AddRange(sightBO.CityMapMarkers());
//availableMapMarkers.AddRange(trafficLightBO.CityMapMarkers());
//availableMapMarkers.AddRange(trafficBO.CityMapMarkers());
//availableMapMarkers.AddRange(cameraBO.CityMapMarkers());
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.Bus));
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.Train));
availableMapMarkers.AddRange(bussStationBO.CityMapMarkers(TransportationType.BRT));
availableMapMarkers.AddRange(cityEventBO.CityMapMarkers());
result.Result = availableMapMarkers;
result.IsSuccess = true;
}
result.Errors = errors;
result.Result = availableMapMarkers;
result.IsSuccess = errors.Count <= 0;
var logHistoryResult = apiBO.LogHistory(apiKey, nameof(this.GetAllCityEvent));
return Json(result);
}
I couldn't find any way to change JsonResult max length like with I did in Asp.net MVC4 or Asp.net Webforms
How can I increase JsonResult maxlength in MVC Core?
Why there is different in IIS publish or local machine when I try to get result from my web API?

Json data serialized with JsonConvert.SerializeObject is always string in ASP.NET Web API

I am developing a ASP.NET MVC Web Api. Project. I am returning data with JSON format. Before I return data to user I serialize data using JsonConvert.SerializeObject to change their json property names.My code return data in JSON format. But with an issue. That is it always return data into string even if the data is array or object.
This is my action method that returns json.
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions!=null && dbRegions.Count()>0)
{
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
if(!string.IsNullOrEmpty(json))
{
json = json.Trim(new char[] { '"' });
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent(json.GetType(),json,Configuration.Formatters.JsonFormatter)
};
}
Actually this code should return Json array. But when I parse data from client (from Android using Volley). It cannot be parsed into Json Array.
This is the data I get:
As you can see the double quote both in the beginning and at the end. The reason I cannot parse it into array in Volley is it is returning as a string because of that double. How can I serialize it trimming that quote? I used trim, but not removed.
You are unnecessarily complicating things. In Web API you can return JSON just by returning any object inside the built-in methods, the framework will serialize it for you.
public IHttpActionResult Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions != null && dbRegions.Count() > 0) {
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
return Ok(regions);
}
As an aside: from what I can see you are mapping manually your domain objects into DTOs: take into consideration the use of an automatic mapping mechanism like AutoMapper.
I am not sure this is the best solution or not. I solved the problem using this way.
This is my action method
public HttpResponseMessage Get()
{
try
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json, Encoding.Default, "application/json")
};
}
catch
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
It's not required to convert object to json string.
You can try :
return Request.CreateResponse<List<ContentRegion>>(HttpStatusCode.OK,regions);
Not tested.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Use this line in your WebApiConfig.
And here your code should be
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
HttpResponseMessage temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "");
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, regions);
return temp;
//string json = JsonConvert.SerializeObject(regions);
//if (!string.IsNullOrEmpty(json))
//{
// json = json.Trim(new char[] { '"' });
//}
//return new HttpResponseMessage(HttpStatusCode.OK)
//{
// Content = new ObjectContent(json.GetType(), json, Configuration.Formatters.JsonFormatter)
//};
}

Hot to get set of properties as map with apache commons-configuration and a properties file

I would like to as if it is possible/supported by commons-configuration of apache to get from a properties file a property as a map
Up to now I have managed to do this indirectly with the following code snippet
Map<String, T> map = new LinkedHashMap<>();
Configuration subset = config.subset(key);
if (!subset.isEmpty()) {
Iterator it = subset.getKeys();
while (it.hasNext()) {
String k = (String) it.next();
//noinspection unchecked
T v = (T) subset.getProperty(k);
map.put(k, v);
}
}
return map;
Does anyone knows a more straight forward way than this?
Thank you very much
I prefer how you did it but if you like: ConfigurationMap
Map<Object,Object> config = new ConfigurationMap(subset);
to get all properties as Map with apache commons confuguration2
Parameters params = new Parameters();
File propertiesFile = new File("properties.properties");
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(propertiesFile)
.setEncoding("UTF-8"));
Configuration config = builder.getConfiguration();
Map<Object,Object> cfg = new ConfigurationMap(config);
cfg.entrySet();
to check out:
for (Map.Entry entry : cfg.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}