content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Microsoft.VisualStudio.Composition;
namespace Microsoft.VisualStudio.ProjectSystem.Debug
{
/// <summary>
/// Interface definition for the LaunchSettingsProvider.
/// </summary>
[ProjectSystemContract(ProjectSystemContractScope.UnconfiguredProject, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne)]
public interface ILaunchSettingsProvider
{
IReceivableSourceBlock<ILaunchSettings> SourceBlock { get; }
ILaunchSettings CurrentSnapshot { get; }
[Obsolete("Use ILaunchSettingsProvider2.GetLaunchSettingsFilePathAsync instead.")]
string LaunchSettingsFile { get; }
ILaunchProfile ActiveProfile { get; }
// Replaces the current set of profiles with the contents of profiles. If changes were
// made, the file will be checked out and updated. If the active profile is different, the
// active profile property is updated.
Task UpdateAndSaveSettingsAsync(ILaunchSettings profiles);
// Blocks until at least one snapshot has been generated.
Task<ILaunchSettings> WaitForFirstSnapshot(int timeout);
/// <summary>
/// Adds the given profile to the list and saves to disk. If a profile with the same
/// name exists (case sensitive), it will be replaced with the new profile. If addToFront is
/// true the profile will be the first one in the list. This is useful since quite often callers want
/// their just added profile to be listed first in the start menu.
/// </summary>
Task AddOrUpdateProfileAsync(ILaunchProfile profile, bool addToFront);
/// <summary>
/// Removes the specified profile from the list and saves to disk.
/// </summary>
Task RemoveProfileAsync(string profileName);
/// <summary>
/// Adds or updates the global settings represented by settingName. Saves the
/// updated settings to disk. Note that the settings object must be serializable.
/// </summary>
Task AddOrUpdateGlobalSettingAsync(string settingName, object settingContent);
/// <summary>
/// Removes the specified global setting and saves the settings to disk
/// </summary>
Task RemoveGlobalSettingAsync(string settingName);
/// <summary>
/// Sets the active profile. This just sets the property it does not validate that the setting matches an
/// existing profile
/// </summary>
Task SetActiveProfileAsync(string profileName);
}
}
| 42.787879 | 161 | 0.696176 | [
"Apache-2.0"
] | M-Lipin/project-system | src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/Debug/ILaunchSettingsProvider.cs | 2,826 | C# |
namespace EnergyTrading.MDM.Test
{
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Xml;
using Microsoft.Http;
using NUnit.Framework;
using EnergyTrading.Contracts.Search;
using EnergyTrading.MDM.Contracts.Sample; using EnergyTrading.Mdm.Contracts;
using EnergyTrading.Search;
[TestFixture]
public class when_a_search_for_a_broker_is_made_with_a_mapping_value_and_results_are_found : IntegrationTestBase
{
private static HttpClient client;
private static HttpContent content;
private static MDM.Broker entity1;
private static MDM.Broker entity2;
private static HttpResponseMessage response;
[TestFixtureSetUp]
public static void ClassInit()
{
Establish_context();
Because_of();
}
[Test]
public void should_return_the_ok_status_code()
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[Test]
public void should_return_the_relevant_search_results()
{
XmlReader reader = XmlReader.Create(
response.Content.ReadAsStream(), new XmlReaderSettings { ProhibitDtd = false });
SyndicationFeed feed = SyndicationFeed.Load(reader);
List<EnergyTrading.MDM.Contracts.Sample.Broker> result =
feed.Items.Select(syndicationItem => (XmlSyndicationContent)syndicationItem.Content).Select(
syndic => syndic.ReadContent<EnergyTrading.MDM.Contracts.Sample.Broker>()).ToList();
Assert.AreEqual(1, result.Where(x => x.ToMdmKey() == entity1.Id).Count(), string.Format("Entity not found in search results {0}", entity1.Id));
Assert.AreEqual(1, result.Where(x => x.ToMdmKey() == entity2.Id).Count(), string.Format("Entity not found in search results {0}", entity2.Id));
}
protected static void Because_of()
{
response = client.Post(ServiceUrl["Broker"] + "search", content);
}
protected static void Establish_context()
{
entity1 = BrokerData.CreateBasicEntityWithOneMapping();
entity2 = BrokerData.CreateBasicEntityWithOneMapping();
client = new HttpClient();
Search search = SearchBuilder.CreateSearch(isMappingSearch: true);
search.AddSearchCriteria(SearchCombinator.Or).AddCriteria(
"MappingValue", SearchCondition.Equals, entity1.Mappings[0].MappingValue).AddCriteria(
"MappingValue", SearchCondition.Equals, entity2.Mappings[0].MappingValue);
content = HttpContentExtensions.CreateDataContract(search);
}
}
[TestFixture]
public class when_a_search_for_a_broker_is_made_with_a_mapping_value_and_a_system_name_and_results_are_found : IntegrationTestBase
{
private static HttpClient client;
private static HttpContent content;
private static MDM.Broker entity1;
private static HttpResponseMessage response;
[TestFixtureSetUp]
public static void ClassInit()
{
Establish_context();
Because_of();
}
[Test]
public void should_return_the_ok_status_code()
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[Test]
public void should_return_the_relevant_search_results()
{
XmlReader reader = XmlReader.Create(
response.Content.ReadAsStream(), new XmlReaderSettings { ProhibitDtd = false });
SyndicationFeed feed = SyndicationFeed.Load(reader);
List<EnergyTrading.MDM.Contracts.Sample.Broker> result =
feed.Items.Select(syndicationItem => (XmlSyndicationContent)syndicationItem.Content).Select(
syndic => syndic.ReadContent<EnergyTrading.MDM.Contracts.Sample.Broker>()).ToList();
Assert.AreEqual(1, result.Where(x => x.ToMdmKey() == entity1.Id).Count(), string.Format("Entity not found in search results {0}", entity1.Id));
}
protected static void Because_of()
{
response = client.Post(ServiceUrl["Broker"] + "search", content);
}
protected static void Establish_context()
{
entity1 = BrokerData.CreateBasicEntityWithOneMapping();
client = new HttpClient();
Search search = SearchBuilder.CreateSearch(isMappingSearch: true);
search.AddSearchCriteria(SearchCombinator.And).AddCriteria(
"MappingValue", SearchCondition.Equals, entity1.Mappings[0].MappingValue).AddCriteria(
"System.Name", SearchCondition.Equals, "Endur");
content = HttpContentExtensions.CreateDataContract(search);
}
}
}
| 36.205882 | 155 | 0.649675 | [
"MIT"
] | RWE-Nexus/EnergyTrading-MDM-Sample | Code/Service/MDM.IntegrationTest.Sample/Broker/search/success_search_results_by_mapping.cs | 4,924 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace AvlTreeRecursive
{
internal class AvlNode<T>
where T : IComparable<T>
{
private int size;
private int height;
public T Value { get; private set; }
public AvlNode<T>[] Children { get; private set; }
public AvlNode<T> Left
{
get
{
return Children[0];
}
set
{
Children[0] = value;
}
}
public AvlNode<T> Right
{
get
{
return Children[1];
}
set
{
Children[1] = value;
}
}
private int Balance => GetHeight(this.Left) - GetHeight(this.Right);
public AvlNode(T value)
{
this.size = 1;
this.height = 1;
this.Value = value;
this.Children = new AvlNode<T>[2];
}
public static int GetSize(AvlNode<T> node)
{
return node == null ? 0 : node.size;
}
public static int GetHeight(AvlNode<T> node)
{
return node == null ? 0 : node.height;
}
public static void RotateRight(ref AvlNode<T> node)
{
Rotate(ref node, 0, 1);
}
public static void RotateLeft(ref AvlNode<T> node)
{
Rotate(ref node, 1, 0);
}
public static bool Contains(AvlNode<T> node, T value)
{
if (node == null)
{
return false;
}
var cmp = value.CompareTo(node.Value);
if (cmp < 0)
{
return Contains(node.Left, value);
}
if (cmp > 0)
{
return Contains(node.Right, value);
}
return true;
}
public static bool Add(ref AvlNode<T> node, T value)
{
if (node == null)
{
node = new AvlNode<T>(value);
return true;
}
var cmp = value.CompareTo(node.Value);
if (cmp < 0)
{
var child = node.Left;
var result = Add(ref child, value);
if (result)
{
node.Left = child;
BalanceIfLeftIsHeavy(ref node);
}
return result;
}
if (cmp > 0)
{
var child = node.Right;
var result = Add(ref child, value);
if (result)
{
node.Right = child;
BalanceIfRightIsHeavy(ref node);
}
return result;
}
return false;
}
public static int IndexOf(AvlNode<T> node, T value)
{
if (node == null)
{
return -1;
}
var cmp = value.CompareTo(node.Value);
if (cmp < 0)
{
return IndexOf(node.Left, value);
}
if (cmp > 0)
{
return IndexOf(node.Right, value) + GetSize(node.Left) + 1;
}
return GetSize(node.Left);
}
public static T AtIndex(AvlNode<T> node, int index)
{
if (node == null)
{
throw new IndexOutOfRangeException("Noooo");
}
var rootIndex = GetSize(node.Left);
if (index < rootIndex)
{
return AtIndex(node.Left, index);
}
if (index > rootIndex)
{
return AtIndex(node.Right, index - rootIndex - 1);
}
return node.Value;
}
public static bool Remove(ref AvlNode<T> node, T value)
{
if (node == null)
{
return false;
}
var cmp = value.CompareTo(node.Value);
if (cmp < 0)
{
var child = node.Left;
var result = Remove(ref child, value);
if (result)
{
node.Left = child;
BalanceIfRightIsHeavy(ref node);
}
return result;
}
if (cmp > 0)
{
var child = node.Right;
var result = Remove(ref child, value);
if (result)
{
node.Right = child;
BalanceIfLeftIsHeavy(ref node);
}
return result;
}
if(node.Left == null)
{
node = node.Right;
}
else if(node.Right == null)
{
node = node.Left;
}
else
{
var child = node.Right;
var replaceNode = RemoveLeftmostChild(ref child);
node.Right = child;
replaceNode.Left = node.Left;
replaceNode.Right = node.Right;
node = replaceNode;
BalanceIfLeftIsHeavy(ref node);
}
return true;
}
private static AvlNode<T> RemoveLeftmostChild(ref AvlNode<T> node)
{
if(node.Left == null)
{
var toReturn = node;
node = node.Right;
return toReturn;
}
var child = node.Left;
var result = RemoveLeftmostChild(ref child);
node.Left = child;
BalanceIfRightIsHeavy(ref node);
return result;
}
private static void BalanceIfLeftIsHeavy(ref AvlNode<T> node)
{
node.UpdateSizes();
if (node.Balance > 1)
{
if (node.Left.Balance < 0)
{
var child = node.Left;
RotateLeft(ref child);
node.Left = child;
}
RotateRight(ref node);
}
}
private static void BalanceIfRightIsHeavy(ref AvlNode<T> node)
{
node.UpdateSizes();
if (node.Balance < -1)
{
if (node.Right.Balance > 0)
{
var child = node.Right;
RotateRight(ref child);
node.Right = child;
}
RotateLeft(ref node);
}
}
private static void Rotate(ref AvlNode<T> root, int left, int right)
{
var newRoot = root.Children[left];
root.Children[left] = newRoot.Children[right];
newRoot.Children[right] = root;
root.UpdateSizes();
newRoot.UpdateSizes();
root = newRoot;
}
private void UpdateSizes()
{
this.size = GetSize(this.Left) + GetSize(this.Right) + 1;
this.height = Math.Max(GetHeight(this.Left), GetHeight(this.Right)) + 1;
}
}
}
| 25.805654 | 84 | 0.410379 | [
"MIT"
] | Alex-Tsvetanov/Data-Structures-and-Algorithms | Topics/10. Dictionaries-Hash-Tables-and-Sets/live-demo-10.07.2017/BinarySearchTreesDemo/AvlTreeRecursive/AvlNode.cs | 7,305 | C# |
//Copyright (C) 2020, Nicolas Morales Escobar. All rights reserved.
using GameSavvy.Byterizer;
using UnityEngine;
namespace LLNet
{
[CreateAssetMenu(menuName = "LLNet/Messages/SpawnCharacter")]
public class Message_SpawnCharacter : ANetMessage
{
public override void Server_ReceiveMessage(int connectionID, ByteStream msgData, LLServer server)
{
}
/// <summary>
/// Tells the local client to spawn a character for the connection ID sent form the server
/// </summary>
/// <param name="msgData"></param>
/// <param name="client"></param>
public override void Client_ReceiveMessage(ByteStream msgData, LLClient client)
{
int connectionID = msgData.PopInt32();
client.SpawnClientCharacter(connectionID);
}
}
} | 30.857143 | 105 | 0.634259 | [
"MIT"
] | Nicolas4677/Custom-Networking-System | Scripts/Networking/NetMessages/Message_SpawnCharacter.cs | 866 | C# |
using System;
using System.Collections.Generic;
namespace deckofcards {
class Deck {
// Properties
// Array of cards that are currently in the deck.
protected List<Card> _cards;
public Deck() {
SetCards(CreateDefaultDeck());
}
public Deck(List<Card> cards) {
SetCards(cards);
}
public void Shuffle() {
List<Card> cards = this.GetCards();
Random random = new Random();
// Count the amount of cards.
int n = cards.Count;
// For every card in the deck, swap it with another.
while (n > 1) {
n--;
int k = random.Next(n + 1);
// Pick a random card to be swapped.
Card cardToBeSwapped = cards[k];
// Swap them
cards[k] = cards[n];
cards[n] = cardToBeSwapped;
}
// Set the new deck of cards to the shuffled version.
this.SetCards(cards);
}
protected List<Card> CreateDefaultDeck() {
List<string> suits = new List<string>() {
"Clubs",
"Hearts",
"Spades",
"Diamonds"
};
List<Card> cards = new List<Card>();
foreach(string suit in suits) {
for (int rank = 0; rank <= 12; rank++) {
Card card = new Card(suit, rank);
cards.Add(card);
}
}
return cards;
}
// Property manipulators.
protected void SetCards(List<Card> cards) { this._cards = cards; }
public List<Card> GetCards() { return this._cards; }
// Misc methods
public void DumpCards() {
foreach(Card card in this._cards) {
card.Dump();
}
}
public Card GetTopCard() {
Card card = this._cards[0];
this._cards.RemoveAt(0);
return card;
}
}
}
| 23.16 | 70 | 0.553253 | [
"MIT"
] | SlagterJ/deckofcards | Deck.cs | 1,737 | C# |
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace Core.Cron.Data
{
public class ServiceView
{
public int ServiceId { get; set; }
public string ServiceName { get; set; }
public string ServiceIdentifier { get; set; }
public DateTimeOffset DateAdded { get; set; }
public byte[] RowVersion { get; set; }
public DateTimeOffset? LastUpdate { get; set; }
public int? UpdateFrequencyInMinutes { get; set; }
private TimeSpan DeltaTime => LastUpdate.HasValue ? DateTimeOffset.UtcNow - LastUpdate.Value.ToUniversalTime() : new TimeSpan();
[NotMapped]
public bool IsAlive => DeltaTime.TotalMinutes <= UpdateFrequencyInMinutes;
[NotMapped]
public string HeartbeatColor => IsAlive ? "green" : "red";
[NotMapped]
private string TimeOff
{
get
{
var totalMinutes = 0;
if (UpdateFrequencyInMinutes.HasValue)
{
totalMinutes = (int)DeltaTime.TotalMinutes - UpdateFrequencyInMinutes.Value;
}
var hours = totalMinutes / 60;
if (hours > 24)
{
return "more than 24 hours ago";
}
if (hours <= 24 && hours > 0)
{
return $"{hours} hours ago";
}
return $"{totalMinutes} minutes ago";
}
}
[NotMapped]
public string HeartbeatTooltip => !IsAlive ? $"Service has stopped responding {TimeOff}" : "Service is working normally";
}
}
| 32.230769 | 136 | 0.545346 | [
"MIT"
] | alinciuca/core-cron | core-cron/Data/ServiceView.cs | 1,678 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Cme.V20191029.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class LivePullInputInfo : AbstractModel
{
/// <summary>
/// 直播拉流地址。
/// </summary>
[JsonProperty("InputUrl")]
public string InputUrl{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "InputUrl", this.InputUrl);
}
}
}
| 29.227273 | 81 | 0.655521 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Cme/V20191029/Models/LivePullInputInfo.cs | 1,300 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElasticLoadBalancing.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.ElasticLoadBalancing.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for LoadBalancerAttributes Object
/// </summary>
public class LoadBalancerAttributesUnmarshaller : IUnmarshaller<LoadBalancerAttributes, XmlUnmarshallerContext>, IUnmarshaller<LoadBalancerAttributes, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public LoadBalancerAttributes Unmarshall(XmlUnmarshallerContext context)
{
LoadBalancerAttributes unmarshalledObject = new LoadBalancerAttributes();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("AccessLog", targetDepth))
{
var unmarshaller = AccessLogUnmarshaller.Instance;
unmarshalledObject.AccessLog = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("AdditionalAttributes/member", targetDepth))
{
var unmarshaller = AdditionalAttributeUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.AdditionalAttributes.Add(item);
continue;
}
if (context.TestExpression("ConnectionDraining", targetDepth))
{
var unmarshaller = ConnectionDrainingUnmarshaller.Instance;
unmarshalledObject.ConnectionDraining = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ConnectionSettings", targetDepth))
{
var unmarshaller = ConnectionSettingsUnmarshaller.Instance;
unmarshalledObject.ConnectionSettings = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CrossZoneLoadBalancing", targetDepth))
{
var unmarshaller = CrossZoneLoadBalancingUnmarshaller.Instance;
unmarshalledObject.CrossZoneLoadBalancing = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public LoadBalancerAttributes Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static LoadBalancerAttributesUnmarshaller _instance = new LoadBalancerAttributesUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static LoadBalancerAttributesUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.663934 | 179 | 0.594131 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/ElasticLoadBalancing/Generated/Model/Internal/MarshallTransformations/LoadBalancerAttributesUnmarshaller.cs | 4,839 | C# |
using SEDC.NotesApp.DataAccess.Interfaces;
using SEDC.NotesApp.Domain.Models;
using SEDC.NotesApp.Dtos.Notes;
using SEDC.NotesApp.Mappers.Notes;
using SEDC.NotesApp.Services.Interfaces;
using SEDC.NotesApp.Shared.CustomExceptions;
using System.Collections.Generic;
using System.Linq;
namespace SEDC.NotesApp.Services.Implementations
{
public class NotesService : INotesService
{
private IRepository<Note> _notesRepository;
private IRepository<User> _usersRepository;
public NotesService(IRepository<Note> notesRepository, IRepository<User> usersRepository)
{
_notesRepository = notesRepository;
_usersRepository = usersRepository;
}
public void AddNote(AddUpdateNoteDto addNoteDto)
{
ValidateNoteInput(addNoteDto);
Note newNote = addNoteDto.ToNote();
_notesRepository.Insert(newNote);
}
public List<NoteDto> GetAllNotes()
{
//read from db
List<Note> notesDb = _notesRepository.GetAll();
//map to dtos
return notesDb.Select(x => x.ToNoteDto()).ToList();
}
public NoteDto GetNoteById(int id)
{
Note noteDb = _notesRepository.GetById(id);
if(noteDb == null)
{
//log
throw new ResourceNotFoundException(id, $"Note with id {id} was not found");
}
return noteDb.ToNoteDto();
}
public void UpdateNote(AddUpdateNoteDto updateNoteDto)
{
Note noteDb = _notesRepository.GetById(updateNoteDto.Id);
if(noteDb == null)
{
throw new ResourceNotFoundException(updateNoteDto.Id, $"Note with id {updateNoteDto.Id} was not found");
}
ValidateNoteInput(updateNoteDto);
noteDb.Text = updateNoteDto.Text;
noteDb.Color = updateNoteDto.Color;
noteDb.Tag = updateNoteDto.Tag;
noteDb.UserId = updateNoteDto.UserId;
_notesRepository.Update(noteDb);
}
#region private methods
private void ValidateNoteInput(AddUpdateNoteDto addNoteDto)
{
User userDb = _usersRepository.GetById(addNoteDto.UserId);
if (userDb == null)
{
throw new NoteException("The user does not exist!");
}
if (string.IsNullOrEmpty(addNoteDto.Text))
{
throw new NoteException("The text must not be empty!");
}
if (addNoteDto.Text.Length > 100)
{
throw new NoteException("The text must not contain more than 100 characters!");
}
if (!string.IsNullOrEmpty(addNoteDto.Color) && addNoteDto.Color.Length > 30)
{
throw new NoteException("The color must not contain more than 30 characters!");
}
}
#endregion
}
}
| 32.956044 | 120 | 0.591197 | [
"MIT"
] | sedc-codecademy/skwd9-09-aspnetwebapi | G2/Class07 - Architecture/Code/SEDC.NotesApp/SEDC.NotesApp.Services/Implementations/NotesService.cs | 3,001 | C# |
namespace CohesionAndCoupling
{
public interface IFileUtils
{
string GetFileExtension(string fileName);
string GetFileNameWithoutExtension(string fileName);
}
} | 21.111111 | 60 | 0.715789 | [
"MIT"
] | sholev/SoftUni | Fundamentals-2.0/HighQualityCode/Homework/High-Quality-Classes/High-Quality-Classes/Cohesion-and-Coupling/IFileUtils.cs | 192 | C# |
namespace SADFM.Infrastructure.Persistence.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("City")]
public partial class City
{
private City() { }
public City(string name)
{
this.Name = name;
}
public Guid CityId { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public Guid ProvinceId { get; set; }
public virtual Province Province { get; set; }
public virtual ICollection<FacilityServiceType> FacilityServiceTypes { get; set; }
public virtual ICollection<Patient> Patients { get; set; }
}
}
| 23.457143 | 90 | 0.627284 | [
"MIT"
] | developersworkspace/EPONS | SourceCode/SADFM/trunk/SADFM.Infrastructure.Persistence/Models/City.cs | 821 | C# |
/*<FILE_LICENSE>
* Azos (A to Z Application Operating System) Framework
* The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
</FILE_LICENSE>*/
using System.Collections.Generic;
using Azos.Apps;
using Azos.Collections;
using Azos.Conf;
using Azos.Data.Access;
namespace Azos.Sky.Mdb
{
/// <summary>
/// Represents a general ancestor for CENTRAL or partitioned areas
/// </summary>
public abstract partial class MdbArea : MdbAppComponent, INamed
{
#region CONSTS
public const string CENTRAL_AREA_NAME = "CENTRAL";
public const string CONFIG_AREA_SECTION = "area";
public const string CONFIG_PARTITION_SECTION = "partition";
public const string CONFIG_SHARD_SECTION = "shard";
public const string CONFIG_START_GDID_ATTR = "start-gdid";
public const string CONFIG_ORDER_ATTR = "order";
public const string CONFIG_PRIMARY_CONNECT_STRING_ATTR = "primary-cs";
public const string CONFIG_SECONDARY_CONNECT_STRING_ATTR = "secondary-cs";
#endregion
#region .ctor
protected MdbArea(MdbDataStore store, IConfigSectionNode node) : base(store)
{
if (store==null || node==null || !node.Exists)
throw new MdbException(StringConsts.ARGUMENT_ERROR+"MdbArea.ctor(store==null|node==null|!Exists)");
ConfigAttribute.Apply(this, node);
var dsnode = node[CommonApplicationLogic.CONFIG_DATA_STORE_SECTION];
if (!dsnode.Exists)
throw new MdbException(StringConsts.MDB_AREA_CONFIG_NO_DATASTORE_ERROR.Args(node.RootPath));
m_PhysicalDataStore = FactoryUtils.MakeAndConfigure<ICRUDDataStoreImplementation>(dsnode, args: new []{ this });
}
protected override void Destructor()
{
DisposableObject.DisposeAndNull(ref m_PhysicalDataStore);
base.Destructor();
}
#endregion
#region Fields
private ICRUDDataStoreImplementation m_PhysicalDataStore;
#endregion
#region Properties
public MdbDataStore Store{ get { return (MdbDataStore)base.ComponentDirector;}}
public abstract string Name{ get;}
/// <summary>
/// Physical data store that services the area
/// </summary>
public ICRUDDataStoreImplementation PhysicalDataStore
{
get { return m_PhysicalDataStore;}
}
/// <summary>
/// Returns all ordered partitions of the area - one for central, or all actual partitions for partitioned area
/// </summary>
public abstract IEnumerable<Partition> AllPartitions { get;}
/// <summary>
/// Returns all ordered shards within ordered partitions
/// </summary>
public abstract IEnumerable<Partition.Shard> AllShards { get;}
#endregion
}
}
| 32.147727 | 120 | 0.696713 | [
"MIT"
] | erxdkh/azos | src/Azos.Sky/Mdb/MdbArea.cs | 2,829 | C# |
using Com.API.Hotels.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Com.API.Hotels.Brokers.BookingBroker
{
public partial class BookingBroker
{
private readonly IBookingServices bookingServices;
public BookingBroker(IBookingServices bookingServices) =>
this.bookingServices = bookingServices;
}
}
| 26 | 65 | 0.752404 | [
"MIT"
] | Huzecode/API.Hotels | Com.API.Hotels/Brokers/BookingBroker/BookingBroker.cs | 418 | C# |
using Assets.Scripts.ServerShared.MessagePackObjects;
using MessagePack;
namespace Cauldron.Shared.MessagePackObjects.Value
{
[MessagePackObject(true)]
public class NumValueCalculatorForCard
{
public enum TypeValue
{
None,
[DisplayText("カウント")]
Count,
[DisplayText("カードのコスト")]
CardCost,
[DisplayText("カードの元々のコスト")]
CardBaseCost,
[DisplayText("カードのパワー")]
CardPower,
[DisplayText("カードの元々のパワー")]
CardBasePower,
[DisplayText("カードのタフネス")]
CardToughness,
[DisplayText("カードの元々のタフネス")]
CardBaseToughness,
}
public TypeValue Type { get; }
public Choice CardsChoice { get; }
public NumValueCalculatorForCard(TypeValue Type, Choice CardsChoice)
{
this.Type = Type;
this.CardsChoice = CardsChoice;
}
}
}
| 25.153846 | 76 | 0.558614 | [
"MIT"
] | iuemon83/Cauldron | Cauldron.Client.Unity/Assets/Scripts/ServerShared/MessagePackObjects/CardObjects/Value/NumValueCalculatorForCard.cs | 1,097 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
//
// Microsoft Cognitive Services (formerly Project Oxford) GitHub:
// https://github.com/Microsoft/Cognitive-Face-Windows
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Cognitive.Face.Contract;
namespace Microsoft.Cognitive.Face
{
#region Enumerations
/// <summary>
/// Supported face attribute types
/// </summary>
public enum FaceAttributeType
{
/// <summary>
/// Analyses age
/// </summary>
Age,
/// <summary>
/// Analyses gender
/// </summary>
Gender,
/// <summary>
/// Analyses facial hair
/// </summary>
FacialHair,
/// <summary>
/// Analyses whether is smiling
/// </summary>
Smile,
/// <summary>
/// Analyses head pose
/// </summary>
HeadPose,
/// <summary>
/// Analyses glasses type
/// </summary>
Glasses,
}
/// <summary>
/// two working modes of Face - Find Similar
/// </summary>
public enum FindSimilarMatchMode
{
/// <summary>
/// matchPerson mode of Face - Find Similar, return the similar faces of the same person with the query face.
/// </summary>
matchPerson,
/// <summary>
/// matchFace mode of Face - Find Similar, return the similar faces of the query face, ignoring if they belong to the same person.
/// </summary>
matchFace
}
#endregion Enumerations
/// <summary>
/// The face service client proxy interface.
/// </summary>
public interface IFaceServiceClient
{
#region Properties
/// <summary>
/// Gets default request headers for all following http request
/// </summary>
HttpRequestHeaders DefaultRequestHeaders
{
get;
}
#endregion Properties
#region Methods
/// <summary>
/// Adds the face to face list asynchronously.
/// </summary>
/// <param name="faceListId">The face list identifier.</param>
/// <param name="imageUrl">The face image URL.</param>
/// <param name="userData">The user data.</param>
/// <param name="targetFace">The target face.</param>
/// <returns>
/// Add face result.
/// </returns>
Task<AddPersistedFaceResult> AddFaceToFaceListAsync(string faceListId, string imageUrl, string userData = null, FaceRectangle targetFace = null);
/// <summary>
/// Adds the face to face list asynchronously.
/// </summary>
/// <param name="faceListId">The face list identifier.</param>
/// <param name="imageStream">The face image stream.</param>
/// <param name="userData">The user data.</param>
/// <param name="targetFace">The target face.</param>
/// <returns>
/// Add face result.
/// </returns>
Task<AddPersistedFaceResult> AddFaceToFaceListAsync(string faceListId, Stream imageStream, string userData = null, FaceRectangle targetFace = null);
/// <summary>
/// Adds a face to a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <param name="imageUrl">The face image URL.</param>
/// <param name="userData">The user data.</param>
/// <param name="targetFace">The target face.</param>
/// <returns>
/// Add person face result.
/// </returns>
Task<AddPersistedFaceResult> AddPersonFaceAsync(string personGroupId, Guid personId, string imageUrl, string userData = null, FaceRectangle targetFace = null);
/// <summary>
/// Adds a face to a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <param name="imageStream">The face image stream.</param>
/// <param name="userData">The user data.</param>
/// <param name="targetFace">The Target Face.</param>
/// <returns>
/// Add person face result.
/// </returns>
Task<AddPersistedFaceResult> AddPersonFaceAsync(string personGroupId, Guid personId, Stream imageStream, string userData = null, FaceRectangle targetFace = null);
/// <summary>
/// Creates the face list asynchronously.
/// </summary>
/// <param name="faceListId">The face list identifier.</param>
/// <param name="name">The name.</param>
/// <param name="userData">The user data.</param>
/// <returns>Task object.</returns>
Task CreateFaceListAsync(string faceListId, string name, string userData);
/// <summary>
/// Creates a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="name">The name.</param>
/// <param name="userData">The user data.</param>
/// <returns>The CreatePersonResult entity.</returns>
Task<CreatePersonResult> CreatePersonAsync(string personGroupId, string name, string userData = null);
/// <summary>
/// Creates the person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group identifier.</param>
/// <param name="name">The name.</param>
/// <param name="userData">The user data.</param>
/// <returns>Task object.</returns>
Task CreatePersonGroupAsync(string personGroupId, string name, string userData = null);
/// <summary>
/// Deletes the face from face list asynchronously.
/// </summary>
/// <param name="faceListId">The face list identifier.</param>
/// <param name="persistedFaceId">The persisted face identifier.</param>
/// <returns>Task object.</returns>
Task DeleteFaceFromFaceListAsync(string faceListId, Guid persistedFaceId);
/// <summary>
/// Deletes the face list asynchronously.
/// </summary>
/// <param name="faceListId">The face list identifier.</param>
/// <returns>Task object.</returns>
Task DeleteFaceListAsync(string faceListId);
/// <summary>
/// Deletes a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <returns>Task object.</returns>
Task DeletePersonAsync(string personGroupId, Guid personId);
/// <summary>
/// Deletes a face of a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <param name="persistedFaceId">The persisted face id.</param>
/// <returns>Task object.</returns>
Task DeletePersonFaceAsync(string personGroupId, Guid personId, Guid persistedFaceId);
/// <summary>
/// Deletes a person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <returns>Task object.</returns>
Task DeletePersonGroupAsync(string personGroupId);
/// <summary>
/// Detects an URL asynchronously.
/// </summary>
/// <param name="imageUrl">The image URL.</param>
/// <param name="returnFaceId">If set to <c>true</c> [return face ID].</param>
/// <param name="returnFaceLandmarks">If set to <c>true</c> [return face landmarks].</param>
/// <param name="returnFaceAttributes">Return face attributes.</param>
/// <returns>The detected faces.</returns>
Task<Microsoft.Cognitive.Face.Contract.Face[]> DetectAsync(string imageUrl, bool returnFaceId = true, bool returnFaceLandmarks = false, IEnumerable<FaceAttributeType> returnFaceAttributes = null);
/// <summary>
/// Detects an image asynchronously.
/// </summary>
/// <param name="imageStream">The image stream.</param>
/// <param name="returnFaceId">If set to <c>true</c> [return face ID].</param>
/// <param name="returnFaceLandmarks">If set to <c>true</c> [return face landmarks].</param>
/// <param name="returnFaceAttributes">Return face attributes.</param>
/// <returns>The detected faces.</returns>
Task<Microsoft.Cognitive.Face.Contract.Face[]> DetectAsync(Stream imageStream, bool returnFaceId = true, bool returnFaceLandmarks = false, IEnumerable<FaceAttributeType> returnFaceAttributes = null);
/// <summary>
/// Finds the similar faces asynchronously.
/// </summary>
/// <param name="faceId">The face identifier.</param>
/// <param name="faceIds">The face identifiers.</param>
/// <param name="maxNumOfCandidatesReturned">The max number of candidates returned.</param>
/// <returns>
/// The similar faces.
/// </returns>
Task<SimilarFace[]> FindSimilarAsync(Guid faceId, Guid[] faceIds, int maxNumOfCandidatesReturned = 20);
/// <summary>
/// Finds the similar faces asynchronously.
/// </summary>
/// <param name="faceId">The face identifier.</param>
/// <param name="faceIds">The face identifiers.</param>
/// <param name="mode">Algorithm mode option, default as "matchPerson".</param>
/// <param name="maxNumOfCandidatesReturned">The max number of candidates returned.</param>
/// <returns>
/// The similar faces.
/// </returns>
Task<SimilarFace[]> FindSimilarAsync(Guid faceId, Guid[] faceIds, FindSimilarMatchMode mode, int maxNumOfCandidatesReturned = 20);
/// <summary>
/// Finds the similar faces asynchronously.
/// </summary>
/// <param name="faceId">The face identifier.</param>
/// <param name="faceListId">The face list identifier.</param>
/// <param name="maxNumOfCandidatesReturned">The max number of candidates returned.</param>
/// <returns>
/// The similar persisted faces.
/// </returns>
Task<SimilarPersistedFace[]> FindSimilarAsync(Guid faceId, string faceListId, int maxNumOfCandidatesReturned = 20);
/// <summary>
/// Finds the similar faces asynchronously.
/// </summary>
/// <param name="faceId">The face identifier.</param>
/// <param name="faceListId">The face list identifier.</param>
/// <param name="mode">Algorithm mode option, default as "matchPerson".</param>
/// <param name="maxNumOfCandidatesReturned">The max number of candidates returned.</param>
/// <returns>
/// The similar persisted faces.
/// </returns>
Task<SimilarPersistedFace[]> FindSimilarAsync(Guid faceId, string faceListId, FindSimilarMatchMode mode, int maxNumOfCandidatesReturned = 20);
/// <summary>
/// Gets the face list asynchronously.
/// </summary>
/// <param name="faceListId">The face list identifier.</param>
/// <returns>Face list object.</returns>
Task<FaceList> GetFaceListAsync(string faceListId);
/// <summary>
/// Gets a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <returns>The person entity.</returns>
Task<Person> GetPersonAsync(string personGroupId, Guid personId);
/// <summary>
/// Gets a face of a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <param name="persistedFaceId">The persisted face id.</param>
/// <returns>The person face entity.</returns>
Task<PersonFace> GetPersonFaceAsync(string personGroupId, Guid personId, Guid persistedFaceId);
/// <summary>
/// Gets a person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <returns>The person group entity.</returns>
Task<PersonGroup> GetPersonGroupAsync(string personGroupId);
/// <summary>
/// Asynchronously list the first 1000 person groups.
/// </summary>
/// <returns>Person group entity array.</returns>
[Obsolete("use ListPersonGroupsAsync instead")]
Task<PersonGroup[]> GetPersonGroupsAsync();
/// <summary>
/// Asynchronously list the top person groups whose Id is larger than "start".
/// </summary>
/// <param name="start">the start point string in listing person groups</param>
/// <param name="top">the number of person groups to list</param>
/// <returns>Person group entity array.</returns>
Task<PersonGroup[]> ListPersonGroupsAsync(string start = "", int top = 1000);
/// <summary>
/// Gets person group training status asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <returns>The person group training status.</returns>
Task<TrainingStatus> GetPersonGroupTrainingStatusAsync(string personGroupId);
/// <summary>
/// Gets all persons inside a person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <returns>
/// The person entity array.
/// </returns>
Task<Person[]> GetPersonsAsync(string personGroupId);
/// <summary>
/// Groups the face asynchronously.
/// </summary>
/// <param name="faceIds">The face ids.</param>
/// <returns>Task object.</returns>
Task<GroupResult> GroupAsync(Guid[] faceIds);
/// <summary>
/// Identities the faces in a given person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="faceIds">The face ids.</param>
/// <param name="maxNumOfCandidatesReturned">The maximum number of candidates returned for each face.</param>
/// <returns>The identification results</returns>
Task<IdentifyResult[]> IdentifyAsync(string personGroupId, Guid[] faceIds, int maxNumOfCandidatesReturned = 1);
/// <summary>
/// Identities the faces in a given person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="faceIds">The face ids.</param>
/// <param name="maxNumOfCandidatesReturned">The maximum number of candidates returned for each face.</param>
/// <param name="confidenceThreshold">user-specified confidence threshold.</param>
/// <returns>The identification results</returns>
Task<IdentifyResult[]> IdentifyAsync(string personGroupId, Guid[] faceIds, float confidenceThreshold, int maxNumOfCandidatesReturned = 1);
/// <summary>
/// Lists the face lists asynchronously.
/// </summary>
/// <returns>FaceListMetadata array.</returns>
Task<FaceListMetadata[]> ListFaceListsAsync();
/// <summary>
/// Trains the person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <returns>Task object.</returns>
Task TrainPersonGroupAsync(string personGroupId);
/// <summary>
/// Updates the face list asynchronously.
/// </summary>
/// <param name="faceListId">The face list identifier.</param>
/// <param name="name">The name.</param>
/// <param name="userData">The user data.</param>
/// <returns>Task object.</returns>
Task UpdateFaceListAsync(string faceListId, string name, string userData);
/// <summary>
/// Updates a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <param name="name">The name.</param>
/// <param name="userData">The user data.</param>
/// <returns>Task object.</returns>
Task UpdatePersonAsync(string personGroupId, Guid personId, string name, string userData = null);
/// <summary>
/// Updates a face of a person asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="personId">The person id.</param>
/// <param name="persistedFaceId">The persisted face id.</param>
/// <param name="userData">The user data.</param>
/// <returns>Task object.</returns>
Task UpdatePersonFaceAsync(string personGroupId, Guid personId, Guid persistedFaceId, string userData = null);
/// <summary>
/// Updates a person group asynchronously.
/// </summary>
/// <param name="personGroupId">The person group id.</param>
/// <param name="name">The name.</param>
/// <param name="userData">The user data.</param>
/// <returns>Task object.</returns>
Task UpdatePersonGroupAsync(string personGroupId, string name, string userData = null);
/// <summary>
/// Verifies whether the specified two faces belong to the same person asynchronously.
/// </summary>
/// <param name="faceId1">The face id 1.</param>
/// <param name="faceId2">The face id 2.</param>
/// <returns>The verification result.</returns>
Task<VerifyResult> VerifyAsync(Guid faceId1, Guid faceId2);
/// <summary>
/// Verify whether one face belong to a person.
/// </summary>
/// <param name="faceId"></param>
/// <param name="personGroupId"></param>
/// <param name="personId"></param>
/// <returns></returns>
Task<VerifyResult> VerifyAsync(Guid faceId, string personGroupId, Guid personId);
#endregion Methods
}
} | 43.089325 | 207 | 0.616089 | [
"Apache-2.0"
] | DXFrance/MarvelBot | Libraries/FaceLibrary/IFaceServiceClient.cs | 19,780 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Utilities
{
using System.Linq;
using Xunit;
public class DynamicEqualityComparerLinqIntegrationTests
{
[Fact]
public void Distinct_removes_duplicates_using_provided_equality_function()
{
var values = new[] { "a", "b", "A" };
Assert.True(
new[] { "a", "b" }.SequenceEqual(
values.Distinct((a, b) => a.Equals(b, StringComparison.OrdinalIgnoreCase))));
}
[Fact]
public void Contains_uses_provided_equality_function()
{
var values = new[] { "a", "b", "A" };
Assert.True(values.Contains("B", (a, b) => a.Equals(b, StringComparison.OrdinalIgnoreCase)));
}
[Fact]
public void Intersect_returns_intersection_using_provided_equality_function()
{
var setA = new[] { "a", "b" };
var setB = new[] { "A", "C" };
Assert.True(
new[] { "a" }.SequenceEqual(
setA.Intersect(setB, (a, b) => a.Equals(b, StringComparison.OrdinalIgnoreCase))));
}
[Fact]
public void GroupBy_groups_items_using_provided_equality_function()
{
var values = new[] { "a", "A" };
Assert.Equal(1, values.GroupBy((a, b) => a.Equals(b, StringComparison.OrdinalIgnoreCase)).Count());
}
[Fact]
public void SequenceEqual_compares_items_using_provided_equality_function()
{
var first = new[] { "a", "A" };
var second = new[] { "A", "a" };
Assert.True(first.SequenceEqual(second, (a, b) => a.Equals(b, StringComparison.OrdinalIgnoreCase)));
}
}
}
| 33.684211 | 133 | 0.546875 | [
"Apache-2.0"
] | TerraVenil/entityframework | test/EntityFramework/UnitTests/Utilities/DynamicEqualityComparerLinqIntegrationTests.cs | 1,920 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.EntityFrameworkCore.Query
{
public class OwnedQueryCosmosTest : OwnedQueryTestBase<OwnedQueryCosmosTest.OwnedQueryCosmosFixture>
{
public OwnedQueryCosmosTest(OwnedQueryCosmosFixture fixture, ITestOutputHelper testOutputHelper)
: base(fixture)
{
ClearLog();
//TestLoggerFactory.TestOutputHelper = testOutputHelper;
}
[ConditionalTheory(Skip = "Issue#17246")]
public override Task Query_loads_reference_nav_automatically_in_projection(bool async)
{
return base.Query_loads_reference_nav_automatically_in_projection(async);
}
[ConditionalTheory(Skip = "SelectMany #17246")]
public override Task Query_with_owned_entity_equality_operator(bool async)
{
return base.Query_with_owned_entity_equality_operator(async);
}
[ConditionalTheory(Skip = "Count #16146")]
public override async Task Navigation_rewrite_on_owned_collection(bool async)
{
await base.Navigation_rewrite_on_owned_collection(async);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""LeafB"") OR ((c[""Discriminator""] = ""LeafA"") OR ((c[""Discriminator""] = ""Branch"") OR (c[""Discriminator""] = ""OwnedPerson""))))");
}
[ConditionalTheory(Skip = "Issue#16926")]
public override async Task Navigation_rewrite_on_owned_collection_with_composition(bool async)
{
await base.Navigation_rewrite_on_owned_collection_with_composition(async);
AssertSql(" ");
}
[ConditionalTheory(Skip = "Issue#16926")]
public override async Task Navigation_rewrite_on_owned_collection_with_composition_complex(bool async)
{
await base.Navigation_rewrite_on_owned_collection_with_composition_complex(async);
AssertSql(" ");
}
public override async Task Navigation_rewrite_on_owned_reference_projecting_entity(bool async)
{
await base.Navigation_rewrite_on_owned_reference_projecting_entity(async);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"") AND (c[""PersonAddress""][""Country""][""Name""] = ""USA""))");
}
public override async Task Navigation_rewrite_on_owned_reference_projecting_scalar(bool async)
{
await base.Navigation_rewrite_on_owned_reference_projecting_scalar(async);
AssertSql(
@"SELECT c[""PersonAddress""][""Country""][""Name""]
FROM root c
WHERE (c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"") AND (c[""PersonAddress""][""Country""][""Name""] = ""USA""))");
}
public override async Task Query_for_base_type_loads_all_owned_navs(bool async)
{
await base.Query_for_base_type_loads_all_owned_navs(async);
AssertSql(
@"SELECT c
FROM root c
WHERE c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"")");
}
public override async Task Query_for_branch_type_loads_all_owned_navs(bool async)
{
await base.Query_for_branch_type_loads_all_owned_navs(async);
AssertSql(
@"SELECT c
FROM root c
WHERE c[""Discriminator""] IN (""Branch"", ""LeafA"")");
}
public override async Task Query_for_branch_type_loads_all_owned_navs_tracking(bool async)
{
await base.Query_for_branch_type_loads_all_owned_navs_tracking(async);
AssertSql(
@"SELECT c
FROM root c
WHERE c[""Discriminator""] IN (""Branch"", ""LeafA"")");
}
public override async Task Query_for_leaf_type_loads_all_owned_navs(bool async)
{
await base.Query_for_leaf_type_loads_all_owned_navs(async);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""LeafA"")");
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Filter_owned_entity_chained_with_regular_entity_followed_by_projecting_owned_collection(bool async)
{
return base.Filter_owned_entity_chained_with_regular_entity_followed_by_projecting_owned_collection(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_filter(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_filter(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_and_scalar(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_and_scalar(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection_count(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection_count(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_property(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_property(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task
Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool async)
{
return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(
async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Project_multiple_owned_navigations(bool async)
{
return base.Project_multiple_owned_navigations(async);
}
[ConditionalTheory(Skip = "LeftJoin #17314")]
public override Task Project_multiple_owned_navigations_with_expansion_on_owned_collections(bool async)
{
return base.Project_multiple_owned_navigations_with_expansion_on_owned_collections(async);
}
[ConditionalTheory(Skip = "SelectMany #17246")]
public override Task SelectMany_on_owned_collection(bool async)
{
return base.SelectMany_on_owned_collection(async);
}
[ConditionalTheory(Skip = "SelectMany #17246")]
public override Task SelectMany_on_owned_reference_followed_by_regular_entity_and_collection(bool async)
{
return base.SelectMany_on_owned_reference_followed_by_regular_entity_and_collection(async);
}
[ConditionalTheory(Skip = "SelectMany #17246")]
public override Task SelectMany_on_owned_reference_with_entity_in_between_ending_in_owned_collection(bool async)
{
return base.SelectMany_on_owned_reference_with_entity_in_between_ending_in_owned_collection(async);
}
[ConditionalTheory(Skip = "SelectMany #17246")]
public override Task Query_with_owned_entity_equality_method(bool async)
{
return base.Query_with_owned_entity_equality_method(async);
}
[ConditionalTheory(Skip = "SelectMany #17246")]
public override Task Query_with_owned_entity_equality_object_method(bool async)
{
return base.Query_with_owned_entity_equality_object_method(async);
}
public override async Task Query_with_OfType_eagerly_loads_correct_owned_navigations(bool async)
{
await base.Query_with_OfType_eagerly_loads_correct_owned_navigations(async);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"") AND (c[""Discriminator""] = ""LeafA""))");
}
[ConditionalTheory(Skip = "Distinct ordering #16156")]
public override Task Query_when_subquery(bool async)
{
return base.Query_when_subquery(async);
}
[ConditionalTheory(Skip = "Count #16146")]
public override Task No_ignored_include_warning_when_implicit_load(bool async)
{
return base.No_ignored_include_warning_when_implicit_load(async);
}
[ConditionalTheory(Skip = "Skip withouth Take #18923")]
public override Task Client_method_skip_loads_owned_navigations(bool async)
{
return base.Client_method_skip_loads_owned_navigations(async);
}
[ConditionalTheory(Skip = "Skip withouth Take #18923")]
public override Task Client_method_skip_loads_owned_navigations_variation_2(bool async)
{
return base.Client_method_skip_loads_owned_navigations_variation_2(async);
}
[ConditionalTheory(Skip = "Composition over embedded collection #16926")]
public override Task Where_owned_collection_navigation_ToList_Count(bool async)
{
return base.Where_owned_collection_navigation_ToList_Count(async);
}
[ConditionalTheory(Skip = "Composition over embedded collection #16926")]
public override Task Where_collection_navigation_ToArray_Count(bool async)
{
return base.Where_collection_navigation_ToArray_Count(async);
}
[ConditionalTheory(Skip = "Composition over embedded collection #16926")]
public override Task Where_collection_navigation_AsEnumerable_Count(bool async)
{
return base.Where_collection_navigation_AsEnumerable_Count(async);
}
[ConditionalTheory(Skip = "Composition over embedded collection #16926")]
public override Task Where_collection_navigation_ToList_Count_member(bool async)
{
return base.Where_collection_navigation_ToList_Count_member(async);
}
[ConditionalTheory(Skip = "Composition over embedded collection #16926")]
public override Task Where_collection_navigation_ToArray_Length_member(bool async)
{
return base.Where_collection_navigation_ToArray_Length_member(async);
}
[ConditionalTheory(Skip = "Issue #16146")]
public override Task GroupBy_with_multiple_aggregates_on_owned_navigation_properties(bool async)
{
return base.GroupBy_with_multiple_aggregates_on_owned_navigation_properties(async);
}
public override async Task Can_query_on_indexer_properties(bool async)
{
await base.Can_query_on_indexer_properties(async);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"") AND (c[""Name""] = ""Mona Cy""))");
}
public override async Task Can_query_on_owned_indexer_properties(bool async)
{
await base.Can_query_on_owned_indexer_properties(async);
AssertSql(
@"SELECT c[""Name""]
FROM root c
WHERE (c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"") AND (c[""PersonAddress""][""ZipCode""] = 38654))");
}
public override async Task Can_query_on_indexer_property_when_property_name_from_closure(bool async)
{
await base.Can_query_on_indexer_property_when_property_name_from_closure(async);
AssertSql(
@"SELECT c[""Name""]
FROM root c
WHERE (c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"") AND (c[""Name""] = ""Mona Cy""))");
}
public override async Task Can_project_indexer_properties(bool async)
{
await base.Can_project_indexer_properties(async);
AssertSql(
@"SELECT c[""Name""]
FROM root c
WHERE c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"")");
}
public override async Task Can_project_owned_indexer_properties(bool async)
{
await base.Can_project_owned_indexer_properties(async);
AssertSql(
@"SELECT c[""PersonAddress""][""AddressLine""]
FROM root c
WHERE c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"")");
}
public override async Task Can_project_indexer_properties_converted(bool async)
{
await base.Can_project_indexer_properties_converted(async);
AssertSql(
@"SELECT c[""Name""]
FROM root c
WHERE c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"")");
}
public override async Task Can_project_owned_indexer_properties_converted(bool async)
{
await base.Can_project_owned_indexer_properties_converted(async);
}
[ConditionalTheory(Skip = "OrderBy requires composite index #17246")]
public override async Task Can_OrderBy_indexer_properties(bool async)
{
await base.Can_OrderBy_indexer_properties(async);
AssertSql(" ");
}
[ConditionalTheory(Skip = "OrderBy requires composite index #17246")]
public override async Task Can_OrderBy_indexer_properties_converted(bool async)
{
await base.Can_OrderBy_indexer_properties_converted(async);
AssertSql(" ");
}
[ConditionalTheory(Skip = "OrderBy requires composite index #17246")]
public override async Task Can_OrderBy_owned_indexer_properties(bool async)
{
await base.Can_OrderBy_owned_indexer_properties(async);
AssertSql(" ");
}
[ConditionalTheory(Skip = "OrderBy requires composite index #17246")]
public override async Task Can_OrderBy_owened_indexer_properties_converted(bool async)
{
await base.Can_OrderBy_owened_indexer_properties_converted(async);
AssertSql(" ");
}
[ConditionalTheory(Skip = "GroupBy #17246")]
public override async Task Can_group_by_indexer_property(bool isAsync)
{
await base.Can_group_by_indexer_property(isAsync);
AssertSql(" ");
}
[ConditionalTheory(Skip = "GroupBy #17246")]
public override async Task Can_group_by_converted_indexer_property(bool isAsync)
{
await base.Can_group_by_converted_indexer_property(isAsync);
AssertSql(" ");
}
[ConditionalTheory(Skip = "GroupBy #17246")]
public override async Task Can_group_by_owned_indexer_property(bool isAsync)
{
await base.Can_group_by_owned_indexer_property(isAsync);
AssertSql(" ");
}
[ConditionalTheory(Skip = "GroupBy #17246")]
public override async Task Can_group_by_converted_owned_indexer_property(bool isAsync)
{
await base.Can_group_by_converted_owned_indexer_property(isAsync);
AssertSql(" ");
}
[ConditionalTheory(Skip = "Join #17246")]
public override async Task Can_join_on_indexer_property_on_query(bool isAsync)
{
await base.Can_join_on_indexer_property_on_query(isAsync);
AssertSql(" ");
}
public override async Task Projecting_indexer_property_ignores_include(bool isAsync)
{
await base.Projecting_indexer_property_ignores_include(isAsync);
AssertSql(
@"SELECT VALUE {""Nation"" : c[""PersonAddress""][""ZipCode""]}
FROM root c
WHERE c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"")");
}
public override async Task Projecting_indexer_property_ignores_include_converted(bool isAsync)
{
await base.Projecting_indexer_property_ignores_include_converted(isAsync);
AssertSql(
@"SELECT VALUE {""Nation"" : c[""PersonAddress""][""ZipCode""]}
FROM root c
WHERE c[""Discriminator""] IN (""OwnedPerson"", ""Branch"", ""LeafB"", ""LeafA"")");
}
[ConditionalTheory(Skip = "Subquery #17246")]
public override async Task Indexer_property_is_pushdown_into_subquery(bool isAsync)
{
await base.Indexer_property_is_pushdown_into_subquery(isAsync);
AssertSql(" ");
}
[ConditionalTheory(Skip = "Composition over owned collection #17246")]
public override async Task Can_query_indexer_property_on_owned_collection(bool isAsync)
{
await base.Can_query_indexer_property_on_owned_collection(isAsync);
AssertSql(" ");
}
[ConditionalTheory(Skip = "No SelectMany, No Ability to Include navigation back to owner #17246")]
public override Task NoTracking_Include_with_cycles_does_not_throw_when_performing_identity_resolution(bool async)
{
return base.NoTracking_Include_with_cycles_does_not_throw_when_performing_identity_resolution(async);
}
[ConditionalTheory(Skip = "No Composite index to process custom ordering #17246")]
public override async Task Ordering_by_identifying_projection(bool async)
{
await base.Ordering_by_identifying_projection(async);
AssertSql(" ");
}
[ConditionalTheory(Skip = "Composition over owned collection #17246")]
public override async Task Query_on_collection_entry_works_for_owned_collection(bool isAsync)
{
await base.Query_on_collection_entry_works_for_owned_collection(isAsync);
AssertSql(" ");
}
private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
private void ClearLog()
=> Fixture.TestSqlLoggerFactory.Clear();
public class OwnedQueryCosmosFixture : OwnedQueryFixtureBase
{
protected override ITestStoreFactory TestStoreFactory
=> CosmosTestStoreFactory.Instance;
public TestSqlLoggerFactory TestSqlLoggerFactory
=> (TestSqlLoggerFactory)ServiceProvider.GetRequiredService<ILoggerFactory>();
protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context)
{
modelBuilder.Entity<OwnedPerson>(
eb =>
{
eb.IndexerProperty<string>("Name");
eb.HasData(
new
{
Id = 1,
id = Guid.NewGuid().ToString(),
Name = "Mona Cy"
});
eb.OwnsOne(
p => p.PersonAddress, ab =>
{
ab.IndexerProperty<string>("AddressLine");
ab.IndexerProperty(typeof(int), "ZipCode");
ab.HasData(
new
{
OwnedPersonId = 1,
PlaceType = "Land",
AddressLine = "804 S. Lakeshore Road",
ZipCode = 38654
},
new
{
OwnedPersonId = 2,
PlaceType = "Land",
AddressLine = "7 Church Dr.",
ZipCode = 28655
},
new
{
OwnedPersonId = 3,
PlaceType = "Land",
AddressLine = "72 Hickory Rd.",
ZipCode = 07728
},
new
{
OwnedPersonId = 4,
PlaceType = "Land",
AddressLine = "28 Strawberry St.",
ZipCode = 19053
});
ab.OwnsOne(
a => a.Country, cb =>
{
cb.HasData(
new
{
OwnedAddressOwnedPersonId = 1,
PlanetId = 1,
Name = "USA"
},
new
{
OwnedAddressOwnedPersonId = 2,
PlanetId = 1,
Name = "USA"
},
new
{
OwnedAddressOwnedPersonId = 3,
PlanetId = 1,
Name = "USA"
},
new
{
OwnedAddressOwnedPersonId = 4,
PlanetId = 1,
Name = "USA"
});
cb.HasOne(cc => cc.Planet).WithMany().HasForeignKey(ee => ee.PlanetId)
.OnDelete(DeleteBehavior.Restrict);
});
});
eb.OwnsMany(
p => p.Orders, ob =>
{
ob.HasKey(o => o.Id);
ob.IndexerProperty<DateTime>("OrderDate");
ob.HasData(
new
{
Id = -10,
ClientId = 1,
OrderDate = Convert.ToDateTime("2018-07-11 10:01:41")
},
new
{
Id = -11,
ClientId = 1,
OrderDate = Convert.ToDateTime("2015-03-03 04:37:59")
},
new
{
Id = -20,
ClientId = 2,
OrderDate = Convert.ToDateTime("2015-05-25 20:35:48")
},
new
{
Id = -30,
ClientId = 3,
OrderDate = Convert.ToDateTime("2014-11-10 04:32:42")
},
new
{
Id = -40,
ClientId = 4,
OrderDate = Convert.ToDateTime("2016-04-25 19:23:56")
}
);
});
});
modelBuilder.Entity<Branch>(
eb =>
{
eb.HasData(
new
{
Id = 2,
id = Guid.NewGuid().ToString(),
Name = "Antigonus Mitul"
});
eb.OwnsOne(
p => p.BranchAddress, ab =>
{
ab.IndexerProperty<string>("BranchName");
ab.HasData(
new
{
BranchId = 2,
PlaceType = "Land",
BranchName = "BranchA"
},
new
{
BranchId = 3,
PlaceType = "Land",
BranchName = "BranchB"
});
ab.OwnsOne(
a => a.Country, cb =>
{
cb.HasData(
new
{
OwnedAddressBranchId = 2,
PlanetId = 1,
Name = "Canada"
},
new
{
OwnedAddressBranchId = 3,
PlanetId = 1,
Name = "Canada"
});
});
});
});
modelBuilder.Entity<LeafA>(
eb =>
{
eb.HasData(
new
{
Id = 3,
id = Guid.NewGuid().ToString(),
Name = "Madalena Morana"
});
eb.OwnsOne(
p => p.LeafAAddress, ab =>
{
ab.IndexerProperty<int>("LeafType");
ab.HasData(
new
{
LeafAId = 3,
PlaceType = "Land",
LeafType = 1
});
ab.OwnsOne(
a => a.Country, cb =>
{
cb.HasData(
new
{
OwnedAddressLeafAId = 3,
PlanetId = 1,
Name = "Mexico"
});
});
});
});
modelBuilder.Entity<LeafB>(
eb =>
{
eb.HasData(
new
{
Id = 4,
id = Guid.NewGuid().ToString(),
Name = "Vanda Waldemar"
});
eb.OwnsOne(
p => p.LeafBAddress, ab =>
{
ab.IndexerProperty<string>("LeafBType");
ab.HasData(
new
{
LeafBId = 4,
PlaceType = "Land",
LeafBType = "Green"
});
ab.OwnsOne(
a => a.Country, cb =>
{
cb.HasData(
new
{
OwnedAddressLeafBId = 4,
PlanetId = 1,
Name = "Panama"
});
});
});
});
modelBuilder.Entity<Planet>(
pb =>
{
pb.HasData(
new
{
Id = 1,
id = Guid.NewGuid().ToString(),
StarId = 1
});
});
modelBuilder.Entity<Moon>(
mb =>
{
mb.HasData(
new
{
Id = 1,
id = Guid.NewGuid().ToString(),
PlanetId = 1,
Diameter = 3474
});
});
modelBuilder.Entity<Star>(
sb =>
{
sb.HasData(
new
{
Id = 1,
id = Guid.NewGuid().ToString(),
Name = "Sol"
});
sb.OwnsMany(
s => s.Composition, ob =>
{
ob.HasKey(o => o.Id);
ob.HasData(
new
{
Id = "H",
Name = "Hydrogen",
StarId = 1
},
new
{
Id = "He",
Name = "Helium",
StarId = 1
});
});
});
modelBuilder.Entity<Barton>(
b =>
{
b.OwnsOne(
e => e.Throned, b => b.HasData(
new
{
BartonId = 1,
Property = "Property",
Value = 42
}));
b.HasData(
new Barton { Id = 1, Simple = "Simple" },
new Barton { Id = 2, Simple = "Not" });
});
modelBuilder.Entity<Fink>().HasData(
new { Id = 1, BartonId = 1 });
}
}
}
}
| 41.379101 | 170 | 0.468771 | [
"Apache-2.0"
] | 0b01/efcore | test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs | 34,055 | C# |
using System;
namespace CleverNimbus.DinDNS
{
public class AppData
{
public string IPAddress { get; set; }
public string LastResultDescription { get; set; }
public bool LastResultCode { get; set; }
public DateTime LastResultDate { get; set; }
}
} | 21.583333 | 51 | 0.718147 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | jfalvarez80/DinDNS | CleverNimbus.DinDNS/AppData.cs | 261 | C# |
using System;
using System.Net;
using Newtonsoft.Json;
using Xels.Bitcoin.Utilities.Extensions;
using Xels.Bitcoin.Utilities.JsonConverters;
namespace Xels.Bitcoin.P2P
{
/// <summary>
/// A class which holds data on a peer's (IPEndPoint) attempts, connections and successful handshake events.
/// </summary>
[JsonObject]
public sealed class PeerAddress
{
/// <summary>
/// The maximum amount of times a peer can be attempted within a give time frame.
/// </summary>
internal const int AttemptThreshold = 5;
/// <summary>
/// The maximum amount of times handshake can be attempted within a give time frame.
/// </summary>
internal const int AttemptHandshakeThreshold = 3;
/// <summary>
/// The amount of hours we will wait before selecting an attempted peer again,
/// if it hasn't yet reached the <see cref="AttemptThreshold"/> amount of attempts.
/// </summary>
internal const int AttempThresholdHours = 1;
/// <summary>
/// The amount of hours after which the peer's failed connection attempts
/// will be reset to zero.
/// </summary>
internal const int AttemptResetThresholdHours = 12;
/// <summary>Endpoint of this peer.</summary>
[JsonProperty(PropertyName = "endpoint")]
[JsonConverter(typeof(IPEndPointConverter))]
public IPEndPoint Endpoint { get; set; }
/// <summary>Used to construct the <see cref="NetworkAddress"/> after deserializing this peer.</summary>
[JsonProperty(PropertyName = "addressTime", NullValueHandling = NullValueHandling.Ignore)]
private DateTimeOffset? addressTime;
/// <summary>The source address of this peer.</summary>
[JsonProperty(PropertyName = "loopback")]
private string loopback;
[JsonIgnore]
public IPAddress Loopback
{
get
{
if (string.IsNullOrEmpty(this.loopback))
return null;
return IPAddress.Parse(this.loopback);
}
}
/// <summary>
/// The amount of connection attempts.
/// <para>
/// This gets reset when a connection was successful.</para>
/// </summary>
[JsonProperty(PropertyName = "connectionAttempts")]
public int ConnectionAttempts { get; private set; }
/// <summary>
/// The amount of handshake attempts.
/// <para>
/// This gets reset when a handshake was successful.</para>
/// </summary>
[JsonIgnore]
public int HandshakedAttempts { get; private set; }
/// <summary>
/// The last successful version handshake.
/// <para>
/// This is set when the connection attempt was successful and a handshake was done.
/// </para>
/// </summary>
[JsonProperty(PropertyName = "lastConnectionHandshake", NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset? LastConnectionHandshake { get; private set; }
/// <summary>
/// The last handshake attempt.
/// </summary>
[JsonIgnore]
public DateTimeOffset? LastHandshakeAttempt { get; private set; }
/// <summary>
/// The last time this peer was seen.
/// <para>
/// This is set via <see cref="Protocol.Behaviors.PingPongBehavior"/> to ensure that a peer is live.
/// </para>
/// </summary>
[JsonProperty(PropertyName = "lastSeen", NullValueHandling = NullValueHandling.Ignore)]
public DateTime? LastSeen { get; private set; }
/// <summary>
/// UTC DateTime when a peer is banned.
/// </summary>
/// <remarks>
/// This is set in <see cref="PeerBanning"/>.
/// </remarks>
[JsonProperty(PropertyName = "bantimestamp", NullValueHandling = NullValueHandling.Ignore)]
public DateTime? BanTimeStamp { get; set; }
/// <summary>
/// UTC DateTime when the ban expires against the peer.
/// </summary>
/// <remarks>
/// This is set in <see cref="PeerBanning"/>.
/// </remarks>
[JsonProperty(PropertyName = "banuntil", NullValueHandling = NullValueHandling.Ignore)]
public DateTime? BanUntil { get; set; }
/// <summary>
/// Reason for banning the peer.
/// <remarks>
/// This is set in <see cref="PeerBanning"/>.
/// </remarks>
[JsonProperty(PropertyName = "banreason", NullValueHandling = NullValueHandling.Ignore)]
public string BanReason { get; set; }
/// <summary>
/// Maintain a count of bad behaviour.
/// <para>
/// Once a certain score is reached ban the peer.
/// </para>
/// </summary>
/// <remarks>
/// The logic around this has not yet been implemented.
/// This is set in <see cref="PeerBanning"/>.
/// </remarks>
[JsonProperty(PropertyName = "banscore", NullValueHandling = NullValueHandling.Ignore)]
public uint? BanScore { get; set; }
/// <summary>
/// <c>True</c> if the peer has had connection attempts but none successful.
/// </summary>
[JsonIgnore]
public bool Attempted
{
get
{
return
(this.LastAttempt != null) &&
(this.LastConnectionSuccess == null) &&
(this.LastConnectionHandshake == null);
}
}
/// <summary>
/// <c>True</c> if the peer has had a successful connection attempt.
/// </summary>
[JsonIgnore]
public bool Connected
{
get
{
return
(this.LastAttempt == null) &&
(this.LastConnectionSuccess != null) &&
(this.LastConnectionHandshake == null);
}
}
/// <summary>
/// <c>True</c> if the peer has never had connection attempts.
/// </summary>
[JsonIgnore]
public bool Fresh
{
get
{
return
(this.LastAttempt == null) &&
(this.LastConnectionSuccess == null) &&
(this.LastConnectionHandshake == null);
}
}
/// <summary>
/// <c>True</c> if the peer has had a successful connection attempt and handshaked.
/// </summary>
[JsonIgnore]
public bool Handshaked
{
get
{
return
(this.LastAttempt == null) &&
(this.LastConnectionSuccess != null) &&
(this.LastConnectionHandshake != null);
}
}
/// <summary>
/// The last connection attempt.
/// <para>
/// This is set regardless of whether or not the connection attempt was successful or not.
/// </para>
/// </summary>
[JsonProperty(PropertyName = "lastConnectionAttempt", NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset? LastAttempt { get; private set; }
/// <summary>
/// The last successful connection attempt.
/// <para>
/// This is set when the connection attempt was successful (but not necessarily handshaked).
/// </para>
/// </summary>
[JsonProperty(PropertyName = "lastConnectionSuccess", NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset? LastConnectionSuccess { get; private set; }
/// <summary>
/// The last time this peer was discovered from.
/// </summary>
[JsonIgnore]
public DateTime? LastDiscoveredFrom { get; private set; }
/// <summary>
/// Determines whether the peer's attempt thresholds has been reached so that it can be reset.
/// <para>
/// Resetting this allows the <see cref="PeerSelector"/> to re-select the peer for connection.
/// </para>
/// <para>
/// <list>
/// <item>The last attempt was more than the <see cref="AttemptResetThresholdHours"/> time ago.</item>
/// <item>The peer has been attempted more than the maximum amount of attempts (<see cref="AttemptThreshold"/>.</item>
/// </list>
/// </para>
/// </summary>
[JsonIgnore]
public bool CanResetAttempts
{
get
{
return
this.Attempted &&
this.ConnectionAttempts >= PeerAddress.AttemptThreshold &&
this.LastAttempt < DateTime.UtcNow.AddHours(-PeerAddress.AttemptResetThresholdHours);
}
}
/// <summary>
/// Resets the amount of <see cref="ConnectionAttempts"/>.
/// <para>
/// This is reset when the amount of failed connection attempts reaches
/// the <see cref="PeerAddress.AttemptThreshold"/> and the last attempt was
/// made more than <see cref="PeerAddress.AttemptResetThresholdHours"/> ago.
/// </para>
/// </summary>
internal void ResetAttempts()
{
this.ConnectionAttempts = 0;
this.LastAttempt = null;
}
/// <summary>
/// Resets the amount of <see cref="HandshakedAttempts"/>.
/// <para>
/// This is reset when the amount of failed handshake attempts reaches
/// the <see cref="PeerAddress.HandshakedAttempts"/> and the last attempt was
/// made more than <see cref="PeerAddress.AttempThresholdHours"/> ago.
/// </para>
/// </summary>
internal void ResetHandshakeAttempts()
{
this.HandshakedAttempts = 0;
}
/// <summary>
/// Increments <see cref="ConnectionAttempts"/> and sets the <see cref="LastAttempt"/>.
/// </summary>
internal void SetAttempted(DateTime peerAttemptedAt)
{
this.ConnectionAttempts += 1;
this.LastAttempt = peerAttemptedAt;
this.LastConnectionSuccess = null;
this.LastConnectionHandshake = null;
}
/// <summary>
/// Increments <see cref="HandshakedAttempts"/> and sets the <see cref="LastHandshakeAttempt"/>.
/// </summary>
internal void SetHandshakeAttempted(DateTimeOffset handshakeAttemptedAt)
{
this.HandshakedAttempts += 1;
this.LastHandshakeAttempt = handshakeAttemptedAt;
}
/// <summary>
/// Sets the <see cref="LastConnectionSuccess"/>, <see cref="addressTime"/> and <see cref="NetworkAddress.Time"/> properties.
/// <para>
/// Resets <see cref="ConnectionAttempts"/> and <see cref="LastAttempt"/>.
/// </para>
/// </summary>
internal void SetConnected(DateTimeOffset peerConnectedAt)
{
this.addressTime = peerConnectedAt;
this.LastAttempt = null;
this.ConnectionAttempts = 0;
this.LastConnectionSuccess = peerConnectedAt;
}
/// <summary>Sets the <see cref="LastDiscoveredFrom"/> time.</summary>
internal void SetDiscoveredFrom(DateTime lastDiscoveredFrom)
{
this.LastDiscoveredFrom = lastDiscoveredFrom;
}
/// <summary>Sets the <see cref="LastConnectionHandshake"/> date.</summary>
internal void SetHandshaked(DateTimeOffset peerHandshakedAt)
{
this.ResetHandshakeAttempts();
this.LastConnectionHandshake = peerHandshakedAt;
this.LastHandshakeAttempt = null;
}
/// <summary>Sets the <see cref="LastSeen"/> date.</summary>
internal void SetLastSeen(DateTime lastSeenAt)
{
this.LastSeen = lastSeenAt;
}
/// <summary>Determines if the peer is currently banned.</summary>
internal bool IsBanned(DateTime currentTime)
{
if (this.BanUntil == null)
return false;
return this.BanUntil > currentTime;
}
/// <summary>
/// Un-bans a peer by resetting the <see cref="BanReason"/>, <see cref="BanScore"/>, <see cref="BanTimeStamp"/> and <see cref="BanUntil"/> properties.
/// </summary>
public void UnBan()
{
this.BanReason = null;
this.BanScore = null;
this.BanTimeStamp = null;
this.BanUntil = null;
}
/// <summary>
/// Creates a new peer address instance.
/// </summary>
/// <param name="endPoint">The end point of the peer.</param>
public static PeerAddress Create(IPEndPoint endPoint)
{
return new PeerAddress
{
ConnectionAttempts = 0,
Endpoint = endPoint.MapToIpv6(),
loopback = IPAddress.Loopback.ToString()
};
}
/// <summary>
/// Creates a new peer address instance and sets the loopback address (source).
/// </summary>
/// <param name="endPoint">The end point of the peer.</param>
/// <param name="loopback">The loopback (source) of the peer.</param>
public static PeerAddress Create(IPEndPoint endPoint, IPAddress loopback)
{
PeerAddress peer = Create(endPoint);
peer.loopback = loopback.ToString();
return peer;
}
}
} | 36.145503 | 158 | 0.561004 | [
"MIT"
] | xels-io/SideChain-SmartContract | src/Xels.Bitcoin/P2P/PeerAddress.cs | 13,665 | C# |
/**
* Copyright 2015 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $
* Revision: $LastChangedRevision: 2623 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Cr.Prpa_mt101103ca {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Datatype;
using Ca.Infoway.Messagebuilder.Datatype.Impl;
using Ca.Infoway.Messagebuilder.Datatype.Lang;
using Ca.Infoway.Messagebuilder.Model;
using System;
[Hl7PartTypeMappingAttribute(new string[] {"PRPA_MT101103CA.FathersName"})]
public class FathersName : MessagePartBean {
private PN value;
private ST semanticsText;
public FathersName() {
this.value = new PNImpl();
this.semanticsText = new STImpl();
}
/**
* <summary>Business Name: Father's Name</summary>
*
* <remarks>Relationship: PRPA_MT101103CA.FathersName.value
* Conformance/Cardinality: MANDATORY (1) <p>It is included as
* a parameter item in order to further constrain the possible
* number of responses and increase the match probability to a
* single record.</p> <p>This parameter does not map to a
* single RIM attribute, instead, in RIM terms Father's name is
* the person name part of "family" for the person
* who is the player in a PersonalRelationship of type of
* "father" to the focal person.</p> <p>This query
* parameter item is the name of the focal person's father.</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"value"})]
public PersonName Value {
get { return this.value.Value; }
set { this.value.Value = value; }
}
/**
* <summary>Relationship:
* PRPA_MT101103CA.FathersName.semanticsText</summary>
*
* <remarks>Conformance/Cardinality: MANDATORY (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"semanticsText"})]
public String SemanticsText {
get { return this.semanticsText.Value; }
set { this.semanticsText.Value = value; }
}
}
} | 41.040541 | 84 | 0.639118 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-r02_04_03/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_04_03/Cr/Prpa_mt101103ca/FathersName.cs | 3,037 | C# |
using System;
using UnityEditor.IMGUI.Controls;
namespace Unity.ProjectAuditor.Editor.UI.Framework
{
public struct TreeItemIdentifier
{
public string nameWithIndex { get; private set; }
public string name { get; private set; }
// stephenm TODO - Pretty sure this can go. Assemblies don't have indeces. I think the most we'll need is a flag
// to say whether this is the "All" TreeItemIdentifier (i.e. (nameWithIndex == "All"))
public int index { get; private set; }
public static int kAll = -1;
public static int kSingle = 0;
public TreeItemIdentifier(string _name, int _index)
{
name = _name;
index = _index;
if (index == kAll)
nameWithIndex = string.Format("All:{1}", index, name);
else
nameWithIndex = string.Format("{0}:{1}", index, name);
}
public TreeItemIdentifier(TreeItemIdentifier treeItemIdentifier)
{
name = treeItemIdentifier.name;
index = treeItemIdentifier.index;
nameWithIndex = treeItemIdentifier.nameWithIndex;
}
public TreeItemIdentifier(string _nameWithIndex)
{
// stephenm TODO - Pretty sure this can go. Assembly names don't have a foo:N (or N:foo?) naming convention like threads do.
// So index should probably always be treated as 0 (sorry, "kSingle")
nameWithIndex = _nameWithIndex;
var tokens = nameWithIndex.Split(':');
if (tokens.Length >= 2)
{
name = tokens[1];
var indexString = tokens[0];
if (indexString == "All")
{
index = kAll;
}
else
{
int intValue;
if (int.TryParse(tokens[0], out intValue))
index = intValue;
else
index = kSingle;
}
}
else
{
index = kSingle;
name = nameWithIndex;
}
}
void UpdateAssemblyNameWithIndex()
{
if (index == kAll)
nameWithIndex = string.Format("All:{1}", index, name);
else
nameWithIndex = string.Format("{0}:{1}", index, name);
}
public void SetName(string newName)
{
name = newName;
UpdateAssemblyNameWithIndex();
}
public void SetIndex(int newIndex)
{
index = newIndex;
UpdateAssemblyNameWithIndex();
}
public void SetAll()
{
SetIndex(kAll);
}
}
class SelectionWindowTreeViewItem : TreeViewItem
{
public readonly TreeItemIdentifier TreeItemIdentifier;
public SelectionWindowTreeViewItem(int id, int depth, string displayName, TreeItemIdentifier treeItemIdentifier)
: base(id, depth, displayName)
{
TreeItemIdentifier = treeItemIdentifier;
}
}
}
| 30.490385 | 136 | 0.524756 | [
"MIT"
] | AndyG-u3d/ProjectAuditor | Editor/UI/Framework/TreeViews/TreeItemIdentifier.cs | 3,171 | C# |
using System;
namespace FluentTransitions.Methods
{
/// <summary>
/// This transition interpolates values with EasingFunctions.ElasticEaseOut to mimic the behavior of a loaded spring.
/// </summary>
public class Spring : EaseWithFunction
{
/// <summary>
/// Interpolates values with EasingFunctions.ElasticEaseOut to mimic the behavior of a loaded spring.
/// </summary>
/// <param name="duration">The duration until the properties should have reached their destination values</param>
public Spring(TimeSpan duration) : this((int)duration.TotalMilliseconds)
{
}
/// <summary>
/// Interpolates values with EasingFunctions.ElasticEaseOut to mimic the behavior of a loaded spring.
/// </summary>
/// <param name="duration">The duration in milliseconds until the properties should have reached their destination values</param>
public Spring(int duration) : base(EasingFunctions.ElasticEaseOut, duration)
{
}
}
} | 36.307692 | 131 | 0.744703 | [
"MIT"
] | awaescher/FluentTransitions | src/FluentTransitions/Methods/Spring.cs | 946 | C# |
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
using ClangSharp.Interop;
namespace ClangSharp
{
public sealed class ObjCSelectorExpr : Expr
{
internal ObjCSelectorExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_ObjCSelectorExpr, CX_StmtClass.CX_StmtClass_ObjCSelectorExpr)
{
}
}
}
| 32.357143 | 169 | 0.743929 | [
"MIT"
] | Color-Of-Code/ClangSharp | sources/ClangSharp/Cursors/Exprs/ObjCSelectorExpr.cs | 453 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using WinApi.Core;
namespace WinApi.UxTheme
{
public static class UxThemeHelpers
{
public static unsafe HResult SetWindowThemeNonClientAttributes(IntPtr hwnd,
WindowThemeNcAttributeFlags mask,
WindowThemeNcAttributeFlags attributes)
{
var opts = new WindowThemeAttributeOptions
{
Mask = (uint) mask,
Flags = (uint) attributes
};
return UxThemeMethods.SetWindowThemeAttribute(hwnd, WindowThemeAttributeType.WTA_NONCLIENT,
new IntPtr(&opts), (uint) Marshal.SizeOf<WindowThemeAttributeOptions>());
}
}
} | 31.230769 | 103 | 0.666256 | [
"Apache-2.0"
] | jjzhang166/WinApi | WinApi/UxTheme/Helpers.cs | 814 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomSwitch : MonoBehaviour
{
public Transform player;
public Transform a;
public Transform b;
public bool isA = false;
bool playerInRange = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (playerInRange && isA)
{
player.position = b.position;
}
else if (playerInRange)
{
player.position = a.position;
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
playerInRange = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
playerInRange = false;
}
}
}
| 18.625 | 45 | 0.521253 | [
"MIT"
] | brimatt16219/Game-Off-2021 | Game Off 2021 (Bug)/Assets/Scripts/RoomSwitch.cs | 894 | C# |
using System;
using Assertion;
using Lemonad.ErrorHandling.Exceptions;
using Lemonad.ErrorHandling.Extensions;
using Xunit;
namespace Lemonad.ErrorHandling.Unit.ExtensionTests.Maybe {
public class ToMaybeTests {
[Fact]
public void Passing_Null_Value_With_Invalid_Null_Check_Throws() {
Assert.Throws<InvalidMaybeStateException>(() => {
string foo = null;
foo.ToMaybe(_ => true).AssertValue(default);
});
}
[Fact]
public void Passing_Null_Value_With_Null_Check_Predicate_Does_Not_Throw() {
var exception = Record.Exception(() => {
string x = null;
var foo = x.ToMaybe(s => s is null == false);
});
Assert.Null(exception);
}
[Fact]
public void Predicate_Overload__Falsy_Predicate__Expects_None() {
string.Empty.ToMaybe(s => s.Length > 5).AssertNone();
}
[Fact]
public void Predicate_Overload__Passing_Null_Predicate__Throws_ArgumentNullException() {
Assert.Throws<ArgumentNullException>(() => {
Func<string, bool> predicate = null;
"foo".ToMaybe(predicate);
});
}
[Fact]
public void Predicate_Overload__Truthy_Predicate__Expects_Value() {
"Foobar".ToMaybe(s => s.Length > 5).AssertValue("Foobar");
}
}
} | 32.659091 | 96 | 0.593598 | [
"MIT"
] | inputfalken/Lemonad | test/Lemonad.ErrorHandling.Unit/ExtensionTests/Maybe/ToMaybeTests.cs | 1,437 | C# |
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.IO;
using System.Reflection;
namespace LiveDemo
{
[TestFixture]
public class SoftUniLiveDemo
{
[Test]
public void LogoSrc()
{
IWebDriver driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
driver.Url = "https://softuni.bg/";
var logo = driver.FindElement(By.XPath(@"//*[@id=""page-header""]/div[1]/div/div/div[1]/a/img[1]"));
var actualImageSrc = logo.GetAttribute("src");
driver.Quit();
Assert.AreEqual("https://softuni.bg/content/images/svg-logos/software-university-logo.svg", actualImageSrc);
}
[Test]
public void LoginWithValidCreadentials()
{
IWebDriver driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
driver.Manage().Window.Maximize();
driver.Url = "https://softuni.bg/";
var loginButton = driver.FindElement(By.XPath(@"//*[@id=""header-nav""]/div[2]/ul/li[2]/span/a"));
loginButton.Click();
var userNameInput = driver.FindElement(By.Id(@"username"));
userNameInput.SendKeys("kaizer");
var passwordInput = driver.FindElement(By.Id(@"password"));
passwordInput.SendKeys("levski");
var loginBut = driver.FindElement(By.XPath(@"/html/body/main/div[2]/div/div[2]/div[1]/form/div[4]/input"));
loginBut.Click();
driver.Quit();
}
}
}
| 31.096154 | 120 | 0.602968 | [
"MIT"
] | kaizer04/SoftUni---QA-Automation | FirstSeleniumProject/LiveDemo/SoftUniLiveDemo.cs | 1,619 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CodeDisplayer;
using MaterialDesignThemes.Wpf;
namespace MaterialDesignColors.WpfExample
{
/// <summary>
/// Interaction logic for Pickers.xaml
/// </summary>
public partial class Pickers : UserControl
{
public Pickers()
{
InitializeComponent();
FutureDatePicker.BlackoutDates.AddDatesInPast();
LoadLocales();
LocaleCombo.SelectionChanged += LocaleCombo_SelectionChanged;
LocaleCombo.SelectedItem = "fr-CA";
}
private void LocaleCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try {
var lang = System.Windows.Markup.XmlLanguage.GetLanguage((string) LocaleCombo.SelectedItem);
LocaleDatePicker.Language = lang;
LocaleDatePickerRTL.Language = lang;
}
catch {
LocaleCombo.SelectedItem = "fr-CA";
}
//HACK: The calendar only refresh when we change the date
LocaleDatePicker.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(1);
LocaleDatePicker.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(-1);
LocaleDatePickerRTL.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(1);
LocaleDatePickerRTL.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(-1);
}
private void LoadLocales()
{
foreach (var ci in CultureInfo.GetCultures(CultureTypes.AllCultures)
.Where(ci => ci.Calendar is GregorianCalendar)
.OrderBy(ci => ci.Name))
{
LocaleCombo.Items.Add(ci.Name);
}
}
public void CalendarDialogOpenedEventHandler(object sender, DialogOpenedEventArgs eventArgs)
{
Calendar.SelectedDate = ((PickersViewModel)DataContext).Date;
}
public void CalendarDialogClosingEventHandler(object sender, DialogClosingEventArgs eventArgs)
{
if (!Equals(eventArgs.Parameter, "1")) return;
if (!Calendar.SelectedDate.HasValue)
{
eventArgs.Cancel();
return;
}
((PickersViewModel)DataContext).Date = Calendar.SelectedDate.Value;
}
public void ClockDialogOpenedEventHandler(object sender, DialogOpenedEventArgs eventArgs)
{
Clock.Time = ((PickersViewModel) DataContext).Time;
}
public void ClockDialogClosingEventHandler(object sender, DialogClosingEventArgs eventArgs)
{
if (Equals(eventArgs.Parameter, "1"))
((PickersViewModel)DataContext).Time = Clock.Time;
}
}
}
| 33.752688 | 108 | 0.640013 | [
"MIT"
] | UTINKA/MaterialDesignInXamlToolkit | MainDemo.Wpf/Pickers.xaml.cs | 3,141 | C# |
using System;
using System.Collections.Generic;
using Unleash;
using Unleash.Strategies;
namespace Dka.AspNetCore.BasicWebApp.Services.Unleash
{
public class TenantGuidStrategy : IStrategy
{
private const string ParameterName = "tenantGuids";
public string Name => UnleashConstants.TenantGuidStrategyName;
public bool IsEnabled(Dictionary<string, string> parameters, UnleashContext context)
{
if (parameters == null || !parameters.ContainsKey(ParameterName) ||
context?.Properties == null || !context.Properties.ContainsKey(UnleashConstants.TenantGuidStrategyName))
{
return false;
}
if (parameters[ParameterName] == null &&
context.Properties[UnleashConstants.TenantGuidStrategyName] == null)
{
return true;
}
if (parameters[ParameterName] == null ||
context.Properties[UnleashConstants.TenantGuidStrategyName] == null)
{
return false;
}
return parameters[ParameterName].Contains(context.Properties[UnleashConstants.TenantGuidStrategyName],
StringComparison.OrdinalIgnoreCase);
}
}
} | 33.973684 | 120 | 0.618125 | [
"Apache-2.0"
] | lwinch2006/basic-asp.net-core-app | Dka.AspNetCore.BasicWebApp/src/Services/Unleash/TenantGuidStrategy.cs | 1,291 | C# |
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Views;
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Xml.Serialization;
using Bumptech.Glide;
namespace GlideSample
{
[Activity(Label = "GlideSample", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : ListActivity
{
CatAdapter adapter;
protected async override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
adapter = new CatAdapter { Parent = this };
ListAdapter = adapter;
await adapter.ReloadAsync();
}
}
public class CatAdapter : BaseAdapter<Image>
{
public Activity Parent { get; set; }
const string CATS_URL = "http://thecatapi.com/api/images/get?format=xml&size=small&results_per_page=100";
static readonly HttpClient http = new HttpClient();
Response lastResponse;
public async Task ReloadAsync ()
{
var serializer = new XmlSerializer(typeof(Response));
using (var rs = await http.GetStreamAsync(CATS_URL))
lastResponse = (Response)serializer.Deserialize(rs);
NotifyDataSetChanged();
}
public override Image this[int position] => lastResponse?.Data?.Images?.Image?[position];
public override int Count => lastResponse?.Data?.Images?.Image?.Count ?? 0;
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = lastResponse?.Data?.Images?.Image?[position];
if (item == null)
return convertView;
var view = convertView ?? LayoutInflater.FromContext(Parent).Inflate(Resource.Layout.ListItem, parent, false);
var imageView = view.FindViewById<ImageView>(Resource.Id.imageView);
Glide.With(Parent).Load(item.Url).Into(imageView);
return view;
}
}
}
| 24.118421 | 113 | 0.727769 | [
"MIT"
] | 4brunu/XamarinComponents | Android/Glide/samples/GlideSample/MainActivity.cs | 1,835 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Fibre
{
// Component that manages advancing through an event chain.
public class FibreManager : MonoBehaviour
{
public List<BaseEvent> FirstEvents = new List<BaseEvent>();
public KeyCode InstantCompleteKey = KeyCode.None;
public uint MaxEventsPerFrame = 100;
private readonly List<RunningEvent> _heads = new List<RunningEvent>();
private List<RunningEvent> _runningEvents = new List<RunningEvent>();
private void Start()
{
_runningEvents.Clear();
// Start the first events.
enabled = StartStartingEvents();
}
private void Update()
{
// If needed, instantly complete running events, then progress events.
// Disable the manager if errors occur.
enabled = InstantComplete() && ProgressEvents();
CleanRunningEvents();
}
// Start running all the starting events.
// Returns false on error.
private bool StartStartingEvents()
{
foreach (BaseEvent e in FirstEvents)
{
if (!StartEvent(new RunningEvent(e)))
{
return false;
}
}
return true;
}
// Start an event.
// Returns false on error.
private bool StartEvent(RunningEvent e)
{
bool success = e.TryStartEvent();
if (success)
{
_heads.Add(e);
_runningEvents.Add(e);
}
return success;
}
// Replace a head with it's next event.
// Returns false on error.
private bool ReplaceHead(RunningEvent curr, out RunningEvent newHead)
{
// Get the next event.
if (curr.TryGetNextEvent(out RunningEvent next))
{
// Remove the current head.
_heads.Remove(curr);
// Start the next event.
newHead = next;
return StartEvent(next);
}
newHead = null;
return false;
}
// Instantly complete running events if the key is pressed.
// Returns false on error.
private bool InstantComplete()
{
if (!Input.GetKeyDown(InstantCompleteKey))
{
return true;
}
// Loop through running events and instantly complete them.
// If any errors occur or an event fails to instantly
// complete then the loop exits early.
foreach (RunningEvent e in _runningEvents)
{
if (!e.TryInstantComplete())
{
return false;
}
}
return true;
}
// Progress all heads through the event chain.
// Returns false on error.
private bool ProgressEvents()
{
// Convert to array because the list may be modified during the loop.
foreach (RunningEvent head in _heads.ToArray())
{
if (!ProgressHead(head))
{
return false;
}
}
return true;
}
// Progress a head through the event chain until an event blocks.
// Returns false on error.
private bool ProgressHead(RunningEvent head)
{
bool success = true;
for (uint i = 0; i < MaxEventsPerFrame; ++i)
{
// Check if the current event is still in progress.
if (!head.TryShouldContinue(out bool shouldContinue))
{
success = false;
break;
}
// Go to the next event.
if (shouldContinue)
{
if (!ReplaceHead(head, out head))
{
success = false;
break;
}
}
else
{
break;
}
}
return success;
}
// Remove completed events from the running list.
// Events that throw an error are also removed.
private void CleanRunningEvents()
{
var newList = new List<RunningEvent>();
foreach (RunningEvent e in _runningEvents)
{
if (e.TryIsInProgress(out bool inProg) && inProg)
{
newList.Add(e);
}
else
{
e.TryEndEvent();
}
}
_runningEvents = newList;
}
}
}
| 29.847561 | 82 | 0.474566 | [
"MIT"
] | FinnPerry/UnityEventChain | FibreManager.cs | 4,895 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Windows.Forms;
namespace ICSharpCode.Scripting.Tests.Utils
{
public class NullPropertyUserControl : UserControl
{
string fooBar;
public string FooBar {
get { return fooBar; }
set { fooBar = value; }
}
public NullPropertyUserControl()
{
}
}
}
| 37.763158 | 93 | 0.754704 | [
"MIT"
] | TetradogOther/SharpDevelop | src/AddIns/BackendBindings/Scripting/Test/Utils/NullPropertyUserControl.cs | 1,437 | C# |
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Cethleann.Graphics;
using Cethleann.KTID;
using Cethleann.Structure;
using Cethleann.Structure.KTID;
using Cethleann.Structure.Resource;
using Cethleann.Structure.Resource.Texture;
using DragonLib;
using DragonLib.CLI;
using DragonLib.IO;
namespace Nyotengu.KTID
{
public static class Program
{
private static void Main(string[] args)
{
Logger.PrintVersion("Nyotengu");
var flags = CommandLineFlags.ParseFlags<KTIDFlags>(CommandLineFlags.PrintHelp, args);
if (flags == null) return;
var ndb = new NDB();
if (!string.IsNullOrEmpty(flags.NDBPath) && File.Exists(flags.NDBPath)) ndb = new NDB(File.ReadAllBytes(flags.NDBPath));
var objdb = new OBJDB(File.ReadAllBytes(flags.OBJDBPath));
var filelist = Cethleann.ManagedFS.Nyotengu.LoadKTIDFileList(flags.FileList, flags.GameId);
var textureSection = new ResourceSectionHeader
{
Magic = DataType.TextureGroup,
Version = 0x30303630
};
var textureHeader = new TextureGroupHeader
{
System = objdb.Header.System
};
foreach (var ktid in flags.Paths)
{
if (!File.Exists(ktid)) continue;
var ktidgroup = new KTIDTextureSet(File.ReadAllBytes(ktid));
var ktidsystem = ktidgroup.Textures.Select(x => objdb.Entries.TryGetValue(x, out var tuple) ? tuple : default).ToArray();
var texturePaths = ktidsystem.SelectMany(x =>
{
var property = x?.GetProperty("KTGLTexContextResourceHash");
return property?.values?.Select(y =>
{
if (!(y is uint hash)) return null;
var reference = (KTIDReference) hash;
var targetPath = Path.Combine(flags.MaterialFolderPath, reference.GetName(ndb, filelist) ?? $"{reference:x8}");
if (!targetPath.EndsWith(".g1t")) targetPath += ".g1t";
if (!File.Exists(targetPath)) targetPath = Path.Combine(flags.MaterialFolderPath, $"{reference:x8}.g1t");
if (!File.Exists(targetPath)) targetPath = Path.Combine(flags.MaterialFolderPath, $"0x{reference:x8}.g1t");
return targetPath;
}) ?? Array.Empty<string?>();
});
var textureBlobs = new List<Memory<byte>>();
var textureInfo = new List<int>();
foreach (var texturePath in texturePaths)
{
if (string.IsNullOrEmpty(texturePath) || !File.Exists(texturePath))
{
Logger.Error("Nyotengu", $"KTID file {ktid} defines a texture that doesn't exist! {texturePath}");
continue;
}
Logger.Info("Nyotengu", $"Loading {texturePath}...");
var texture = new G1TextureGroup(File.ReadAllBytes(texturePath));
textureBlobs.AddRange(texture.Textures.Select(x => x.blob));
textureInfo.AddRange(texture.Textures.Select(x => (int) x.usage));
}
textureHeader.Count = textureBlobs.Count;
var blockSize = SizeHelper.SizeOf<int>() * textureHeader.Count;
textureHeader.TableOffset = SizeHelper.SizeOf<ResourceSectionHeader>() + SizeHelper.SizeOf<TextureGroupHeader>() + blockSize;
var combinedTexture = new Span<byte>(new byte[textureHeader.TableOffset + blockSize + textureBlobs.Sum(x => x.Length)]);
textureSection.Size = combinedTexture.Length;
MemoryMarshal.Write(combinedTexture, ref textureSection);
var offset = SizeHelper.SizeOf<ResourceSectionHeader>();
MemoryMarshal.Write(combinedTexture.Slice(offset), ref textureHeader);
offset += SizeHelper.SizeOf<TextureGroupHeader>();
MemoryMarshal.Cast<int, byte>(textureInfo.ToArray()).CopyTo(combinedTexture.Slice(offset));
offset = textureHeader.TableOffset;
var baseOffset = blockSize;
for (var i = 0; i < textureBlobs.Count; ++i)
{
BinaryPrimitives.WriteInt32LittleEndian(combinedTexture.Slice(offset + i * 4), baseOffset);
textureBlobs[i].Span.CopyTo(combinedTexture.Slice(offset + baseOffset));
baseOffset += textureBlobs[i].Length;
}
var destination = Path.ChangeExtension(ktid, ".g1t");
Logger.Info("Nyotengu", $"Saving {destination}");
File.WriteAllBytes(destination, combinedTexture.ToArray());
}
}
}
}
| 47.566038 | 141 | 0.58092 | [
"MIT"
] | TGEnigma/Cethleann | Nyotengu.KTID/Program.cs | 5,044 | C# |
using System.Collections.Generic;
using TUNING;
using System;
/*
* Tools to add a new building
*
* AddBuildingToPlanScreen
* adds the building to the build menu
* Arguments:
* category: the category to add the building to
* buildingId: the PrefabID of the building, usually just called Id or ID in the config class
* (optional) parentId: the buildingID will be added after parentId
* (optional) index: the index in the menu to add the building
* Note: max one optional argument is possible and missing or invalid optional arguments will place the building last in the list
*
* IntoTechTree
* Adds a tech requirement to the building
* Arguments:
* Tech: The name of the tech the building requires
* BuildingID: the PrefabID of the building, usually just called Id or ID in the config class
* Note: not calling this class will make the building available from the start
*
* AddStrings
* Adds Name, Description and Effect strings
* Usage is self explainatory. Allows easy and clean access to correctly formatting strings
*/
namespace NightLib.AddBuilding
{
internal static class AddBuilding
{
internal static void AddBuildingToPlanScreen(HashedString category, string buildingId, string parentId)
{
int index = GetCategoryIndex(category, buildingId);
if (index == -1)
return;
int? indexBuilding = null;
if (!parentId.IsNullOrWhiteSpace())
{
indexBuilding = (BUILDINGS.PLANORDER[index].data as IList<string>)?.IndexOf(parentId);
if (indexBuilding != null)
{
++indexBuilding;
}
}
if (indexBuilding == null)
{
Console.WriteLine("ERROR: building \"" + parentId + "\" not found in category " + category + ". Placing " + buildingId + " at the end of the list");
}
AddBuildingToPlanScreen(category, buildingId, indexBuilding);
}
internal static void AddBuildingToPlanScreen(HashedString category, string buildingId, int? index = null)
{
int CategoryIndex = GetCategoryIndex(category, buildingId);
if (CategoryIndex == -1)
return;
if (index != null)
{
if (index >= 0 && index < (BUILDINGS.PLANORDER[CategoryIndex].data as IList<string>)?.Count)
{
(BUILDINGS.PLANORDER[CategoryIndex].data as IList<string>)?.Insert(index.Value, buildingId);
return;
}
}
(BUILDINGS.PLANORDER[CategoryIndex].data as IList<string>)?.Add(buildingId);
}
internal static void ReplaceBuildingInPlanScreen(HashedString category, string buildingId, string parentId)
{
int index = GetCategoryIndex(category, buildingId);
if (index == -1)
return;
int? indexBuilding = null;
indexBuilding = (BUILDINGS.PLANORDER[index].data as IList<string>)?.IndexOf(parentId);
if (indexBuilding != null)
{
(BUILDINGS.PLANORDER[index].data as IList<string>)?.Remove(parentId);
(BUILDINGS.PLANORDER[index].data as IList<string>)?.Insert(indexBuilding.Value, buildingId);
return;
}
if (indexBuilding == null)
{
Console.WriteLine("ERROR: building \"" + parentId + "\" not found in category " + category + ". Placing " + buildingId + " at the end of the list");
}
AddBuildingToPlanScreen(category, buildingId, indexBuilding);
}
private static int GetCategoryIndex(HashedString category, string buildingId)
{
int index = BUILDINGS.PLANORDER.FindIndex(x => x.category == category);
if (index == -1)
{
Console.WriteLine("ERROR: can't add building " + buildingId + " to non-existing category " + category);
}
return index;
}
// --------------------------------------
internal static void IntoTechTree(string Tech, string BuildingID)
{
#if DLC1
int a = Db.Get().Techs.Count;
if (Db.Get().Techs.Get(Tech) != null)
{
Db.Get().Techs.Get(Tech).unlockedItemIDs.Add(BuildingID);
}
#else
var TechGroup = new List<string>(Database.Techs.TECH_GROUPING[Tech]) { };
TechGroup.Insert(1, BuildingID);
Database.Techs.TECH_GROUPING[Tech] = TechGroup.ToArray();
#endif
// TODO figure out how to control the order within a group
}
internal static void ReplaceInTechTree(string Tech, string BuildingID, string old)
{
#if DLC1
if (Db.Get().Techs.TryGet(Tech) != null)
{
int iIndex = Db.Get().Techs.Get(Tech).unlockedItemIDs.FindIndex( x => x == old);
if (iIndex >= 0)
{
Db.Get().Techs.Get(Tech).unlockedItemIDs[iIndex] = BuildingID;
}
}
#else
var TechGroup = new List<string>(Database.Techs.TECH_GROUPING[Tech]) { };
int index = TechGroup.FindIndex(x => x == old);
if (index != -1)
{
TechGroup[index] = BuildingID;
Database.Techs.TECH_GROUPING[Tech] = TechGroup.ToArray();
}
else
{
IntoTechTree(Tech, BuildingID);
}
#endif
}
private static int GetTechCategoryIndex(HashedString category, string buildingId)
{
int index = BUILDINGS.PLANORDER.FindIndex(x => x.category == category);
if (index == -1)
{
Console.WriteLine("ERROR: can't add building " + buildingId + " to non-existing category " + category);
}
return index;
}
internal static void AddStrings(string ID, string Name, string Description, string Effect)
{
// UI.FormatAsLink(Name, ID); would be the clean implementation of a link, but it has a nameclash with TURING
Strings.Add($"STRINGS.BUILDINGS.PREFABS.{ID.ToUpperInvariant()}.NAME", "<link=\"" + ID + "\">" + Name + "</link>");
Strings.Add($"STRINGS.BUILDINGS.PREFABS.{ID.ToUpperInvariant()}.DESC", Description);
Strings.Add($"STRINGS.BUILDINGS.PREFABS.{ID.ToUpperInvariant()}.EFFECT", Effect);
}
}
}
| 36.651934 | 164 | 0.572656 | [
"MIT"
] | bohemond-of-antioch/sky-oni-mods | PipedOutput/Source/NightLib/AddBuilding.cs | 6,634 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Container for the parameters to the CreateCluster operation.
/// Creates a new cluster with the specified parameters.
///
///
/// <para>
/// To create a cluster in Virtual Private Cloud (VPC), you must provide a cluster subnet
/// group name. The cluster subnet group identifies the subnets of your VPC that Amazon
/// Redshift uses when creating the cluster. For more information about managing clusters,
/// go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html">Amazon
/// Redshift Clusters</a> in the <i>Amazon Redshift Cluster Management Guide</i>.
/// </para>
/// </summary>
public partial class CreateClusterRequest : AmazonRedshiftRequest
{
private string _additionalInfo;
private bool? _allowVersionUpgrade;
private int? _automatedSnapshotRetentionPeriod;
private string _availabilityZone;
private string _clusterIdentifier;
private string _clusterParameterGroupName;
private List<string> _clusterSecurityGroups = new List<string>();
private string _clusterSubnetGroupName;
private string _clusterType;
private string _clusterVersion;
private string _dbName;
private string _elasticIp;
private bool? _encrypted;
private bool? _enhancedVpcRouting;
private string _hsmClientCertificateIdentifier;
private string _hsmConfigurationIdentifier;
private List<string> _iamRoles = new List<string>();
private string _kmsKeyId;
private string _maintenanceTrackName;
private int? _manualSnapshotRetentionPeriod;
private string _masterUsername;
private string _masterUserPassword;
private string _nodeType;
private int? _numberOfNodes;
private int? _port;
private string _preferredMaintenanceWindow;
private bool? _publiclyAccessible;
private string _snapshotScheduleIdentifier;
private List<Tag> _tags = new List<Tag>();
private List<string> _vpcSecurityGroupIds = new List<string>();
/// <summary>
/// Gets and sets the property AdditionalInfo.
/// <para>
/// Reserved.
/// </para>
/// </summary>
public string AdditionalInfo
{
get { return this._additionalInfo; }
set { this._additionalInfo = value; }
}
// Check to see if AdditionalInfo property is set
internal bool IsSetAdditionalInfo()
{
return this._additionalInfo != null;
}
/// <summary>
/// Gets and sets the property AllowVersionUpgrade.
/// <para>
/// If <code>true</code>, major version upgrades can be applied during the maintenance
/// window to the Amazon Redshift engine that is running on the cluster.
/// </para>
///
/// <para>
/// When a new major version of the Amazon Redshift engine is released, you can request
/// that the service automatically apply upgrades during the maintenance window to the
/// Amazon Redshift engine that is running on your cluster.
/// </para>
///
/// <para>
/// Default: <code>true</code>
/// </para>
/// </summary>
public bool AllowVersionUpgrade
{
get { return this._allowVersionUpgrade.GetValueOrDefault(); }
set { this._allowVersionUpgrade = value; }
}
// Check to see if AllowVersionUpgrade property is set
internal bool IsSetAllowVersionUpgrade()
{
return this._allowVersionUpgrade.HasValue;
}
/// <summary>
/// Gets and sets the property AutomatedSnapshotRetentionPeriod.
/// <para>
/// The number of days that automated snapshots are retained. If the value is 0, automated
/// snapshots are disabled. Even if automated snapshots are disabled, you can still create
/// manual snapshots when you want with <a>CreateClusterSnapshot</a>.
/// </para>
///
/// <para>
/// Default: <code>1</code>
/// </para>
///
/// <para>
/// Constraints: Must be a value from 0 to 35.
/// </para>
/// </summary>
public int AutomatedSnapshotRetentionPeriod
{
get { return this._automatedSnapshotRetentionPeriod.GetValueOrDefault(); }
set { this._automatedSnapshotRetentionPeriod = value; }
}
// Check to see if AutomatedSnapshotRetentionPeriod property is set
internal bool IsSetAutomatedSnapshotRetentionPeriod()
{
return this._automatedSnapshotRetentionPeriod.HasValue;
}
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The EC2 Availability Zone (AZ) in which you want Amazon Redshift to provision the
/// cluster. For example, if you have several EC2 instances running in a specific Availability
/// Zone, then you might want the cluster to be provisioned in the same zone in order
/// to decrease network latency.
/// </para>
///
/// <para>
/// Default: A random, system-chosen Availability Zone in the region that is specified
/// by the endpoint.
/// </para>
///
/// <para>
/// Example: <code>us-east-2d</code>
/// </para>
///
/// <para>
/// Constraint: The specified Availability Zone must be in the same region as the current
/// endpoint.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property ClusterIdentifier.
/// <para>
/// A unique identifier for the cluster. You use this identifier to refer to the cluster
/// for any subsequent cluster operations such as deleting or modifying. The identifier
/// also appears in the Amazon Redshift console.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must contain from 1 to 63 alphanumeric characters or hyphens.
/// </para>
/// </li> <li>
/// <para>
/// Alphabetic characters must be lowercase.
/// </para>
/// </li> <li>
/// <para>
/// First character must be a letter.
/// </para>
/// </li> <li>
/// <para>
/// Cannot end with a hyphen or contain two consecutive hyphens.
/// </para>
/// </li> <li>
/// <para>
/// Must be unique for all clusters within an AWS account.
/// </para>
/// </li> </ul>
/// <para>
/// Example: <code>myexamplecluster</code>
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ClusterIdentifier
{
get { return this._clusterIdentifier; }
set { this._clusterIdentifier = value; }
}
// Check to see if ClusterIdentifier property is set
internal bool IsSetClusterIdentifier()
{
return this._clusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property ClusterParameterGroupName.
/// <para>
/// The name of the parameter group to be associated with this cluster.
/// </para>
///
/// <para>
/// Default: The default Amazon Redshift cluster parameter group. For information about
/// the default parameter group, go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html">Working
/// with Amazon Redshift Parameter Groups</a>
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must be 1 to 255 alphanumeric characters or hyphens.
/// </para>
/// </li> <li>
/// <para>
/// First character must be a letter.
/// </para>
/// </li> <li>
/// <para>
/// Cannot end with a hyphen or contain two consecutive hyphens.
/// </para>
/// </li> </ul>
/// </summary>
public string ClusterParameterGroupName
{
get { return this._clusterParameterGroupName; }
set { this._clusterParameterGroupName = value; }
}
// Check to see if ClusterParameterGroupName property is set
internal bool IsSetClusterParameterGroupName()
{
return this._clusterParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property ClusterSecurityGroups.
/// <para>
/// A list of security groups to be associated with this cluster.
/// </para>
///
/// <para>
/// Default: The default cluster security group for Amazon Redshift.
/// </para>
/// </summary>
public List<string> ClusterSecurityGroups
{
get { return this._clusterSecurityGroups; }
set { this._clusterSecurityGroups = value; }
}
// Check to see if ClusterSecurityGroups property is set
internal bool IsSetClusterSecurityGroups()
{
return this._clusterSecurityGroups != null && this._clusterSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property ClusterSubnetGroupName.
/// <para>
/// The name of a cluster subnet group to be associated with this cluster.
/// </para>
///
/// <para>
/// If this parameter is not provided the resulting cluster will be deployed outside virtual
/// private cloud (VPC).
/// </para>
/// </summary>
public string ClusterSubnetGroupName
{
get { return this._clusterSubnetGroupName; }
set { this._clusterSubnetGroupName = value; }
}
// Check to see if ClusterSubnetGroupName property is set
internal bool IsSetClusterSubnetGroupName()
{
return this._clusterSubnetGroupName != null;
}
/// <summary>
/// Gets and sets the property ClusterType.
/// <para>
/// The type of the cluster. When cluster type is specified as
/// </para>
/// <ul> <li>
/// <para>
/// <code>single-node</code>, the <b>NumberOfNodes</b> parameter is not required.
/// </para>
/// </li> <li>
/// <para>
/// <code>multi-node</code>, the <b>NumberOfNodes</b> parameter is required.
/// </para>
/// </li> </ul>
/// <para>
/// Valid Values: <code>multi-node</code> | <code>single-node</code>
/// </para>
///
/// <para>
/// Default: <code>multi-node</code>
/// </para>
/// </summary>
public string ClusterType
{
get { return this._clusterType; }
set { this._clusterType = value; }
}
// Check to see if ClusterType property is set
internal bool IsSetClusterType()
{
return this._clusterType != null;
}
/// <summary>
/// Gets and sets the property ClusterVersion.
/// <para>
/// The version of the Amazon Redshift engine software that you want to deploy on the
/// cluster.
/// </para>
///
/// <para>
/// The version selected runs on all the nodes in the cluster.
/// </para>
///
/// <para>
/// Constraints: Only version 1.0 is currently available.
/// </para>
///
/// <para>
/// Example: <code>1.0</code>
/// </para>
/// </summary>
public string ClusterVersion
{
get { return this._clusterVersion; }
set { this._clusterVersion = value; }
}
// Check to see if ClusterVersion property is set
internal bool IsSetClusterVersion()
{
return this._clusterVersion != null;
}
/// <summary>
/// Gets and sets the property DBName.
/// <para>
/// The name of the first database to be created when the cluster is created.
/// </para>
///
/// <para>
/// To create additional databases after the cluster is created, connect to the cluster
/// with a SQL client and use SQL commands to create a database. For more information,
/// go to <a href="https://docs.aws.amazon.com/redshift/latest/dg/t_creating_database.html">Create
/// a Database</a> in the Amazon Redshift Database Developer Guide.
/// </para>
///
/// <para>
/// Default: <code>dev</code>
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must contain 1 to 64 alphanumeric characters.
/// </para>
/// </li> <li>
/// <para>
/// Must contain only lowercase letters.
/// </para>
/// </li> <li>
/// <para>
/// Cannot be a word that is reserved by the service. A list of reserved words can be
/// found in <a href="https://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved
/// Words</a> in the Amazon Redshift Database Developer Guide.
/// </para>
/// </li> </ul>
/// </summary>
public string DBName
{
get { return this._dbName; }
set { this._dbName = value; }
}
// Check to see if DBName property is set
internal bool IsSetDBName()
{
return this._dbName != null;
}
/// <summary>
/// Gets and sets the property ElasticIp.
/// <para>
/// The Elastic IP (EIP) address for the cluster.
/// </para>
///
/// <para>
/// Constraints: The cluster must be provisioned in EC2-VPC and publicly-accessible through
/// an Internet gateway. For more information about provisioning clusters in EC2-VPC,
/// go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#cluster-platforms">Supported
/// Platforms to Launch Your Cluster</a> in the Amazon Redshift Cluster Management Guide.
/// </para>
/// </summary>
public string ElasticIp
{
get { return this._elasticIp; }
set { this._elasticIp = value; }
}
// Check to see if ElasticIp property is set
internal bool IsSetElasticIp()
{
return this._elasticIp != null;
}
/// <summary>
/// Gets and sets the property Encrypted.
/// <para>
/// If <code>true</code>, the data in the cluster is encrypted at rest.
/// </para>
///
/// <para>
/// Default: false
/// </para>
/// </summary>
public bool Encrypted
{
get { return this._encrypted.GetValueOrDefault(); }
set { this._encrypted = value; }
}
// Check to see if Encrypted property is set
internal bool IsSetEncrypted()
{
return this._encrypted.HasValue;
}
/// <summary>
/// Gets and sets the property EnhancedVpcRouting.
/// <para>
/// An option that specifies whether to create the cluster with enhanced VPC routing enabled.
/// To create a cluster that uses enhanced VPC routing, the cluster must be in a VPC.
/// For more information, see <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/enhanced-vpc-routing.html">Enhanced
/// VPC Routing</a> in the Amazon Redshift Cluster Management Guide.
/// </para>
///
/// <para>
/// If this option is <code>true</code>, enhanced VPC routing is enabled.
/// </para>
///
/// <para>
/// Default: false
/// </para>
/// </summary>
public bool EnhancedVpcRouting
{
get { return this._enhancedVpcRouting.GetValueOrDefault(); }
set { this._enhancedVpcRouting = value; }
}
// Check to see if EnhancedVpcRouting property is set
internal bool IsSetEnhancedVpcRouting()
{
return this._enhancedVpcRouting.HasValue;
}
/// <summary>
/// Gets and sets the property HsmClientCertificateIdentifier.
/// <para>
/// Specifies the name of the HSM client certificate the Amazon Redshift cluster uses
/// to retrieve the data encryption keys stored in an HSM.
/// </para>
/// </summary>
public string HsmClientCertificateIdentifier
{
get { return this._hsmClientCertificateIdentifier; }
set { this._hsmClientCertificateIdentifier = value; }
}
// Check to see if HsmClientCertificateIdentifier property is set
internal bool IsSetHsmClientCertificateIdentifier()
{
return this._hsmClientCertificateIdentifier != null;
}
/// <summary>
/// Gets and sets the property HsmConfigurationIdentifier.
/// <para>
/// Specifies the name of the HSM configuration that contains the information the Amazon
/// Redshift cluster can use to retrieve and store keys in an HSM.
/// </para>
/// </summary>
public string HsmConfigurationIdentifier
{
get { return this._hsmConfigurationIdentifier; }
set { this._hsmConfigurationIdentifier = value; }
}
// Check to see if HsmConfigurationIdentifier property is set
internal bool IsSetHsmConfigurationIdentifier()
{
return this._hsmConfigurationIdentifier != null;
}
/// <summary>
/// Gets and sets the property IamRoles.
/// <para>
/// A list of AWS Identity and Access Management (IAM) roles that can be used by the cluster
/// to access other AWS services. You must supply the IAM roles in their Amazon Resource
/// Name (ARN) format. You can supply up to 10 IAM roles in a single request.
/// </para>
///
/// <para>
/// A cluster can have up to 10 IAM roles associated with it at any time.
/// </para>
/// </summary>
public List<string> IamRoles
{
get { return this._iamRoles; }
set { this._iamRoles = value; }
}
// Check to see if IamRoles property is set
internal bool IsSetIamRoles()
{
return this._iamRoles != null && this._iamRoles.Count > 0;
}
/// <summary>
/// Gets and sets the property KmsKeyId.
/// <para>
/// The AWS Key Management Service (KMS) key ID of the encryption key that you want to
/// use to encrypt data in the cluster.
/// </para>
/// </summary>
public string KmsKeyId
{
get { return this._kmsKeyId; }
set { this._kmsKeyId = value; }
}
// Check to see if KmsKeyId property is set
internal bool IsSetKmsKeyId()
{
return this._kmsKeyId != null;
}
/// <summary>
/// Gets and sets the property MaintenanceTrackName.
/// <para>
/// An optional parameter for the name of the maintenance track for the cluster. If you
/// don't provide a maintenance track name, the cluster is assigned to the <code>current</code>
/// track.
/// </para>
/// </summary>
public string MaintenanceTrackName
{
get { return this._maintenanceTrackName; }
set { this._maintenanceTrackName = value; }
}
// Check to see if MaintenanceTrackName property is set
internal bool IsSetMaintenanceTrackName()
{
return this._maintenanceTrackName != null;
}
/// <summary>
/// Gets and sets the property ManualSnapshotRetentionPeriod.
/// <para>
/// The default number of days to retain a manual snapshot. If the value is -1, the snapshot
/// is retained indefinitely. This setting doesn't change the retention period of existing
/// snapshots.
/// </para>
///
/// <para>
/// The value must be either -1 or an integer between 1 and 3,653.
/// </para>
/// </summary>
public int ManualSnapshotRetentionPeriod
{
get { return this._manualSnapshotRetentionPeriod.GetValueOrDefault(); }
set { this._manualSnapshotRetentionPeriod = value; }
}
// Check to see if ManualSnapshotRetentionPeriod property is set
internal bool IsSetManualSnapshotRetentionPeriod()
{
return this._manualSnapshotRetentionPeriod.HasValue;
}
/// <summary>
/// Gets and sets the property MasterUsername.
/// <para>
/// The user name associated with the master user account for the cluster that is being
/// created.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must be 1 - 128 alphanumeric characters. The user name can't be <code>PUBLIC</code>.
/// </para>
/// </li> <li>
/// <para>
/// First character must be a letter.
/// </para>
/// </li> <li>
/// <para>
/// Cannot be a reserved word. A list of reserved words can be found in <a href="https://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html">Reserved
/// Words</a> in the Amazon Redshift Database Developer Guide.
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Required=true)]
public string MasterUsername
{
get { return this._masterUsername; }
set { this._masterUsername = value; }
}
// Check to see if MasterUsername property is set
internal bool IsSetMasterUsername()
{
return this._masterUsername != null;
}
/// <summary>
/// Gets and sets the property MasterUserPassword.
/// <para>
/// The password associated with the master user account for the cluster that is being
/// created.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must be between 8 and 64 characters in length.
/// </para>
/// </li> <li>
/// <para>
/// Must contain at least one uppercase letter.
/// </para>
/// </li> <li>
/// <para>
/// Must contain at least one lowercase letter.
/// </para>
/// </li> <li>
/// <para>
/// Must contain one number.
/// </para>
/// </li> <li>
/// <para>
/// Can be any printable ASCII character (ASCII code 33 to 126) except ' (single quote),
/// " (double quote), \, /, @, or space.
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Required=true)]
public string MasterUserPassword
{
get { return this._masterUserPassword; }
set { this._masterUserPassword = value; }
}
// Check to see if MasterUserPassword property is set
internal bool IsSetMasterUserPassword()
{
return this._masterUserPassword != null;
}
/// <summary>
/// Gets and sets the property NodeType.
/// <para>
/// The node type to be provisioned for the cluster. For information about node types,
/// go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#how-many-nodes">
/// Working with Clusters</a> in the <i>Amazon Redshift Cluster Management Guide</i>.
///
/// </para>
///
/// <para>
/// Valid Values: <code>ds2.xlarge</code> | <code>ds2.8xlarge</code> | <code>dc1.large</code>
/// | <code>dc1.8xlarge</code> | <code>dc2.large</code> | <code>dc2.8xlarge</code> | <code>ra3.16xlarge</code>
///
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string NodeType
{
get { return this._nodeType; }
set { this._nodeType = value; }
}
// Check to see if NodeType property is set
internal bool IsSetNodeType()
{
return this._nodeType != null;
}
/// <summary>
/// Gets and sets the property NumberOfNodes.
/// <para>
/// The number of compute nodes in the cluster. This parameter is required when the <b>ClusterType</b>
/// parameter is specified as <code>multi-node</code>.
/// </para>
///
/// <para>
/// For information about determining how many nodes you need, go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#how-many-nodes">
/// Working with Clusters</a> in the <i>Amazon Redshift Cluster Management Guide</i>.
///
/// </para>
///
/// <para>
/// If you don't specify this parameter, you get a single-node cluster. When requesting
/// a multi-node cluster, you must specify the number of nodes that you want in the cluster.
/// </para>
///
/// <para>
/// Default: <code>1</code>
/// </para>
///
/// <para>
/// Constraints: Value must be at least 1 and no more than 100.
/// </para>
/// </summary>
public int NumberOfNodes
{
get { return this._numberOfNodes.GetValueOrDefault(); }
set { this._numberOfNodes = value; }
}
// Check to see if NumberOfNodes property is set
internal bool IsSetNumberOfNodes()
{
return this._numberOfNodes.HasValue;
}
/// <summary>
/// Gets and sets the property Port.
/// <para>
/// The port number on which the cluster accepts incoming connections.
/// </para>
///
/// <para>
/// The cluster is accessible only via the JDBC and ODBC connection strings. Part of the
/// connection string requires the port on which the cluster will listen for incoming
/// connections.
/// </para>
///
/// <para>
/// Default: <code>5439</code>
/// </para>
///
/// <para>
/// Valid Values: <code>1150-65535</code>
/// </para>
/// </summary>
public int Port
{
get { return this._port.GetValueOrDefault(); }
set { this._port = value; }
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this._port.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// The weekly time range (in UTC) during which automated cluster maintenance can occur.
/// </para>
///
/// <para>
/// Format: <code>ddd:hh24:mi-ddd:hh24:mi</code>
/// </para>
///
/// <para>
/// Default: A 30-minute window selected at random from an 8-hour block of time per region,
/// occurring on a random day of the week. For more information about the time blocks
/// for each region, see <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-maintenance-windows">Maintenance
/// Windows</a> in Amazon Redshift Cluster Management Guide.
/// </para>
///
/// <para>
/// Valid Days: Mon | Tue | Wed | Thu | Fri | Sat | Sun
/// </para>
///
/// <para>
/// Constraints: Minimum 30-minute window.
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property PubliclyAccessible.
/// <para>
/// If <code>true</code>, the cluster can be accessed from a public network.
/// </para>
/// </summary>
public bool PubliclyAccessible
{
get { return this._publiclyAccessible.GetValueOrDefault(); }
set { this._publiclyAccessible = value; }
}
// Check to see if PubliclyAccessible property is set
internal bool IsSetPubliclyAccessible()
{
return this._publiclyAccessible.HasValue;
}
/// <summary>
/// Gets and sets the property SnapshotScheduleIdentifier.
/// <para>
/// A unique identifier for the snapshot schedule.
/// </para>
/// </summary>
public string SnapshotScheduleIdentifier
{
get { return this._snapshotScheduleIdentifier; }
set { this._snapshotScheduleIdentifier = value; }
}
// Check to see if SnapshotScheduleIdentifier property is set
internal bool IsSetSnapshotScheduleIdentifier()
{
return this._snapshotScheduleIdentifier != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// A list of tag instances.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property VpcSecurityGroupIds.
/// <para>
/// A list of Virtual Private Cloud (VPC) security groups to be associated with the cluster.
/// </para>
///
/// <para>
/// Default: The default VPC security group is associated with the cluster.
/// </para>
/// </summary>
public List<string> VpcSecurityGroupIds
{
get { return this._vpcSecurityGroupIds; }
set { this._vpcSecurityGroupIds = value; }
}
// Check to see if VpcSecurityGroupIds property is set
internal bool IsSetVpcSecurityGroupIds()
{
return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0;
}
}
} | 35.190118 | 178 | 0.551462 | [
"Apache-2.0"
] | UpendoVentures/aws-sdk-net | sdk/src/Services/Redshift/Generated/Model/CreateClusterRequest.cs | 32,762 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenRPA.Net
{
public class SocketMessage : BaseMessage
{
public SocketMessage() { }
public SocketMessage(Message msg)
{
id = msg.id;
replyto = msg.replyto;
command = msg.command;
data = msg.data;
count = 1;
index = 0;
}
public SocketMessage(Message msg, string data, int count, int index)
{
id = msg.id;
replyto = msg.replyto;
command = msg.command;
this.data = data;
this.count = count;
this.index = index;
}
public int count { get; set; }
public int index { get; set; }
public void Send(WebSocketClient ws)
{
ws.PushMessage(this);
}
public override string ToString()
{
if (string.IsNullOrEmpty(id)) return base.ToString();
if (string.IsNullOrEmpty(command)) return id;
return id + ":" + command;
}
[Newtonsoft.Json.Serialization.OnError]
internal void OnError(System.Runtime.Serialization.StreamingContext context, Newtonsoft.Json.Serialization.ErrorContext errorContext)
{
errorContext.Handled = true;
}
}
}
| 28.16 | 141 | 0.554688 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SynergERP/openrpa | OpenRPA.Net/SocketMessage.cs | 1,410 | C# |
namespace MiniWebERP.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Storage;
internal static class EfExpressionHelper
{
private static readonly Type StringType = typeof(string);
private static readonly MethodInfo ValueBufferGetValueMethod =
typeof(ValueBuffer).GetRuntimeProperties().Single(p => p.GetIndexParameters().Any()).GetMethod;
private static readonly MethodInfo EfPropertyMethod =
typeof(EF).GetTypeInfo().GetDeclaredMethod(nameof(Property));
public static Expression<Func<TEntity, bool>> BuildByIdPredicate<TEntity>(
DbContext dbContext,
object[] id)
where TEntity : class
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
var entityType = typeof(TEntity);
var entityParameter = Expression.Parameter(entityType, "e");
var keyProperties = dbContext.Model.FindEntityType(entityType).FindPrimaryKey().Properties;
var predicate = BuildPredicate(keyProperties, new ValueBuffer(id), entityParameter);
return Expression.Lambda<Func<TEntity, bool>>(predicate, entityParameter);
}
private static BinaryExpression BuildPredicate(
IReadOnlyList<IProperty> keyProperties,
ValueBuffer keyValues,
ParameterExpression entityParameter)
{
var keyValuesConstant = Expression.Constant(keyValues);
BinaryExpression predicate = null;
for (var i = 0; i < keyProperties.Count; i++)
{
var property = keyProperties[i];
var equalsExpression =
Expression.Equal(
Expression.Call(
EfPropertyMethod.MakeGenericMethod(property.ClrType),
entityParameter,
Expression.Constant(property.Name, StringType)),
Expression.Convert(
Expression.Call(
keyValuesConstant,
ValueBufferGetValueMethod,
Expression.Constant(i)),
property.ClrType));
predicate = predicate == null ? equalsExpression : Expression.AndAlso(predicate, equalsExpression);
}
return predicate;
}
}
}
| 37.026667 | 115 | 0.593086 | [
"Apache-2.0"
] | GiK986/MiniWebERP | Data/MiniWebERP.Data/EfExpressionHelper.cs | 2,779 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Extensions;
public partial class AzureMySqlCredentialScanPropertiesAutoGenerated
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject into a new instance of <see cref="AzureMySqlCredentialScanPropertiesAutoGenerated"
/// />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject instance to deserialize from.</param>
internal AzureMySqlCredentialScanPropertiesAutoGenerated(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
__azureMySqlScanProperties = new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.AzureMySqlScanProperties(json);
AfterFromJson(json);
}
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IAzureMySqlCredentialScanPropertiesAutoGenerated.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IAzureMySqlCredentialScanPropertiesAutoGenerated.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IAzureMySqlCredentialScanPropertiesAutoGenerated FromJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json ? new AzureMySqlCredentialScanPropertiesAutoGenerated(json) : null;
}
/// <summary>
/// Serializes this instance of <see cref="AzureMySqlCredentialScanPropertiesAutoGenerated" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode"
/// />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="AzureMySqlCredentialScanPropertiesAutoGenerated" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode"
/// />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
__azureMySqlScanProperties?.ToJson(container, serializationMode);
AfterToJson(ref container);
return container;
}
}
} | 65.712963 | 265 | 0.697055 | [
"MIT"
] | Agazoth/azure-powershell | src/Purview/Purviewdata.Autorest/generated/api/Models/Api20211001Preview/AzureMySqlCredentialScanPropertiesAutoGenerated.json.cs | 6,990 | C# |
//*******************************************************************************************//
// //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer //
// //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup //
// //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved. //
// https://www.bytescout.com //
// https://pdf.co //
// //
//*******************************************************************************************//
using System.Diagnostics;
using Bytescout.PDFRenderer;
namespace PDF2TIFF
{
class Program
{
static void Main()
{
// Create Bytescout.PDFRenderer.RasterRenderer object instance and register it.
RasterRenderer renderer = new RasterRenderer();
renderer.RegistrationName = "demo";
renderer.RegistrationKey = "demo";
// Load PDF document.
renderer.LoadDocumentFromFile("multipage.pdf");
int startPage = 0;
int endPage = renderer.GetPageCount() - 1;
// Save PDF document to black-and-white multi-page TIFF at 120 DPI
RenderingOptions renderingOptions = new RenderingOptions();
renderingOptions.TIFFCompression = TIFFCompression.CCITT4;
renderer.SaveMultipageTiff("multipage.tiff", startPage, endPage, 120, renderingOptions);
// Cleanup
renderer.Dispose();
// Open result document in default associated application (for demo purpose)
ProcessStartInfo processStartInfo = new ProcessStartInfo("multipage.tiff");
processStartInfo.UseShellExecute = true;
Process.Start(processStartInfo);
}
}
}
| 47.653061 | 101 | 0.424411 | [
"Apache-2.0"
] | atkins126/ByteScout-SDK-SourceCode | PDF Renderer SDK/C#/Convert PDF To Multipage TIFF/Program.cs | 2,336 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace WS.Finances.Core.Lib.Data
{
public interface IRepository<TModel>
where TModel : class, IModel
{
IQueryable<TModel> Get();
TModel Get(TModel key);
bool Put(TModel item);
bool Delete(TModel key);
void Clear();
}
}
| 16.904762 | 41 | 0.622535 | [
"MIT"
] | davebrunger/WS.Finances.Core | WS.Finances.Core.Lib/Data/IRepository.cs | 355 | C# |
using System;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Codecs.Lucene42
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Lucene40LiveDocsFormat = YAF.Lucene.Net.Codecs.Lucene40.Lucene40LiveDocsFormat;
using Lucene40SegmentInfoFormat = YAF.Lucene.Net.Codecs.Lucene40.Lucene40SegmentInfoFormat;
using Lucene41StoredFieldsFormat = YAF.Lucene.Net.Codecs.Lucene41.Lucene41StoredFieldsFormat;
using PerFieldDocValuesFormat = YAF.Lucene.Net.Codecs.PerField.PerFieldDocValuesFormat;
using PerFieldPostingsFormat = YAF.Lucene.Net.Codecs.PerField.PerFieldPostingsFormat;
using SegmentWriteState = YAF.Lucene.Net.Index.SegmentWriteState;
/// <summary>
/// Implements the Lucene 4.2 index format, with configurable per-field postings
/// and docvalues formats.
/// <para/>
/// If you want to reuse functionality of this codec in another codec, extend
/// <see cref="FilterCodec"/>.
/// <para/>
/// See <see cref="Lucene.Net.Codecs.Lucene42"/> package documentation for file format details.
/// <para/>
/// @lucene.experimental
/// </summary>
// NOTE: if we make largish changes in a minor release, easier to just make Lucene43Codec or whatever
// if they are backwards compatible or smallish we can probably do the backwards in the postingsreader
// (it writes a minor version, etc).
[Obsolete("Only for reading old 4.2 segments")]
[CodecName("Lucene42")] // LUCENENET specific - using CodecName attribute to ensure the default name passed from subclasses is the same as this class name
public class Lucene42Codec : Codec
{
private readonly StoredFieldsFormat fieldsFormat = new Lucene41StoredFieldsFormat();
private readonly TermVectorsFormat vectorsFormat = new Lucene42TermVectorsFormat();
private readonly FieldInfosFormat fieldInfosFormat = new Lucene42FieldInfosFormat();
private readonly SegmentInfoFormat infosFormat = new Lucene40SegmentInfoFormat();
private readonly LiveDocsFormat liveDocsFormat = new Lucene40LiveDocsFormat();
private readonly PostingsFormat postingsFormat;
private class PerFieldPostingsFormatAnonymousClass : PerFieldPostingsFormat
{
private readonly Lucene42Codec outerInstance;
public PerFieldPostingsFormatAnonymousClass(Lucene42Codec outerInstance)
{
this.outerInstance = outerInstance;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override PostingsFormat GetPostingsFormatForField(string field)
{
return outerInstance.GetPostingsFormatForField(field);
}
}
private readonly DocValuesFormat docValuesFormat;
private class PerFieldDocValuesFormatAnonymousClass : PerFieldDocValuesFormat
{
private readonly Lucene42Codec outerInstance;
public PerFieldDocValuesFormatAnonymousClass(Lucene42Codec outerInstance)
{
this.outerInstance = outerInstance;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override DocValuesFormat GetDocValuesFormatForField(string field)
{
return outerInstance.GetDocValuesFormatForField(field);
}
}
/// <summary>
/// Sole constructor. </summary>
public Lucene42Codec()
: base()
{
postingsFormat = new PerFieldPostingsFormatAnonymousClass(this);
docValuesFormat = new PerFieldDocValuesFormatAnonymousClass(this);
}
public override sealed StoredFieldsFormat StoredFieldsFormat => fieldsFormat;
public override sealed TermVectorsFormat TermVectorsFormat => vectorsFormat;
public override sealed PostingsFormat PostingsFormat => postingsFormat;
public override FieldInfosFormat FieldInfosFormat => fieldInfosFormat;
public override SegmentInfoFormat SegmentInfoFormat => infosFormat;
public override sealed LiveDocsFormat LiveDocsFormat => liveDocsFormat;
/// <summary>
/// Returns the postings format that should be used for writing
/// new segments of <paramref name="field"/>.
/// <para/>
/// The default implementation always returns "Lucene41"
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual PostingsFormat GetPostingsFormatForField(string field)
{
// LUCENENET specific - lazy initialize the codec to ensure we get the correct type if overridden.
if (defaultFormat == null)
{
defaultFormat = Codecs.PostingsFormat.ForName("Lucene41");
}
return defaultFormat;
}
/// <summary>
/// Returns the docvalues format that should be used for writing
/// new segments of <paramref name="field"/>.
/// <para/>
/// The default implementation always returns "Lucene42"
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual DocValuesFormat GetDocValuesFormatForField(string field)
{
// LUCENENET specific - lazy initialize the codec to ensure we get the correct type if overridden.
if (defaultDVFormat == null)
{
defaultDVFormat = Codecs.DocValuesFormat.ForName("Lucene42");
}
return defaultDVFormat;
}
public override sealed DocValuesFormat DocValuesFormat => docValuesFormat;
// LUCENENET specific - lazy initialize the codecs to ensure we get the correct type if overridden.
private PostingsFormat defaultFormat;
private DocValuesFormat defaultDVFormat;
private readonly NormsFormat normsFormat = new Lucene42NormsFormatAnonymousClass();
private class Lucene42NormsFormatAnonymousClass : Lucene42NormsFormat
{
public override DocValuesConsumer NormsConsumer(SegmentWriteState state)
{
throw UnsupportedOperationException.Create("this codec can only be used for reading");
}
}
public override NormsFormat NormsFormat => normsFormat;
}
} | 44.858896 | 159 | 0.670131 | [
"Apache-2.0"
] | Spinks90/YAFNET | yafsrc/Lucene.Net/Lucene.Net/Codecs/Lucene42/Lucene42Codec.cs | 7,150 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlayerStatus.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Aupli.ApplicationServices.Player.Ari
{
using System;
using Sundew.Base.Equality;
/// <summary>
/// Stores the status of a music player.
/// </summary>
public class PlayerStatus : IEquatable<PlayerStatus>
{
/// <summary>
/// The no status.
/// </summary>
public static readonly PlayerStatus NoStatus =
new PlayerStatus(string.Empty, string.Empty, string.Empty, PlayerState.Unknown, -1, TimeSpan.Zero);
/// <summary>
/// Initializes a new instance of the <see cref="PlayerStatus" /> class.
/// </summary>
/// <param name="playlistName">Name of the playlist.</param>
/// <param name="artist">The artist.</param>
/// <param name="title">The title.</param>
/// <param name="playerState">Result of the player.</param>
/// <param name="track">The track.</param>
/// <param name="elapsed">The elapsed.</param>
public PlayerStatus(string playlistName, string artist, string title, PlayerState playerState, int track, TimeSpan elapsed)
{
this.PlaylistName = playlistName;
this.Artist = artist;
this.Title = title;
this.State = playerState;
this.Track = track;
this.Elapsed = elapsed;
}
/// <summary>
/// Gets the name of the playlist.
/// </summary>
/// <value>
/// The name of the playlist.
/// </value>
public string PlaylistName { get; }
/// <summary>
/// Gets the artist.
/// </summary>
/// <value>
/// The artist.
/// </value>
public string Artist { get; }
/// <summary>
/// Gets the title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title { get; }
/// <summary>
/// Gets the state.
/// </summary>
/// <value>
/// The state.
/// </value>
public PlayerState State { get; }
/// <summary>
/// Gets the track.
/// </summary>
/// <value>
/// The track.
/// </value>
public int Track { get; }
/// <summary>
/// Gets the elapsed.
/// </summary>
/// <value>
/// The elapsed.
/// </value>
public TimeSpan Elapsed { get; }
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.
/// </returns>
public bool Equals(PlayerStatus? other)
{
return EqualityHelper.Equals(this, other, rhs => this.PlaylistName == rhs.PlaylistName &&
this.Artist == rhs.Artist &&
this.Title == rhs.Title &&
this.State == rhs.State &&
this.Track == rhs.Track &&
this.Elapsed == rhs.Elapsed);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>
/// <see langword="true" /> if the specified object is equal to the current object; otherwise, <see langword="false" />.
/// </returns>
public override bool Equals(object? obj)
{
return EqualityHelper.Equals(this, obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return EqualityHelper.GetHashCode(this.PlaylistName.GetHashCode(), this.Artist.GetHashCode(), this.Title.GetHashCode(), this.Track.GetHashCode(), this.State.GetHashCode(), this.Elapsed.GetHashCode());
}
}
} | 37.793893 | 212 | 0.491416 | [
"MIT"
] | hugener/Aupli | Source/Aupli/ApplicationServices/Player/Ari/PlayerStatus.cs | 4,953 | C# |
namespace Ignore
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
/// <summary>
/// A holder for a regex and replacer function.
/// The function is invoked if the input matches the regex.
/// </summary>
public class Replacer
{
private readonly string name;
private readonly Regex regex;
private readonly MatchEvaluator matchEvaluator;
public Replacer(string name, Regex regex, Func<Match, string> replacer)
{
this.name = name;
this.regex = regex;
matchEvaluator = new MatchEvaluator(replacer);
}
public string Invoke(string pattern)
{
return regex.Replace(pattern, matchEvaluator);
}
public override string ToString()
{
return name;
}
}
}
| 23.783784 | 79 | 0.595455 | [
"MIT"
] | goelhardik/Ignore.NET | src/Ignore/Replacer.cs | 880 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Compute
{
/// <summary>
/// Operations for managing the virtual machines in compute management.
/// </summary>
internal partial class VirtualMachineOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineOperations
{
/// <summary>
/// Initializes a new instance of the VirtualMachineOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualMachineOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Captures the VM by copying VirtualHardDisks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Capture Virtual Machine
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The compute long running operation response.
/// </returns>
public async Task<ComputeOperationResponse> BeginCapturingAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.DestinationContainerName == null)
{
throw new ArgumentNullException("parameters.DestinationContainerName");
}
if (parameters.VirtualHardDiskNamePrefix == null)
{
throw new ArgumentNullException("parameters.VirtualHardDiskNamePrefix");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCapturingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
url = url + "/capture";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject virtualMachineCaptureParametersValue = new JObject();
requestDoc = virtualMachineCaptureParametersValue;
virtualMachineCaptureParametersValue["vhdPrefix"] = parameters.VirtualHardDiskNamePrefix;
virtualMachineCaptureParametersValue["destinationContainerName"] = parameters.DestinationContainerName;
virtualMachineCaptureParametersValue["overwriteVhds"] = parameters.Overwrite;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ComputeOperationResponse result = null;
// Deserialize Response
result = new ComputeOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Virtual Machine
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Create Virtual Machine operation response.
/// </returns>
public async Task<VirtualMachineCreateOrUpdateResponse> BeginCreatingOrUpdatingAsync(string resourceGroupName, VirtualMachine parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Extensions != null)
{
foreach (VirtualMachineExtension extensionsParameterItem in parameters.Extensions)
{
if (extensionsParameterItem.Location == null)
{
throw new ArgumentNullException("parameters.Extensions.Location");
}
}
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.StorageProfile != null)
{
if (parameters.StorageProfile.DataDisks != null)
{
foreach (DataDisk dataDisksParameterItem in parameters.StorageProfile.DataDisks)
{
if (dataDisksParameterItem.CreateOption == null)
{
throw new ArgumentNullException("parameters.StorageProfile.DataDisks.CreateOption");
}
if (dataDisksParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.StorageProfile.DataDisks.Name");
}
if (dataDisksParameterItem.VirtualHardDisk == null)
{
throw new ArgumentNullException("parameters.StorageProfile.DataDisks.VirtualHardDisk");
}
}
}
if (parameters.StorageProfile.OSDisk != null)
{
if (parameters.StorageProfile.OSDisk.CreateOption == null)
{
throw new ArgumentNullException("parameters.StorageProfile.OSDisk.CreateOption");
}
if (parameters.StorageProfile.OSDisk.Name == null)
{
throw new ArgumentNullException("parameters.StorageProfile.OSDisk.Name");
}
if (parameters.StorageProfile.OSDisk.VirtualHardDisk == null)
{
throw new ArgumentNullException("parameters.StorageProfile.OSDisk.VirtualHardDisk");
}
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreatingOrUpdatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
if (parameters.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject virtualMachineJsonValue = new JObject();
requestDoc = virtualMachineJsonValue;
if (parameters.Plan != null)
{
JObject planValue = new JObject();
virtualMachineJsonValue["plan"] = planValue;
if (parameters.Plan.Name != null)
{
planValue["name"] = parameters.Plan.Name;
}
if (parameters.Plan.Publisher != null)
{
planValue["publisher"] = parameters.Plan.Publisher;
}
if (parameters.Plan.Product != null)
{
planValue["product"] = parameters.Plan.Product;
}
if (parameters.Plan.PromotionCode != null)
{
planValue["promotionCode"] = parameters.Plan.PromotionCode;
}
}
JObject propertiesValue = new JObject();
virtualMachineJsonValue["properties"] = propertiesValue;
if (parameters.HardwareProfile != null)
{
JObject hardwareProfileValue = new JObject();
propertiesValue["hardwareProfile"] = hardwareProfileValue;
if (parameters.HardwareProfile.VirtualMachineSize != null)
{
hardwareProfileValue["vmSize"] = parameters.HardwareProfile.VirtualMachineSize;
}
}
if (parameters.StorageProfile != null)
{
JObject storageProfileValue = new JObject();
propertiesValue["storageProfile"] = storageProfileValue;
if (parameters.StorageProfile.ImageReference != null)
{
JObject imageReferenceValue = new JObject();
storageProfileValue["imageReference"] = imageReferenceValue;
if (parameters.StorageProfile.ImageReference.Publisher != null)
{
imageReferenceValue["publisher"] = parameters.StorageProfile.ImageReference.Publisher;
}
if (parameters.StorageProfile.ImageReference.Offer != null)
{
imageReferenceValue["offer"] = parameters.StorageProfile.ImageReference.Offer;
}
if (parameters.StorageProfile.ImageReference.Sku != null)
{
imageReferenceValue["sku"] = parameters.StorageProfile.ImageReference.Sku;
}
if (parameters.StorageProfile.ImageReference.Version != null)
{
imageReferenceValue["version"] = parameters.StorageProfile.ImageReference.Version;
}
}
if (parameters.StorageProfile.OSDisk != null)
{
JObject osDiskValue = new JObject();
storageProfileValue["osDisk"] = osDiskValue;
if (parameters.StorageProfile.OSDisk.OperatingSystemType != null)
{
osDiskValue["osType"] = parameters.StorageProfile.OSDisk.OperatingSystemType;
}
osDiskValue["name"] = parameters.StorageProfile.OSDisk.Name;
JObject vhdValue = new JObject();
osDiskValue["vhd"] = vhdValue;
if (parameters.StorageProfile.OSDisk.VirtualHardDisk.Uri != null)
{
vhdValue["uri"] = parameters.StorageProfile.OSDisk.VirtualHardDisk.Uri;
}
if (parameters.StorageProfile.OSDisk.SourceImage != null)
{
JObject imageValue = new JObject();
osDiskValue["image"] = imageValue;
if (parameters.StorageProfile.OSDisk.SourceImage.Uri != null)
{
imageValue["uri"] = parameters.StorageProfile.OSDisk.SourceImage.Uri;
}
}
if (parameters.StorageProfile.OSDisk.Caching != null)
{
osDiskValue["caching"] = parameters.StorageProfile.OSDisk.Caching;
}
osDiskValue["createOption"] = parameters.StorageProfile.OSDisk.CreateOption;
if (parameters.StorageProfile.OSDisk.DiskSizeGB != null)
{
osDiskValue["diskSizeGB"] = parameters.StorageProfile.OSDisk.DiskSizeGB.Value;
}
}
if (parameters.StorageProfile.DataDisks != null)
{
if (parameters.StorageProfile.DataDisks is ILazyCollection == false || ((ILazyCollection)parameters.StorageProfile.DataDisks).IsInitialized)
{
JArray dataDisksArray = new JArray();
foreach (DataDisk dataDisksItem in parameters.StorageProfile.DataDisks)
{
JObject dataDiskValue = new JObject();
dataDisksArray.Add(dataDiskValue);
dataDiskValue["lun"] = dataDisksItem.Lun;
dataDiskValue["name"] = dataDisksItem.Name;
JObject vhdValue2 = new JObject();
dataDiskValue["vhd"] = vhdValue2;
if (dataDisksItem.VirtualHardDisk.Uri != null)
{
vhdValue2["uri"] = dataDisksItem.VirtualHardDisk.Uri;
}
if (dataDisksItem.SourceImage != null)
{
JObject imageValue2 = new JObject();
dataDiskValue["image"] = imageValue2;
if (dataDisksItem.SourceImage.Uri != null)
{
imageValue2["uri"] = dataDisksItem.SourceImage.Uri;
}
}
if (dataDisksItem.Caching != null)
{
dataDiskValue["caching"] = dataDisksItem.Caching;
}
dataDiskValue["createOption"] = dataDisksItem.CreateOption;
if (dataDisksItem.DiskSizeGB != null)
{
dataDiskValue["diskSizeGB"] = dataDisksItem.DiskSizeGB.Value;
}
}
storageProfileValue["dataDisks"] = dataDisksArray;
}
}
}
if (parameters.OSProfile != null)
{
JObject osProfileValue = new JObject();
propertiesValue["osProfile"] = osProfileValue;
if (parameters.OSProfile.ComputerName != null)
{
osProfileValue["computerName"] = parameters.OSProfile.ComputerName;
}
if (parameters.OSProfile.AdminUsername != null)
{
osProfileValue["adminUsername"] = parameters.OSProfile.AdminUsername;
}
if (parameters.OSProfile.AdminPassword != null)
{
osProfileValue["adminPassword"] = parameters.OSProfile.AdminPassword;
}
if (parameters.OSProfile.CustomData != null)
{
osProfileValue["customData"] = parameters.OSProfile.CustomData;
}
if (parameters.OSProfile.WindowsConfiguration != null)
{
JObject windowsConfigurationValue = new JObject();
osProfileValue["windowsConfiguration"] = windowsConfigurationValue;
if (parameters.OSProfile.WindowsConfiguration.ProvisionVMAgent != null)
{
windowsConfigurationValue["provisionVMAgent"] = parameters.OSProfile.WindowsConfiguration.ProvisionVMAgent.Value;
}
if (parameters.OSProfile.WindowsConfiguration.EnableAutomaticUpdates != null)
{
windowsConfigurationValue["enableAutomaticUpdates"] = parameters.OSProfile.WindowsConfiguration.EnableAutomaticUpdates.Value;
}
if (parameters.OSProfile.WindowsConfiguration.TimeZone != null)
{
windowsConfigurationValue["timeZone"] = parameters.OSProfile.WindowsConfiguration.TimeZone;
}
if (parameters.OSProfile.WindowsConfiguration.AdditionalUnattendContents != null)
{
if (parameters.OSProfile.WindowsConfiguration.AdditionalUnattendContents is ILazyCollection == false || ((ILazyCollection)parameters.OSProfile.WindowsConfiguration.AdditionalUnattendContents).IsInitialized)
{
JArray additionalUnattendContentArray = new JArray();
foreach (AdditionalUnattendContent additionalUnattendContentItem in parameters.OSProfile.WindowsConfiguration.AdditionalUnattendContents)
{
JObject additionalUnattendContentValue = new JObject();
additionalUnattendContentArray.Add(additionalUnattendContentValue);
if (additionalUnattendContentItem.PassName != null)
{
additionalUnattendContentValue["passName"] = additionalUnattendContentItem.PassName;
}
if (additionalUnattendContentItem.ComponentName != null)
{
additionalUnattendContentValue["componentName"] = additionalUnattendContentItem.ComponentName;
}
if (additionalUnattendContentItem.SettingName != null)
{
additionalUnattendContentValue["settingName"] = additionalUnattendContentItem.SettingName;
}
if (additionalUnattendContentItem.Content != null)
{
additionalUnattendContentValue["content"] = additionalUnattendContentItem.Content;
}
}
windowsConfigurationValue["additionalUnattendContent"] = additionalUnattendContentArray;
}
}
if (parameters.OSProfile.WindowsConfiguration.WinRMConfiguration != null)
{
JObject winRMValue = new JObject();
windowsConfigurationValue["winRM"] = winRMValue;
if (parameters.OSProfile.WindowsConfiguration.WinRMConfiguration.Listeners != null)
{
if (parameters.OSProfile.WindowsConfiguration.WinRMConfiguration.Listeners is ILazyCollection == false || ((ILazyCollection)parameters.OSProfile.WindowsConfiguration.WinRMConfiguration.Listeners).IsInitialized)
{
JArray listenersArray = new JArray();
foreach (WinRMListener listenersItem in parameters.OSProfile.WindowsConfiguration.WinRMConfiguration.Listeners)
{
JObject winRMListenerValue = new JObject();
listenersArray.Add(winRMListenerValue);
if (listenersItem.Protocol != null)
{
winRMListenerValue["protocol"] = listenersItem.Protocol;
}
if (listenersItem.CertificateUrl != null)
{
winRMListenerValue["certificateUrl"] = listenersItem.CertificateUrl.AbsoluteUri;
}
}
winRMValue["listeners"] = listenersArray;
}
}
}
}
if (parameters.OSProfile.LinuxConfiguration != null)
{
JObject linuxConfigurationValue = new JObject();
osProfileValue["linuxConfiguration"] = linuxConfigurationValue;
if (parameters.OSProfile.LinuxConfiguration.DisablePasswordAuthentication != null)
{
linuxConfigurationValue["disablePasswordAuthentication"] = parameters.OSProfile.LinuxConfiguration.DisablePasswordAuthentication.Value;
}
if (parameters.OSProfile.LinuxConfiguration.SshConfiguration != null)
{
JObject sshValue = new JObject();
linuxConfigurationValue["ssh"] = sshValue;
if (parameters.OSProfile.LinuxConfiguration.SshConfiguration.PublicKeys != null)
{
if (parameters.OSProfile.LinuxConfiguration.SshConfiguration.PublicKeys is ILazyCollection == false || ((ILazyCollection)parameters.OSProfile.LinuxConfiguration.SshConfiguration.PublicKeys).IsInitialized)
{
JArray publicKeysArray = new JArray();
foreach (SshPublicKey publicKeysItem in parameters.OSProfile.LinuxConfiguration.SshConfiguration.PublicKeys)
{
JObject sshPublicKeyValue = new JObject();
publicKeysArray.Add(sshPublicKeyValue);
if (publicKeysItem.Path != null)
{
sshPublicKeyValue["path"] = publicKeysItem.Path;
}
if (publicKeysItem.KeyData != null)
{
sshPublicKeyValue["keyData"] = publicKeysItem.KeyData;
}
}
sshValue["publicKeys"] = publicKeysArray;
}
}
}
}
if (parameters.OSProfile.Secrets != null)
{
if (parameters.OSProfile.Secrets is ILazyCollection == false || ((ILazyCollection)parameters.OSProfile.Secrets).IsInitialized)
{
JArray secretsArray = new JArray();
foreach (VaultSecretGroup secretsItem in parameters.OSProfile.Secrets)
{
JObject vaultSecretGroupValue = new JObject();
secretsArray.Add(vaultSecretGroupValue);
if (secretsItem.SourceVault != null)
{
JObject sourceVaultValue = new JObject();
vaultSecretGroupValue["sourceVault"] = sourceVaultValue;
if (secretsItem.SourceVault.ReferenceUri != null)
{
sourceVaultValue["id"] = secretsItem.SourceVault.ReferenceUri;
}
}
if (secretsItem.VaultCertificates != null)
{
if (secretsItem.VaultCertificates is ILazyCollection == false || ((ILazyCollection)secretsItem.VaultCertificates).IsInitialized)
{
JArray vaultCertificatesArray = new JArray();
foreach (VaultCertificate vaultCertificatesItem in secretsItem.VaultCertificates)
{
JObject vaultCertificateValue = new JObject();
vaultCertificatesArray.Add(vaultCertificateValue);
if (vaultCertificatesItem.CertificateUrl != null)
{
vaultCertificateValue["certificateUrl"] = vaultCertificatesItem.CertificateUrl;
}
if (vaultCertificatesItem.CertificateStore != null)
{
vaultCertificateValue["certificateStore"] = vaultCertificatesItem.CertificateStore;
}
}
vaultSecretGroupValue["vaultCertificates"] = vaultCertificatesArray;
}
}
}
osProfileValue["secrets"] = secretsArray;
}
}
}
if (parameters.NetworkProfile != null)
{
JObject networkProfileValue = new JObject();
propertiesValue["networkProfile"] = networkProfileValue;
if (parameters.NetworkProfile.NetworkInterfaces != null)
{
if (parameters.NetworkProfile.NetworkInterfaces is ILazyCollection == false || ((ILazyCollection)parameters.NetworkProfile.NetworkInterfaces).IsInitialized)
{
JArray networkInterfacesArray = new JArray();
foreach (NetworkInterfaceReference networkInterfacesItem in parameters.NetworkProfile.NetworkInterfaces)
{
JObject networkInterfaceReferenceJsonValue = new JObject();
networkInterfacesArray.Add(networkInterfaceReferenceJsonValue);
JObject propertiesValue2 = new JObject();
networkInterfaceReferenceJsonValue["properties"] = propertiesValue2;
if (networkInterfacesItem.Primary != null)
{
propertiesValue2["primary"] = networkInterfacesItem.Primary.Value;
}
if (networkInterfacesItem.ReferenceUri != null)
{
networkInterfaceReferenceJsonValue["id"] = networkInterfacesItem.ReferenceUri;
}
}
networkProfileValue["networkInterfaces"] = networkInterfacesArray;
}
}
}
if (parameters.AvailabilitySetReference != null)
{
JObject availabilitySetValue = new JObject();
propertiesValue["availabilitySet"] = availabilitySetValue;
if (parameters.AvailabilitySetReference.ReferenceUri != null)
{
availabilitySetValue["id"] = parameters.AvailabilitySetReference.ReferenceUri;
}
}
if (parameters.ProvisioningState != null)
{
propertiesValue["provisioningState"] = parameters.ProvisioningState;
}
if (parameters.InstanceView != null)
{
JObject instanceViewValue = new JObject();
propertiesValue["instanceView"] = instanceViewValue;
if (parameters.InstanceView.PlatformUpdateDomain != null)
{
instanceViewValue["platformUpdateDomain"] = parameters.InstanceView.PlatformUpdateDomain.Value;
}
if (parameters.InstanceView.PlatformFaultDomain != null)
{
instanceViewValue["platformFaultDomain"] = parameters.InstanceView.PlatformFaultDomain.Value;
}
if (parameters.InstanceView.RemoteDesktopThumbprint != null)
{
instanceViewValue["rdpThumbPrint"] = parameters.InstanceView.RemoteDesktopThumbprint;
}
if (parameters.InstanceView.VMAgent != null)
{
JObject vmAgentValue = new JObject();
instanceViewValue["vmAgent"] = vmAgentValue;
if (parameters.InstanceView.VMAgent.VMAgentVersion != null)
{
vmAgentValue["vmAgentVersion"] = parameters.InstanceView.VMAgent.VMAgentVersion;
}
if (parameters.InstanceView.VMAgent.ExtensionHandlers != null)
{
if (parameters.InstanceView.VMAgent.ExtensionHandlers is ILazyCollection == false || ((ILazyCollection)parameters.InstanceView.VMAgent.ExtensionHandlers).IsInitialized)
{
JArray extensionHandlersArray = new JArray();
foreach (VirtualMachineExtensionHandlerInstanceView extensionHandlersItem in parameters.InstanceView.VMAgent.ExtensionHandlers)
{
JObject virtualMachineExtensionHandlerInstanceViewValue = new JObject();
extensionHandlersArray.Add(virtualMachineExtensionHandlerInstanceViewValue);
if (extensionHandlersItem.Type != null)
{
virtualMachineExtensionHandlerInstanceViewValue["type"] = extensionHandlersItem.Type;
}
if (extensionHandlersItem.TypeHandlerVersion != null)
{
virtualMachineExtensionHandlerInstanceViewValue["typeHandlerVersion"] = extensionHandlersItem.TypeHandlerVersion;
}
if (extensionHandlersItem.Status != null)
{
JObject statusValue = new JObject();
virtualMachineExtensionHandlerInstanceViewValue["status"] = statusValue;
if (extensionHandlersItem.Status.Code != null)
{
statusValue["code"] = extensionHandlersItem.Status.Code;
}
if (extensionHandlersItem.Status.Level != null)
{
statusValue["level"] = extensionHandlersItem.Status.Level;
}
if (extensionHandlersItem.Status.DisplayStatus != null)
{
statusValue["displayStatus"] = extensionHandlersItem.Status.DisplayStatus;
}
if (extensionHandlersItem.Status.Message != null)
{
statusValue["message"] = extensionHandlersItem.Status.Message;
}
if (extensionHandlersItem.Status.Time != null)
{
statusValue["time"] = extensionHandlersItem.Status.Time.Value;
}
}
}
vmAgentValue["extensionHandlers"] = extensionHandlersArray;
}
}
if (parameters.InstanceView.VMAgent.Statuses != null)
{
JArray statusesArray = new JArray();
foreach (InstanceViewStatus statusesItem in parameters.InstanceView.VMAgent.Statuses)
{
JObject instanceViewStatusValue = new JObject();
statusesArray.Add(instanceViewStatusValue);
if (statusesItem.Code != null)
{
instanceViewStatusValue["code"] = statusesItem.Code;
}
if (statusesItem.Level != null)
{
instanceViewStatusValue["level"] = statusesItem.Level;
}
if (statusesItem.DisplayStatus != null)
{
instanceViewStatusValue["displayStatus"] = statusesItem.DisplayStatus;
}
if (statusesItem.Message != null)
{
instanceViewStatusValue["message"] = statusesItem.Message;
}
if (statusesItem.Time != null)
{
instanceViewStatusValue["time"] = statusesItem.Time.Value;
}
}
vmAgentValue["statuses"] = statusesArray;
}
}
if (parameters.InstanceView.Disks != null)
{
if (parameters.InstanceView.Disks is ILazyCollection == false || ((ILazyCollection)parameters.InstanceView.Disks).IsInitialized)
{
JArray disksArray = new JArray();
foreach (DiskInstanceView disksItem in parameters.InstanceView.Disks)
{
JObject diskInstanceViewValue = new JObject();
disksArray.Add(diskInstanceViewValue);
if (disksItem.Name != null)
{
diskInstanceViewValue["name"] = disksItem.Name;
}
if (disksItem.Statuses != null)
{
JArray statusesArray2 = new JArray();
foreach (InstanceViewStatus statusesItem2 in disksItem.Statuses)
{
JObject instanceViewStatusValue2 = new JObject();
statusesArray2.Add(instanceViewStatusValue2);
if (statusesItem2.Code != null)
{
instanceViewStatusValue2["code"] = statusesItem2.Code;
}
if (statusesItem2.Level != null)
{
instanceViewStatusValue2["level"] = statusesItem2.Level;
}
if (statusesItem2.DisplayStatus != null)
{
instanceViewStatusValue2["displayStatus"] = statusesItem2.DisplayStatus;
}
if (statusesItem2.Message != null)
{
instanceViewStatusValue2["message"] = statusesItem2.Message;
}
if (statusesItem2.Time != null)
{
instanceViewStatusValue2["time"] = statusesItem2.Time.Value;
}
}
diskInstanceViewValue["statuses"] = statusesArray2;
}
}
instanceViewValue["disks"] = disksArray;
}
}
if (parameters.InstanceView.Extensions != null)
{
if (parameters.InstanceView.Extensions is ILazyCollection == false || ((ILazyCollection)parameters.InstanceView.Extensions).IsInitialized)
{
JArray extensionsArray = new JArray();
foreach (VirtualMachineExtensionInstanceView extensionsItem in parameters.InstanceView.Extensions)
{
JObject virtualMachineExtensionInstanceViewValue = new JObject();
extensionsArray.Add(virtualMachineExtensionInstanceViewValue);
if (extensionsItem.Name != null)
{
virtualMachineExtensionInstanceViewValue["name"] = extensionsItem.Name;
}
if (extensionsItem.ExtensionType != null)
{
virtualMachineExtensionInstanceViewValue["type"] = extensionsItem.ExtensionType;
}
if (extensionsItem.TypeHandlerVersion != null)
{
virtualMachineExtensionInstanceViewValue["typeHandlerVersion"] = extensionsItem.TypeHandlerVersion;
}
if (extensionsItem.SubStatuses != null)
{
if (extensionsItem.SubStatuses is ILazyCollection == false || ((ILazyCollection)extensionsItem.SubStatuses).IsInitialized)
{
JArray substatusesArray = new JArray();
foreach (InstanceViewStatus substatusesItem in extensionsItem.SubStatuses)
{
JObject instanceViewStatusValue3 = new JObject();
substatusesArray.Add(instanceViewStatusValue3);
if (substatusesItem.Code != null)
{
instanceViewStatusValue3["code"] = substatusesItem.Code;
}
if (substatusesItem.Level != null)
{
instanceViewStatusValue3["level"] = substatusesItem.Level;
}
if (substatusesItem.DisplayStatus != null)
{
instanceViewStatusValue3["displayStatus"] = substatusesItem.DisplayStatus;
}
if (substatusesItem.Message != null)
{
instanceViewStatusValue3["message"] = substatusesItem.Message;
}
if (substatusesItem.Time != null)
{
instanceViewStatusValue3["time"] = substatusesItem.Time.Value;
}
}
virtualMachineExtensionInstanceViewValue["substatuses"] = substatusesArray;
}
}
if (extensionsItem.Statuses != null)
{
JArray statusesArray3 = new JArray();
foreach (InstanceViewStatus statusesItem3 in extensionsItem.Statuses)
{
JObject instanceViewStatusValue4 = new JObject();
statusesArray3.Add(instanceViewStatusValue4);
if (statusesItem3.Code != null)
{
instanceViewStatusValue4["code"] = statusesItem3.Code;
}
if (statusesItem3.Level != null)
{
instanceViewStatusValue4["level"] = statusesItem3.Level;
}
if (statusesItem3.DisplayStatus != null)
{
instanceViewStatusValue4["displayStatus"] = statusesItem3.DisplayStatus;
}
if (statusesItem3.Message != null)
{
instanceViewStatusValue4["message"] = statusesItem3.Message;
}
if (statusesItem3.Time != null)
{
instanceViewStatusValue4["time"] = statusesItem3.Time.Value;
}
}
virtualMachineExtensionInstanceViewValue["statuses"] = statusesArray3;
}
}
instanceViewValue["extensions"] = extensionsArray;
}
}
if (parameters.InstanceView.Statuses != null)
{
JArray statusesArray4 = new JArray();
foreach (InstanceViewStatus statusesItem4 in parameters.InstanceView.Statuses)
{
JObject instanceViewStatusValue5 = new JObject();
statusesArray4.Add(instanceViewStatusValue5);
if (statusesItem4.Code != null)
{
instanceViewStatusValue5["code"] = statusesItem4.Code;
}
if (statusesItem4.Level != null)
{
instanceViewStatusValue5["level"] = statusesItem4.Level;
}
if (statusesItem4.DisplayStatus != null)
{
instanceViewStatusValue5["displayStatus"] = statusesItem4.DisplayStatus;
}
if (statusesItem4.Message != null)
{
instanceViewStatusValue5["message"] = statusesItem4.Message;
}
if (statusesItem4.Time != null)
{
instanceViewStatusValue5["time"] = statusesItem4.Time.Value;
}
}
instanceViewValue["statuses"] = statusesArray4;
}
}
if (parameters.Extensions != null)
{
JArray resourcesArray = new JArray();
foreach (VirtualMachineExtension resourcesItem in parameters.Extensions)
{
JObject virtualMachineExtensionJsonValue = new JObject();
resourcesArray.Add(virtualMachineExtensionJsonValue);
JObject propertiesValue3 = new JObject();
virtualMachineExtensionJsonValue["properties"] = propertiesValue3;
if (resourcesItem.Publisher != null)
{
propertiesValue3["publisher"] = resourcesItem.Publisher;
}
if (resourcesItem.ExtensionType != null)
{
propertiesValue3["type"] = resourcesItem.ExtensionType;
}
if (resourcesItem.TypeHandlerVersion != null)
{
propertiesValue3["typeHandlerVersion"] = resourcesItem.TypeHandlerVersion;
}
propertiesValue3["autoUpgradeMinorVersion"] = resourcesItem.AutoUpgradeMinorVersion;
if (resourcesItem.Settings != null)
{
propertiesValue3["settings"] = JObject.Parse(resourcesItem.Settings);
}
if (resourcesItem.ProtectedSettings != null)
{
propertiesValue3["protectedSettings"] = JObject.Parse(resourcesItem.ProtectedSettings);
}
if (resourcesItem.ProvisioningState != null)
{
propertiesValue3["provisioningState"] = resourcesItem.ProvisioningState;
}
if (resourcesItem.InstanceView != null)
{
JObject instanceViewValue2 = new JObject();
propertiesValue3["instanceView"] = instanceViewValue2;
if (resourcesItem.InstanceView.Name != null)
{
instanceViewValue2["name"] = resourcesItem.InstanceView.Name;
}
if (resourcesItem.InstanceView.ExtensionType != null)
{
instanceViewValue2["type"] = resourcesItem.InstanceView.ExtensionType;
}
if (resourcesItem.InstanceView.TypeHandlerVersion != null)
{
instanceViewValue2["typeHandlerVersion"] = resourcesItem.InstanceView.TypeHandlerVersion;
}
if (resourcesItem.InstanceView.SubStatuses != null)
{
if (resourcesItem.InstanceView.SubStatuses is ILazyCollection == false || ((ILazyCollection)resourcesItem.InstanceView.SubStatuses).IsInitialized)
{
JArray substatusesArray2 = new JArray();
foreach (InstanceViewStatus substatusesItem2 in resourcesItem.InstanceView.SubStatuses)
{
JObject instanceViewStatusValue6 = new JObject();
substatusesArray2.Add(instanceViewStatusValue6);
if (substatusesItem2.Code != null)
{
instanceViewStatusValue6["code"] = substatusesItem2.Code;
}
if (substatusesItem2.Level != null)
{
instanceViewStatusValue6["level"] = substatusesItem2.Level;
}
if (substatusesItem2.DisplayStatus != null)
{
instanceViewStatusValue6["displayStatus"] = substatusesItem2.DisplayStatus;
}
if (substatusesItem2.Message != null)
{
instanceViewStatusValue6["message"] = substatusesItem2.Message;
}
if (substatusesItem2.Time != null)
{
instanceViewStatusValue6["time"] = substatusesItem2.Time.Value;
}
}
instanceViewValue2["substatuses"] = substatusesArray2;
}
}
if (resourcesItem.InstanceView.Statuses != null)
{
JArray statusesArray5 = new JArray();
foreach (InstanceViewStatus statusesItem5 in resourcesItem.InstanceView.Statuses)
{
JObject instanceViewStatusValue7 = new JObject();
statusesArray5.Add(instanceViewStatusValue7);
if (statusesItem5.Code != null)
{
instanceViewStatusValue7["code"] = statusesItem5.Code;
}
if (statusesItem5.Level != null)
{
instanceViewStatusValue7["level"] = statusesItem5.Level;
}
if (statusesItem5.DisplayStatus != null)
{
instanceViewStatusValue7["displayStatus"] = statusesItem5.DisplayStatus;
}
if (statusesItem5.Message != null)
{
instanceViewStatusValue7["message"] = statusesItem5.Message;
}
if (statusesItem5.Time != null)
{
instanceViewStatusValue7["time"] = statusesItem5.Time.Value;
}
}
instanceViewValue2["statuses"] = statusesArray5;
}
}
if (resourcesItem.Id != null)
{
virtualMachineExtensionJsonValue["id"] = resourcesItem.Id;
}
if (resourcesItem.Name != null)
{
virtualMachineExtensionJsonValue["name"] = resourcesItem.Name;
}
if (resourcesItem.Type != null)
{
virtualMachineExtensionJsonValue["type"] = resourcesItem.Type;
}
virtualMachineExtensionJsonValue["location"] = resourcesItem.Location;
if (resourcesItem.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in resourcesItem.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
virtualMachineExtensionJsonValue["tags"] = tagsDictionary;
}
}
virtualMachineJsonValue["resources"] = resourcesArray;
}
if (parameters.Id != null)
{
virtualMachineJsonValue["id"] = parameters.Id;
}
if (parameters.Name != null)
{
virtualMachineJsonValue["name"] = parameters.Name;
}
if (parameters.Type != null)
{
virtualMachineJsonValue["type"] = parameters.Type;
}
virtualMachineJsonValue["location"] = parameters.Location;
if (parameters.Tags != null)
{
JObject tagsDictionary2 = new JObject();
foreach (KeyValuePair<string, string> pair2 in parameters.Tags)
{
string tagsKey2 = pair2.Key;
string tagsValue2 = pair2.Value;
tagsDictionary2[tagsKey2] = tagsValue2;
}
virtualMachineJsonValue["tags"] = tagsDictionary2;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
VirtualMachine virtualMachineInstance = new VirtualMachine();
result.VirtualMachine = virtualMachineInstance;
JToken planValue2 = responseDoc["plan"];
if (planValue2 != null && planValue2.Type != JTokenType.Null)
{
Plan planInstance = new Plan();
virtualMachineInstance.Plan = planInstance;
JToken nameValue = planValue2["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
planInstance.Name = nameInstance;
}
JToken publisherValue = planValue2["publisher"];
if (publisherValue != null && publisherValue.Type != JTokenType.Null)
{
string publisherInstance = ((string)publisherValue);
planInstance.Publisher = publisherInstance;
}
JToken productValue = planValue2["product"];
if (productValue != null && productValue.Type != JTokenType.Null)
{
string productInstance = ((string)productValue);
planInstance.Product = productInstance;
}
JToken promotionCodeValue = planValue2["promotionCode"];
if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
{
string promotionCodeInstance = ((string)promotionCodeValue);
planInstance.PromotionCode = promotionCodeInstance;
}
}
JToken propertiesValue4 = responseDoc["properties"];
if (propertiesValue4 != null && propertiesValue4.Type != JTokenType.Null)
{
JToken hardwareProfileValue2 = propertiesValue4["hardwareProfile"];
if (hardwareProfileValue2 != null && hardwareProfileValue2.Type != JTokenType.Null)
{
HardwareProfile hardwareProfileInstance = new HardwareProfile();
virtualMachineInstance.HardwareProfile = hardwareProfileInstance;
JToken vmSizeValue = hardwareProfileValue2["vmSize"];
if (vmSizeValue != null && vmSizeValue.Type != JTokenType.Null)
{
string vmSizeInstance = ((string)vmSizeValue);
hardwareProfileInstance.VirtualMachineSize = vmSizeInstance;
}
}
JToken storageProfileValue2 = propertiesValue4["storageProfile"];
if (storageProfileValue2 != null && storageProfileValue2.Type != JTokenType.Null)
{
StorageProfile storageProfileInstance = new StorageProfile();
virtualMachineInstance.StorageProfile = storageProfileInstance;
JToken imageReferenceValue2 = storageProfileValue2["imageReference"];
if (imageReferenceValue2 != null && imageReferenceValue2.Type != JTokenType.Null)
{
ImageReference imageReferenceInstance = new ImageReference();
storageProfileInstance.ImageReference = imageReferenceInstance;
JToken publisherValue2 = imageReferenceValue2["publisher"];
if (publisherValue2 != null && publisherValue2.Type != JTokenType.Null)
{
string publisherInstance2 = ((string)publisherValue2);
imageReferenceInstance.Publisher = publisherInstance2;
}
JToken offerValue = imageReferenceValue2["offer"];
if (offerValue != null && offerValue.Type != JTokenType.Null)
{
string offerInstance = ((string)offerValue);
imageReferenceInstance.Offer = offerInstance;
}
JToken skuValue = imageReferenceValue2["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
string skuInstance = ((string)skuValue);
imageReferenceInstance.Sku = skuInstance;
}
JToken versionValue = imageReferenceValue2["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
imageReferenceInstance.Version = versionInstance;
}
}
JToken osDiskValue2 = storageProfileValue2["osDisk"];
if (osDiskValue2 != null && osDiskValue2.Type != JTokenType.Null)
{
OSDisk osDiskInstance = new OSDisk();
storageProfileInstance.OSDisk = osDiskInstance;
JToken osTypeValue = osDiskValue2["osType"];
if (osTypeValue != null && osTypeValue.Type != JTokenType.Null)
{
string osTypeInstance = ((string)osTypeValue);
osDiskInstance.OperatingSystemType = osTypeInstance;
}
JToken nameValue2 = osDiskValue2["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
osDiskInstance.Name = nameInstance2;
}
JToken vhdValue3 = osDiskValue2["vhd"];
if (vhdValue3 != null && vhdValue3.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance = new VirtualHardDisk();
osDiskInstance.VirtualHardDisk = vhdInstance;
JToken uriValue = vhdValue3["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
vhdInstance.Uri = uriInstance;
}
}
JToken imageValue3 = osDiskValue2["image"];
if (imageValue3 != null && imageValue3.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance = new VirtualHardDisk();
osDiskInstance.SourceImage = imageInstance;
JToken uriValue2 = imageValue3["uri"];
if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
{
string uriInstance2 = ((string)uriValue2);
imageInstance.Uri = uriInstance2;
}
}
JToken cachingValue = osDiskValue2["caching"];
if (cachingValue != null && cachingValue.Type != JTokenType.Null)
{
string cachingInstance = ((string)cachingValue);
osDiskInstance.Caching = cachingInstance;
}
JToken createOptionValue = osDiskValue2["createOption"];
if (createOptionValue != null && createOptionValue.Type != JTokenType.Null)
{
string createOptionInstance = ((string)createOptionValue);
osDiskInstance.CreateOption = createOptionInstance;
}
JToken diskSizeGBValue = osDiskValue2["diskSizeGB"];
if (diskSizeGBValue != null && diskSizeGBValue.Type != JTokenType.Null)
{
int diskSizeGBInstance = ((int)diskSizeGBValue);
osDiskInstance.DiskSizeGB = diskSizeGBInstance;
}
}
JToken dataDisksArray2 = storageProfileValue2["dataDisks"];
if (dataDisksArray2 != null && dataDisksArray2.Type != JTokenType.Null)
{
foreach (JToken dataDisksValue in ((JArray)dataDisksArray2))
{
DataDisk dataDiskInstance = new DataDisk();
storageProfileInstance.DataDisks.Add(dataDiskInstance);
JToken lunValue = dataDisksValue["lun"];
if (lunValue != null && lunValue.Type != JTokenType.Null)
{
int lunInstance = ((int)lunValue);
dataDiskInstance.Lun = lunInstance;
}
JToken nameValue3 = dataDisksValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dataDiskInstance.Name = nameInstance3;
}
JToken vhdValue4 = dataDisksValue["vhd"];
if (vhdValue4 != null && vhdValue4.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance2 = new VirtualHardDisk();
dataDiskInstance.VirtualHardDisk = vhdInstance2;
JToken uriValue3 = vhdValue4["uri"];
if (uriValue3 != null && uriValue3.Type != JTokenType.Null)
{
string uriInstance3 = ((string)uriValue3);
vhdInstance2.Uri = uriInstance3;
}
}
JToken imageValue4 = dataDisksValue["image"];
if (imageValue4 != null && imageValue4.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance2 = new VirtualHardDisk();
dataDiskInstance.SourceImage = imageInstance2;
JToken uriValue4 = imageValue4["uri"];
if (uriValue4 != null && uriValue4.Type != JTokenType.Null)
{
string uriInstance4 = ((string)uriValue4);
imageInstance2.Uri = uriInstance4;
}
}
JToken cachingValue2 = dataDisksValue["caching"];
if (cachingValue2 != null && cachingValue2.Type != JTokenType.Null)
{
string cachingInstance2 = ((string)cachingValue2);
dataDiskInstance.Caching = cachingInstance2;
}
JToken createOptionValue2 = dataDisksValue["createOption"];
if (createOptionValue2 != null && createOptionValue2.Type != JTokenType.Null)
{
string createOptionInstance2 = ((string)createOptionValue2);
dataDiskInstance.CreateOption = createOptionInstance2;
}
JToken diskSizeGBValue2 = dataDisksValue["diskSizeGB"];
if (diskSizeGBValue2 != null && diskSizeGBValue2.Type != JTokenType.Null)
{
int diskSizeGBInstance2 = ((int)diskSizeGBValue2);
dataDiskInstance.DiskSizeGB = diskSizeGBInstance2;
}
}
}
}
JToken osProfileValue2 = propertiesValue4["osProfile"];
if (osProfileValue2 != null && osProfileValue2.Type != JTokenType.Null)
{
OSProfile osProfileInstance = new OSProfile();
virtualMachineInstance.OSProfile = osProfileInstance;
JToken computerNameValue = osProfileValue2["computerName"];
if (computerNameValue != null && computerNameValue.Type != JTokenType.Null)
{
string computerNameInstance = ((string)computerNameValue);
osProfileInstance.ComputerName = computerNameInstance;
}
JToken adminUsernameValue = osProfileValue2["adminUsername"];
if (adminUsernameValue != null && adminUsernameValue.Type != JTokenType.Null)
{
string adminUsernameInstance = ((string)adminUsernameValue);
osProfileInstance.AdminUsername = adminUsernameInstance;
}
JToken adminPasswordValue = osProfileValue2["adminPassword"];
if (adminPasswordValue != null && adminPasswordValue.Type != JTokenType.Null)
{
string adminPasswordInstance = ((string)adminPasswordValue);
osProfileInstance.AdminPassword = adminPasswordInstance;
}
JToken customDataValue = osProfileValue2["customData"];
if (customDataValue != null && customDataValue.Type != JTokenType.Null)
{
string customDataInstance = ((string)customDataValue);
osProfileInstance.CustomData = customDataInstance;
}
JToken windowsConfigurationValue2 = osProfileValue2["windowsConfiguration"];
if (windowsConfigurationValue2 != null && windowsConfigurationValue2.Type != JTokenType.Null)
{
WindowsConfiguration windowsConfigurationInstance = new WindowsConfiguration();
osProfileInstance.WindowsConfiguration = windowsConfigurationInstance;
JToken provisionVMAgentValue = windowsConfigurationValue2["provisionVMAgent"];
if (provisionVMAgentValue != null && provisionVMAgentValue.Type != JTokenType.Null)
{
bool provisionVMAgentInstance = ((bool)provisionVMAgentValue);
windowsConfigurationInstance.ProvisionVMAgent = provisionVMAgentInstance;
}
JToken enableAutomaticUpdatesValue = windowsConfigurationValue2["enableAutomaticUpdates"];
if (enableAutomaticUpdatesValue != null && enableAutomaticUpdatesValue.Type != JTokenType.Null)
{
bool enableAutomaticUpdatesInstance = ((bool)enableAutomaticUpdatesValue);
windowsConfigurationInstance.EnableAutomaticUpdates = enableAutomaticUpdatesInstance;
}
JToken timeZoneValue = windowsConfigurationValue2["timeZone"];
if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
{
string timeZoneInstance = ((string)timeZoneValue);
windowsConfigurationInstance.TimeZone = timeZoneInstance;
}
JToken additionalUnattendContentArray2 = windowsConfigurationValue2["additionalUnattendContent"];
if (additionalUnattendContentArray2 != null && additionalUnattendContentArray2.Type != JTokenType.Null)
{
foreach (JToken additionalUnattendContentValue2 in ((JArray)additionalUnattendContentArray2))
{
AdditionalUnattendContent additionalUnattendContentInstance = new AdditionalUnattendContent();
windowsConfigurationInstance.AdditionalUnattendContents.Add(additionalUnattendContentInstance);
JToken passNameValue = additionalUnattendContentValue2["passName"];
if (passNameValue != null && passNameValue.Type != JTokenType.Null)
{
string passNameInstance = ((string)passNameValue);
additionalUnattendContentInstance.PassName = passNameInstance;
}
JToken componentNameValue = additionalUnattendContentValue2["componentName"];
if (componentNameValue != null && componentNameValue.Type != JTokenType.Null)
{
string componentNameInstance = ((string)componentNameValue);
additionalUnattendContentInstance.ComponentName = componentNameInstance;
}
JToken settingNameValue = additionalUnattendContentValue2["settingName"];
if (settingNameValue != null && settingNameValue.Type != JTokenType.Null)
{
string settingNameInstance = ((string)settingNameValue);
additionalUnattendContentInstance.SettingName = settingNameInstance;
}
JToken contentValue = additionalUnattendContentValue2["content"];
if (contentValue != null && contentValue.Type != JTokenType.Null)
{
string contentInstance = ((string)contentValue);
additionalUnattendContentInstance.Content = contentInstance;
}
}
}
JToken winRMValue2 = windowsConfigurationValue2["winRM"];
if (winRMValue2 != null && winRMValue2.Type != JTokenType.Null)
{
WinRMConfiguration winRMInstance = new WinRMConfiguration();
windowsConfigurationInstance.WinRMConfiguration = winRMInstance;
JToken listenersArray2 = winRMValue2["listeners"];
if (listenersArray2 != null && listenersArray2.Type != JTokenType.Null)
{
foreach (JToken listenersValue in ((JArray)listenersArray2))
{
WinRMListener winRMListenerInstance = new WinRMListener();
winRMInstance.Listeners.Add(winRMListenerInstance);
JToken protocolValue = listenersValue["protocol"];
if (protocolValue != null && protocolValue.Type != JTokenType.Null)
{
string protocolInstance = ((string)protocolValue);
winRMListenerInstance.Protocol = protocolInstance;
}
JToken certificateUrlValue = listenersValue["certificateUrl"];
if (certificateUrlValue != null && certificateUrlValue.Type != JTokenType.Null)
{
Uri certificateUrlInstance = TypeConversion.TryParseUri(((string)certificateUrlValue));
winRMListenerInstance.CertificateUrl = certificateUrlInstance;
}
}
}
}
}
JToken linuxConfigurationValue2 = osProfileValue2["linuxConfiguration"];
if (linuxConfigurationValue2 != null && linuxConfigurationValue2.Type != JTokenType.Null)
{
LinuxConfiguration linuxConfigurationInstance = new LinuxConfiguration();
osProfileInstance.LinuxConfiguration = linuxConfigurationInstance;
JToken disablePasswordAuthenticationValue = linuxConfigurationValue2["disablePasswordAuthentication"];
if (disablePasswordAuthenticationValue != null && disablePasswordAuthenticationValue.Type != JTokenType.Null)
{
bool disablePasswordAuthenticationInstance = ((bool)disablePasswordAuthenticationValue);
linuxConfigurationInstance.DisablePasswordAuthentication = disablePasswordAuthenticationInstance;
}
JToken sshValue2 = linuxConfigurationValue2["ssh"];
if (sshValue2 != null && sshValue2.Type != JTokenType.Null)
{
SshConfiguration sshInstance = new SshConfiguration();
linuxConfigurationInstance.SshConfiguration = sshInstance;
JToken publicKeysArray2 = sshValue2["publicKeys"];
if (publicKeysArray2 != null && publicKeysArray2.Type != JTokenType.Null)
{
foreach (JToken publicKeysValue in ((JArray)publicKeysArray2))
{
SshPublicKey sshPublicKeyInstance = new SshPublicKey();
sshInstance.PublicKeys.Add(sshPublicKeyInstance);
JToken pathValue = publicKeysValue["path"];
if (pathValue != null && pathValue.Type != JTokenType.Null)
{
string pathInstance = ((string)pathValue);
sshPublicKeyInstance.Path = pathInstance;
}
JToken keyDataValue = publicKeysValue["keyData"];
if (keyDataValue != null && keyDataValue.Type != JTokenType.Null)
{
string keyDataInstance = ((string)keyDataValue);
sshPublicKeyInstance.KeyData = keyDataInstance;
}
}
}
}
}
JToken secretsArray2 = osProfileValue2["secrets"];
if (secretsArray2 != null && secretsArray2.Type != JTokenType.Null)
{
foreach (JToken secretsValue in ((JArray)secretsArray2))
{
VaultSecretGroup vaultSecretGroupInstance = new VaultSecretGroup();
osProfileInstance.Secrets.Add(vaultSecretGroupInstance);
JToken sourceVaultValue2 = secretsValue["sourceVault"];
if (sourceVaultValue2 != null && sourceVaultValue2.Type != JTokenType.Null)
{
SourceVaultReference sourceVaultInstance = new SourceVaultReference();
vaultSecretGroupInstance.SourceVault = sourceVaultInstance;
JToken idValue = sourceVaultValue2["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
sourceVaultInstance.ReferenceUri = idInstance;
}
}
JToken vaultCertificatesArray2 = secretsValue["vaultCertificates"];
if (vaultCertificatesArray2 != null && vaultCertificatesArray2.Type != JTokenType.Null)
{
foreach (JToken vaultCertificatesValue in ((JArray)vaultCertificatesArray2))
{
VaultCertificate vaultCertificateInstance = new VaultCertificate();
vaultSecretGroupInstance.VaultCertificates.Add(vaultCertificateInstance);
JToken certificateUrlValue2 = vaultCertificatesValue["certificateUrl"];
if (certificateUrlValue2 != null && certificateUrlValue2.Type != JTokenType.Null)
{
string certificateUrlInstance2 = ((string)certificateUrlValue2);
vaultCertificateInstance.CertificateUrl = certificateUrlInstance2;
}
JToken certificateStoreValue = vaultCertificatesValue["certificateStore"];
if (certificateStoreValue != null && certificateStoreValue.Type != JTokenType.Null)
{
string certificateStoreInstance = ((string)certificateStoreValue);
vaultCertificateInstance.CertificateStore = certificateStoreInstance;
}
}
}
}
}
}
JToken networkProfileValue2 = propertiesValue4["networkProfile"];
if (networkProfileValue2 != null && networkProfileValue2.Type != JTokenType.Null)
{
NetworkProfile networkProfileInstance = new NetworkProfile();
virtualMachineInstance.NetworkProfile = networkProfileInstance;
JToken networkInterfacesArray2 = networkProfileValue2["networkInterfaces"];
if (networkInterfacesArray2 != null && networkInterfacesArray2.Type != JTokenType.Null)
{
foreach (JToken networkInterfacesValue in ((JArray)networkInterfacesArray2))
{
NetworkInterfaceReference networkInterfaceReferenceJsonInstance = new NetworkInterfaceReference();
networkProfileInstance.NetworkInterfaces.Add(networkInterfaceReferenceJsonInstance);
JToken propertiesValue5 = networkInterfacesValue["properties"];
if (propertiesValue5 != null && propertiesValue5.Type != JTokenType.Null)
{
JToken primaryValue = propertiesValue5["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
bool primaryInstance = ((bool)primaryValue);
networkInterfaceReferenceJsonInstance.Primary = primaryInstance;
}
}
JToken idValue2 = networkInterfacesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
networkInterfaceReferenceJsonInstance.ReferenceUri = idInstance2;
}
}
}
}
JToken availabilitySetValue2 = propertiesValue4["availabilitySet"];
if (availabilitySetValue2 != null && availabilitySetValue2.Type != JTokenType.Null)
{
AvailabilitySetReference availabilitySetInstance = new AvailabilitySetReference();
virtualMachineInstance.AvailabilitySetReference = availabilitySetInstance;
JToken idValue3 = availabilitySetValue2["id"];
if (idValue3 != null && idValue3.Type != JTokenType.Null)
{
string idInstance3 = ((string)idValue3);
availabilitySetInstance.ReferenceUri = idInstance3;
}
}
JToken provisioningStateValue = propertiesValue4["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
virtualMachineInstance.ProvisioningState = provisioningStateInstance;
}
JToken instanceViewValue3 = propertiesValue4["instanceView"];
if (instanceViewValue3 != null && instanceViewValue3.Type != JTokenType.Null)
{
VirtualMachineInstanceView instanceViewInstance = new VirtualMachineInstanceView();
virtualMachineInstance.InstanceView = instanceViewInstance;
JToken platformUpdateDomainValue = instanceViewValue3["platformUpdateDomain"];
if (platformUpdateDomainValue != null && platformUpdateDomainValue.Type != JTokenType.Null)
{
int platformUpdateDomainInstance = ((int)platformUpdateDomainValue);
instanceViewInstance.PlatformUpdateDomain = platformUpdateDomainInstance;
}
JToken platformFaultDomainValue = instanceViewValue3["platformFaultDomain"];
if (platformFaultDomainValue != null && platformFaultDomainValue.Type != JTokenType.Null)
{
int platformFaultDomainInstance = ((int)platformFaultDomainValue);
instanceViewInstance.PlatformFaultDomain = platformFaultDomainInstance;
}
JToken rdpThumbPrintValue = instanceViewValue3["rdpThumbPrint"];
if (rdpThumbPrintValue != null && rdpThumbPrintValue.Type != JTokenType.Null)
{
string rdpThumbPrintInstance = ((string)rdpThumbPrintValue);
instanceViewInstance.RemoteDesktopThumbprint = rdpThumbPrintInstance;
}
JToken vmAgentValue2 = instanceViewValue3["vmAgent"];
if (vmAgentValue2 != null && vmAgentValue2.Type != JTokenType.Null)
{
VirtualMachineAgentInstanceView vmAgentInstance = new VirtualMachineAgentInstanceView();
instanceViewInstance.VMAgent = vmAgentInstance;
JToken vmAgentVersionValue = vmAgentValue2["vmAgentVersion"];
if (vmAgentVersionValue != null && vmAgentVersionValue.Type != JTokenType.Null)
{
string vmAgentVersionInstance = ((string)vmAgentVersionValue);
vmAgentInstance.VMAgentVersion = vmAgentVersionInstance;
}
JToken extensionHandlersArray2 = vmAgentValue2["extensionHandlers"];
if (extensionHandlersArray2 != null && extensionHandlersArray2.Type != JTokenType.Null)
{
foreach (JToken extensionHandlersValue in ((JArray)extensionHandlersArray2))
{
VirtualMachineExtensionHandlerInstanceView virtualMachineExtensionHandlerInstanceViewInstance = new VirtualMachineExtensionHandlerInstanceView();
vmAgentInstance.ExtensionHandlers.Add(virtualMachineExtensionHandlerInstanceViewInstance);
JToken typeValue = extensionHandlersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
virtualMachineExtensionHandlerInstanceViewInstance.Type = typeInstance;
}
JToken typeHandlerVersionValue = extensionHandlersValue["typeHandlerVersion"];
if (typeHandlerVersionValue != null && typeHandlerVersionValue.Type != JTokenType.Null)
{
string typeHandlerVersionInstance = ((string)typeHandlerVersionValue);
virtualMachineExtensionHandlerInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance;
}
JToken statusValue2 = extensionHandlersValue["status"];
if (statusValue2 != null && statusValue2.Type != JTokenType.Null)
{
InstanceViewStatus statusInstance = new InstanceViewStatus();
virtualMachineExtensionHandlerInstanceViewInstance.Status = statusInstance;
JToken codeValue = statusValue2["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
statusInstance.Code = codeInstance;
}
JToken levelValue = statusValue2["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
statusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusValue2["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
statusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusValue2["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
statusInstance.Message = messageInstance;
}
JToken timeValue = statusValue2["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
statusInstance.Time = timeInstance;
}
}
}
}
JToken statusesArray6 = vmAgentValue2["statuses"];
if (statusesArray6 != null && statusesArray6.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray6))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
vmAgentInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue2 = statusesValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
instanceViewStatusInstance.Code = codeInstance2;
}
JToken levelValue2 = statusesValue["level"];
if (levelValue2 != null && levelValue2.Type != JTokenType.Null)
{
string levelInstance2 = ((string)levelValue2);
instanceViewStatusInstance.Level = levelInstance2;
}
JToken displayStatusValue2 = statusesValue["displayStatus"];
if (displayStatusValue2 != null && displayStatusValue2.Type != JTokenType.Null)
{
string displayStatusInstance2 = ((string)displayStatusValue2);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance2;
}
JToken messageValue2 = statusesValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
instanceViewStatusInstance.Message = messageInstance2;
}
JToken timeValue2 = statusesValue["time"];
if (timeValue2 != null && timeValue2.Type != JTokenType.Null)
{
DateTimeOffset timeInstance2 = ((DateTimeOffset)timeValue2);
instanceViewStatusInstance.Time = timeInstance2;
}
}
}
}
JToken disksArray2 = instanceViewValue3["disks"];
if (disksArray2 != null && disksArray2.Type != JTokenType.Null)
{
foreach (JToken disksValue in ((JArray)disksArray2))
{
DiskInstanceView diskInstanceViewInstance = new DiskInstanceView();
instanceViewInstance.Disks.Add(diskInstanceViewInstance);
JToken nameValue4 = disksValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
diskInstanceViewInstance.Name = nameInstance4;
}
JToken statusesArray7 = disksValue["statuses"];
if (statusesArray7 != null && statusesArray7.Type != JTokenType.Null)
{
foreach (JToken statusesValue2 in ((JArray)statusesArray7))
{
InstanceViewStatus instanceViewStatusInstance2 = new InstanceViewStatus();
diskInstanceViewInstance.Statuses.Add(instanceViewStatusInstance2);
JToken codeValue3 = statusesValue2["code"];
if (codeValue3 != null && codeValue3.Type != JTokenType.Null)
{
string codeInstance3 = ((string)codeValue3);
instanceViewStatusInstance2.Code = codeInstance3;
}
JToken levelValue3 = statusesValue2["level"];
if (levelValue3 != null && levelValue3.Type != JTokenType.Null)
{
string levelInstance3 = ((string)levelValue3);
instanceViewStatusInstance2.Level = levelInstance3;
}
JToken displayStatusValue3 = statusesValue2["displayStatus"];
if (displayStatusValue3 != null && displayStatusValue3.Type != JTokenType.Null)
{
string displayStatusInstance3 = ((string)displayStatusValue3);
instanceViewStatusInstance2.DisplayStatus = displayStatusInstance3;
}
JToken messageValue3 = statusesValue2["message"];
if (messageValue3 != null && messageValue3.Type != JTokenType.Null)
{
string messageInstance3 = ((string)messageValue3);
instanceViewStatusInstance2.Message = messageInstance3;
}
JToken timeValue3 = statusesValue2["time"];
if (timeValue3 != null && timeValue3.Type != JTokenType.Null)
{
DateTimeOffset timeInstance3 = ((DateTimeOffset)timeValue3);
instanceViewStatusInstance2.Time = timeInstance3;
}
}
}
}
}
JToken extensionsArray2 = instanceViewValue3["extensions"];
if (extensionsArray2 != null && extensionsArray2.Type != JTokenType.Null)
{
foreach (JToken extensionsValue in ((JArray)extensionsArray2))
{
VirtualMachineExtensionInstanceView virtualMachineExtensionInstanceViewInstance = new VirtualMachineExtensionInstanceView();
instanceViewInstance.Extensions.Add(virtualMachineExtensionInstanceViewInstance);
JToken nameValue5 = extensionsValue["name"];
if (nameValue5 != null && nameValue5.Type != JTokenType.Null)
{
string nameInstance5 = ((string)nameValue5);
virtualMachineExtensionInstanceViewInstance.Name = nameInstance5;
}
JToken typeValue2 = extensionsValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
virtualMachineExtensionInstanceViewInstance.ExtensionType = typeInstance2;
}
JToken typeHandlerVersionValue2 = extensionsValue["typeHandlerVersion"];
if (typeHandlerVersionValue2 != null && typeHandlerVersionValue2.Type != JTokenType.Null)
{
string typeHandlerVersionInstance2 = ((string)typeHandlerVersionValue2);
virtualMachineExtensionInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance2;
}
JToken substatusesArray3 = extensionsValue["substatuses"];
if (substatusesArray3 != null && substatusesArray3.Type != JTokenType.Null)
{
foreach (JToken substatusesValue in ((JArray)substatusesArray3))
{
InstanceViewStatus instanceViewStatusInstance3 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.SubStatuses.Add(instanceViewStatusInstance3);
JToken codeValue4 = substatusesValue["code"];
if (codeValue4 != null && codeValue4.Type != JTokenType.Null)
{
string codeInstance4 = ((string)codeValue4);
instanceViewStatusInstance3.Code = codeInstance4;
}
JToken levelValue4 = substatusesValue["level"];
if (levelValue4 != null && levelValue4.Type != JTokenType.Null)
{
string levelInstance4 = ((string)levelValue4);
instanceViewStatusInstance3.Level = levelInstance4;
}
JToken displayStatusValue4 = substatusesValue["displayStatus"];
if (displayStatusValue4 != null && displayStatusValue4.Type != JTokenType.Null)
{
string displayStatusInstance4 = ((string)displayStatusValue4);
instanceViewStatusInstance3.DisplayStatus = displayStatusInstance4;
}
JToken messageValue4 = substatusesValue["message"];
if (messageValue4 != null && messageValue4.Type != JTokenType.Null)
{
string messageInstance4 = ((string)messageValue4);
instanceViewStatusInstance3.Message = messageInstance4;
}
JToken timeValue4 = substatusesValue["time"];
if (timeValue4 != null && timeValue4.Type != JTokenType.Null)
{
DateTimeOffset timeInstance4 = ((DateTimeOffset)timeValue4);
instanceViewStatusInstance3.Time = timeInstance4;
}
}
}
JToken statusesArray8 = extensionsValue["statuses"];
if (statusesArray8 != null && statusesArray8.Type != JTokenType.Null)
{
foreach (JToken statusesValue3 in ((JArray)statusesArray8))
{
InstanceViewStatus instanceViewStatusInstance4 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.Statuses.Add(instanceViewStatusInstance4);
JToken codeValue5 = statusesValue3["code"];
if (codeValue5 != null && codeValue5.Type != JTokenType.Null)
{
string codeInstance5 = ((string)codeValue5);
instanceViewStatusInstance4.Code = codeInstance5;
}
JToken levelValue5 = statusesValue3["level"];
if (levelValue5 != null && levelValue5.Type != JTokenType.Null)
{
string levelInstance5 = ((string)levelValue5);
instanceViewStatusInstance4.Level = levelInstance5;
}
JToken displayStatusValue5 = statusesValue3["displayStatus"];
if (displayStatusValue5 != null && displayStatusValue5.Type != JTokenType.Null)
{
string displayStatusInstance5 = ((string)displayStatusValue5);
instanceViewStatusInstance4.DisplayStatus = displayStatusInstance5;
}
JToken messageValue5 = statusesValue3["message"];
if (messageValue5 != null && messageValue5.Type != JTokenType.Null)
{
string messageInstance5 = ((string)messageValue5);
instanceViewStatusInstance4.Message = messageInstance5;
}
JToken timeValue5 = statusesValue3["time"];
if (timeValue5 != null && timeValue5.Type != JTokenType.Null)
{
DateTimeOffset timeInstance5 = ((DateTimeOffset)timeValue5);
instanceViewStatusInstance4.Time = timeInstance5;
}
}
}
}
}
JToken statusesArray9 = instanceViewValue3["statuses"];
if (statusesArray9 != null && statusesArray9.Type != JTokenType.Null)
{
foreach (JToken statusesValue4 in ((JArray)statusesArray9))
{
InstanceViewStatus instanceViewStatusInstance5 = new InstanceViewStatus();
instanceViewInstance.Statuses.Add(instanceViewStatusInstance5);
JToken codeValue6 = statusesValue4["code"];
if (codeValue6 != null && codeValue6.Type != JTokenType.Null)
{
string codeInstance6 = ((string)codeValue6);
instanceViewStatusInstance5.Code = codeInstance6;
}
JToken levelValue6 = statusesValue4["level"];
if (levelValue6 != null && levelValue6.Type != JTokenType.Null)
{
string levelInstance6 = ((string)levelValue6);
instanceViewStatusInstance5.Level = levelInstance6;
}
JToken displayStatusValue6 = statusesValue4["displayStatus"];
if (displayStatusValue6 != null && displayStatusValue6.Type != JTokenType.Null)
{
string displayStatusInstance6 = ((string)displayStatusValue6);
instanceViewStatusInstance5.DisplayStatus = displayStatusInstance6;
}
JToken messageValue6 = statusesValue4["message"];
if (messageValue6 != null && messageValue6.Type != JTokenType.Null)
{
string messageInstance6 = ((string)messageValue6);
instanceViewStatusInstance5.Message = messageInstance6;
}
JToken timeValue6 = statusesValue4["time"];
if (timeValue6 != null && timeValue6.Type != JTokenType.Null)
{
DateTimeOffset timeInstance6 = ((DateTimeOffset)timeValue6);
instanceViewStatusInstance5.Time = timeInstance6;
}
}
}
}
}
JToken resourcesArray2 = responseDoc["resources"];
if (resourcesArray2 != null && resourcesArray2.Type != JTokenType.Null)
{
virtualMachineInstance.Extensions = new List<VirtualMachineExtension>();
foreach (JToken resourcesValue in ((JArray)resourcesArray2))
{
VirtualMachineExtension virtualMachineExtensionJsonInstance = new VirtualMachineExtension();
virtualMachineInstance.Extensions.Add(virtualMachineExtensionJsonInstance);
JToken propertiesValue6 = resourcesValue["properties"];
if (propertiesValue6 != null && propertiesValue6.Type != JTokenType.Null)
{
JToken publisherValue3 = propertiesValue6["publisher"];
if (publisherValue3 != null && publisherValue3.Type != JTokenType.Null)
{
string publisherInstance3 = ((string)publisherValue3);
virtualMachineExtensionJsonInstance.Publisher = publisherInstance3;
}
JToken typeValue3 = propertiesValue6["type"];
if (typeValue3 != null && typeValue3.Type != JTokenType.Null)
{
string typeInstance3 = ((string)typeValue3);
virtualMachineExtensionJsonInstance.ExtensionType = typeInstance3;
}
JToken typeHandlerVersionValue3 = propertiesValue6["typeHandlerVersion"];
if (typeHandlerVersionValue3 != null && typeHandlerVersionValue3.Type != JTokenType.Null)
{
string typeHandlerVersionInstance3 = ((string)typeHandlerVersionValue3);
virtualMachineExtensionJsonInstance.TypeHandlerVersion = typeHandlerVersionInstance3;
}
JToken autoUpgradeMinorVersionValue = propertiesValue6["autoUpgradeMinorVersion"];
if (autoUpgradeMinorVersionValue != null && autoUpgradeMinorVersionValue.Type != JTokenType.Null)
{
bool autoUpgradeMinorVersionInstance = ((bool)autoUpgradeMinorVersionValue);
virtualMachineExtensionJsonInstance.AutoUpgradeMinorVersion = autoUpgradeMinorVersionInstance;
}
JToken settingsValue = propertiesValue6["settings"];
if (settingsValue != null && settingsValue.Type != JTokenType.Null)
{
string settingsInstance = settingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.Settings = settingsInstance;
}
JToken protectedSettingsValue = propertiesValue6["protectedSettings"];
if (protectedSettingsValue != null && protectedSettingsValue.Type != JTokenType.Null)
{
string protectedSettingsInstance = protectedSettingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.ProtectedSettings = protectedSettingsInstance;
}
JToken provisioningStateValue2 = propertiesValue6["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
virtualMachineExtensionJsonInstance.ProvisioningState = provisioningStateInstance2;
}
JToken instanceViewValue4 = propertiesValue6["instanceView"];
if (instanceViewValue4 != null && instanceViewValue4.Type != JTokenType.Null)
{
VirtualMachineExtensionInstanceView instanceViewInstance2 = new VirtualMachineExtensionInstanceView();
virtualMachineExtensionJsonInstance.InstanceView = instanceViewInstance2;
JToken nameValue6 = instanceViewValue4["name"];
if (nameValue6 != null && nameValue6.Type != JTokenType.Null)
{
string nameInstance6 = ((string)nameValue6);
instanceViewInstance2.Name = nameInstance6;
}
JToken typeValue4 = instanceViewValue4["type"];
if (typeValue4 != null && typeValue4.Type != JTokenType.Null)
{
string typeInstance4 = ((string)typeValue4);
instanceViewInstance2.ExtensionType = typeInstance4;
}
JToken typeHandlerVersionValue4 = instanceViewValue4["typeHandlerVersion"];
if (typeHandlerVersionValue4 != null && typeHandlerVersionValue4.Type != JTokenType.Null)
{
string typeHandlerVersionInstance4 = ((string)typeHandlerVersionValue4);
instanceViewInstance2.TypeHandlerVersion = typeHandlerVersionInstance4;
}
JToken substatusesArray4 = instanceViewValue4["substatuses"];
if (substatusesArray4 != null && substatusesArray4.Type != JTokenType.Null)
{
foreach (JToken substatusesValue2 in ((JArray)substatusesArray4))
{
InstanceViewStatus instanceViewStatusInstance6 = new InstanceViewStatus();
instanceViewInstance2.SubStatuses.Add(instanceViewStatusInstance6);
JToken codeValue7 = substatusesValue2["code"];
if (codeValue7 != null && codeValue7.Type != JTokenType.Null)
{
string codeInstance7 = ((string)codeValue7);
instanceViewStatusInstance6.Code = codeInstance7;
}
JToken levelValue7 = substatusesValue2["level"];
if (levelValue7 != null && levelValue7.Type != JTokenType.Null)
{
string levelInstance7 = ((string)levelValue7);
instanceViewStatusInstance6.Level = levelInstance7;
}
JToken displayStatusValue7 = substatusesValue2["displayStatus"];
if (displayStatusValue7 != null && displayStatusValue7.Type != JTokenType.Null)
{
string displayStatusInstance7 = ((string)displayStatusValue7);
instanceViewStatusInstance6.DisplayStatus = displayStatusInstance7;
}
JToken messageValue7 = substatusesValue2["message"];
if (messageValue7 != null && messageValue7.Type != JTokenType.Null)
{
string messageInstance7 = ((string)messageValue7);
instanceViewStatusInstance6.Message = messageInstance7;
}
JToken timeValue7 = substatusesValue2["time"];
if (timeValue7 != null && timeValue7.Type != JTokenType.Null)
{
DateTimeOffset timeInstance7 = ((DateTimeOffset)timeValue7);
instanceViewStatusInstance6.Time = timeInstance7;
}
}
}
JToken statusesArray10 = instanceViewValue4["statuses"];
if (statusesArray10 != null && statusesArray10.Type != JTokenType.Null)
{
foreach (JToken statusesValue5 in ((JArray)statusesArray10))
{
InstanceViewStatus instanceViewStatusInstance7 = new InstanceViewStatus();
instanceViewInstance2.Statuses.Add(instanceViewStatusInstance7);
JToken codeValue8 = statusesValue5["code"];
if (codeValue8 != null && codeValue8.Type != JTokenType.Null)
{
string codeInstance8 = ((string)codeValue8);
instanceViewStatusInstance7.Code = codeInstance8;
}
JToken levelValue8 = statusesValue5["level"];
if (levelValue8 != null && levelValue8.Type != JTokenType.Null)
{
string levelInstance8 = ((string)levelValue8);
instanceViewStatusInstance7.Level = levelInstance8;
}
JToken displayStatusValue8 = statusesValue5["displayStatus"];
if (displayStatusValue8 != null && displayStatusValue8.Type != JTokenType.Null)
{
string displayStatusInstance8 = ((string)displayStatusValue8);
instanceViewStatusInstance7.DisplayStatus = displayStatusInstance8;
}
JToken messageValue8 = statusesValue5["message"];
if (messageValue8 != null && messageValue8.Type != JTokenType.Null)
{
string messageInstance8 = ((string)messageValue8);
instanceViewStatusInstance7.Message = messageInstance8;
}
JToken timeValue8 = statusesValue5["time"];
if (timeValue8 != null && timeValue8.Type != JTokenType.Null)
{
DateTimeOffset timeInstance8 = ((DateTimeOffset)timeValue8);
instanceViewStatusInstance7.Time = timeInstance8;
}
}
}
}
}
JToken idValue4 = resourcesValue["id"];
if (idValue4 != null && idValue4.Type != JTokenType.Null)
{
string idInstance4 = ((string)idValue4);
virtualMachineExtensionJsonInstance.Id = idInstance4;
}
JToken nameValue7 = resourcesValue["name"];
if (nameValue7 != null && nameValue7.Type != JTokenType.Null)
{
string nameInstance7 = ((string)nameValue7);
virtualMachineExtensionJsonInstance.Name = nameInstance7;
}
JToken typeValue5 = resourcesValue["type"];
if (typeValue5 != null && typeValue5.Type != JTokenType.Null)
{
string typeInstance5 = ((string)typeValue5);
virtualMachineExtensionJsonInstance.Type = typeInstance5;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineExtensionJsonInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)resourcesValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey3 = ((string)property.Name);
string tagsValue3 = ((string)property.Value);
virtualMachineExtensionJsonInstance.Tags.Add(tagsKey3, tagsValue3);
}
}
}
}
JToken idValue5 = responseDoc["id"];
if (idValue5 != null && idValue5.Type != JTokenType.Null)
{
string idInstance5 = ((string)idValue5);
virtualMachineInstance.Id = idInstance5;
}
JToken nameValue8 = responseDoc["name"];
if (nameValue8 != null && nameValue8.Type != JTokenType.Null)
{
string nameInstance8 = ((string)nameValue8);
virtualMachineInstance.Name = nameInstance8;
}
JToken typeValue6 = responseDoc["type"];
if (typeValue6 != null && typeValue6.Type != JTokenType.Null)
{
string typeInstance6 = ((string)typeValue6);
virtualMachineInstance.Type = typeInstance6;
}
JToken locationValue2 = responseDoc["location"];
if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
{
string locationInstance2 = ((string)locationValue2);
virtualMachineInstance.Location = locationInstance2;
}
JToken tagsSequenceElement2 = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null)
{
foreach (JProperty property2 in tagsSequenceElement2)
{
string tagsKey4 = ((string)property2.Name);
string tagsValue4 = ((string)property2.Value);
virtualMachineInstance.Tags.Add(tagsKey4, tagsValue4);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources.
/// You are not billed for the compute resources that this Virtual
/// Machine uses.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The compute long running operation response.
/// </returns>
public async Task<ComputeOperationResponse> BeginDeallocatingAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "BeginDeallocatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
url = url + "/deallocate";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ComputeOperationResponse result = null;
// Deserialize Response
result = new ComputeOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The compute long running operation response.
/// </returns>
public async Task<DeleteOperationResponse> BeginDeletingAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DeleteOperationResponse result = null;
// Deserialize Response
result = new DeleteOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The compute long running operation response.
/// </returns>
public async Task<ComputeOperationResponse> BeginPoweringOffAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "BeginPoweringOffAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
url = url + "/powerOff";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ComputeOperationResponse result = null;
// Deserialize Response
result = new ComputeOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The compute long running operation response.
/// </returns>
public async Task<ComputeOperationResponse> BeginRestartingAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "BeginRestartingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
url = url + "/restart";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ComputeOperationResponse result = null;
// Deserialize Response
result = new ComputeOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The compute long running operation response.
/// </returns>
public async Task<ComputeOperationResponse> BeginStartingAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "BeginStartingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
url = url + "/start";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ComputeOperationResponse result = null;
// Deserialize Response
result = new ComputeOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Captures the VM by copying VirtualHardDisks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Capture Virtual Machine
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Compute service response for long-running operations.
/// </returns>
public async Task<ComputeLongRunningOperationResponse> CaptureAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CaptureAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ComputeOperationResponse response = await client.VirtualMachines.BeginCapturingAsync(resourceGroupName, vmName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ComputeLongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Compute.Models.ComputeOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Virtual Machine
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Compute service response for long-running operations.
/// </returns>
public async Task<ComputeLongRunningOperationResponse> CreateOrUpdateAsync(string resourceGroupName, VirtualMachine parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
VirtualMachineCreateOrUpdateResponse response = await client.VirtualMachines.BeginCreatingOrUpdatingAsync(resourceGroupName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ComputeLongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Compute.Models.ComputeOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources.
/// You are not billed for the compute resources that this Virtual
/// Machine uses.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Compute service response for long-running operations.
/// </returns>
public async Task<ComputeLongRunningOperationResponse> DeallocateAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "DeallocateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ComputeOperationResponse response = await client.VirtualMachines.BeginDeallocatingAsync(resourceGroupName, vmName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ComputeLongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Compute.Models.ComputeOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The compute long running operation response.
/// </returns>
public async Task<DeleteOperationResponse> DeleteAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
DeleteOperationResponse response = await client.VirtualMachines.BeginDeletingAsync(resourceGroupName, vmName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
DeleteOperationResponse result = await client.GetDeleteOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetDeleteOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Sets the state of the VM as Generalized.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> GeneralizeAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "GeneralizeAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
url = url + "/generalize";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to get a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The GetVM operation response.
/// </returns>
public async Task<VirtualMachineGetResponse> GetAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
VirtualMachine virtualMachineInstance = new VirtualMachine();
result.VirtualMachine = virtualMachineInstance;
JToken planValue = responseDoc["plan"];
if (planValue != null && planValue.Type != JTokenType.Null)
{
Plan planInstance = new Plan();
virtualMachineInstance.Plan = planInstance;
JToken nameValue = planValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
planInstance.Name = nameInstance;
}
JToken publisherValue = planValue["publisher"];
if (publisherValue != null && publisherValue.Type != JTokenType.Null)
{
string publisherInstance = ((string)publisherValue);
planInstance.Publisher = publisherInstance;
}
JToken productValue = planValue["product"];
if (productValue != null && productValue.Type != JTokenType.Null)
{
string productInstance = ((string)productValue);
planInstance.Product = productInstance;
}
JToken promotionCodeValue = planValue["promotionCode"];
if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
{
string promotionCodeInstance = ((string)promotionCodeValue);
planInstance.PromotionCode = promotionCodeInstance;
}
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken hardwareProfileValue = propertiesValue["hardwareProfile"];
if (hardwareProfileValue != null && hardwareProfileValue.Type != JTokenType.Null)
{
HardwareProfile hardwareProfileInstance = new HardwareProfile();
virtualMachineInstance.HardwareProfile = hardwareProfileInstance;
JToken vmSizeValue = hardwareProfileValue["vmSize"];
if (vmSizeValue != null && vmSizeValue.Type != JTokenType.Null)
{
string vmSizeInstance = ((string)vmSizeValue);
hardwareProfileInstance.VirtualMachineSize = vmSizeInstance;
}
}
JToken storageProfileValue = propertiesValue["storageProfile"];
if (storageProfileValue != null && storageProfileValue.Type != JTokenType.Null)
{
StorageProfile storageProfileInstance = new StorageProfile();
virtualMachineInstance.StorageProfile = storageProfileInstance;
JToken imageReferenceValue = storageProfileValue["imageReference"];
if (imageReferenceValue != null && imageReferenceValue.Type != JTokenType.Null)
{
ImageReference imageReferenceInstance = new ImageReference();
storageProfileInstance.ImageReference = imageReferenceInstance;
JToken publisherValue2 = imageReferenceValue["publisher"];
if (publisherValue2 != null && publisherValue2.Type != JTokenType.Null)
{
string publisherInstance2 = ((string)publisherValue2);
imageReferenceInstance.Publisher = publisherInstance2;
}
JToken offerValue = imageReferenceValue["offer"];
if (offerValue != null && offerValue.Type != JTokenType.Null)
{
string offerInstance = ((string)offerValue);
imageReferenceInstance.Offer = offerInstance;
}
JToken skuValue = imageReferenceValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
string skuInstance = ((string)skuValue);
imageReferenceInstance.Sku = skuInstance;
}
JToken versionValue = imageReferenceValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
imageReferenceInstance.Version = versionInstance;
}
}
JToken osDiskValue = storageProfileValue["osDisk"];
if (osDiskValue != null && osDiskValue.Type != JTokenType.Null)
{
OSDisk osDiskInstance = new OSDisk();
storageProfileInstance.OSDisk = osDiskInstance;
JToken osTypeValue = osDiskValue["osType"];
if (osTypeValue != null && osTypeValue.Type != JTokenType.Null)
{
string osTypeInstance = ((string)osTypeValue);
osDiskInstance.OperatingSystemType = osTypeInstance;
}
JToken nameValue2 = osDiskValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
osDiskInstance.Name = nameInstance2;
}
JToken vhdValue = osDiskValue["vhd"];
if (vhdValue != null && vhdValue.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance = new VirtualHardDisk();
osDiskInstance.VirtualHardDisk = vhdInstance;
JToken uriValue = vhdValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
vhdInstance.Uri = uriInstance;
}
}
JToken imageValue = osDiskValue["image"];
if (imageValue != null && imageValue.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance = new VirtualHardDisk();
osDiskInstance.SourceImage = imageInstance;
JToken uriValue2 = imageValue["uri"];
if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
{
string uriInstance2 = ((string)uriValue2);
imageInstance.Uri = uriInstance2;
}
}
JToken cachingValue = osDiskValue["caching"];
if (cachingValue != null && cachingValue.Type != JTokenType.Null)
{
string cachingInstance = ((string)cachingValue);
osDiskInstance.Caching = cachingInstance;
}
JToken createOptionValue = osDiskValue["createOption"];
if (createOptionValue != null && createOptionValue.Type != JTokenType.Null)
{
string createOptionInstance = ((string)createOptionValue);
osDiskInstance.CreateOption = createOptionInstance;
}
JToken diskSizeGBValue = osDiskValue["diskSizeGB"];
if (diskSizeGBValue != null && diskSizeGBValue.Type != JTokenType.Null)
{
int diskSizeGBInstance = ((int)diskSizeGBValue);
osDiskInstance.DiskSizeGB = diskSizeGBInstance;
}
}
JToken dataDisksArray = storageProfileValue["dataDisks"];
if (dataDisksArray != null && dataDisksArray.Type != JTokenType.Null)
{
foreach (JToken dataDisksValue in ((JArray)dataDisksArray))
{
DataDisk dataDiskInstance = new DataDisk();
storageProfileInstance.DataDisks.Add(dataDiskInstance);
JToken lunValue = dataDisksValue["lun"];
if (lunValue != null && lunValue.Type != JTokenType.Null)
{
int lunInstance = ((int)lunValue);
dataDiskInstance.Lun = lunInstance;
}
JToken nameValue3 = dataDisksValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dataDiskInstance.Name = nameInstance3;
}
JToken vhdValue2 = dataDisksValue["vhd"];
if (vhdValue2 != null && vhdValue2.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance2 = new VirtualHardDisk();
dataDiskInstance.VirtualHardDisk = vhdInstance2;
JToken uriValue3 = vhdValue2["uri"];
if (uriValue3 != null && uriValue3.Type != JTokenType.Null)
{
string uriInstance3 = ((string)uriValue3);
vhdInstance2.Uri = uriInstance3;
}
}
JToken imageValue2 = dataDisksValue["image"];
if (imageValue2 != null && imageValue2.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance2 = new VirtualHardDisk();
dataDiskInstance.SourceImage = imageInstance2;
JToken uriValue4 = imageValue2["uri"];
if (uriValue4 != null && uriValue4.Type != JTokenType.Null)
{
string uriInstance4 = ((string)uriValue4);
imageInstance2.Uri = uriInstance4;
}
}
JToken cachingValue2 = dataDisksValue["caching"];
if (cachingValue2 != null && cachingValue2.Type != JTokenType.Null)
{
string cachingInstance2 = ((string)cachingValue2);
dataDiskInstance.Caching = cachingInstance2;
}
JToken createOptionValue2 = dataDisksValue["createOption"];
if (createOptionValue2 != null && createOptionValue2.Type != JTokenType.Null)
{
string createOptionInstance2 = ((string)createOptionValue2);
dataDiskInstance.CreateOption = createOptionInstance2;
}
JToken diskSizeGBValue2 = dataDisksValue["diskSizeGB"];
if (diskSizeGBValue2 != null && diskSizeGBValue2.Type != JTokenType.Null)
{
int diskSizeGBInstance2 = ((int)diskSizeGBValue2);
dataDiskInstance.DiskSizeGB = diskSizeGBInstance2;
}
}
}
}
JToken osProfileValue = propertiesValue["osProfile"];
if (osProfileValue != null && osProfileValue.Type != JTokenType.Null)
{
OSProfile osProfileInstance = new OSProfile();
virtualMachineInstance.OSProfile = osProfileInstance;
JToken computerNameValue = osProfileValue["computerName"];
if (computerNameValue != null && computerNameValue.Type != JTokenType.Null)
{
string computerNameInstance = ((string)computerNameValue);
osProfileInstance.ComputerName = computerNameInstance;
}
JToken adminUsernameValue = osProfileValue["adminUsername"];
if (adminUsernameValue != null && adminUsernameValue.Type != JTokenType.Null)
{
string adminUsernameInstance = ((string)adminUsernameValue);
osProfileInstance.AdminUsername = adminUsernameInstance;
}
JToken adminPasswordValue = osProfileValue["adminPassword"];
if (adminPasswordValue != null && adminPasswordValue.Type != JTokenType.Null)
{
string adminPasswordInstance = ((string)adminPasswordValue);
osProfileInstance.AdminPassword = adminPasswordInstance;
}
JToken customDataValue = osProfileValue["customData"];
if (customDataValue != null && customDataValue.Type != JTokenType.Null)
{
string customDataInstance = ((string)customDataValue);
osProfileInstance.CustomData = customDataInstance;
}
JToken windowsConfigurationValue = osProfileValue["windowsConfiguration"];
if (windowsConfigurationValue != null && windowsConfigurationValue.Type != JTokenType.Null)
{
WindowsConfiguration windowsConfigurationInstance = new WindowsConfiguration();
osProfileInstance.WindowsConfiguration = windowsConfigurationInstance;
JToken provisionVMAgentValue = windowsConfigurationValue["provisionVMAgent"];
if (provisionVMAgentValue != null && provisionVMAgentValue.Type != JTokenType.Null)
{
bool provisionVMAgentInstance = ((bool)provisionVMAgentValue);
windowsConfigurationInstance.ProvisionVMAgent = provisionVMAgentInstance;
}
JToken enableAutomaticUpdatesValue = windowsConfigurationValue["enableAutomaticUpdates"];
if (enableAutomaticUpdatesValue != null && enableAutomaticUpdatesValue.Type != JTokenType.Null)
{
bool enableAutomaticUpdatesInstance = ((bool)enableAutomaticUpdatesValue);
windowsConfigurationInstance.EnableAutomaticUpdates = enableAutomaticUpdatesInstance;
}
JToken timeZoneValue = windowsConfigurationValue["timeZone"];
if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
{
string timeZoneInstance = ((string)timeZoneValue);
windowsConfigurationInstance.TimeZone = timeZoneInstance;
}
JToken additionalUnattendContentArray = windowsConfigurationValue["additionalUnattendContent"];
if (additionalUnattendContentArray != null && additionalUnattendContentArray.Type != JTokenType.Null)
{
foreach (JToken additionalUnattendContentValue in ((JArray)additionalUnattendContentArray))
{
AdditionalUnattendContent additionalUnattendContentInstance = new AdditionalUnattendContent();
windowsConfigurationInstance.AdditionalUnattendContents.Add(additionalUnattendContentInstance);
JToken passNameValue = additionalUnattendContentValue["passName"];
if (passNameValue != null && passNameValue.Type != JTokenType.Null)
{
string passNameInstance = ((string)passNameValue);
additionalUnattendContentInstance.PassName = passNameInstance;
}
JToken componentNameValue = additionalUnattendContentValue["componentName"];
if (componentNameValue != null && componentNameValue.Type != JTokenType.Null)
{
string componentNameInstance = ((string)componentNameValue);
additionalUnattendContentInstance.ComponentName = componentNameInstance;
}
JToken settingNameValue = additionalUnattendContentValue["settingName"];
if (settingNameValue != null && settingNameValue.Type != JTokenType.Null)
{
string settingNameInstance = ((string)settingNameValue);
additionalUnattendContentInstance.SettingName = settingNameInstance;
}
JToken contentValue = additionalUnattendContentValue["content"];
if (contentValue != null && contentValue.Type != JTokenType.Null)
{
string contentInstance = ((string)contentValue);
additionalUnattendContentInstance.Content = contentInstance;
}
}
}
JToken winRMValue = windowsConfigurationValue["winRM"];
if (winRMValue != null && winRMValue.Type != JTokenType.Null)
{
WinRMConfiguration winRMInstance = new WinRMConfiguration();
windowsConfigurationInstance.WinRMConfiguration = winRMInstance;
JToken listenersArray = winRMValue["listeners"];
if (listenersArray != null && listenersArray.Type != JTokenType.Null)
{
foreach (JToken listenersValue in ((JArray)listenersArray))
{
WinRMListener winRMListenerInstance = new WinRMListener();
winRMInstance.Listeners.Add(winRMListenerInstance);
JToken protocolValue = listenersValue["protocol"];
if (protocolValue != null && protocolValue.Type != JTokenType.Null)
{
string protocolInstance = ((string)protocolValue);
winRMListenerInstance.Protocol = protocolInstance;
}
JToken certificateUrlValue = listenersValue["certificateUrl"];
if (certificateUrlValue != null && certificateUrlValue.Type != JTokenType.Null)
{
Uri certificateUrlInstance = TypeConversion.TryParseUri(((string)certificateUrlValue));
winRMListenerInstance.CertificateUrl = certificateUrlInstance;
}
}
}
}
}
JToken linuxConfigurationValue = osProfileValue["linuxConfiguration"];
if (linuxConfigurationValue != null && linuxConfigurationValue.Type != JTokenType.Null)
{
LinuxConfiguration linuxConfigurationInstance = new LinuxConfiguration();
osProfileInstance.LinuxConfiguration = linuxConfigurationInstance;
JToken disablePasswordAuthenticationValue = linuxConfigurationValue["disablePasswordAuthentication"];
if (disablePasswordAuthenticationValue != null && disablePasswordAuthenticationValue.Type != JTokenType.Null)
{
bool disablePasswordAuthenticationInstance = ((bool)disablePasswordAuthenticationValue);
linuxConfigurationInstance.DisablePasswordAuthentication = disablePasswordAuthenticationInstance;
}
JToken sshValue = linuxConfigurationValue["ssh"];
if (sshValue != null && sshValue.Type != JTokenType.Null)
{
SshConfiguration sshInstance = new SshConfiguration();
linuxConfigurationInstance.SshConfiguration = sshInstance;
JToken publicKeysArray = sshValue["publicKeys"];
if (publicKeysArray != null && publicKeysArray.Type != JTokenType.Null)
{
foreach (JToken publicKeysValue in ((JArray)publicKeysArray))
{
SshPublicKey sshPublicKeyInstance = new SshPublicKey();
sshInstance.PublicKeys.Add(sshPublicKeyInstance);
JToken pathValue = publicKeysValue["path"];
if (pathValue != null && pathValue.Type != JTokenType.Null)
{
string pathInstance = ((string)pathValue);
sshPublicKeyInstance.Path = pathInstance;
}
JToken keyDataValue = publicKeysValue["keyData"];
if (keyDataValue != null && keyDataValue.Type != JTokenType.Null)
{
string keyDataInstance = ((string)keyDataValue);
sshPublicKeyInstance.KeyData = keyDataInstance;
}
}
}
}
}
JToken secretsArray = osProfileValue["secrets"];
if (secretsArray != null && secretsArray.Type != JTokenType.Null)
{
foreach (JToken secretsValue in ((JArray)secretsArray))
{
VaultSecretGroup vaultSecretGroupInstance = new VaultSecretGroup();
osProfileInstance.Secrets.Add(vaultSecretGroupInstance);
JToken sourceVaultValue = secretsValue["sourceVault"];
if (sourceVaultValue != null && sourceVaultValue.Type != JTokenType.Null)
{
SourceVaultReference sourceVaultInstance = new SourceVaultReference();
vaultSecretGroupInstance.SourceVault = sourceVaultInstance;
JToken idValue = sourceVaultValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
sourceVaultInstance.ReferenceUri = idInstance;
}
}
JToken vaultCertificatesArray = secretsValue["vaultCertificates"];
if (vaultCertificatesArray != null && vaultCertificatesArray.Type != JTokenType.Null)
{
foreach (JToken vaultCertificatesValue in ((JArray)vaultCertificatesArray))
{
VaultCertificate vaultCertificateInstance = new VaultCertificate();
vaultSecretGroupInstance.VaultCertificates.Add(vaultCertificateInstance);
JToken certificateUrlValue2 = vaultCertificatesValue["certificateUrl"];
if (certificateUrlValue2 != null && certificateUrlValue2.Type != JTokenType.Null)
{
string certificateUrlInstance2 = ((string)certificateUrlValue2);
vaultCertificateInstance.CertificateUrl = certificateUrlInstance2;
}
JToken certificateStoreValue = vaultCertificatesValue["certificateStore"];
if (certificateStoreValue != null && certificateStoreValue.Type != JTokenType.Null)
{
string certificateStoreInstance = ((string)certificateStoreValue);
vaultCertificateInstance.CertificateStore = certificateStoreInstance;
}
}
}
}
}
}
JToken networkProfileValue = propertiesValue["networkProfile"];
if (networkProfileValue != null && networkProfileValue.Type != JTokenType.Null)
{
NetworkProfile networkProfileInstance = new NetworkProfile();
virtualMachineInstance.NetworkProfile = networkProfileInstance;
JToken networkInterfacesArray = networkProfileValue["networkInterfaces"];
if (networkInterfacesArray != null && networkInterfacesArray.Type != JTokenType.Null)
{
foreach (JToken networkInterfacesValue in ((JArray)networkInterfacesArray))
{
NetworkInterfaceReference networkInterfaceReferenceJsonInstance = new NetworkInterfaceReference();
networkProfileInstance.NetworkInterfaces.Add(networkInterfaceReferenceJsonInstance);
JToken propertiesValue2 = networkInterfacesValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken primaryValue = propertiesValue2["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
bool primaryInstance = ((bool)primaryValue);
networkInterfaceReferenceJsonInstance.Primary = primaryInstance;
}
}
JToken idValue2 = networkInterfacesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
networkInterfaceReferenceJsonInstance.ReferenceUri = idInstance2;
}
}
}
}
JToken availabilitySetValue = propertiesValue["availabilitySet"];
if (availabilitySetValue != null && availabilitySetValue.Type != JTokenType.Null)
{
AvailabilitySetReference availabilitySetInstance = new AvailabilitySetReference();
virtualMachineInstance.AvailabilitySetReference = availabilitySetInstance;
JToken idValue3 = availabilitySetValue["id"];
if (idValue3 != null && idValue3.Type != JTokenType.Null)
{
string idInstance3 = ((string)idValue3);
availabilitySetInstance.ReferenceUri = idInstance3;
}
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
virtualMachineInstance.ProvisioningState = provisioningStateInstance;
}
JToken instanceViewValue = propertiesValue["instanceView"];
if (instanceViewValue != null && instanceViewValue.Type != JTokenType.Null)
{
VirtualMachineInstanceView instanceViewInstance = new VirtualMachineInstanceView();
virtualMachineInstance.InstanceView = instanceViewInstance;
JToken platformUpdateDomainValue = instanceViewValue["platformUpdateDomain"];
if (platformUpdateDomainValue != null && platformUpdateDomainValue.Type != JTokenType.Null)
{
int platformUpdateDomainInstance = ((int)platformUpdateDomainValue);
instanceViewInstance.PlatformUpdateDomain = platformUpdateDomainInstance;
}
JToken platformFaultDomainValue = instanceViewValue["platformFaultDomain"];
if (platformFaultDomainValue != null && platformFaultDomainValue.Type != JTokenType.Null)
{
int platformFaultDomainInstance = ((int)platformFaultDomainValue);
instanceViewInstance.PlatformFaultDomain = platformFaultDomainInstance;
}
JToken rdpThumbPrintValue = instanceViewValue["rdpThumbPrint"];
if (rdpThumbPrintValue != null && rdpThumbPrintValue.Type != JTokenType.Null)
{
string rdpThumbPrintInstance = ((string)rdpThumbPrintValue);
instanceViewInstance.RemoteDesktopThumbprint = rdpThumbPrintInstance;
}
JToken vmAgentValue = instanceViewValue["vmAgent"];
if (vmAgentValue != null && vmAgentValue.Type != JTokenType.Null)
{
VirtualMachineAgentInstanceView vmAgentInstance = new VirtualMachineAgentInstanceView();
instanceViewInstance.VMAgent = vmAgentInstance;
JToken vmAgentVersionValue = vmAgentValue["vmAgentVersion"];
if (vmAgentVersionValue != null && vmAgentVersionValue.Type != JTokenType.Null)
{
string vmAgentVersionInstance = ((string)vmAgentVersionValue);
vmAgentInstance.VMAgentVersion = vmAgentVersionInstance;
}
JToken extensionHandlersArray = vmAgentValue["extensionHandlers"];
if (extensionHandlersArray != null && extensionHandlersArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlersValue in ((JArray)extensionHandlersArray))
{
VirtualMachineExtensionHandlerInstanceView virtualMachineExtensionHandlerInstanceViewInstance = new VirtualMachineExtensionHandlerInstanceView();
vmAgentInstance.ExtensionHandlers.Add(virtualMachineExtensionHandlerInstanceViewInstance);
JToken typeValue = extensionHandlersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
virtualMachineExtensionHandlerInstanceViewInstance.Type = typeInstance;
}
JToken typeHandlerVersionValue = extensionHandlersValue["typeHandlerVersion"];
if (typeHandlerVersionValue != null && typeHandlerVersionValue.Type != JTokenType.Null)
{
string typeHandlerVersionInstance = ((string)typeHandlerVersionValue);
virtualMachineExtensionHandlerInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance;
}
JToken statusValue = extensionHandlersValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
InstanceViewStatus statusInstance = new InstanceViewStatus();
virtualMachineExtensionHandlerInstanceViewInstance.Status = statusInstance;
JToken codeValue = statusValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
statusInstance.Code = codeInstance;
}
JToken levelValue = statusValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
statusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
statusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
statusInstance.Message = messageInstance;
}
JToken timeValue = statusValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
statusInstance.Time = timeInstance;
}
}
}
}
JToken statusesArray = vmAgentValue["statuses"];
if (statusesArray != null && statusesArray.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
vmAgentInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue2 = statusesValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
instanceViewStatusInstance.Code = codeInstance2;
}
JToken levelValue2 = statusesValue["level"];
if (levelValue2 != null && levelValue2.Type != JTokenType.Null)
{
string levelInstance2 = ((string)levelValue2);
instanceViewStatusInstance.Level = levelInstance2;
}
JToken displayStatusValue2 = statusesValue["displayStatus"];
if (displayStatusValue2 != null && displayStatusValue2.Type != JTokenType.Null)
{
string displayStatusInstance2 = ((string)displayStatusValue2);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance2;
}
JToken messageValue2 = statusesValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
instanceViewStatusInstance.Message = messageInstance2;
}
JToken timeValue2 = statusesValue["time"];
if (timeValue2 != null && timeValue2.Type != JTokenType.Null)
{
DateTimeOffset timeInstance2 = ((DateTimeOffset)timeValue2);
instanceViewStatusInstance.Time = timeInstance2;
}
}
}
}
JToken disksArray = instanceViewValue["disks"];
if (disksArray != null && disksArray.Type != JTokenType.Null)
{
foreach (JToken disksValue in ((JArray)disksArray))
{
DiskInstanceView diskInstanceViewInstance = new DiskInstanceView();
instanceViewInstance.Disks.Add(diskInstanceViewInstance);
JToken nameValue4 = disksValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
diskInstanceViewInstance.Name = nameInstance4;
}
JToken statusesArray2 = disksValue["statuses"];
if (statusesArray2 != null && statusesArray2.Type != JTokenType.Null)
{
foreach (JToken statusesValue2 in ((JArray)statusesArray2))
{
InstanceViewStatus instanceViewStatusInstance2 = new InstanceViewStatus();
diskInstanceViewInstance.Statuses.Add(instanceViewStatusInstance2);
JToken codeValue3 = statusesValue2["code"];
if (codeValue3 != null && codeValue3.Type != JTokenType.Null)
{
string codeInstance3 = ((string)codeValue3);
instanceViewStatusInstance2.Code = codeInstance3;
}
JToken levelValue3 = statusesValue2["level"];
if (levelValue3 != null && levelValue3.Type != JTokenType.Null)
{
string levelInstance3 = ((string)levelValue3);
instanceViewStatusInstance2.Level = levelInstance3;
}
JToken displayStatusValue3 = statusesValue2["displayStatus"];
if (displayStatusValue3 != null && displayStatusValue3.Type != JTokenType.Null)
{
string displayStatusInstance3 = ((string)displayStatusValue3);
instanceViewStatusInstance2.DisplayStatus = displayStatusInstance3;
}
JToken messageValue3 = statusesValue2["message"];
if (messageValue3 != null && messageValue3.Type != JTokenType.Null)
{
string messageInstance3 = ((string)messageValue3);
instanceViewStatusInstance2.Message = messageInstance3;
}
JToken timeValue3 = statusesValue2["time"];
if (timeValue3 != null && timeValue3.Type != JTokenType.Null)
{
DateTimeOffset timeInstance3 = ((DateTimeOffset)timeValue3);
instanceViewStatusInstance2.Time = timeInstance3;
}
}
}
}
}
JToken extensionsArray = instanceViewValue["extensions"];
if (extensionsArray != null && extensionsArray.Type != JTokenType.Null)
{
foreach (JToken extensionsValue in ((JArray)extensionsArray))
{
VirtualMachineExtensionInstanceView virtualMachineExtensionInstanceViewInstance = new VirtualMachineExtensionInstanceView();
instanceViewInstance.Extensions.Add(virtualMachineExtensionInstanceViewInstance);
JToken nameValue5 = extensionsValue["name"];
if (nameValue5 != null && nameValue5.Type != JTokenType.Null)
{
string nameInstance5 = ((string)nameValue5);
virtualMachineExtensionInstanceViewInstance.Name = nameInstance5;
}
JToken typeValue2 = extensionsValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
virtualMachineExtensionInstanceViewInstance.ExtensionType = typeInstance2;
}
JToken typeHandlerVersionValue2 = extensionsValue["typeHandlerVersion"];
if (typeHandlerVersionValue2 != null && typeHandlerVersionValue2.Type != JTokenType.Null)
{
string typeHandlerVersionInstance2 = ((string)typeHandlerVersionValue2);
virtualMachineExtensionInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance2;
}
JToken substatusesArray = extensionsValue["substatuses"];
if (substatusesArray != null && substatusesArray.Type != JTokenType.Null)
{
foreach (JToken substatusesValue in ((JArray)substatusesArray))
{
InstanceViewStatus instanceViewStatusInstance3 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.SubStatuses.Add(instanceViewStatusInstance3);
JToken codeValue4 = substatusesValue["code"];
if (codeValue4 != null && codeValue4.Type != JTokenType.Null)
{
string codeInstance4 = ((string)codeValue4);
instanceViewStatusInstance3.Code = codeInstance4;
}
JToken levelValue4 = substatusesValue["level"];
if (levelValue4 != null && levelValue4.Type != JTokenType.Null)
{
string levelInstance4 = ((string)levelValue4);
instanceViewStatusInstance3.Level = levelInstance4;
}
JToken displayStatusValue4 = substatusesValue["displayStatus"];
if (displayStatusValue4 != null && displayStatusValue4.Type != JTokenType.Null)
{
string displayStatusInstance4 = ((string)displayStatusValue4);
instanceViewStatusInstance3.DisplayStatus = displayStatusInstance4;
}
JToken messageValue4 = substatusesValue["message"];
if (messageValue4 != null && messageValue4.Type != JTokenType.Null)
{
string messageInstance4 = ((string)messageValue4);
instanceViewStatusInstance3.Message = messageInstance4;
}
JToken timeValue4 = substatusesValue["time"];
if (timeValue4 != null && timeValue4.Type != JTokenType.Null)
{
DateTimeOffset timeInstance4 = ((DateTimeOffset)timeValue4);
instanceViewStatusInstance3.Time = timeInstance4;
}
}
}
JToken statusesArray3 = extensionsValue["statuses"];
if (statusesArray3 != null && statusesArray3.Type != JTokenType.Null)
{
foreach (JToken statusesValue3 in ((JArray)statusesArray3))
{
InstanceViewStatus instanceViewStatusInstance4 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.Statuses.Add(instanceViewStatusInstance4);
JToken codeValue5 = statusesValue3["code"];
if (codeValue5 != null && codeValue5.Type != JTokenType.Null)
{
string codeInstance5 = ((string)codeValue5);
instanceViewStatusInstance4.Code = codeInstance5;
}
JToken levelValue5 = statusesValue3["level"];
if (levelValue5 != null && levelValue5.Type != JTokenType.Null)
{
string levelInstance5 = ((string)levelValue5);
instanceViewStatusInstance4.Level = levelInstance5;
}
JToken displayStatusValue5 = statusesValue3["displayStatus"];
if (displayStatusValue5 != null && displayStatusValue5.Type != JTokenType.Null)
{
string displayStatusInstance5 = ((string)displayStatusValue5);
instanceViewStatusInstance4.DisplayStatus = displayStatusInstance5;
}
JToken messageValue5 = statusesValue3["message"];
if (messageValue5 != null && messageValue5.Type != JTokenType.Null)
{
string messageInstance5 = ((string)messageValue5);
instanceViewStatusInstance4.Message = messageInstance5;
}
JToken timeValue5 = statusesValue3["time"];
if (timeValue5 != null && timeValue5.Type != JTokenType.Null)
{
DateTimeOffset timeInstance5 = ((DateTimeOffset)timeValue5);
instanceViewStatusInstance4.Time = timeInstance5;
}
}
}
}
}
JToken statusesArray4 = instanceViewValue["statuses"];
if (statusesArray4 != null && statusesArray4.Type != JTokenType.Null)
{
foreach (JToken statusesValue4 in ((JArray)statusesArray4))
{
InstanceViewStatus instanceViewStatusInstance5 = new InstanceViewStatus();
instanceViewInstance.Statuses.Add(instanceViewStatusInstance5);
JToken codeValue6 = statusesValue4["code"];
if (codeValue6 != null && codeValue6.Type != JTokenType.Null)
{
string codeInstance6 = ((string)codeValue6);
instanceViewStatusInstance5.Code = codeInstance6;
}
JToken levelValue6 = statusesValue4["level"];
if (levelValue6 != null && levelValue6.Type != JTokenType.Null)
{
string levelInstance6 = ((string)levelValue6);
instanceViewStatusInstance5.Level = levelInstance6;
}
JToken displayStatusValue6 = statusesValue4["displayStatus"];
if (displayStatusValue6 != null && displayStatusValue6.Type != JTokenType.Null)
{
string displayStatusInstance6 = ((string)displayStatusValue6);
instanceViewStatusInstance5.DisplayStatus = displayStatusInstance6;
}
JToken messageValue6 = statusesValue4["message"];
if (messageValue6 != null && messageValue6.Type != JTokenType.Null)
{
string messageInstance6 = ((string)messageValue6);
instanceViewStatusInstance5.Message = messageInstance6;
}
JToken timeValue6 = statusesValue4["time"];
if (timeValue6 != null && timeValue6.Type != JTokenType.Null)
{
DateTimeOffset timeInstance6 = ((DateTimeOffset)timeValue6);
instanceViewStatusInstance5.Time = timeInstance6;
}
}
}
}
}
JToken resourcesArray = responseDoc["resources"];
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
virtualMachineInstance.Extensions = new List<VirtualMachineExtension>();
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineExtension virtualMachineExtensionJsonInstance = new VirtualMachineExtension();
virtualMachineInstance.Extensions.Add(virtualMachineExtensionJsonInstance);
JToken propertiesValue3 = resourcesValue["properties"];
if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
{
JToken publisherValue3 = propertiesValue3["publisher"];
if (publisherValue3 != null && publisherValue3.Type != JTokenType.Null)
{
string publisherInstance3 = ((string)publisherValue3);
virtualMachineExtensionJsonInstance.Publisher = publisherInstance3;
}
JToken typeValue3 = propertiesValue3["type"];
if (typeValue3 != null && typeValue3.Type != JTokenType.Null)
{
string typeInstance3 = ((string)typeValue3);
virtualMachineExtensionJsonInstance.ExtensionType = typeInstance3;
}
JToken typeHandlerVersionValue3 = propertiesValue3["typeHandlerVersion"];
if (typeHandlerVersionValue3 != null && typeHandlerVersionValue3.Type != JTokenType.Null)
{
string typeHandlerVersionInstance3 = ((string)typeHandlerVersionValue3);
virtualMachineExtensionJsonInstance.TypeHandlerVersion = typeHandlerVersionInstance3;
}
JToken autoUpgradeMinorVersionValue = propertiesValue3["autoUpgradeMinorVersion"];
if (autoUpgradeMinorVersionValue != null && autoUpgradeMinorVersionValue.Type != JTokenType.Null)
{
bool autoUpgradeMinorVersionInstance = ((bool)autoUpgradeMinorVersionValue);
virtualMachineExtensionJsonInstance.AutoUpgradeMinorVersion = autoUpgradeMinorVersionInstance;
}
JToken settingsValue = propertiesValue3["settings"];
if (settingsValue != null && settingsValue.Type != JTokenType.Null)
{
string settingsInstance = settingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.Settings = settingsInstance;
}
JToken protectedSettingsValue = propertiesValue3["protectedSettings"];
if (protectedSettingsValue != null && protectedSettingsValue.Type != JTokenType.Null)
{
string protectedSettingsInstance = protectedSettingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.ProtectedSettings = protectedSettingsInstance;
}
JToken provisioningStateValue2 = propertiesValue3["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
virtualMachineExtensionJsonInstance.ProvisioningState = provisioningStateInstance2;
}
JToken instanceViewValue2 = propertiesValue3["instanceView"];
if (instanceViewValue2 != null && instanceViewValue2.Type != JTokenType.Null)
{
VirtualMachineExtensionInstanceView instanceViewInstance2 = new VirtualMachineExtensionInstanceView();
virtualMachineExtensionJsonInstance.InstanceView = instanceViewInstance2;
JToken nameValue6 = instanceViewValue2["name"];
if (nameValue6 != null && nameValue6.Type != JTokenType.Null)
{
string nameInstance6 = ((string)nameValue6);
instanceViewInstance2.Name = nameInstance6;
}
JToken typeValue4 = instanceViewValue2["type"];
if (typeValue4 != null && typeValue4.Type != JTokenType.Null)
{
string typeInstance4 = ((string)typeValue4);
instanceViewInstance2.ExtensionType = typeInstance4;
}
JToken typeHandlerVersionValue4 = instanceViewValue2["typeHandlerVersion"];
if (typeHandlerVersionValue4 != null && typeHandlerVersionValue4.Type != JTokenType.Null)
{
string typeHandlerVersionInstance4 = ((string)typeHandlerVersionValue4);
instanceViewInstance2.TypeHandlerVersion = typeHandlerVersionInstance4;
}
JToken substatusesArray2 = instanceViewValue2["substatuses"];
if (substatusesArray2 != null && substatusesArray2.Type != JTokenType.Null)
{
foreach (JToken substatusesValue2 in ((JArray)substatusesArray2))
{
InstanceViewStatus instanceViewStatusInstance6 = new InstanceViewStatus();
instanceViewInstance2.SubStatuses.Add(instanceViewStatusInstance6);
JToken codeValue7 = substatusesValue2["code"];
if (codeValue7 != null && codeValue7.Type != JTokenType.Null)
{
string codeInstance7 = ((string)codeValue7);
instanceViewStatusInstance6.Code = codeInstance7;
}
JToken levelValue7 = substatusesValue2["level"];
if (levelValue7 != null && levelValue7.Type != JTokenType.Null)
{
string levelInstance7 = ((string)levelValue7);
instanceViewStatusInstance6.Level = levelInstance7;
}
JToken displayStatusValue7 = substatusesValue2["displayStatus"];
if (displayStatusValue7 != null && displayStatusValue7.Type != JTokenType.Null)
{
string displayStatusInstance7 = ((string)displayStatusValue7);
instanceViewStatusInstance6.DisplayStatus = displayStatusInstance7;
}
JToken messageValue7 = substatusesValue2["message"];
if (messageValue7 != null && messageValue7.Type != JTokenType.Null)
{
string messageInstance7 = ((string)messageValue7);
instanceViewStatusInstance6.Message = messageInstance7;
}
JToken timeValue7 = substatusesValue2["time"];
if (timeValue7 != null && timeValue7.Type != JTokenType.Null)
{
DateTimeOffset timeInstance7 = ((DateTimeOffset)timeValue7);
instanceViewStatusInstance6.Time = timeInstance7;
}
}
}
JToken statusesArray5 = instanceViewValue2["statuses"];
if (statusesArray5 != null && statusesArray5.Type != JTokenType.Null)
{
foreach (JToken statusesValue5 in ((JArray)statusesArray5))
{
InstanceViewStatus instanceViewStatusInstance7 = new InstanceViewStatus();
instanceViewInstance2.Statuses.Add(instanceViewStatusInstance7);
JToken codeValue8 = statusesValue5["code"];
if (codeValue8 != null && codeValue8.Type != JTokenType.Null)
{
string codeInstance8 = ((string)codeValue8);
instanceViewStatusInstance7.Code = codeInstance8;
}
JToken levelValue8 = statusesValue5["level"];
if (levelValue8 != null && levelValue8.Type != JTokenType.Null)
{
string levelInstance8 = ((string)levelValue8);
instanceViewStatusInstance7.Level = levelInstance8;
}
JToken displayStatusValue8 = statusesValue5["displayStatus"];
if (displayStatusValue8 != null && displayStatusValue8.Type != JTokenType.Null)
{
string displayStatusInstance8 = ((string)displayStatusValue8);
instanceViewStatusInstance7.DisplayStatus = displayStatusInstance8;
}
JToken messageValue8 = statusesValue5["message"];
if (messageValue8 != null && messageValue8.Type != JTokenType.Null)
{
string messageInstance8 = ((string)messageValue8);
instanceViewStatusInstance7.Message = messageInstance8;
}
JToken timeValue8 = statusesValue5["time"];
if (timeValue8 != null && timeValue8.Type != JTokenType.Null)
{
DateTimeOffset timeInstance8 = ((DateTimeOffset)timeValue8);
instanceViewStatusInstance7.Time = timeInstance8;
}
}
}
}
}
JToken idValue4 = resourcesValue["id"];
if (idValue4 != null && idValue4.Type != JTokenType.Null)
{
string idInstance4 = ((string)idValue4);
virtualMachineExtensionJsonInstance.Id = idInstance4;
}
JToken nameValue7 = resourcesValue["name"];
if (nameValue7 != null && nameValue7.Type != JTokenType.Null)
{
string nameInstance7 = ((string)nameValue7);
virtualMachineExtensionJsonInstance.Name = nameInstance7;
}
JToken typeValue5 = resourcesValue["type"];
if (typeValue5 != null && typeValue5.Type != JTokenType.Null)
{
string typeInstance5 = ((string)typeValue5);
virtualMachineExtensionJsonInstance.Type = typeInstance5;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineExtensionJsonInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)resourcesValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
virtualMachineExtensionJsonInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken idValue5 = responseDoc["id"];
if (idValue5 != null && idValue5.Type != JTokenType.Null)
{
string idInstance5 = ((string)idValue5);
virtualMachineInstance.Id = idInstance5;
}
JToken nameValue8 = responseDoc["name"];
if (nameValue8 != null && nameValue8.Type != JTokenType.Null)
{
string nameInstance8 = ((string)nameValue8);
virtualMachineInstance.Name = nameInstance8;
}
JToken typeValue6 = responseDoc["type"];
if (typeValue6 != null && typeValue6.Type != JTokenType.Null)
{
string typeInstance6 = ((string)typeValue6);
virtualMachineInstance.Type = typeInstance6;
}
JToken locationValue2 = responseDoc["location"];
if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
{
string locationInstance2 = ((string)locationValue2);
virtualMachineInstance.Location = locationInstance2;
}
JToken tagsSequenceElement2 = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null)
{
foreach (JProperty property2 in tagsSequenceElement2)
{
string tagsKey2 = ((string)property2.Name);
string tagsValue2 = ((string)property2.Value);
virtualMachineInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to get a virtual machine along with its instance view.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The GetVM operation response.
/// </returns>
public async Task<VirtualMachineGetResponse> GetWithInstanceViewAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "GetWithInstanceViewAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
List<string> queryParameters = new List<string>();
queryParameters.Add("$expand=instanceView");
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
VirtualMachine virtualMachineInstance = new VirtualMachine();
result.VirtualMachine = virtualMachineInstance;
JToken planValue = responseDoc["plan"];
if (planValue != null && planValue.Type != JTokenType.Null)
{
Plan planInstance = new Plan();
virtualMachineInstance.Plan = planInstance;
JToken nameValue = planValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
planInstance.Name = nameInstance;
}
JToken publisherValue = planValue["publisher"];
if (publisherValue != null && publisherValue.Type != JTokenType.Null)
{
string publisherInstance = ((string)publisherValue);
planInstance.Publisher = publisherInstance;
}
JToken productValue = planValue["product"];
if (productValue != null && productValue.Type != JTokenType.Null)
{
string productInstance = ((string)productValue);
planInstance.Product = productInstance;
}
JToken promotionCodeValue = planValue["promotionCode"];
if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
{
string promotionCodeInstance = ((string)promotionCodeValue);
planInstance.PromotionCode = promotionCodeInstance;
}
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken hardwareProfileValue = propertiesValue["hardwareProfile"];
if (hardwareProfileValue != null && hardwareProfileValue.Type != JTokenType.Null)
{
HardwareProfile hardwareProfileInstance = new HardwareProfile();
virtualMachineInstance.HardwareProfile = hardwareProfileInstance;
JToken vmSizeValue = hardwareProfileValue["vmSize"];
if (vmSizeValue != null && vmSizeValue.Type != JTokenType.Null)
{
string vmSizeInstance = ((string)vmSizeValue);
hardwareProfileInstance.VirtualMachineSize = vmSizeInstance;
}
}
JToken storageProfileValue = propertiesValue["storageProfile"];
if (storageProfileValue != null && storageProfileValue.Type != JTokenType.Null)
{
StorageProfile storageProfileInstance = new StorageProfile();
virtualMachineInstance.StorageProfile = storageProfileInstance;
JToken imageReferenceValue = storageProfileValue["imageReference"];
if (imageReferenceValue != null && imageReferenceValue.Type != JTokenType.Null)
{
ImageReference imageReferenceInstance = new ImageReference();
storageProfileInstance.ImageReference = imageReferenceInstance;
JToken publisherValue2 = imageReferenceValue["publisher"];
if (publisherValue2 != null && publisherValue2.Type != JTokenType.Null)
{
string publisherInstance2 = ((string)publisherValue2);
imageReferenceInstance.Publisher = publisherInstance2;
}
JToken offerValue = imageReferenceValue["offer"];
if (offerValue != null && offerValue.Type != JTokenType.Null)
{
string offerInstance = ((string)offerValue);
imageReferenceInstance.Offer = offerInstance;
}
JToken skuValue = imageReferenceValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
string skuInstance = ((string)skuValue);
imageReferenceInstance.Sku = skuInstance;
}
JToken versionValue = imageReferenceValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
imageReferenceInstance.Version = versionInstance;
}
}
JToken osDiskValue = storageProfileValue["osDisk"];
if (osDiskValue != null && osDiskValue.Type != JTokenType.Null)
{
OSDisk osDiskInstance = new OSDisk();
storageProfileInstance.OSDisk = osDiskInstance;
JToken osTypeValue = osDiskValue["osType"];
if (osTypeValue != null && osTypeValue.Type != JTokenType.Null)
{
string osTypeInstance = ((string)osTypeValue);
osDiskInstance.OperatingSystemType = osTypeInstance;
}
JToken nameValue2 = osDiskValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
osDiskInstance.Name = nameInstance2;
}
JToken vhdValue = osDiskValue["vhd"];
if (vhdValue != null && vhdValue.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance = new VirtualHardDisk();
osDiskInstance.VirtualHardDisk = vhdInstance;
JToken uriValue = vhdValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
vhdInstance.Uri = uriInstance;
}
}
JToken imageValue = osDiskValue["image"];
if (imageValue != null && imageValue.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance = new VirtualHardDisk();
osDiskInstance.SourceImage = imageInstance;
JToken uriValue2 = imageValue["uri"];
if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
{
string uriInstance2 = ((string)uriValue2);
imageInstance.Uri = uriInstance2;
}
}
JToken cachingValue = osDiskValue["caching"];
if (cachingValue != null && cachingValue.Type != JTokenType.Null)
{
string cachingInstance = ((string)cachingValue);
osDiskInstance.Caching = cachingInstance;
}
JToken createOptionValue = osDiskValue["createOption"];
if (createOptionValue != null && createOptionValue.Type != JTokenType.Null)
{
string createOptionInstance = ((string)createOptionValue);
osDiskInstance.CreateOption = createOptionInstance;
}
JToken diskSizeGBValue = osDiskValue["diskSizeGB"];
if (diskSizeGBValue != null && diskSizeGBValue.Type != JTokenType.Null)
{
int diskSizeGBInstance = ((int)diskSizeGBValue);
osDiskInstance.DiskSizeGB = diskSizeGBInstance;
}
}
JToken dataDisksArray = storageProfileValue["dataDisks"];
if (dataDisksArray != null && dataDisksArray.Type != JTokenType.Null)
{
foreach (JToken dataDisksValue in ((JArray)dataDisksArray))
{
DataDisk dataDiskInstance = new DataDisk();
storageProfileInstance.DataDisks.Add(dataDiskInstance);
JToken lunValue = dataDisksValue["lun"];
if (lunValue != null && lunValue.Type != JTokenType.Null)
{
int lunInstance = ((int)lunValue);
dataDiskInstance.Lun = lunInstance;
}
JToken nameValue3 = dataDisksValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dataDiskInstance.Name = nameInstance3;
}
JToken vhdValue2 = dataDisksValue["vhd"];
if (vhdValue2 != null && vhdValue2.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance2 = new VirtualHardDisk();
dataDiskInstance.VirtualHardDisk = vhdInstance2;
JToken uriValue3 = vhdValue2["uri"];
if (uriValue3 != null && uriValue3.Type != JTokenType.Null)
{
string uriInstance3 = ((string)uriValue3);
vhdInstance2.Uri = uriInstance3;
}
}
JToken imageValue2 = dataDisksValue["image"];
if (imageValue2 != null && imageValue2.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance2 = new VirtualHardDisk();
dataDiskInstance.SourceImage = imageInstance2;
JToken uriValue4 = imageValue2["uri"];
if (uriValue4 != null && uriValue4.Type != JTokenType.Null)
{
string uriInstance4 = ((string)uriValue4);
imageInstance2.Uri = uriInstance4;
}
}
JToken cachingValue2 = dataDisksValue["caching"];
if (cachingValue2 != null && cachingValue2.Type != JTokenType.Null)
{
string cachingInstance2 = ((string)cachingValue2);
dataDiskInstance.Caching = cachingInstance2;
}
JToken createOptionValue2 = dataDisksValue["createOption"];
if (createOptionValue2 != null && createOptionValue2.Type != JTokenType.Null)
{
string createOptionInstance2 = ((string)createOptionValue2);
dataDiskInstance.CreateOption = createOptionInstance2;
}
JToken diskSizeGBValue2 = dataDisksValue["diskSizeGB"];
if (diskSizeGBValue2 != null && diskSizeGBValue2.Type != JTokenType.Null)
{
int diskSizeGBInstance2 = ((int)diskSizeGBValue2);
dataDiskInstance.DiskSizeGB = diskSizeGBInstance2;
}
}
}
}
JToken osProfileValue = propertiesValue["osProfile"];
if (osProfileValue != null && osProfileValue.Type != JTokenType.Null)
{
OSProfile osProfileInstance = new OSProfile();
virtualMachineInstance.OSProfile = osProfileInstance;
JToken computerNameValue = osProfileValue["computerName"];
if (computerNameValue != null && computerNameValue.Type != JTokenType.Null)
{
string computerNameInstance = ((string)computerNameValue);
osProfileInstance.ComputerName = computerNameInstance;
}
JToken adminUsernameValue = osProfileValue["adminUsername"];
if (adminUsernameValue != null && adminUsernameValue.Type != JTokenType.Null)
{
string adminUsernameInstance = ((string)adminUsernameValue);
osProfileInstance.AdminUsername = adminUsernameInstance;
}
JToken adminPasswordValue = osProfileValue["adminPassword"];
if (adminPasswordValue != null && adminPasswordValue.Type != JTokenType.Null)
{
string adminPasswordInstance = ((string)adminPasswordValue);
osProfileInstance.AdminPassword = adminPasswordInstance;
}
JToken customDataValue = osProfileValue["customData"];
if (customDataValue != null && customDataValue.Type != JTokenType.Null)
{
string customDataInstance = ((string)customDataValue);
osProfileInstance.CustomData = customDataInstance;
}
JToken windowsConfigurationValue = osProfileValue["windowsConfiguration"];
if (windowsConfigurationValue != null && windowsConfigurationValue.Type != JTokenType.Null)
{
WindowsConfiguration windowsConfigurationInstance = new WindowsConfiguration();
osProfileInstance.WindowsConfiguration = windowsConfigurationInstance;
JToken provisionVMAgentValue = windowsConfigurationValue["provisionVMAgent"];
if (provisionVMAgentValue != null && provisionVMAgentValue.Type != JTokenType.Null)
{
bool provisionVMAgentInstance = ((bool)provisionVMAgentValue);
windowsConfigurationInstance.ProvisionVMAgent = provisionVMAgentInstance;
}
JToken enableAutomaticUpdatesValue = windowsConfigurationValue["enableAutomaticUpdates"];
if (enableAutomaticUpdatesValue != null && enableAutomaticUpdatesValue.Type != JTokenType.Null)
{
bool enableAutomaticUpdatesInstance = ((bool)enableAutomaticUpdatesValue);
windowsConfigurationInstance.EnableAutomaticUpdates = enableAutomaticUpdatesInstance;
}
JToken timeZoneValue = windowsConfigurationValue["timeZone"];
if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
{
string timeZoneInstance = ((string)timeZoneValue);
windowsConfigurationInstance.TimeZone = timeZoneInstance;
}
JToken additionalUnattendContentArray = windowsConfigurationValue["additionalUnattendContent"];
if (additionalUnattendContentArray != null && additionalUnattendContentArray.Type != JTokenType.Null)
{
foreach (JToken additionalUnattendContentValue in ((JArray)additionalUnattendContentArray))
{
AdditionalUnattendContent additionalUnattendContentInstance = new AdditionalUnattendContent();
windowsConfigurationInstance.AdditionalUnattendContents.Add(additionalUnattendContentInstance);
JToken passNameValue = additionalUnattendContentValue["passName"];
if (passNameValue != null && passNameValue.Type != JTokenType.Null)
{
string passNameInstance = ((string)passNameValue);
additionalUnattendContentInstance.PassName = passNameInstance;
}
JToken componentNameValue = additionalUnattendContentValue["componentName"];
if (componentNameValue != null && componentNameValue.Type != JTokenType.Null)
{
string componentNameInstance = ((string)componentNameValue);
additionalUnattendContentInstance.ComponentName = componentNameInstance;
}
JToken settingNameValue = additionalUnattendContentValue["settingName"];
if (settingNameValue != null && settingNameValue.Type != JTokenType.Null)
{
string settingNameInstance = ((string)settingNameValue);
additionalUnattendContentInstance.SettingName = settingNameInstance;
}
JToken contentValue = additionalUnattendContentValue["content"];
if (contentValue != null && contentValue.Type != JTokenType.Null)
{
string contentInstance = ((string)contentValue);
additionalUnattendContentInstance.Content = contentInstance;
}
}
}
JToken winRMValue = windowsConfigurationValue["winRM"];
if (winRMValue != null && winRMValue.Type != JTokenType.Null)
{
WinRMConfiguration winRMInstance = new WinRMConfiguration();
windowsConfigurationInstance.WinRMConfiguration = winRMInstance;
JToken listenersArray = winRMValue["listeners"];
if (listenersArray != null && listenersArray.Type != JTokenType.Null)
{
foreach (JToken listenersValue in ((JArray)listenersArray))
{
WinRMListener winRMListenerInstance = new WinRMListener();
winRMInstance.Listeners.Add(winRMListenerInstance);
JToken protocolValue = listenersValue["protocol"];
if (protocolValue != null && protocolValue.Type != JTokenType.Null)
{
string protocolInstance = ((string)protocolValue);
winRMListenerInstance.Protocol = protocolInstance;
}
JToken certificateUrlValue = listenersValue["certificateUrl"];
if (certificateUrlValue != null && certificateUrlValue.Type != JTokenType.Null)
{
Uri certificateUrlInstance = TypeConversion.TryParseUri(((string)certificateUrlValue));
winRMListenerInstance.CertificateUrl = certificateUrlInstance;
}
}
}
}
}
JToken linuxConfigurationValue = osProfileValue["linuxConfiguration"];
if (linuxConfigurationValue != null && linuxConfigurationValue.Type != JTokenType.Null)
{
LinuxConfiguration linuxConfigurationInstance = new LinuxConfiguration();
osProfileInstance.LinuxConfiguration = linuxConfigurationInstance;
JToken disablePasswordAuthenticationValue = linuxConfigurationValue["disablePasswordAuthentication"];
if (disablePasswordAuthenticationValue != null && disablePasswordAuthenticationValue.Type != JTokenType.Null)
{
bool disablePasswordAuthenticationInstance = ((bool)disablePasswordAuthenticationValue);
linuxConfigurationInstance.DisablePasswordAuthentication = disablePasswordAuthenticationInstance;
}
JToken sshValue = linuxConfigurationValue["ssh"];
if (sshValue != null && sshValue.Type != JTokenType.Null)
{
SshConfiguration sshInstance = new SshConfiguration();
linuxConfigurationInstance.SshConfiguration = sshInstance;
JToken publicKeysArray = sshValue["publicKeys"];
if (publicKeysArray != null && publicKeysArray.Type != JTokenType.Null)
{
foreach (JToken publicKeysValue in ((JArray)publicKeysArray))
{
SshPublicKey sshPublicKeyInstance = new SshPublicKey();
sshInstance.PublicKeys.Add(sshPublicKeyInstance);
JToken pathValue = publicKeysValue["path"];
if (pathValue != null && pathValue.Type != JTokenType.Null)
{
string pathInstance = ((string)pathValue);
sshPublicKeyInstance.Path = pathInstance;
}
JToken keyDataValue = publicKeysValue["keyData"];
if (keyDataValue != null && keyDataValue.Type != JTokenType.Null)
{
string keyDataInstance = ((string)keyDataValue);
sshPublicKeyInstance.KeyData = keyDataInstance;
}
}
}
}
}
JToken secretsArray = osProfileValue["secrets"];
if (secretsArray != null && secretsArray.Type != JTokenType.Null)
{
foreach (JToken secretsValue in ((JArray)secretsArray))
{
VaultSecretGroup vaultSecretGroupInstance = new VaultSecretGroup();
osProfileInstance.Secrets.Add(vaultSecretGroupInstance);
JToken sourceVaultValue = secretsValue["sourceVault"];
if (sourceVaultValue != null && sourceVaultValue.Type != JTokenType.Null)
{
SourceVaultReference sourceVaultInstance = new SourceVaultReference();
vaultSecretGroupInstance.SourceVault = sourceVaultInstance;
JToken idValue = sourceVaultValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
sourceVaultInstance.ReferenceUri = idInstance;
}
}
JToken vaultCertificatesArray = secretsValue["vaultCertificates"];
if (vaultCertificatesArray != null && vaultCertificatesArray.Type != JTokenType.Null)
{
foreach (JToken vaultCertificatesValue in ((JArray)vaultCertificatesArray))
{
VaultCertificate vaultCertificateInstance = new VaultCertificate();
vaultSecretGroupInstance.VaultCertificates.Add(vaultCertificateInstance);
JToken certificateUrlValue2 = vaultCertificatesValue["certificateUrl"];
if (certificateUrlValue2 != null && certificateUrlValue2.Type != JTokenType.Null)
{
string certificateUrlInstance2 = ((string)certificateUrlValue2);
vaultCertificateInstance.CertificateUrl = certificateUrlInstance2;
}
JToken certificateStoreValue = vaultCertificatesValue["certificateStore"];
if (certificateStoreValue != null && certificateStoreValue.Type != JTokenType.Null)
{
string certificateStoreInstance = ((string)certificateStoreValue);
vaultCertificateInstance.CertificateStore = certificateStoreInstance;
}
}
}
}
}
}
JToken networkProfileValue = propertiesValue["networkProfile"];
if (networkProfileValue != null && networkProfileValue.Type != JTokenType.Null)
{
NetworkProfile networkProfileInstance = new NetworkProfile();
virtualMachineInstance.NetworkProfile = networkProfileInstance;
JToken networkInterfacesArray = networkProfileValue["networkInterfaces"];
if (networkInterfacesArray != null && networkInterfacesArray.Type != JTokenType.Null)
{
foreach (JToken networkInterfacesValue in ((JArray)networkInterfacesArray))
{
NetworkInterfaceReference networkInterfaceReferenceJsonInstance = new NetworkInterfaceReference();
networkProfileInstance.NetworkInterfaces.Add(networkInterfaceReferenceJsonInstance);
JToken propertiesValue2 = networkInterfacesValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken primaryValue = propertiesValue2["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
bool primaryInstance = ((bool)primaryValue);
networkInterfaceReferenceJsonInstance.Primary = primaryInstance;
}
}
JToken idValue2 = networkInterfacesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
networkInterfaceReferenceJsonInstance.ReferenceUri = idInstance2;
}
}
}
}
JToken availabilitySetValue = propertiesValue["availabilitySet"];
if (availabilitySetValue != null && availabilitySetValue.Type != JTokenType.Null)
{
AvailabilitySetReference availabilitySetInstance = new AvailabilitySetReference();
virtualMachineInstance.AvailabilitySetReference = availabilitySetInstance;
JToken idValue3 = availabilitySetValue["id"];
if (idValue3 != null && idValue3.Type != JTokenType.Null)
{
string idInstance3 = ((string)idValue3);
availabilitySetInstance.ReferenceUri = idInstance3;
}
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
virtualMachineInstance.ProvisioningState = provisioningStateInstance;
}
JToken instanceViewValue = propertiesValue["instanceView"];
if (instanceViewValue != null && instanceViewValue.Type != JTokenType.Null)
{
VirtualMachineInstanceView instanceViewInstance = new VirtualMachineInstanceView();
virtualMachineInstance.InstanceView = instanceViewInstance;
JToken platformUpdateDomainValue = instanceViewValue["platformUpdateDomain"];
if (platformUpdateDomainValue != null && platformUpdateDomainValue.Type != JTokenType.Null)
{
int platformUpdateDomainInstance = ((int)platformUpdateDomainValue);
instanceViewInstance.PlatformUpdateDomain = platformUpdateDomainInstance;
}
JToken platformFaultDomainValue = instanceViewValue["platformFaultDomain"];
if (platformFaultDomainValue != null && platformFaultDomainValue.Type != JTokenType.Null)
{
int platformFaultDomainInstance = ((int)platformFaultDomainValue);
instanceViewInstance.PlatformFaultDomain = platformFaultDomainInstance;
}
JToken rdpThumbPrintValue = instanceViewValue["rdpThumbPrint"];
if (rdpThumbPrintValue != null && rdpThumbPrintValue.Type != JTokenType.Null)
{
string rdpThumbPrintInstance = ((string)rdpThumbPrintValue);
instanceViewInstance.RemoteDesktopThumbprint = rdpThumbPrintInstance;
}
JToken vmAgentValue = instanceViewValue["vmAgent"];
if (vmAgentValue != null && vmAgentValue.Type != JTokenType.Null)
{
VirtualMachineAgentInstanceView vmAgentInstance = new VirtualMachineAgentInstanceView();
instanceViewInstance.VMAgent = vmAgentInstance;
JToken vmAgentVersionValue = vmAgentValue["vmAgentVersion"];
if (vmAgentVersionValue != null && vmAgentVersionValue.Type != JTokenType.Null)
{
string vmAgentVersionInstance = ((string)vmAgentVersionValue);
vmAgentInstance.VMAgentVersion = vmAgentVersionInstance;
}
JToken extensionHandlersArray = vmAgentValue["extensionHandlers"];
if (extensionHandlersArray != null && extensionHandlersArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlersValue in ((JArray)extensionHandlersArray))
{
VirtualMachineExtensionHandlerInstanceView virtualMachineExtensionHandlerInstanceViewInstance = new VirtualMachineExtensionHandlerInstanceView();
vmAgentInstance.ExtensionHandlers.Add(virtualMachineExtensionHandlerInstanceViewInstance);
JToken typeValue = extensionHandlersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
virtualMachineExtensionHandlerInstanceViewInstance.Type = typeInstance;
}
JToken typeHandlerVersionValue = extensionHandlersValue["typeHandlerVersion"];
if (typeHandlerVersionValue != null && typeHandlerVersionValue.Type != JTokenType.Null)
{
string typeHandlerVersionInstance = ((string)typeHandlerVersionValue);
virtualMachineExtensionHandlerInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance;
}
JToken statusValue = extensionHandlersValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
InstanceViewStatus statusInstance = new InstanceViewStatus();
virtualMachineExtensionHandlerInstanceViewInstance.Status = statusInstance;
JToken codeValue = statusValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
statusInstance.Code = codeInstance;
}
JToken levelValue = statusValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
statusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
statusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
statusInstance.Message = messageInstance;
}
JToken timeValue = statusValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
statusInstance.Time = timeInstance;
}
}
}
}
JToken statusesArray = vmAgentValue["statuses"];
if (statusesArray != null && statusesArray.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
vmAgentInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue2 = statusesValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
instanceViewStatusInstance.Code = codeInstance2;
}
JToken levelValue2 = statusesValue["level"];
if (levelValue2 != null && levelValue2.Type != JTokenType.Null)
{
string levelInstance2 = ((string)levelValue2);
instanceViewStatusInstance.Level = levelInstance2;
}
JToken displayStatusValue2 = statusesValue["displayStatus"];
if (displayStatusValue2 != null && displayStatusValue2.Type != JTokenType.Null)
{
string displayStatusInstance2 = ((string)displayStatusValue2);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance2;
}
JToken messageValue2 = statusesValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
instanceViewStatusInstance.Message = messageInstance2;
}
JToken timeValue2 = statusesValue["time"];
if (timeValue2 != null && timeValue2.Type != JTokenType.Null)
{
DateTimeOffset timeInstance2 = ((DateTimeOffset)timeValue2);
instanceViewStatusInstance.Time = timeInstance2;
}
}
}
}
JToken disksArray = instanceViewValue["disks"];
if (disksArray != null && disksArray.Type != JTokenType.Null)
{
foreach (JToken disksValue in ((JArray)disksArray))
{
DiskInstanceView diskInstanceViewInstance = new DiskInstanceView();
instanceViewInstance.Disks.Add(diskInstanceViewInstance);
JToken nameValue4 = disksValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
diskInstanceViewInstance.Name = nameInstance4;
}
JToken statusesArray2 = disksValue["statuses"];
if (statusesArray2 != null && statusesArray2.Type != JTokenType.Null)
{
foreach (JToken statusesValue2 in ((JArray)statusesArray2))
{
InstanceViewStatus instanceViewStatusInstance2 = new InstanceViewStatus();
diskInstanceViewInstance.Statuses.Add(instanceViewStatusInstance2);
JToken codeValue3 = statusesValue2["code"];
if (codeValue3 != null && codeValue3.Type != JTokenType.Null)
{
string codeInstance3 = ((string)codeValue3);
instanceViewStatusInstance2.Code = codeInstance3;
}
JToken levelValue3 = statusesValue2["level"];
if (levelValue3 != null && levelValue3.Type != JTokenType.Null)
{
string levelInstance3 = ((string)levelValue3);
instanceViewStatusInstance2.Level = levelInstance3;
}
JToken displayStatusValue3 = statusesValue2["displayStatus"];
if (displayStatusValue3 != null && displayStatusValue3.Type != JTokenType.Null)
{
string displayStatusInstance3 = ((string)displayStatusValue3);
instanceViewStatusInstance2.DisplayStatus = displayStatusInstance3;
}
JToken messageValue3 = statusesValue2["message"];
if (messageValue3 != null && messageValue3.Type != JTokenType.Null)
{
string messageInstance3 = ((string)messageValue3);
instanceViewStatusInstance2.Message = messageInstance3;
}
JToken timeValue3 = statusesValue2["time"];
if (timeValue3 != null && timeValue3.Type != JTokenType.Null)
{
DateTimeOffset timeInstance3 = ((DateTimeOffset)timeValue3);
instanceViewStatusInstance2.Time = timeInstance3;
}
}
}
}
}
JToken extensionsArray = instanceViewValue["extensions"];
if (extensionsArray != null && extensionsArray.Type != JTokenType.Null)
{
foreach (JToken extensionsValue in ((JArray)extensionsArray))
{
VirtualMachineExtensionInstanceView virtualMachineExtensionInstanceViewInstance = new VirtualMachineExtensionInstanceView();
instanceViewInstance.Extensions.Add(virtualMachineExtensionInstanceViewInstance);
JToken nameValue5 = extensionsValue["name"];
if (nameValue5 != null && nameValue5.Type != JTokenType.Null)
{
string nameInstance5 = ((string)nameValue5);
virtualMachineExtensionInstanceViewInstance.Name = nameInstance5;
}
JToken typeValue2 = extensionsValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
virtualMachineExtensionInstanceViewInstance.ExtensionType = typeInstance2;
}
JToken typeHandlerVersionValue2 = extensionsValue["typeHandlerVersion"];
if (typeHandlerVersionValue2 != null && typeHandlerVersionValue2.Type != JTokenType.Null)
{
string typeHandlerVersionInstance2 = ((string)typeHandlerVersionValue2);
virtualMachineExtensionInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance2;
}
JToken substatusesArray = extensionsValue["substatuses"];
if (substatusesArray != null && substatusesArray.Type != JTokenType.Null)
{
foreach (JToken substatusesValue in ((JArray)substatusesArray))
{
InstanceViewStatus instanceViewStatusInstance3 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.SubStatuses.Add(instanceViewStatusInstance3);
JToken codeValue4 = substatusesValue["code"];
if (codeValue4 != null && codeValue4.Type != JTokenType.Null)
{
string codeInstance4 = ((string)codeValue4);
instanceViewStatusInstance3.Code = codeInstance4;
}
JToken levelValue4 = substatusesValue["level"];
if (levelValue4 != null && levelValue4.Type != JTokenType.Null)
{
string levelInstance4 = ((string)levelValue4);
instanceViewStatusInstance3.Level = levelInstance4;
}
JToken displayStatusValue4 = substatusesValue["displayStatus"];
if (displayStatusValue4 != null && displayStatusValue4.Type != JTokenType.Null)
{
string displayStatusInstance4 = ((string)displayStatusValue4);
instanceViewStatusInstance3.DisplayStatus = displayStatusInstance4;
}
JToken messageValue4 = substatusesValue["message"];
if (messageValue4 != null && messageValue4.Type != JTokenType.Null)
{
string messageInstance4 = ((string)messageValue4);
instanceViewStatusInstance3.Message = messageInstance4;
}
JToken timeValue4 = substatusesValue["time"];
if (timeValue4 != null && timeValue4.Type != JTokenType.Null)
{
DateTimeOffset timeInstance4 = ((DateTimeOffset)timeValue4);
instanceViewStatusInstance3.Time = timeInstance4;
}
}
}
JToken statusesArray3 = extensionsValue["statuses"];
if (statusesArray3 != null && statusesArray3.Type != JTokenType.Null)
{
foreach (JToken statusesValue3 in ((JArray)statusesArray3))
{
InstanceViewStatus instanceViewStatusInstance4 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.Statuses.Add(instanceViewStatusInstance4);
JToken codeValue5 = statusesValue3["code"];
if (codeValue5 != null && codeValue5.Type != JTokenType.Null)
{
string codeInstance5 = ((string)codeValue5);
instanceViewStatusInstance4.Code = codeInstance5;
}
JToken levelValue5 = statusesValue3["level"];
if (levelValue5 != null && levelValue5.Type != JTokenType.Null)
{
string levelInstance5 = ((string)levelValue5);
instanceViewStatusInstance4.Level = levelInstance5;
}
JToken displayStatusValue5 = statusesValue3["displayStatus"];
if (displayStatusValue5 != null && displayStatusValue5.Type != JTokenType.Null)
{
string displayStatusInstance5 = ((string)displayStatusValue5);
instanceViewStatusInstance4.DisplayStatus = displayStatusInstance5;
}
JToken messageValue5 = statusesValue3["message"];
if (messageValue5 != null && messageValue5.Type != JTokenType.Null)
{
string messageInstance5 = ((string)messageValue5);
instanceViewStatusInstance4.Message = messageInstance5;
}
JToken timeValue5 = statusesValue3["time"];
if (timeValue5 != null && timeValue5.Type != JTokenType.Null)
{
DateTimeOffset timeInstance5 = ((DateTimeOffset)timeValue5);
instanceViewStatusInstance4.Time = timeInstance5;
}
}
}
}
}
JToken statusesArray4 = instanceViewValue["statuses"];
if (statusesArray4 != null && statusesArray4.Type != JTokenType.Null)
{
foreach (JToken statusesValue4 in ((JArray)statusesArray4))
{
InstanceViewStatus instanceViewStatusInstance5 = new InstanceViewStatus();
instanceViewInstance.Statuses.Add(instanceViewStatusInstance5);
JToken codeValue6 = statusesValue4["code"];
if (codeValue6 != null && codeValue6.Type != JTokenType.Null)
{
string codeInstance6 = ((string)codeValue6);
instanceViewStatusInstance5.Code = codeInstance6;
}
JToken levelValue6 = statusesValue4["level"];
if (levelValue6 != null && levelValue6.Type != JTokenType.Null)
{
string levelInstance6 = ((string)levelValue6);
instanceViewStatusInstance5.Level = levelInstance6;
}
JToken displayStatusValue6 = statusesValue4["displayStatus"];
if (displayStatusValue6 != null && displayStatusValue6.Type != JTokenType.Null)
{
string displayStatusInstance6 = ((string)displayStatusValue6);
instanceViewStatusInstance5.DisplayStatus = displayStatusInstance6;
}
JToken messageValue6 = statusesValue4["message"];
if (messageValue6 != null && messageValue6.Type != JTokenType.Null)
{
string messageInstance6 = ((string)messageValue6);
instanceViewStatusInstance5.Message = messageInstance6;
}
JToken timeValue6 = statusesValue4["time"];
if (timeValue6 != null && timeValue6.Type != JTokenType.Null)
{
DateTimeOffset timeInstance6 = ((DateTimeOffset)timeValue6);
instanceViewStatusInstance5.Time = timeInstance6;
}
}
}
}
}
JToken resourcesArray = responseDoc["resources"];
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
virtualMachineInstance.Extensions = new List<VirtualMachineExtension>();
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineExtension virtualMachineExtensionJsonInstance = new VirtualMachineExtension();
virtualMachineInstance.Extensions.Add(virtualMachineExtensionJsonInstance);
JToken propertiesValue3 = resourcesValue["properties"];
if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
{
JToken publisherValue3 = propertiesValue3["publisher"];
if (publisherValue3 != null && publisherValue3.Type != JTokenType.Null)
{
string publisherInstance3 = ((string)publisherValue3);
virtualMachineExtensionJsonInstance.Publisher = publisherInstance3;
}
JToken typeValue3 = propertiesValue3["type"];
if (typeValue3 != null && typeValue3.Type != JTokenType.Null)
{
string typeInstance3 = ((string)typeValue3);
virtualMachineExtensionJsonInstance.ExtensionType = typeInstance3;
}
JToken typeHandlerVersionValue3 = propertiesValue3["typeHandlerVersion"];
if (typeHandlerVersionValue3 != null && typeHandlerVersionValue3.Type != JTokenType.Null)
{
string typeHandlerVersionInstance3 = ((string)typeHandlerVersionValue3);
virtualMachineExtensionJsonInstance.TypeHandlerVersion = typeHandlerVersionInstance3;
}
JToken autoUpgradeMinorVersionValue = propertiesValue3["autoUpgradeMinorVersion"];
if (autoUpgradeMinorVersionValue != null && autoUpgradeMinorVersionValue.Type != JTokenType.Null)
{
bool autoUpgradeMinorVersionInstance = ((bool)autoUpgradeMinorVersionValue);
virtualMachineExtensionJsonInstance.AutoUpgradeMinorVersion = autoUpgradeMinorVersionInstance;
}
JToken settingsValue = propertiesValue3["settings"];
if (settingsValue != null && settingsValue.Type != JTokenType.Null)
{
string settingsInstance = settingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.Settings = settingsInstance;
}
JToken protectedSettingsValue = propertiesValue3["protectedSettings"];
if (protectedSettingsValue != null && protectedSettingsValue.Type != JTokenType.Null)
{
string protectedSettingsInstance = protectedSettingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.ProtectedSettings = protectedSettingsInstance;
}
JToken provisioningStateValue2 = propertiesValue3["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
virtualMachineExtensionJsonInstance.ProvisioningState = provisioningStateInstance2;
}
JToken instanceViewValue2 = propertiesValue3["instanceView"];
if (instanceViewValue2 != null && instanceViewValue2.Type != JTokenType.Null)
{
VirtualMachineExtensionInstanceView instanceViewInstance2 = new VirtualMachineExtensionInstanceView();
virtualMachineExtensionJsonInstance.InstanceView = instanceViewInstance2;
JToken nameValue6 = instanceViewValue2["name"];
if (nameValue6 != null && nameValue6.Type != JTokenType.Null)
{
string nameInstance6 = ((string)nameValue6);
instanceViewInstance2.Name = nameInstance6;
}
JToken typeValue4 = instanceViewValue2["type"];
if (typeValue4 != null && typeValue4.Type != JTokenType.Null)
{
string typeInstance4 = ((string)typeValue4);
instanceViewInstance2.ExtensionType = typeInstance4;
}
JToken typeHandlerVersionValue4 = instanceViewValue2["typeHandlerVersion"];
if (typeHandlerVersionValue4 != null && typeHandlerVersionValue4.Type != JTokenType.Null)
{
string typeHandlerVersionInstance4 = ((string)typeHandlerVersionValue4);
instanceViewInstance2.TypeHandlerVersion = typeHandlerVersionInstance4;
}
JToken substatusesArray2 = instanceViewValue2["substatuses"];
if (substatusesArray2 != null && substatusesArray2.Type != JTokenType.Null)
{
foreach (JToken substatusesValue2 in ((JArray)substatusesArray2))
{
InstanceViewStatus instanceViewStatusInstance6 = new InstanceViewStatus();
instanceViewInstance2.SubStatuses.Add(instanceViewStatusInstance6);
JToken codeValue7 = substatusesValue2["code"];
if (codeValue7 != null && codeValue7.Type != JTokenType.Null)
{
string codeInstance7 = ((string)codeValue7);
instanceViewStatusInstance6.Code = codeInstance7;
}
JToken levelValue7 = substatusesValue2["level"];
if (levelValue7 != null && levelValue7.Type != JTokenType.Null)
{
string levelInstance7 = ((string)levelValue7);
instanceViewStatusInstance6.Level = levelInstance7;
}
JToken displayStatusValue7 = substatusesValue2["displayStatus"];
if (displayStatusValue7 != null && displayStatusValue7.Type != JTokenType.Null)
{
string displayStatusInstance7 = ((string)displayStatusValue7);
instanceViewStatusInstance6.DisplayStatus = displayStatusInstance7;
}
JToken messageValue7 = substatusesValue2["message"];
if (messageValue7 != null && messageValue7.Type != JTokenType.Null)
{
string messageInstance7 = ((string)messageValue7);
instanceViewStatusInstance6.Message = messageInstance7;
}
JToken timeValue7 = substatusesValue2["time"];
if (timeValue7 != null && timeValue7.Type != JTokenType.Null)
{
DateTimeOffset timeInstance7 = ((DateTimeOffset)timeValue7);
instanceViewStatusInstance6.Time = timeInstance7;
}
}
}
JToken statusesArray5 = instanceViewValue2["statuses"];
if (statusesArray5 != null && statusesArray5.Type != JTokenType.Null)
{
foreach (JToken statusesValue5 in ((JArray)statusesArray5))
{
InstanceViewStatus instanceViewStatusInstance7 = new InstanceViewStatus();
instanceViewInstance2.Statuses.Add(instanceViewStatusInstance7);
JToken codeValue8 = statusesValue5["code"];
if (codeValue8 != null && codeValue8.Type != JTokenType.Null)
{
string codeInstance8 = ((string)codeValue8);
instanceViewStatusInstance7.Code = codeInstance8;
}
JToken levelValue8 = statusesValue5["level"];
if (levelValue8 != null && levelValue8.Type != JTokenType.Null)
{
string levelInstance8 = ((string)levelValue8);
instanceViewStatusInstance7.Level = levelInstance8;
}
JToken displayStatusValue8 = statusesValue5["displayStatus"];
if (displayStatusValue8 != null && displayStatusValue8.Type != JTokenType.Null)
{
string displayStatusInstance8 = ((string)displayStatusValue8);
instanceViewStatusInstance7.DisplayStatus = displayStatusInstance8;
}
JToken messageValue8 = statusesValue5["message"];
if (messageValue8 != null && messageValue8.Type != JTokenType.Null)
{
string messageInstance8 = ((string)messageValue8);
instanceViewStatusInstance7.Message = messageInstance8;
}
JToken timeValue8 = statusesValue5["time"];
if (timeValue8 != null && timeValue8.Type != JTokenType.Null)
{
DateTimeOffset timeInstance8 = ((DateTimeOffset)timeValue8);
instanceViewStatusInstance7.Time = timeInstance8;
}
}
}
}
}
JToken idValue4 = resourcesValue["id"];
if (idValue4 != null && idValue4.Type != JTokenType.Null)
{
string idInstance4 = ((string)idValue4);
virtualMachineExtensionJsonInstance.Id = idInstance4;
}
JToken nameValue7 = resourcesValue["name"];
if (nameValue7 != null && nameValue7.Type != JTokenType.Null)
{
string nameInstance7 = ((string)nameValue7);
virtualMachineExtensionJsonInstance.Name = nameInstance7;
}
JToken typeValue5 = resourcesValue["type"];
if (typeValue5 != null && typeValue5.Type != JTokenType.Null)
{
string typeInstance5 = ((string)typeValue5);
virtualMachineExtensionJsonInstance.Type = typeInstance5;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineExtensionJsonInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)resourcesValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
virtualMachineExtensionJsonInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken idValue5 = responseDoc["id"];
if (idValue5 != null && idValue5.Type != JTokenType.Null)
{
string idInstance5 = ((string)idValue5);
virtualMachineInstance.Id = idInstance5;
}
JToken nameValue8 = responseDoc["name"];
if (nameValue8 != null && nameValue8.Type != JTokenType.Null)
{
string nameInstance8 = ((string)nameValue8);
virtualMachineInstance.Name = nameInstance8;
}
JToken typeValue6 = responseDoc["type"];
if (typeValue6 != null && typeValue6.Type != JTokenType.Null)
{
string typeInstance6 = ((string)typeValue6);
virtualMachineInstance.Type = typeInstance6;
}
JToken locationValue2 = responseDoc["location"];
if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
{
string locationInstance2 = ((string)locationValue2);
virtualMachineInstance.Location = locationInstance2;
}
JToken tagsSequenceElement2 = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null)
{
foreach (JProperty property2 in tagsSequenceElement2)
{
string tagsKey2 = ((string)property2.Name);
string tagsValue2 = ((string)property2.Value);
virtualMachineInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Virtual Machine operation response.
/// </returns>
public async Task<VirtualMachineListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
VirtualMachine virtualMachineJsonInstance = new VirtualMachine();
result.VirtualMachines.Add(virtualMachineJsonInstance);
JToken planValue = valueValue["plan"];
if (planValue != null && planValue.Type != JTokenType.Null)
{
Plan planInstance = new Plan();
virtualMachineJsonInstance.Plan = planInstance;
JToken nameValue = planValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
planInstance.Name = nameInstance;
}
JToken publisherValue = planValue["publisher"];
if (publisherValue != null && publisherValue.Type != JTokenType.Null)
{
string publisherInstance = ((string)publisherValue);
planInstance.Publisher = publisherInstance;
}
JToken productValue = planValue["product"];
if (productValue != null && productValue.Type != JTokenType.Null)
{
string productInstance = ((string)productValue);
planInstance.Product = productInstance;
}
JToken promotionCodeValue = planValue["promotionCode"];
if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
{
string promotionCodeInstance = ((string)promotionCodeValue);
planInstance.PromotionCode = promotionCodeInstance;
}
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken hardwareProfileValue = propertiesValue["hardwareProfile"];
if (hardwareProfileValue != null && hardwareProfileValue.Type != JTokenType.Null)
{
HardwareProfile hardwareProfileInstance = new HardwareProfile();
virtualMachineJsonInstance.HardwareProfile = hardwareProfileInstance;
JToken vmSizeValue = hardwareProfileValue["vmSize"];
if (vmSizeValue != null && vmSizeValue.Type != JTokenType.Null)
{
string vmSizeInstance = ((string)vmSizeValue);
hardwareProfileInstance.VirtualMachineSize = vmSizeInstance;
}
}
JToken storageProfileValue = propertiesValue["storageProfile"];
if (storageProfileValue != null && storageProfileValue.Type != JTokenType.Null)
{
StorageProfile storageProfileInstance = new StorageProfile();
virtualMachineJsonInstance.StorageProfile = storageProfileInstance;
JToken imageReferenceValue = storageProfileValue["imageReference"];
if (imageReferenceValue != null && imageReferenceValue.Type != JTokenType.Null)
{
ImageReference imageReferenceInstance = new ImageReference();
storageProfileInstance.ImageReference = imageReferenceInstance;
JToken publisherValue2 = imageReferenceValue["publisher"];
if (publisherValue2 != null && publisherValue2.Type != JTokenType.Null)
{
string publisherInstance2 = ((string)publisherValue2);
imageReferenceInstance.Publisher = publisherInstance2;
}
JToken offerValue = imageReferenceValue["offer"];
if (offerValue != null && offerValue.Type != JTokenType.Null)
{
string offerInstance = ((string)offerValue);
imageReferenceInstance.Offer = offerInstance;
}
JToken skuValue = imageReferenceValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
string skuInstance = ((string)skuValue);
imageReferenceInstance.Sku = skuInstance;
}
JToken versionValue = imageReferenceValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
imageReferenceInstance.Version = versionInstance;
}
}
JToken osDiskValue = storageProfileValue["osDisk"];
if (osDiskValue != null && osDiskValue.Type != JTokenType.Null)
{
OSDisk osDiskInstance = new OSDisk();
storageProfileInstance.OSDisk = osDiskInstance;
JToken osTypeValue = osDiskValue["osType"];
if (osTypeValue != null && osTypeValue.Type != JTokenType.Null)
{
string osTypeInstance = ((string)osTypeValue);
osDiskInstance.OperatingSystemType = osTypeInstance;
}
JToken nameValue2 = osDiskValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
osDiskInstance.Name = nameInstance2;
}
JToken vhdValue = osDiskValue["vhd"];
if (vhdValue != null && vhdValue.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance = new VirtualHardDisk();
osDiskInstance.VirtualHardDisk = vhdInstance;
JToken uriValue = vhdValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
vhdInstance.Uri = uriInstance;
}
}
JToken imageValue = osDiskValue["image"];
if (imageValue != null && imageValue.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance = new VirtualHardDisk();
osDiskInstance.SourceImage = imageInstance;
JToken uriValue2 = imageValue["uri"];
if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
{
string uriInstance2 = ((string)uriValue2);
imageInstance.Uri = uriInstance2;
}
}
JToken cachingValue = osDiskValue["caching"];
if (cachingValue != null && cachingValue.Type != JTokenType.Null)
{
string cachingInstance = ((string)cachingValue);
osDiskInstance.Caching = cachingInstance;
}
JToken createOptionValue = osDiskValue["createOption"];
if (createOptionValue != null && createOptionValue.Type != JTokenType.Null)
{
string createOptionInstance = ((string)createOptionValue);
osDiskInstance.CreateOption = createOptionInstance;
}
JToken diskSizeGBValue = osDiskValue["diskSizeGB"];
if (diskSizeGBValue != null && diskSizeGBValue.Type != JTokenType.Null)
{
int diskSizeGBInstance = ((int)diskSizeGBValue);
osDiskInstance.DiskSizeGB = diskSizeGBInstance;
}
}
JToken dataDisksArray = storageProfileValue["dataDisks"];
if (dataDisksArray != null && dataDisksArray.Type != JTokenType.Null)
{
foreach (JToken dataDisksValue in ((JArray)dataDisksArray))
{
DataDisk dataDiskInstance = new DataDisk();
storageProfileInstance.DataDisks.Add(dataDiskInstance);
JToken lunValue = dataDisksValue["lun"];
if (lunValue != null && lunValue.Type != JTokenType.Null)
{
int lunInstance = ((int)lunValue);
dataDiskInstance.Lun = lunInstance;
}
JToken nameValue3 = dataDisksValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dataDiskInstance.Name = nameInstance3;
}
JToken vhdValue2 = dataDisksValue["vhd"];
if (vhdValue2 != null && vhdValue2.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance2 = new VirtualHardDisk();
dataDiskInstance.VirtualHardDisk = vhdInstance2;
JToken uriValue3 = vhdValue2["uri"];
if (uriValue3 != null && uriValue3.Type != JTokenType.Null)
{
string uriInstance3 = ((string)uriValue3);
vhdInstance2.Uri = uriInstance3;
}
}
JToken imageValue2 = dataDisksValue["image"];
if (imageValue2 != null && imageValue2.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance2 = new VirtualHardDisk();
dataDiskInstance.SourceImage = imageInstance2;
JToken uriValue4 = imageValue2["uri"];
if (uriValue4 != null && uriValue4.Type != JTokenType.Null)
{
string uriInstance4 = ((string)uriValue4);
imageInstance2.Uri = uriInstance4;
}
}
JToken cachingValue2 = dataDisksValue["caching"];
if (cachingValue2 != null && cachingValue2.Type != JTokenType.Null)
{
string cachingInstance2 = ((string)cachingValue2);
dataDiskInstance.Caching = cachingInstance2;
}
JToken createOptionValue2 = dataDisksValue["createOption"];
if (createOptionValue2 != null && createOptionValue2.Type != JTokenType.Null)
{
string createOptionInstance2 = ((string)createOptionValue2);
dataDiskInstance.CreateOption = createOptionInstance2;
}
JToken diskSizeGBValue2 = dataDisksValue["diskSizeGB"];
if (diskSizeGBValue2 != null && diskSizeGBValue2.Type != JTokenType.Null)
{
int diskSizeGBInstance2 = ((int)diskSizeGBValue2);
dataDiskInstance.DiskSizeGB = diskSizeGBInstance2;
}
}
}
}
JToken osProfileValue = propertiesValue["osProfile"];
if (osProfileValue != null && osProfileValue.Type != JTokenType.Null)
{
OSProfile osProfileInstance = new OSProfile();
virtualMachineJsonInstance.OSProfile = osProfileInstance;
JToken computerNameValue = osProfileValue["computerName"];
if (computerNameValue != null && computerNameValue.Type != JTokenType.Null)
{
string computerNameInstance = ((string)computerNameValue);
osProfileInstance.ComputerName = computerNameInstance;
}
JToken adminUsernameValue = osProfileValue["adminUsername"];
if (adminUsernameValue != null && adminUsernameValue.Type != JTokenType.Null)
{
string adminUsernameInstance = ((string)adminUsernameValue);
osProfileInstance.AdminUsername = adminUsernameInstance;
}
JToken adminPasswordValue = osProfileValue["adminPassword"];
if (adminPasswordValue != null && adminPasswordValue.Type != JTokenType.Null)
{
string adminPasswordInstance = ((string)adminPasswordValue);
osProfileInstance.AdminPassword = adminPasswordInstance;
}
JToken customDataValue = osProfileValue["customData"];
if (customDataValue != null && customDataValue.Type != JTokenType.Null)
{
string customDataInstance = ((string)customDataValue);
osProfileInstance.CustomData = customDataInstance;
}
JToken windowsConfigurationValue = osProfileValue["windowsConfiguration"];
if (windowsConfigurationValue != null && windowsConfigurationValue.Type != JTokenType.Null)
{
WindowsConfiguration windowsConfigurationInstance = new WindowsConfiguration();
osProfileInstance.WindowsConfiguration = windowsConfigurationInstance;
JToken provisionVMAgentValue = windowsConfigurationValue["provisionVMAgent"];
if (provisionVMAgentValue != null && provisionVMAgentValue.Type != JTokenType.Null)
{
bool provisionVMAgentInstance = ((bool)provisionVMAgentValue);
windowsConfigurationInstance.ProvisionVMAgent = provisionVMAgentInstance;
}
JToken enableAutomaticUpdatesValue = windowsConfigurationValue["enableAutomaticUpdates"];
if (enableAutomaticUpdatesValue != null && enableAutomaticUpdatesValue.Type != JTokenType.Null)
{
bool enableAutomaticUpdatesInstance = ((bool)enableAutomaticUpdatesValue);
windowsConfigurationInstance.EnableAutomaticUpdates = enableAutomaticUpdatesInstance;
}
JToken timeZoneValue = windowsConfigurationValue["timeZone"];
if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
{
string timeZoneInstance = ((string)timeZoneValue);
windowsConfigurationInstance.TimeZone = timeZoneInstance;
}
JToken additionalUnattendContentArray = windowsConfigurationValue["additionalUnattendContent"];
if (additionalUnattendContentArray != null && additionalUnattendContentArray.Type != JTokenType.Null)
{
foreach (JToken additionalUnattendContentValue in ((JArray)additionalUnattendContentArray))
{
AdditionalUnattendContent additionalUnattendContentInstance = new AdditionalUnattendContent();
windowsConfigurationInstance.AdditionalUnattendContents.Add(additionalUnattendContentInstance);
JToken passNameValue = additionalUnattendContentValue["passName"];
if (passNameValue != null && passNameValue.Type != JTokenType.Null)
{
string passNameInstance = ((string)passNameValue);
additionalUnattendContentInstance.PassName = passNameInstance;
}
JToken componentNameValue = additionalUnattendContentValue["componentName"];
if (componentNameValue != null && componentNameValue.Type != JTokenType.Null)
{
string componentNameInstance = ((string)componentNameValue);
additionalUnattendContentInstance.ComponentName = componentNameInstance;
}
JToken settingNameValue = additionalUnattendContentValue["settingName"];
if (settingNameValue != null && settingNameValue.Type != JTokenType.Null)
{
string settingNameInstance = ((string)settingNameValue);
additionalUnattendContentInstance.SettingName = settingNameInstance;
}
JToken contentValue = additionalUnattendContentValue["content"];
if (contentValue != null && contentValue.Type != JTokenType.Null)
{
string contentInstance = ((string)contentValue);
additionalUnattendContentInstance.Content = contentInstance;
}
}
}
JToken winRMValue = windowsConfigurationValue["winRM"];
if (winRMValue != null && winRMValue.Type != JTokenType.Null)
{
WinRMConfiguration winRMInstance = new WinRMConfiguration();
windowsConfigurationInstance.WinRMConfiguration = winRMInstance;
JToken listenersArray = winRMValue["listeners"];
if (listenersArray != null && listenersArray.Type != JTokenType.Null)
{
foreach (JToken listenersValue in ((JArray)listenersArray))
{
WinRMListener winRMListenerInstance = new WinRMListener();
winRMInstance.Listeners.Add(winRMListenerInstance);
JToken protocolValue = listenersValue["protocol"];
if (protocolValue != null && protocolValue.Type != JTokenType.Null)
{
string protocolInstance = ((string)protocolValue);
winRMListenerInstance.Protocol = protocolInstance;
}
JToken certificateUrlValue = listenersValue["certificateUrl"];
if (certificateUrlValue != null && certificateUrlValue.Type != JTokenType.Null)
{
Uri certificateUrlInstance = TypeConversion.TryParseUri(((string)certificateUrlValue));
winRMListenerInstance.CertificateUrl = certificateUrlInstance;
}
}
}
}
}
JToken linuxConfigurationValue = osProfileValue["linuxConfiguration"];
if (linuxConfigurationValue != null && linuxConfigurationValue.Type != JTokenType.Null)
{
LinuxConfiguration linuxConfigurationInstance = new LinuxConfiguration();
osProfileInstance.LinuxConfiguration = linuxConfigurationInstance;
JToken disablePasswordAuthenticationValue = linuxConfigurationValue["disablePasswordAuthentication"];
if (disablePasswordAuthenticationValue != null && disablePasswordAuthenticationValue.Type != JTokenType.Null)
{
bool disablePasswordAuthenticationInstance = ((bool)disablePasswordAuthenticationValue);
linuxConfigurationInstance.DisablePasswordAuthentication = disablePasswordAuthenticationInstance;
}
JToken sshValue = linuxConfigurationValue["ssh"];
if (sshValue != null && sshValue.Type != JTokenType.Null)
{
SshConfiguration sshInstance = new SshConfiguration();
linuxConfigurationInstance.SshConfiguration = sshInstance;
JToken publicKeysArray = sshValue["publicKeys"];
if (publicKeysArray != null && publicKeysArray.Type != JTokenType.Null)
{
foreach (JToken publicKeysValue in ((JArray)publicKeysArray))
{
SshPublicKey sshPublicKeyInstance = new SshPublicKey();
sshInstance.PublicKeys.Add(sshPublicKeyInstance);
JToken pathValue = publicKeysValue["path"];
if (pathValue != null && pathValue.Type != JTokenType.Null)
{
string pathInstance = ((string)pathValue);
sshPublicKeyInstance.Path = pathInstance;
}
JToken keyDataValue = publicKeysValue["keyData"];
if (keyDataValue != null && keyDataValue.Type != JTokenType.Null)
{
string keyDataInstance = ((string)keyDataValue);
sshPublicKeyInstance.KeyData = keyDataInstance;
}
}
}
}
}
JToken secretsArray = osProfileValue["secrets"];
if (secretsArray != null && secretsArray.Type != JTokenType.Null)
{
foreach (JToken secretsValue in ((JArray)secretsArray))
{
VaultSecretGroup vaultSecretGroupInstance = new VaultSecretGroup();
osProfileInstance.Secrets.Add(vaultSecretGroupInstance);
JToken sourceVaultValue = secretsValue["sourceVault"];
if (sourceVaultValue != null && sourceVaultValue.Type != JTokenType.Null)
{
SourceVaultReference sourceVaultInstance = new SourceVaultReference();
vaultSecretGroupInstance.SourceVault = sourceVaultInstance;
JToken idValue = sourceVaultValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
sourceVaultInstance.ReferenceUri = idInstance;
}
}
JToken vaultCertificatesArray = secretsValue["vaultCertificates"];
if (vaultCertificatesArray != null && vaultCertificatesArray.Type != JTokenType.Null)
{
foreach (JToken vaultCertificatesValue in ((JArray)vaultCertificatesArray))
{
VaultCertificate vaultCertificateInstance = new VaultCertificate();
vaultSecretGroupInstance.VaultCertificates.Add(vaultCertificateInstance);
JToken certificateUrlValue2 = vaultCertificatesValue["certificateUrl"];
if (certificateUrlValue2 != null && certificateUrlValue2.Type != JTokenType.Null)
{
string certificateUrlInstance2 = ((string)certificateUrlValue2);
vaultCertificateInstance.CertificateUrl = certificateUrlInstance2;
}
JToken certificateStoreValue = vaultCertificatesValue["certificateStore"];
if (certificateStoreValue != null && certificateStoreValue.Type != JTokenType.Null)
{
string certificateStoreInstance = ((string)certificateStoreValue);
vaultCertificateInstance.CertificateStore = certificateStoreInstance;
}
}
}
}
}
}
JToken networkProfileValue = propertiesValue["networkProfile"];
if (networkProfileValue != null && networkProfileValue.Type != JTokenType.Null)
{
NetworkProfile networkProfileInstance = new NetworkProfile();
virtualMachineJsonInstance.NetworkProfile = networkProfileInstance;
JToken networkInterfacesArray = networkProfileValue["networkInterfaces"];
if (networkInterfacesArray != null && networkInterfacesArray.Type != JTokenType.Null)
{
foreach (JToken networkInterfacesValue in ((JArray)networkInterfacesArray))
{
NetworkInterfaceReference networkInterfaceReferenceJsonInstance = new NetworkInterfaceReference();
networkProfileInstance.NetworkInterfaces.Add(networkInterfaceReferenceJsonInstance);
JToken propertiesValue2 = networkInterfacesValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken primaryValue = propertiesValue2["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
bool primaryInstance = ((bool)primaryValue);
networkInterfaceReferenceJsonInstance.Primary = primaryInstance;
}
}
JToken idValue2 = networkInterfacesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
networkInterfaceReferenceJsonInstance.ReferenceUri = idInstance2;
}
}
}
}
JToken availabilitySetValue = propertiesValue["availabilitySet"];
if (availabilitySetValue != null && availabilitySetValue.Type != JTokenType.Null)
{
AvailabilitySetReference availabilitySetInstance = new AvailabilitySetReference();
virtualMachineJsonInstance.AvailabilitySetReference = availabilitySetInstance;
JToken idValue3 = availabilitySetValue["id"];
if (idValue3 != null && idValue3.Type != JTokenType.Null)
{
string idInstance3 = ((string)idValue3);
availabilitySetInstance.ReferenceUri = idInstance3;
}
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
virtualMachineJsonInstance.ProvisioningState = provisioningStateInstance;
}
JToken instanceViewValue = propertiesValue["instanceView"];
if (instanceViewValue != null && instanceViewValue.Type != JTokenType.Null)
{
VirtualMachineInstanceView instanceViewInstance = new VirtualMachineInstanceView();
virtualMachineJsonInstance.InstanceView = instanceViewInstance;
JToken platformUpdateDomainValue = instanceViewValue["platformUpdateDomain"];
if (platformUpdateDomainValue != null && platformUpdateDomainValue.Type != JTokenType.Null)
{
int platformUpdateDomainInstance = ((int)platformUpdateDomainValue);
instanceViewInstance.PlatformUpdateDomain = platformUpdateDomainInstance;
}
JToken platformFaultDomainValue = instanceViewValue["platformFaultDomain"];
if (platformFaultDomainValue != null && platformFaultDomainValue.Type != JTokenType.Null)
{
int platformFaultDomainInstance = ((int)platformFaultDomainValue);
instanceViewInstance.PlatformFaultDomain = platformFaultDomainInstance;
}
JToken rdpThumbPrintValue = instanceViewValue["rdpThumbPrint"];
if (rdpThumbPrintValue != null && rdpThumbPrintValue.Type != JTokenType.Null)
{
string rdpThumbPrintInstance = ((string)rdpThumbPrintValue);
instanceViewInstance.RemoteDesktopThumbprint = rdpThumbPrintInstance;
}
JToken vmAgentValue = instanceViewValue["vmAgent"];
if (vmAgentValue != null && vmAgentValue.Type != JTokenType.Null)
{
VirtualMachineAgentInstanceView vmAgentInstance = new VirtualMachineAgentInstanceView();
instanceViewInstance.VMAgent = vmAgentInstance;
JToken vmAgentVersionValue = vmAgentValue["vmAgentVersion"];
if (vmAgentVersionValue != null && vmAgentVersionValue.Type != JTokenType.Null)
{
string vmAgentVersionInstance = ((string)vmAgentVersionValue);
vmAgentInstance.VMAgentVersion = vmAgentVersionInstance;
}
JToken extensionHandlersArray = vmAgentValue["extensionHandlers"];
if (extensionHandlersArray != null && extensionHandlersArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlersValue in ((JArray)extensionHandlersArray))
{
VirtualMachineExtensionHandlerInstanceView virtualMachineExtensionHandlerInstanceViewInstance = new VirtualMachineExtensionHandlerInstanceView();
vmAgentInstance.ExtensionHandlers.Add(virtualMachineExtensionHandlerInstanceViewInstance);
JToken typeValue = extensionHandlersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
virtualMachineExtensionHandlerInstanceViewInstance.Type = typeInstance;
}
JToken typeHandlerVersionValue = extensionHandlersValue["typeHandlerVersion"];
if (typeHandlerVersionValue != null && typeHandlerVersionValue.Type != JTokenType.Null)
{
string typeHandlerVersionInstance = ((string)typeHandlerVersionValue);
virtualMachineExtensionHandlerInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance;
}
JToken statusValue = extensionHandlersValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
InstanceViewStatus statusInstance = new InstanceViewStatus();
virtualMachineExtensionHandlerInstanceViewInstance.Status = statusInstance;
JToken codeValue = statusValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
statusInstance.Code = codeInstance;
}
JToken levelValue = statusValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
statusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
statusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
statusInstance.Message = messageInstance;
}
JToken timeValue = statusValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
statusInstance.Time = timeInstance;
}
}
}
}
JToken statusesArray = vmAgentValue["statuses"];
if (statusesArray != null && statusesArray.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
vmAgentInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue2 = statusesValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
instanceViewStatusInstance.Code = codeInstance2;
}
JToken levelValue2 = statusesValue["level"];
if (levelValue2 != null && levelValue2.Type != JTokenType.Null)
{
string levelInstance2 = ((string)levelValue2);
instanceViewStatusInstance.Level = levelInstance2;
}
JToken displayStatusValue2 = statusesValue["displayStatus"];
if (displayStatusValue2 != null && displayStatusValue2.Type != JTokenType.Null)
{
string displayStatusInstance2 = ((string)displayStatusValue2);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance2;
}
JToken messageValue2 = statusesValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
instanceViewStatusInstance.Message = messageInstance2;
}
JToken timeValue2 = statusesValue["time"];
if (timeValue2 != null && timeValue2.Type != JTokenType.Null)
{
DateTimeOffset timeInstance2 = ((DateTimeOffset)timeValue2);
instanceViewStatusInstance.Time = timeInstance2;
}
}
}
}
JToken disksArray = instanceViewValue["disks"];
if (disksArray != null && disksArray.Type != JTokenType.Null)
{
foreach (JToken disksValue in ((JArray)disksArray))
{
DiskInstanceView diskInstanceViewInstance = new DiskInstanceView();
instanceViewInstance.Disks.Add(diskInstanceViewInstance);
JToken nameValue4 = disksValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
diskInstanceViewInstance.Name = nameInstance4;
}
JToken statusesArray2 = disksValue["statuses"];
if (statusesArray2 != null && statusesArray2.Type != JTokenType.Null)
{
foreach (JToken statusesValue2 in ((JArray)statusesArray2))
{
InstanceViewStatus instanceViewStatusInstance2 = new InstanceViewStatus();
diskInstanceViewInstance.Statuses.Add(instanceViewStatusInstance2);
JToken codeValue3 = statusesValue2["code"];
if (codeValue3 != null && codeValue3.Type != JTokenType.Null)
{
string codeInstance3 = ((string)codeValue3);
instanceViewStatusInstance2.Code = codeInstance3;
}
JToken levelValue3 = statusesValue2["level"];
if (levelValue3 != null && levelValue3.Type != JTokenType.Null)
{
string levelInstance3 = ((string)levelValue3);
instanceViewStatusInstance2.Level = levelInstance3;
}
JToken displayStatusValue3 = statusesValue2["displayStatus"];
if (displayStatusValue3 != null && displayStatusValue3.Type != JTokenType.Null)
{
string displayStatusInstance3 = ((string)displayStatusValue3);
instanceViewStatusInstance2.DisplayStatus = displayStatusInstance3;
}
JToken messageValue3 = statusesValue2["message"];
if (messageValue3 != null && messageValue3.Type != JTokenType.Null)
{
string messageInstance3 = ((string)messageValue3);
instanceViewStatusInstance2.Message = messageInstance3;
}
JToken timeValue3 = statusesValue2["time"];
if (timeValue3 != null && timeValue3.Type != JTokenType.Null)
{
DateTimeOffset timeInstance3 = ((DateTimeOffset)timeValue3);
instanceViewStatusInstance2.Time = timeInstance3;
}
}
}
}
}
JToken extensionsArray = instanceViewValue["extensions"];
if (extensionsArray != null && extensionsArray.Type != JTokenType.Null)
{
foreach (JToken extensionsValue in ((JArray)extensionsArray))
{
VirtualMachineExtensionInstanceView virtualMachineExtensionInstanceViewInstance = new VirtualMachineExtensionInstanceView();
instanceViewInstance.Extensions.Add(virtualMachineExtensionInstanceViewInstance);
JToken nameValue5 = extensionsValue["name"];
if (nameValue5 != null && nameValue5.Type != JTokenType.Null)
{
string nameInstance5 = ((string)nameValue5);
virtualMachineExtensionInstanceViewInstance.Name = nameInstance5;
}
JToken typeValue2 = extensionsValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
virtualMachineExtensionInstanceViewInstance.ExtensionType = typeInstance2;
}
JToken typeHandlerVersionValue2 = extensionsValue["typeHandlerVersion"];
if (typeHandlerVersionValue2 != null && typeHandlerVersionValue2.Type != JTokenType.Null)
{
string typeHandlerVersionInstance2 = ((string)typeHandlerVersionValue2);
virtualMachineExtensionInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance2;
}
JToken substatusesArray = extensionsValue["substatuses"];
if (substatusesArray != null && substatusesArray.Type != JTokenType.Null)
{
foreach (JToken substatusesValue in ((JArray)substatusesArray))
{
InstanceViewStatus instanceViewStatusInstance3 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.SubStatuses.Add(instanceViewStatusInstance3);
JToken codeValue4 = substatusesValue["code"];
if (codeValue4 != null && codeValue4.Type != JTokenType.Null)
{
string codeInstance4 = ((string)codeValue4);
instanceViewStatusInstance3.Code = codeInstance4;
}
JToken levelValue4 = substatusesValue["level"];
if (levelValue4 != null && levelValue4.Type != JTokenType.Null)
{
string levelInstance4 = ((string)levelValue4);
instanceViewStatusInstance3.Level = levelInstance4;
}
JToken displayStatusValue4 = substatusesValue["displayStatus"];
if (displayStatusValue4 != null && displayStatusValue4.Type != JTokenType.Null)
{
string displayStatusInstance4 = ((string)displayStatusValue4);
instanceViewStatusInstance3.DisplayStatus = displayStatusInstance4;
}
JToken messageValue4 = substatusesValue["message"];
if (messageValue4 != null && messageValue4.Type != JTokenType.Null)
{
string messageInstance4 = ((string)messageValue4);
instanceViewStatusInstance3.Message = messageInstance4;
}
JToken timeValue4 = substatusesValue["time"];
if (timeValue4 != null && timeValue4.Type != JTokenType.Null)
{
DateTimeOffset timeInstance4 = ((DateTimeOffset)timeValue4);
instanceViewStatusInstance3.Time = timeInstance4;
}
}
}
JToken statusesArray3 = extensionsValue["statuses"];
if (statusesArray3 != null && statusesArray3.Type != JTokenType.Null)
{
foreach (JToken statusesValue3 in ((JArray)statusesArray3))
{
InstanceViewStatus instanceViewStatusInstance4 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.Statuses.Add(instanceViewStatusInstance4);
JToken codeValue5 = statusesValue3["code"];
if (codeValue5 != null && codeValue5.Type != JTokenType.Null)
{
string codeInstance5 = ((string)codeValue5);
instanceViewStatusInstance4.Code = codeInstance5;
}
JToken levelValue5 = statusesValue3["level"];
if (levelValue5 != null && levelValue5.Type != JTokenType.Null)
{
string levelInstance5 = ((string)levelValue5);
instanceViewStatusInstance4.Level = levelInstance5;
}
JToken displayStatusValue5 = statusesValue3["displayStatus"];
if (displayStatusValue5 != null && displayStatusValue5.Type != JTokenType.Null)
{
string displayStatusInstance5 = ((string)displayStatusValue5);
instanceViewStatusInstance4.DisplayStatus = displayStatusInstance5;
}
JToken messageValue5 = statusesValue3["message"];
if (messageValue5 != null && messageValue5.Type != JTokenType.Null)
{
string messageInstance5 = ((string)messageValue5);
instanceViewStatusInstance4.Message = messageInstance5;
}
JToken timeValue5 = statusesValue3["time"];
if (timeValue5 != null && timeValue5.Type != JTokenType.Null)
{
DateTimeOffset timeInstance5 = ((DateTimeOffset)timeValue5);
instanceViewStatusInstance4.Time = timeInstance5;
}
}
}
}
}
JToken statusesArray4 = instanceViewValue["statuses"];
if (statusesArray4 != null && statusesArray4.Type != JTokenType.Null)
{
foreach (JToken statusesValue4 in ((JArray)statusesArray4))
{
InstanceViewStatus instanceViewStatusInstance5 = new InstanceViewStatus();
instanceViewInstance.Statuses.Add(instanceViewStatusInstance5);
JToken codeValue6 = statusesValue4["code"];
if (codeValue6 != null && codeValue6.Type != JTokenType.Null)
{
string codeInstance6 = ((string)codeValue6);
instanceViewStatusInstance5.Code = codeInstance6;
}
JToken levelValue6 = statusesValue4["level"];
if (levelValue6 != null && levelValue6.Type != JTokenType.Null)
{
string levelInstance6 = ((string)levelValue6);
instanceViewStatusInstance5.Level = levelInstance6;
}
JToken displayStatusValue6 = statusesValue4["displayStatus"];
if (displayStatusValue6 != null && displayStatusValue6.Type != JTokenType.Null)
{
string displayStatusInstance6 = ((string)displayStatusValue6);
instanceViewStatusInstance5.DisplayStatus = displayStatusInstance6;
}
JToken messageValue6 = statusesValue4["message"];
if (messageValue6 != null && messageValue6.Type != JTokenType.Null)
{
string messageInstance6 = ((string)messageValue6);
instanceViewStatusInstance5.Message = messageInstance6;
}
JToken timeValue6 = statusesValue4["time"];
if (timeValue6 != null && timeValue6.Type != JTokenType.Null)
{
DateTimeOffset timeInstance6 = ((DateTimeOffset)timeValue6);
instanceViewStatusInstance5.Time = timeInstance6;
}
}
}
}
}
JToken resourcesArray = valueValue["resources"];
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
virtualMachineJsonInstance.Extensions = new List<VirtualMachineExtension>();
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineExtension virtualMachineExtensionJsonInstance = new VirtualMachineExtension();
virtualMachineJsonInstance.Extensions.Add(virtualMachineExtensionJsonInstance);
JToken propertiesValue3 = resourcesValue["properties"];
if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
{
JToken publisherValue3 = propertiesValue3["publisher"];
if (publisherValue3 != null && publisherValue3.Type != JTokenType.Null)
{
string publisherInstance3 = ((string)publisherValue3);
virtualMachineExtensionJsonInstance.Publisher = publisherInstance3;
}
JToken typeValue3 = propertiesValue3["type"];
if (typeValue3 != null && typeValue3.Type != JTokenType.Null)
{
string typeInstance3 = ((string)typeValue3);
virtualMachineExtensionJsonInstance.ExtensionType = typeInstance3;
}
JToken typeHandlerVersionValue3 = propertiesValue3["typeHandlerVersion"];
if (typeHandlerVersionValue3 != null && typeHandlerVersionValue3.Type != JTokenType.Null)
{
string typeHandlerVersionInstance3 = ((string)typeHandlerVersionValue3);
virtualMachineExtensionJsonInstance.TypeHandlerVersion = typeHandlerVersionInstance3;
}
JToken autoUpgradeMinorVersionValue = propertiesValue3["autoUpgradeMinorVersion"];
if (autoUpgradeMinorVersionValue != null && autoUpgradeMinorVersionValue.Type != JTokenType.Null)
{
bool autoUpgradeMinorVersionInstance = ((bool)autoUpgradeMinorVersionValue);
virtualMachineExtensionJsonInstance.AutoUpgradeMinorVersion = autoUpgradeMinorVersionInstance;
}
JToken settingsValue = propertiesValue3["settings"];
if (settingsValue != null && settingsValue.Type != JTokenType.Null)
{
string settingsInstance = settingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.Settings = settingsInstance;
}
JToken protectedSettingsValue = propertiesValue3["protectedSettings"];
if (protectedSettingsValue != null && protectedSettingsValue.Type != JTokenType.Null)
{
string protectedSettingsInstance = protectedSettingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.ProtectedSettings = protectedSettingsInstance;
}
JToken provisioningStateValue2 = propertiesValue3["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
virtualMachineExtensionJsonInstance.ProvisioningState = provisioningStateInstance2;
}
JToken instanceViewValue2 = propertiesValue3["instanceView"];
if (instanceViewValue2 != null && instanceViewValue2.Type != JTokenType.Null)
{
VirtualMachineExtensionInstanceView instanceViewInstance2 = new VirtualMachineExtensionInstanceView();
virtualMachineExtensionJsonInstance.InstanceView = instanceViewInstance2;
JToken nameValue6 = instanceViewValue2["name"];
if (nameValue6 != null && nameValue6.Type != JTokenType.Null)
{
string nameInstance6 = ((string)nameValue6);
instanceViewInstance2.Name = nameInstance6;
}
JToken typeValue4 = instanceViewValue2["type"];
if (typeValue4 != null && typeValue4.Type != JTokenType.Null)
{
string typeInstance4 = ((string)typeValue4);
instanceViewInstance2.ExtensionType = typeInstance4;
}
JToken typeHandlerVersionValue4 = instanceViewValue2["typeHandlerVersion"];
if (typeHandlerVersionValue4 != null && typeHandlerVersionValue4.Type != JTokenType.Null)
{
string typeHandlerVersionInstance4 = ((string)typeHandlerVersionValue4);
instanceViewInstance2.TypeHandlerVersion = typeHandlerVersionInstance4;
}
JToken substatusesArray2 = instanceViewValue2["substatuses"];
if (substatusesArray2 != null && substatusesArray2.Type != JTokenType.Null)
{
foreach (JToken substatusesValue2 in ((JArray)substatusesArray2))
{
InstanceViewStatus instanceViewStatusInstance6 = new InstanceViewStatus();
instanceViewInstance2.SubStatuses.Add(instanceViewStatusInstance6);
JToken codeValue7 = substatusesValue2["code"];
if (codeValue7 != null && codeValue7.Type != JTokenType.Null)
{
string codeInstance7 = ((string)codeValue7);
instanceViewStatusInstance6.Code = codeInstance7;
}
JToken levelValue7 = substatusesValue2["level"];
if (levelValue7 != null && levelValue7.Type != JTokenType.Null)
{
string levelInstance7 = ((string)levelValue7);
instanceViewStatusInstance6.Level = levelInstance7;
}
JToken displayStatusValue7 = substatusesValue2["displayStatus"];
if (displayStatusValue7 != null && displayStatusValue7.Type != JTokenType.Null)
{
string displayStatusInstance7 = ((string)displayStatusValue7);
instanceViewStatusInstance6.DisplayStatus = displayStatusInstance7;
}
JToken messageValue7 = substatusesValue2["message"];
if (messageValue7 != null && messageValue7.Type != JTokenType.Null)
{
string messageInstance7 = ((string)messageValue7);
instanceViewStatusInstance6.Message = messageInstance7;
}
JToken timeValue7 = substatusesValue2["time"];
if (timeValue7 != null && timeValue7.Type != JTokenType.Null)
{
DateTimeOffset timeInstance7 = ((DateTimeOffset)timeValue7);
instanceViewStatusInstance6.Time = timeInstance7;
}
}
}
JToken statusesArray5 = instanceViewValue2["statuses"];
if (statusesArray5 != null && statusesArray5.Type != JTokenType.Null)
{
foreach (JToken statusesValue5 in ((JArray)statusesArray5))
{
InstanceViewStatus instanceViewStatusInstance7 = new InstanceViewStatus();
instanceViewInstance2.Statuses.Add(instanceViewStatusInstance7);
JToken codeValue8 = statusesValue5["code"];
if (codeValue8 != null && codeValue8.Type != JTokenType.Null)
{
string codeInstance8 = ((string)codeValue8);
instanceViewStatusInstance7.Code = codeInstance8;
}
JToken levelValue8 = statusesValue5["level"];
if (levelValue8 != null && levelValue8.Type != JTokenType.Null)
{
string levelInstance8 = ((string)levelValue8);
instanceViewStatusInstance7.Level = levelInstance8;
}
JToken displayStatusValue8 = statusesValue5["displayStatus"];
if (displayStatusValue8 != null && displayStatusValue8.Type != JTokenType.Null)
{
string displayStatusInstance8 = ((string)displayStatusValue8);
instanceViewStatusInstance7.DisplayStatus = displayStatusInstance8;
}
JToken messageValue8 = statusesValue5["message"];
if (messageValue8 != null && messageValue8.Type != JTokenType.Null)
{
string messageInstance8 = ((string)messageValue8);
instanceViewStatusInstance7.Message = messageInstance8;
}
JToken timeValue8 = statusesValue5["time"];
if (timeValue8 != null && timeValue8.Type != JTokenType.Null)
{
DateTimeOffset timeInstance8 = ((DateTimeOffset)timeValue8);
instanceViewStatusInstance7.Time = timeInstance8;
}
}
}
}
}
JToken idValue4 = resourcesValue["id"];
if (idValue4 != null && idValue4.Type != JTokenType.Null)
{
string idInstance4 = ((string)idValue4);
virtualMachineExtensionJsonInstance.Id = idInstance4;
}
JToken nameValue7 = resourcesValue["name"];
if (nameValue7 != null && nameValue7.Type != JTokenType.Null)
{
string nameInstance7 = ((string)nameValue7);
virtualMachineExtensionJsonInstance.Name = nameInstance7;
}
JToken typeValue5 = resourcesValue["type"];
if (typeValue5 != null && typeValue5.Type != JTokenType.Null)
{
string typeInstance5 = ((string)typeValue5);
virtualMachineExtensionJsonInstance.Type = typeInstance5;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineExtensionJsonInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)resourcesValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
virtualMachineExtensionJsonInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken idValue5 = valueValue["id"];
if (idValue5 != null && idValue5.Type != JTokenType.Null)
{
string idInstance5 = ((string)idValue5);
virtualMachineJsonInstance.Id = idInstance5;
}
JToken nameValue8 = valueValue["name"];
if (nameValue8 != null && nameValue8.Type != JTokenType.Null)
{
string nameInstance8 = ((string)nameValue8);
virtualMachineJsonInstance.Name = nameInstance8;
}
JToken typeValue6 = valueValue["type"];
if (typeValue6 != null && typeValue6.Type != JTokenType.Null)
{
string typeInstance6 = ((string)typeValue6);
virtualMachineJsonInstance.Type = typeInstance6;
}
JToken locationValue2 = valueValue["location"];
if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
{
string locationInstance2 = ((string)locationValue2);
virtualMachineJsonInstance.Location = locationInstance2;
}
JToken tagsSequenceElement2 = ((JToken)valueValue["tags"]);
if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null)
{
foreach (JProperty property2 in tagsSequenceElement2)
{
string tagsKey2 = ((string)property2.Name);
string tagsValue2 = ((string)property2.Value);
virtualMachineJsonInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines.
/// Do this till nextLink is not null to fetch all the Virtual
/// Machines.
/// </summary>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Virtual Machine operation response.
/// </returns>
public async Task<VirtualMachineListResponse> ListAllAsync(ListParameters parameters, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAllAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
VirtualMachine virtualMachineJsonInstance = new VirtualMachine();
result.VirtualMachines.Add(virtualMachineJsonInstance);
JToken planValue = valueValue["plan"];
if (planValue != null && planValue.Type != JTokenType.Null)
{
Plan planInstance = new Plan();
virtualMachineJsonInstance.Plan = planInstance;
JToken nameValue = planValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
planInstance.Name = nameInstance;
}
JToken publisherValue = planValue["publisher"];
if (publisherValue != null && publisherValue.Type != JTokenType.Null)
{
string publisherInstance = ((string)publisherValue);
planInstance.Publisher = publisherInstance;
}
JToken productValue = planValue["product"];
if (productValue != null && productValue.Type != JTokenType.Null)
{
string productInstance = ((string)productValue);
planInstance.Product = productInstance;
}
JToken promotionCodeValue = planValue["promotionCode"];
if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
{
string promotionCodeInstance = ((string)promotionCodeValue);
planInstance.PromotionCode = promotionCodeInstance;
}
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken hardwareProfileValue = propertiesValue["hardwareProfile"];
if (hardwareProfileValue != null && hardwareProfileValue.Type != JTokenType.Null)
{
HardwareProfile hardwareProfileInstance = new HardwareProfile();
virtualMachineJsonInstance.HardwareProfile = hardwareProfileInstance;
JToken vmSizeValue = hardwareProfileValue["vmSize"];
if (vmSizeValue != null && vmSizeValue.Type != JTokenType.Null)
{
string vmSizeInstance = ((string)vmSizeValue);
hardwareProfileInstance.VirtualMachineSize = vmSizeInstance;
}
}
JToken storageProfileValue = propertiesValue["storageProfile"];
if (storageProfileValue != null && storageProfileValue.Type != JTokenType.Null)
{
StorageProfile storageProfileInstance = new StorageProfile();
virtualMachineJsonInstance.StorageProfile = storageProfileInstance;
JToken imageReferenceValue = storageProfileValue["imageReference"];
if (imageReferenceValue != null && imageReferenceValue.Type != JTokenType.Null)
{
ImageReference imageReferenceInstance = new ImageReference();
storageProfileInstance.ImageReference = imageReferenceInstance;
JToken publisherValue2 = imageReferenceValue["publisher"];
if (publisherValue2 != null && publisherValue2.Type != JTokenType.Null)
{
string publisherInstance2 = ((string)publisherValue2);
imageReferenceInstance.Publisher = publisherInstance2;
}
JToken offerValue = imageReferenceValue["offer"];
if (offerValue != null && offerValue.Type != JTokenType.Null)
{
string offerInstance = ((string)offerValue);
imageReferenceInstance.Offer = offerInstance;
}
JToken skuValue = imageReferenceValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
string skuInstance = ((string)skuValue);
imageReferenceInstance.Sku = skuInstance;
}
JToken versionValue = imageReferenceValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
imageReferenceInstance.Version = versionInstance;
}
}
JToken osDiskValue = storageProfileValue["osDisk"];
if (osDiskValue != null && osDiskValue.Type != JTokenType.Null)
{
OSDisk osDiskInstance = new OSDisk();
storageProfileInstance.OSDisk = osDiskInstance;
JToken osTypeValue = osDiskValue["osType"];
if (osTypeValue != null && osTypeValue.Type != JTokenType.Null)
{
string osTypeInstance = ((string)osTypeValue);
osDiskInstance.OperatingSystemType = osTypeInstance;
}
JToken nameValue2 = osDiskValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
osDiskInstance.Name = nameInstance2;
}
JToken vhdValue = osDiskValue["vhd"];
if (vhdValue != null && vhdValue.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance = new VirtualHardDisk();
osDiskInstance.VirtualHardDisk = vhdInstance;
JToken uriValue = vhdValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
vhdInstance.Uri = uriInstance;
}
}
JToken imageValue = osDiskValue["image"];
if (imageValue != null && imageValue.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance = new VirtualHardDisk();
osDiskInstance.SourceImage = imageInstance;
JToken uriValue2 = imageValue["uri"];
if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
{
string uriInstance2 = ((string)uriValue2);
imageInstance.Uri = uriInstance2;
}
}
JToken cachingValue = osDiskValue["caching"];
if (cachingValue != null && cachingValue.Type != JTokenType.Null)
{
string cachingInstance = ((string)cachingValue);
osDiskInstance.Caching = cachingInstance;
}
JToken createOptionValue = osDiskValue["createOption"];
if (createOptionValue != null && createOptionValue.Type != JTokenType.Null)
{
string createOptionInstance = ((string)createOptionValue);
osDiskInstance.CreateOption = createOptionInstance;
}
JToken diskSizeGBValue = osDiskValue["diskSizeGB"];
if (diskSizeGBValue != null && diskSizeGBValue.Type != JTokenType.Null)
{
int diskSizeGBInstance = ((int)diskSizeGBValue);
osDiskInstance.DiskSizeGB = diskSizeGBInstance;
}
}
JToken dataDisksArray = storageProfileValue["dataDisks"];
if (dataDisksArray != null && dataDisksArray.Type != JTokenType.Null)
{
foreach (JToken dataDisksValue in ((JArray)dataDisksArray))
{
DataDisk dataDiskInstance = new DataDisk();
storageProfileInstance.DataDisks.Add(dataDiskInstance);
JToken lunValue = dataDisksValue["lun"];
if (lunValue != null && lunValue.Type != JTokenType.Null)
{
int lunInstance = ((int)lunValue);
dataDiskInstance.Lun = lunInstance;
}
JToken nameValue3 = dataDisksValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dataDiskInstance.Name = nameInstance3;
}
JToken vhdValue2 = dataDisksValue["vhd"];
if (vhdValue2 != null && vhdValue2.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance2 = new VirtualHardDisk();
dataDiskInstance.VirtualHardDisk = vhdInstance2;
JToken uriValue3 = vhdValue2["uri"];
if (uriValue3 != null && uriValue3.Type != JTokenType.Null)
{
string uriInstance3 = ((string)uriValue3);
vhdInstance2.Uri = uriInstance3;
}
}
JToken imageValue2 = dataDisksValue["image"];
if (imageValue2 != null && imageValue2.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance2 = new VirtualHardDisk();
dataDiskInstance.SourceImage = imageInstance2;
JToken uriValue4 = imageValue2["uri"];
if (uriValue4 != null && uriValue4.Type != JTokenType.Null)
{
string uriInstance4 = ((string)uriValue4);
imageInstance2.Uri = uriInstance4;
}
}
JToken cachingValue2 = dataDisksValue["caching"];
if (cachingValue2 != null && cachingValue2.Type != JTokenType.Null)
{
string cachingInstance2 = ((string)cachingValue2);
dataDiskInstance.Caching = cachingInstance2;
}
JToken createOptionValue2 = dataDisksValue["createOption"];
if (createOptionValue2 != null && createOptionValue2.Type != JTokenType.Null)
{
string createOptionInstance2 = ((string)createOptionValue2);
dataDiskInstance.CreateOption = createOptionInstance2;
}
JToken diskSizeGBValue2 = dataDisksValue["diskSizeGB"];
if (diskSizeGBValue2 != null && diskSizeGBValue2.Type != JTokenType.Null)
{
int diskSizeGBInstance2 = ((int)diskSizeGBValue2);
dataDiskInstance.DiskSizeGB = diskSizeGBInstance2;
}
}
}
}
JToken osProfileValue = propertiesValue["osProfile"];
if (osProfileValue != null && osProfileValue.Type != JTokenType.Null)
{
OSProfile osProfileInstance = new OSProfile();
virtualMachineJsonInstance.OSProfile = osProfileInstance;
JToken computerNameValue = osProfileValue["computerName"];
if (computerNameValue != null && computerNameValue.Type != JTokenType.Null)
{
string computerNameInstance = ((string)computerNameValue);
osProfileInstance.ComputerName = computerNameInstance;
}
JToken adminUsernameValue = osProfileValue["adminUsername"];
if (adminUsernameValue != null && adminUsernameValue.Type != JTokenType.Null)
{
string adminUsernameInstance = ((string)adminUsernameValue);
osProfileInstance.AdminUsername = adminUsernameInstance;
}
JToken adminPasswordValue = osProfileValue["adminPassword"];
if (adminPasswordValue != null && adminPasswordValue.Type != JTokenType.Null)
{
string adminPasswordInstance = ((string)adminPasswordValue);
osProfileInstance.AdminPassword = adminPasswordInstance;
}
JToken customDataValue = osProfileValue["customData"];
if (customDataValue != null && customDataValue.Type != JTokenType.Null)
{
string customDataInstance = ((string)customDataValue);
osProfileInstance.CustomData = customDataInstance;
}
JToken windowsConfigurationValue = osProfileValue["windowsConfiguration"];
if (windowsConfigurationValue != null && windowsConfigurationValue.Type != JTokenType.Null)
{
WindowsConfiguration windowsConfigurationInstance = new WindowsConfiguration();
osProfileInstance.WindowsConfiguration = windowsConfigurationInstance;
JToken provisionVMAgentValue = windowsConfigurationValue["provisionVMAgent"];
if (provisionVMAgentValue != null && provisionVMAgentValue.Type != JTokenType.Null)
{
bool provisionVMAgentInstance = ((bool)provisionVMAgentValue);
windowsConfigurationInstance.ProvisionVMAgent = provisionVMAgentInstance;
}
JToken enableAutomaticUpdatesValue = windowsConfigurationValue["enableAutomaticUpdates"];
if (enableAutomaticUpdatesValue != null && enableAutomaticUpdatesValue.Type != JTokenType.Null)
{
bool enableAutomaticUpdatesInstance = ((bool)enableAutomaticUpdatesValue);
windowsConfigurationInstance.EnableAutomaticUpdates = enableAutomaticUpdatesInstance;
}
JToken timeZoneValue = windowsConfigurationValue["timeZone"];
if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
{
string timeZoneInstance = ((string)timeZoneValue);
windowsConfigurationInstance.TimeZone = timeZoneInstance;
}
JToken additionalUnattendContentArray = windowsConfigurationValue["additionalUnattendContent"];
if (additionalUnattendContentArray != null && additionalUnattendContentArray.Type != JTokenType.Null)
{
foreach (JToken additionalUnattendContentValue in ((JArray)additionalUnattendContentArray))
{
AdditionalUnattendContent additionalUnattendContentInstance = new AdditionalUnattendContent();
windowsConfigurationInstance.AdditionalUnattendContents.Add(additionalUnattendContentInstance);
JToken passNameValue = additionalUnattendContentValue["passName"];
if (passNameValue != null && passNameValue.Type != JTokenType.Null)
{
string passNameInstance = ((string)passNameValue);
additionalUnattendContentInstance.PassName = passNameInstance;
}
JToken componentNameValue = additionalUnattendContentValue["componentName"];
if (componentNameValue != null && componentNameValue.Type != JTokenType.Null)
{
string componentNameInstance = ((string)componentNameValue);
additionalUnattendContentInstance.ComponentName = componentNameInstance;
}
JToken settingNameValue = additionalUnattendContentValue["settingName"];
if (settingNameValue != null && settingNameValue.Type != JTokenType.Null)
{
string settingNameInstance = ((string)settingNameValue);
additionalUnattendContentInstance.SettingName = settingNameInstance;
}
JToken contentValue = additionalUnattendContentValue["content"];
if (contentValue != null && contentValue.Type != JTokenType.Null)
{
string contentInstance = ((string)contentValue);
additionalUnattendContentInstance.Content = contentInstance;
}
}
}
JToken winRMValue = windowsConfigurationValue["winRM"];
if (winRMValue != null && winRMValue.Type != JTokenType.Null)
{
WinRMConfiguration winRMInstance = new WinRMConfiguration();
windowsConfigurationInstance.WinRMConfiguration = winRMInstance;
JToken listenersArray = winRMValue["listeners"];
if (listenersArray != null && listenersArray.Type != JTokenType.Null)
{
foreach (JToken listenersValue in ((JArray)listenersArray))
{
WinRMListener winRMListenerInstance = new WinRMListener();
winRMInstance.Listeners.Add(winRMListenerInstance);
JToken protocolValue = listenersValue["protocol"];
if (protocolValue != null && protocolValue.Type != JTokenType.Null)
{
string protocolInstance = ((string)protocolValue);
winRMListenerInstance.Protocol = protocolInstance;
}
JToken certificateUrlValue = listenersValue["certificateUrl"];
if (certificateUrlValue != null && certificateUrlValue.Type != JTokenType.Null)
{
Uri certificateUrlInstance = TypeConversion.TryParseUri(((string)certificateUrlValue));
winRMListenerInstance.CertificateUrl = certificateUrlInstance;
}
}
}
}
}
JToken linuxConfigurationValue = osProfileValue["linuxConfiguration"];
if (linuxConfigurationValue != null && linuxConfigurationValue.Type != JTokenType.Null)
{
LinuxConfiguration linuxConfigurationInstance = new LinuxConfiguration();
osProfileInstance.LinuxConfiguration = linuxConfigurationInstance;
JToken disablePasswordAuthenticationValue = linuxConfigurationValue["disablePasswordAuthentication"];
if (disablePasswordAuthenticationValue != null && disablePasswordAuthenticationValue.Type != JTokenType.Null)
{
bool disablePasswordAuthenticationInstance = ((bool)disablePasswordAuthenticationValue);
linuxConfigurationInstance.DisablePasswordAuthentication = disablePasswordAuthenticationInstance;
}
JToken sshValue = linuxConfigurationValue["ssh"];
if (sshValue != null && sshValue.Type != JTokenType.Null)
{
SshConfiguration sshInstance = new SshConfiguration();
linuxConfigurationInstance.SshConfiguration = sshInstance;
JToken publicKeysArray = sshValue["publicKeys"];
if (publicKeysArray != null && publicKeysArray.Type != JTokenType.Null)
{
foreach (JToken publicKeysValue in ((JArray)publicKeysArray))
{
SshPublicKey sshPublicKeyInstance = new SshPublicKey();
sshInstance.PublicKeys.Add(sshPublicKeyInstance);
JToken pathValue = publicKeysValue["path"];
if (pathValue != null && pathValue.Type != JTokenType.Null)
{
string pathInstance = ((string)pathValue);
sshPublicKeyInstance.Path = pathInstance;
}
JToken keyDataValue = publicKeysValue["keyData"];
if (keyDataValue != null && keyDataValue.Type != JTokenType.Null)
{
string keyDataInstance = ((string)keyDataValue);
sshPublicKeyInstance.KeyData = keyDataInstance;
}
}
}
}
}
JToken secretsArray = osProfileValue["secrets"];
if (secretsArray != null && secretsArray.Type != JTokenType.Null)
{
foreach (JToken secretsValue in ((JArray)secretsArray))
{
VaultSecretGroup vaultSecretGroupInstance = new VaultSecretGroup();
osProfileInstance.Secrets.Add(vaultSecretGroupInstance);
JToken sourceVaultValue = secretsValue["sourceVault"];
if (sourceVaultValue != null && sourceVaultValue.Type != JTokenType.Null)
{
SourceVaultReference sourceVaultInstance = new SourceVaultReference();
vaultSecretGroupInstance.SourceVault = sourceVaultInstance;
JToken idValue = sourceVaultValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
sourceVaultInstance.ReferenceUri = idInstance;
}
}
JToken vaultCertificatesArray = secretsValue["vaultCertificates"];
if (vaultCertificatesArray != null && vaultCertificatesArray.Type != JTokenType.Null)
{
foreach (JToken vaultCertificatesValue in ((JArray)vaultCertificatesArray))
{
VaultCertificate vaultCertificateInstance = new VaultCertificate();
vaultSecretGroupInstance.VaultCertificates.Add(vaultCertificateInstance);
JToken certificateUrlValue2 = vaultCertificatesValue["certificateUrl"];
if (certificateUrlValue2 != null && certificateUrlValue2.Type != JTokenType.Null)
{
string certificateUrlInstance2 = ((string)certificateUrlValue2);
vaultCertificateInstance.CertificateUrl = certificateUrlInstance2;
}
JToken certificateStoreValue = vaultCertificatesValue["certificateStore"];
if (certificateStoreValue != null && certificateStoreValue.Type != JTokenType.Null)
{
string certificateStoreInstance = ((string)certificateStoreValue);
vaultCertificateInstance.CertificateStore = certificateStoreInstance;
}
}
}
}
}
}
JToken networkProfileValue = propertiesValue["networkProfile"];
if (networkProfileValue != null && networkProfileValue.Type != JTokenType.Null)
{
NetworkProfile networkProfileInstance = new NetworkProfile();
virtualMachineJsonInstance.NetworkProfile = networkProfileInstance;
JToken networkInterfacesArray = networkProfileValue["networkInterfaces"];
if (networkInterfacesArray != null && networkInterfacesArray.Type != JTokenType.Null)
{
foreach (JToken networkInterfacesValue in ((JArray)networkInterfacesArray))
{
NetworkInterfaceReference networkInterfaceReferenceJsonInstance = new NetworkInterfaceReference();
networkProfileInstance.NetworkInterfaces.Add(networkInterfaceReferenceJsonInstance);
JToken propertiesValue2 = networkInterfacesValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken primaryValue = propertiesValue2["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
bool primaryInstance = ((bool)primaryValue);
networkInterfaceReferenceJsonInstance.Primary = primaryInstance;
}
}
JToken idValue2 = networkInterfacesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
networkInterfaceReferenceJsonInstance.ReferenceUri = idInstance2;
}
}
}
}
JToken availabilitySetValue = propertiesValue["availabilitySet"];
if (availabilitySetValue != null && availabilitySetValue.Type != JTokenType.Null)
{
AvailabilitySetReference availabilitySetInstance = new AvailabilitySetReference();
virtualMachineJsonInstance.AvailabilitySetReference = availabilitySetInstance;
JToken idValue3 = availabilitySetValue["id"];
if (idValue3 != null && idValue3.Type != JTokenType.Null)
{
string idInstance3 = ((string)idValue3);
availabilitySetInstance.ReferenceUri = idInstance3;
}
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
virtualMachineJsonInstance.ProvisioningState = provisioningStateInstance;
}
JToken instanceViewValue = propertiesValue["instanceView"];
if (instanceViewValue != null && instanceViewValue.Type != JTokenType.Null)
{
VirtualMachineInstanceView instanceViewInstance = new VirtualMachineInstanceView();
virtualMachineJsonInstance.InstanceView = instanceViewInstance;
JToken platformUpdateDomainValue = instanceViewValue["platformUpdateDomain"];
if (platformUpdateDomainValue != null && platformUpdateDomainValue.Type != JTokenType.Null)
{
int platformUpdateDomainInstance = ((int)platformUpdateDomainValue);
instanceViewInstance.PlatformUpdateDomain = platformUpdateDomainInstance;
}
JToken platformFaultDomainValue = instanceViewValue["platformFaultDomain"];
if (platformFaultDomainValue != null && platformFaultDomainValue.Type != JTokenType.Null)
{
int platformFaultDomainInstance = ((int)platformFaultDomainValue);
instanceViewInstance.PlatformFaultDomain = platformFaultDomainInstance;
}
JToken rdpThumbPrintValue = instanceViewValue["rdpThumbPrint"];
if (rdpThumbPrintValue != null && rdpThumbPrintValue.Type != JTokenType.Null)
{
string rdpThumbPrintInstance = ((string)rdpThumbPrintValue);
instanceViewInstance.RemoteDesktopThumbprint = rdpThumbPrintInstance;
}
JToken vmAgentValue = instanceViewValue["vmAgent"];
if (vmAgentValue != null && vmAgentValue.Type != JTokenType.Null)
{
VirtualMachineAgentInstanceView vmAgentInstance = new VirtualMachineAgentInstanceView();
instanceViewInstance.VMAgent = vmAgentInstance;
JToken vmAgentVersionValue = vmAgentValue["vmAgentVersion"];
if (vmAgentVersionValue != null && vmAgentVersionValue.Type != JTokenType.Null)
{
string vmAgentVersionInstance = ((string)vmAgentVersionValue);
vmAgentInstance.VMAgentVersion = vmAgentVersionInstance;
}
JToken extensionHandlersArray = vmAgentValue["extensionHandlers"];
if (extensionHandlersArray != null && extensionHandlersArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlersValue in ((JArray)extensionHandlersArray))
{
VirtualMachineExtensionHandlerInstanceView virtualMachineExtensionHandlerInstanceViewInstance = new VirtualMachineExtensionHandlerInstanceView();
vmAgentInstance.ExtensionHandlers.Add(virtualMachineExtensionHandlerInstanceViewInstance);
JToken typeValue = extensionHandlersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
virtualMachineExtensionHandlerInstanceViewInstance.Type = typeInstance;
}
JToken typeHandlerVersionValue = extensionHandlersValue["typeHandlerVersion"];
if (typeHandlerVersionValue != null && typeHandlerVersionValue.Type != JTokenType.Null)
{
string typeHandlerVersionInstance = ((string)typeHandlerVersionValue);
virtualMachineExtensionHandlerInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance;
}
JToken statusValue = extensionHandlersValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
InstanceViewStatus statusInstance = new InstanceViewStatus();
virtualMachineExtensionHandlerInstanceViewInstance.Status = statusInstance;
JToken codeValue = statusValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
statusInstance.Code = codeInstance;
}
JToken levelValue = statusValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
statusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
statusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
statusInstance.Message = messageInstance;
}
JToken timeValue = statusValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
statusInstance.Time = timeInstance;
}
}
}
}
JToken statusesArray = vmAgentValue["statuses"];
if (statusesArray != null && statusesArray.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
vmAgentInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue2 = statusesValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
instanceViewStatusInstance.Code = codeInstance2;
}
JToken levelValue2 = statusesValue["level"];
if (levelValue2 != null && levelValue2.Type != JTokenType.Null)
{
string levelInstance2 = ((string)levelValue2);
instanceViewStatusInstance.Level = levelInstance2;
}
JToken displayStatusValue2 = statusesValue["displayStatus"];
if (displayStatusValue2 != null && displayStatusValue2.Type != JTokenType.Null)
{
string displayStatusInstance2 = ((string)displayStatusValue2);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance2;
}
JToken messageValue2 = statusesValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
instanceViewStatusInstance.Message = messageInstance2;
}
JToken timeValue2 = statusesValue["time"];
if (timeValue2 != null && timeValue2.Type != JTokenType.Null)
{
DateTimeOffset timeInstance2 = ((DateTimeOffset)timeValue2);
instanceViewStatusInstance.Time = timeInstance2;
}
}
}
}
JToken disksArray = instanceViewValue["disks"];
if (disksArray != null && disksArray.Type != JTokenType.Null)
{
foreach (JToken disksValue in ((JArray)disksArray))
{
DiskInstanceView diskInstanceViewInstance = new DiskInstanceView();
instanceViewInstance.Disks.Add(diskInstanceViewInstance);
JToken nameValue4 = disksValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
diskInstanceViewInstance.Name = nameInstance4;
}
JToken statusesArray2 = disksValue["statuses"];
if (statusesArray2 != null && statusesArray2.Type != JTokenType.Null)
{
foreach (JToken statusesValue2 in ((JArray)statusesArray2))
{
InstanceViewStatus instanceViewStatusInstance2 = new InstanceViewStatus();
diskInstanceViewInstance.Statuses.Add(instanceViewStatusInstance2);
JToken codeValue3 = statusesValue2["code"];
if (codeValue3 != null && codeValue3.Type != JTokenType.Null)
{
string codeInstance3 = ((string)codeValue3);
instanceViewStatusInstance2.Code = codeInstance3;
}
JToken levelValue3 = statusesValue2["level"];
if (levelValue3 != null && levelValue3.Type != JTokenType.Null)
{
string levelInstance3 = ((string)levelValue3);
instanceViewStatusInstance2.Level = levelInstance3;
}
JToken displayStatusValue3 = statusesValue2["displayStatus"];
if (displayStatusValue3 != null && displayStatusValue3.Type != JTokenType.Null)
{
string displayStatusInstance3 = ((string)displayStatusValue3);
instanceViewStatusInstance2.DisplayStatus = displayStatusInstance3;
}
JToken messageValue3 = statusesValue2["message"];
if (messageValue3 != null && messageValue3.Type != JTokenType.Null)
{
string messageInstance3 = ((string)messageValue3);
instanceViewStatusInstance2.Message = messageInstance3;
}
JToken timeValue3 = statusesValue2["time"];
if (timeValue3 != null && timeValue3.Type != JTokenType.Null)
{
DateTimeOffset timeInstance3 = ((DateTimeOffset)timeValue3);
instanceViewStatusInstance2.Time = timeInstance3;
}
}
}
}
}
JToken extensionsArray = instanceViewValue["extensions"];
if (extensionsArray != null && extensionsArray.Type != JTokenType.Null)
{
foreach (JToken extensionsValue in ((JArray)extensionsArray))
{
VirtualMachineExtensionInstanceView virtualMachineExtensionInstanceViewInstance = new VirtualMachineExtensionInstanceView();
instanceViewInstance.Extensions.Add(virtualMachineExtensionInstanceViewInstance);
JToken nameValue5 = extensionsValue["name"];
if (nameValue5 != null && nameValue5.Type != JTokenType.Null)
{
string nameInstance5 = ((string)nameValue5);
virtualMachineExtensionInstanceViewInstance.Name = nameInstance5;
}
JToken typeValue2 = extensionsValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
virtualMachineExtensionInstanceViewInstance.ExtensionType = typeInstance2;
}
JToken typeHandlerVersionValue2 = extensionsValue["typeHandlerVersion"];
if (typeHandlerVersionValue2 != null && typeHandlerVersionValue2.Type != JTokenType.Null)
{
string typeHandlerVersionInstance2 = ((string)typeHandlerVersionValue2);
virtualMachineExtensionInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance2;
}
JToken substatusesArray = extensionsValue["substatuses"];
if (substatusesArray != null && substatusesArray.Type != JTokenType.Null)
{
foreach (JToken substatusesValue in ((JArray)substatusesArray))
{
InstanceViewStatus instanceViewStatusInstance3 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.SubStatuses.Add(instanceViewStatusInstance3);
JToken codeValue4 = substatusesValue["code"];
if (codeValue4 != null && codeValue4.Type != JTokenType.Null)
{
string codeInstance4 = ((string)codeValue4);
instanceViewStatusInstance3.Code = codeInstance4;
}
JToken levelValue4 = substatusesValue["level"];
if (levelValue4 != null && levelValue4.Type != JTokenType.Null)
{
string levelInstance4 = ((string)levelValue4);
instanceViewStatusInstance3.Level = levelInstance4;
}
JToken displayStatusValue4 = substatusesValue["displayStatus"];
if (displayStatusValue4 != null && displayStatusValue4.Type != JTokenType.Null)
{
string displayStatusInstance4 = ((string)displayStatusValue4);
instanceViewStatusInstance3.DisplayStatus = displayStatusInstance4;
}
JToken messageValue4 = substatusesValue["message"];
if (messageValue4 != null && messageValue4.Type != JTokenType.Null)
{
string messageInstance4 = ((string)messageValue4);
instanceViewStatusInstance3.Message = messageInstance4;
}
JToken timeValue4 = substatusesValue["time"];
if (timeValue4 != null && timeValue4.Type != JTokenType.Null)
{
DateTimeOffset timeInstance4 = ((DateTimeOffset)timeValue4);
instanceViewStatusInstance3.Time = timeInstance4;
}
}
}
JToken statusesArray3 = extensionsValue["statuses"];
if (statusesArray3 != null && statusesArray3.Type != JTokenType.Null)
{
foreach (JToken statusesValue3 in ((JArray)statusesArray3))
{
InstanceViewStatus instanceViewStatusInstance4 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.Statuses.Add(instanceViewStatusInstance4);
JToken codeValue5 = statusesValue3["code"];
if (codeValue5 != null && codeValue5.Type != JTokenType.Null)
{
string codeInstance5 = ((string)codeValue5);
instanceViewStatusInstance4.Code = codeInstance5;
}
JToken levelValue5 = statusesValue3["level"];
if (levelValue5 != null && levelValue5.Type != JTokenType.Null)
{
string levelInstance5 = ((string)levelValue5);
instanceViewStatusInstance4.Level = levelInstance5;
}
JToken displayStatusValue5 = statusesValue3["displayStatus"];
if (displayStatusValue5 != null && displayStatusValue5.Type != JTokenType.Null)
{
string displayStatusInstance5 = ((string)displayStatusValue5);
instanceViewStatusInstance4.DisplayStatus = displayStatusInstance5;
}
JToken messageValue5 = statusesValue3["message"];
if (messageValue5 != null && messageValue5.Type != JTokenType.Null)
{
string messageInstance5 = ((string)messageValue5);
instanceViewStatusInstance4.Message = messageInstance5;
}
JToken timeValue5 = statusesValue3["time"];
if (timeValue5 != null && timeValue5.Type != JTokenType.Null)
{
DateTimeOffset timeInstance5 = ((DateTimeOffset)timeValue5);
instanceViewStatusInstance4.Time = timeInstance5;
}
}
}
}
}
JToken statusesArray4 = instanceViewValue["statuses"];
if (statusesArray4 != null && statusesArray4.Type != JTokenType.Null)
{
foreach (JToken statusesValue4 in ((JArray)statusesArray4))
{
InstanceViewStatus instanceViewStatusInstance5 = new InstanceViewStatus();
instanceViewInstance.Statuses.Add(instanceViewStatusInstance5);
JToken codeValue6 = statusesValue4["code"];
if (codeValue6 != null && codeValue6.Type != JTokenType.Null)
{
string codeInstance6 = ((string)codeValue6);
instanceViewStatusInstance5.Code = codeInstance6;
}
JToken levelValue6 = statusesValue4["level"];
if (levelValue6 != null && levelValue6.Type != JTokenType.Null)
{
string levelInstance6 = ((string)levelValue6);
instanceViewStatusInstance5.Level = levelInstance6;
}
JToken displayStatusValue6 = statusesValue4["displayStatus"];
if (displayStatusValue6 != null && displayStatusValue6.Type != JTokenType.Null)
{
string displayStatusInstance6 = ((string)displayStatusValue6);
instanceViewStatusInstance5.DisplayStatus = displayStatusInstance6;
}
JToken messageValue6 = statusesValue4["message"];
if (messageValue6 != null && messageValue6.Type != JTokenType.Null)
{
string messageInstance6 = ((string)messageValue6);
instanceViewStatusInstance5.Message = messageInstance6;
}
JToken timeValue6 = statusesValue4["time"];
if (timeValue6 != null && timeValue6.Type != JTokenType.Null)
{
DateTimeOffset timeInstance6 = ((DateTimeOffset)timeValue6);
instanceViewStatusInstance5.Time = timeInstance6;
}
}
}
}
}
JToken resourcesArray = valueValue["resources"];
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
virtualMachineJsonInstance.Extensions = new List<VirtualMachineExtension>();
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineExtension virtualMachineExtensionJsonInstance = new VirtualMachineExtension();
virtualMachineJsonInstance.Extensions.Add(virtualMachineExtensionJsonInstance);
JToken propertiesValue3 = resourcesValue["properties"];
if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
{
JToken publisherValue3 = propertiesValue3["publisher"];
if (publisherValue3 != null && publisherValue3.Type != JTokenType.Null)
{
string publisherInstance3 = ((string)publisherValue3);
virtualMachineExtensionJsonInstance.Publisher = publisherInstance3;
}
JToken typeValue3 = propertiesValue3["type"];
if (typeValue3 != null && typeValue3.Type != JTokenType.Null)
{
string typeInstance3 = ((string)typeValue3);
virtualMachineExtensionJsonInstance.ExtensionType = typeInstance3;
}
JToken typeHandlerVersionValue3 = propertiesValue3["typeHandlerVersion"];
if (typeHandlerVersionValue3 != null && typeHandlerVersionValue3.Type != JTokenType.Null)
{
string typeHandlerVersionInstance3 = ((string)typeHandlerVersionValue3);
virtualMachineExtensionJsonInstance.TypeHandlerVersion = typeHandlerVersionInstance3;
}
JToken autoUpgradeMinorVersionValue = propertiesValue3["autoUpgradeMinorVersion"];
if (autoUpgradeMinorVersionValue != null && autoUpgradeMinorVersionValue.Type != JTokenType.Null)
{
bool autoUpgradeMinorVersionInstance = ((bool)autoUpgradeMinorVersionValue);
virtualMachineExtensionJsonInstance.AutoUpgradeMinorVersion = autoUpgradeMinorVersionInstance;
}
JToken settingsValue = propertiesValue3["settings"];
if (settingsValue != null && settingsValue.Type != JTokenType.Null)
{
string settingsInstance = settingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.Settings = settingsInstance;
}
JToken protectedSettingsValue = propertiesValue3["protectedSettings"];
if (protectedSettingsValue != null && protectedSettingsValue.Type != JTokenType.Null)
{
string protectedSettingsInstance = protectedSettingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.ProtectedSettings = protectedSettingsInstance;
}
JToken provisioningStateValue2 = propertiesValue3["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
virtualMachineExtensionJsonInstance.ProvisioningState = provisioningStateInstance2;
}
JToken instanceViewValue2 = propertiesValue3["instanceView"];
if (instanceViewValue2 != null && instanceViewValue2.Type != JTokenType.Null)
{
VirtualMachineExtensionInstanceView instanceViewInstance2 = new VirtualMachineExtensionInstanceView();
virtualMachineExtensionJsonInstance.InstanceView = instanceViewInstance2;
JToken nameValue6 = instanceViewValue2["name"];
if (nameValue6 != null && nameValue6.Type != JTokenType.Null)
{
string nameInstance6 = ((string)nameValue6);
instanceViewInstance2.Name = nameInstance6;
}
JToken typeValue4 = instanceViewValue2["type"];
if (typeValue4 != null && typeValue4.Type != JTokenType.Null)
{
string typeInstance4 = ((string)typeValue4);
instanceViewInstance2.ExtensionType = typeInstance4;
}
JToken typeHandlerVersionValue4 = instanceViewValue2["typeHandlerVersion"];
if (typeHandlerVersionValue4 != null && typeHandlerVersionValue4.Type != JTokenType.Null)
{
string typeHandlerVersionInstance4 = ((string)typeHandlerVersionValue4);
instanceViewInstance2.TypeHandlerVersion = typeHandlerVersionInstance4;
}
JToken substatusesArray2 = instanceViewValue2["substatuses"];
if (substatusesArray2 != null && substatusesArray2.Type != JTokenType.Null)
{
foreach (JToken substatusesValue2 in ((JArray)substatusesArray2))
{
InstanceViewStatus instanceViewStatusInstance6 = new InstanceViewStatus();
instanceViewInstance2.SubStatuses.Add(instanceViewStatusInstance6);
JToken codeValue7 = substatusesValue2["code"];
if (codeValue7 != null && codeValue7.Type != JTokenType.Null)
{
string codeInstance7 = ((string)codeValue7);
instanceViewStatusInstance6.Code = codeInstance7;
}
JToken levelValue7 = substatusesValue2["level"];
if (levelValue7 != null && levelValue7.Type != JTokenType.Null)
{
string levelInstance7 = ((string)levelValue7);
instanceViewStatusInstance6.Level = levelInstance7;
}
JToken displayStatusValue7 = substatusesValue2["displayStatus"];
if (displayStatusValue7 != null && displayStatusValue7.Type != JTokenType.Null)
{
string displayStatusInstance7 = ((string)displayStatusValue7);
instanceViewStatusInstance6.DisplayStatus = displayStatusInstance7;
}
JToken messageValue7 = substatusesValue2["message"];
if (messageValue7 != null && messageValue7.Type != JTokenType.Null)
{
string messageInstance7 = ((string)messageValue7);
instanceViewStatusInstance6.Message = messageInstance7;
}
JToken timeValue7 = substatusesValue2["time"];
if (timeValue7 != null && timeValue7.Type != JTokenType.Null)
{
DateTimeOffset timeInstance7 = ((DateTimeOffset)timeValue7);
instanceViewStatusInstance6.Time = timeInstance7;
}
}
}
JToken statusesArray5 = instanceViewValue2["statuses"];
if (statusesArray5 != null && statusesArray5.Type != JTokenType.Null)
{
foreach (JToken statusesValue5 in ((JArray)statusesArray5))
{
InstanceViewStatus instanceViewStatusInstance7 = new InstanceViewStatus();
instanceViewInstance2.Statuses.Add(instanceViewStatusInstance7);
JToken codeValue8 = statusesValue5["code"];
if (codeValue8 != null && codeValue8.Type != JTokenType.Null)
{
string codeInstance8 = ((string)codeValue8);
instanceViewStatusInstance7.Code = codeInstance8;
}
JToken levelValue8 = statusesValue5["level"];
if (levelValue8 != null && levelValue8.Type != JTokenType.Null)
{
string levelInstance8 = ((string)levelValue8);
instanceViewStatusInstance7.Level = levelInstance8;
}
JToken displayStatusValue8 = statusesValue5["displayStatus"];
if (displayStatusValue8 != null && displayStatusValue8.Type != JTokenType.Null)
{
string displayStatusInstance8 = ((string)displayStatusValue8);
instanceViewStatusInstance7.DisplayStatus = displayStatusInstance8;
}
JToken messageValue8 = statusesValue5["message"];
if (messageValue8 != null && messageValue8.Type != JTokenType.Null)
{
string messageInstance8 = ((string)messageValue8);
instanceViewStatusInstance7.Message = messageInstance8;
}
JToken timeValue8 = statusesValue5["time"];
if (timeValue8 != null && timeValue8.Type != JTokenType.Null)
{
DateTimeOffset timeInstance8 = ((DateTimeOffset)timeValue8);
instanceViewStatusInstance7.Time = timeInstance8;
}
}
}
}
}
JToken idValue4 = resourcesValue["id"];
if (idValue4 != null && idValue4.Type != JTokenType.Null)
{
string idInstance4 = ((string)idValue4);
virtualMachineExtensionJsonInstance.Id = idInstance4;
}
JToken nameValue7 = resourcesValue["name"];
if (nameValue7 != null && nameValue7.Type != JTokenType.Null)
{
string nameInstance7 = ((string)nameValue7);
virtualMachineExtensionJsonInstance.Name = nameInstance7;
}
JToken typeValue5 = resourcesValue["type"];
if (typeValue5 != null && typeValue5.Type != JTokenType.Null)
{
string typeInstance5 = ((string)typeValue5);
virtualMachineExtensionJsonInstance.Type = typeInstance5;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineExtensionJsonInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)resourcesValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
virtualMachineExtensionJsonInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken idValue5 = valueValue["id"];
if (idValue5 != null && idValue5.Type != JTokenType.Null)
{
string idInstance5 = ((string)idValue5);
virtualMachineJsonInstance.Id = idInstance5;
}
JToken nameValue8 = valueValue["name"];
if (nameValue8 != null && nameValue8.Type != JTokenType.Null)
{
string nameInstance8 = ((string)nameValue8);
virtualMachineJsonInstance.Name = nameInstance8;
}
JToken typeValue6 = valueValue["type"];
if (typeValue6 != null && typeValue6.Type != JTokenType.Null)
{
string typeInstance6 = ((string)typeValue6);
virtualMachineJsonInstance.Type = typeInstance6;
}
JToken locationValue2 = valueValue["location"];
if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
{
string locationInstance2 = ((string)locationValue2);
virtualMachineJsonInstance.Location = locationInstance2;
}
JToken tagsSequenceElement2 = ((JToken)valueValue["tags"]);
if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null)
{
foreach (JProperty property2 in tagsSequenceElement2)
{
string tagsKey2 = ((string)property2.Name);
string tagsValue2 = ((string)property2.Value);
virtualMachineJsonInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Lists virtual-machine-sizes available to be used for a virtual
/// machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Virtual Machine operation response.
/// </returns>
public async Task<VirtualMachineSizeListResponse> ListAvailableSizesAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vmName == null)
{
throw new ArgumentNullException("vmName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "ListAvailableSizesAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Compute";
url = url + "/";
url = url + "virtualMachines";
url = url + "/";
url = url + Uri.EscapeDataString(vmName);
url = url + "/vmSizes";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineSizeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineSizeListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
VirtualMachineSize virtualMachineSizeInstance = new VirtualMachineSize();
result.VirtualMachineSizes.Add(virtualMachineSizeInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
virtualMachineSizeInstance.Name = nameInstance;
}
JToken numberOfCoresValue = valueValue["numberOfCores"];
if (numberOfCoresValue != null && numberOfCoresValue.Type != JTokenType.Null)
{
int numberOfCoresInstance = ((int)numberOfCoresValue);
virtualMachineSizeInstance.NumberOfCores = numberOfCoresInstance;
}
JToken osDiskSizeInMBValue = valueValue["osDiskSizeInMB"];
if (osDiskSizeInMBValue != null && osDiskSizeInMBValue.Type != JTokenType.Null)
{
int osDiskSizeInMBInstance = ((int)osDiskSizeInMBValue);
virtualMachineSizeInstance.OSDiskSizeInMB = osDiskSizeInMBInstance;
}
JToken resourceDiskSizeInMBValue = valueValue["resourceDiskSizeInMB"];
if (resourceDiskSizeInMBValue != null && resourceDiskSizeInMBValue.Type != JTokenType.Null)
{
int resourceDiskSizeInMBInstance = ((int)resourceDiskSizeInMBValue);
virtualMachineSizeInstance.ResourceDiskSizeInMB = resourceDiskSizeInMBInstance;
}
JToken memoryInMBValue = valueValue["memoryInMB"];
if (memoryInMBValue != null && memoryInMBValue.Type != JTokenType.Null)
{
int memoryInMBInstance = ((int)memoryInMBValue);
virtualMachineSizeInstance.MemoryInMB = memoryInMBInstance;
}
JToken maxDataDiskCountValue = valueValue["maxDataDiskCount"];
if (maxDataDiskCountValue != null && maxDataDiskCountValue.Type != JTokenType.Null)
{
int maxDataDiskCountInstance = ((int)maxDataDiskCountValue);
virtualMachineSizeInstance.MaxDataDiskCount = maxDataDiskCountInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the next page of Virtual Machines. NextLink is obtained by
/// making a ListAll() callwhich fetches the first page of Virtual
/// Machines and a link to fetch the next page.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to
/// ListVirtualMachines operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Virtual Machine operation response.
/// </returns>
public async Task<VirtualMachineListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VirtualMachineListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VirtualMachineListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
VirtualMachine virtualMachineJsonInstance = new VirtualMachine();
result.VirtualMachines.Add(virtualMachineJsonInstance);
JToken planValue = valueValue["plan"];
if (planValue != null && planValue.Type != JTokenType.Null)
{
Plan planInstance = new Plan();
virtualMachineJsonInstance.Plan = planInstance;
JToken nameValue = planValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
planInstance.Name = nameInstance;
}
JToken publisherValue = planValue["publisher"];
if (publisherValue != null && publisherValue.Type != JTokenType.Null)
{
string publisherInstance = ((string)publisherValue);
planInstance.Publisher = publisherInstance;
}
JToken productValue = planValue["product"];
if (productValue != null && productValue.Type != JTokenType.Null)
{
string productInstance = ((string)productValue);
planInstance.Product = productInstance;
}
JToken promotionCodeValue = planValue["promotionCode"];
if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
{
string promotionCodeInstance = ((string)promotionCodeValue);
planInstance.PromotionCode = promotionCodeInstance;
}
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken hardwareProfileValue = propertiesValue["hardwareProfile"];
if (hardwareProfileValue != null && hardwareProfileValue.Type != JTokenType.Null)
{
HardwareProfile hardwareProfileInstance = new HardwareProfile();
virtualMachineJsonInstance.HardwareProfile = hardwareProfileInstance;
JToken vmSizeValue = hardwareProfileValue["vmSize"];
if (vmSizeValue != null && vmSizeValue.Type != JTokenType.Null)
{
string vmSizeInstance = ((string)vmSizeValue);
hardwareProfileInstance.VirtualMachineSize = vmSizeInstance;
}
}
JToken storageProfileValue = propertiesValue["storageProfile"];
if (storageProfileValue != null && storageProfileValue.Type != JTokenType.Null)
{
StorageProfile storageProfileInstance = new StorageProfile();
virtualMachineJsonInstance.StorageProfile = storageProfileInstance;
JToken imageReferenceValue = storageProfileValue["imageReference"];
if (imageReferenceValue != null && imageReferenceValue.Type != JTokenType.Null)
{
ImageReference imageReferenceInstance = new ImageReference();
storageProfileInstance.ImageReference = imageReferenceInstance;
JToken publisherValue2 = imageReferenceValue["publisher"];
if (publisherValue2 != null && publisherValue2.Type != JTokenType.Null)
{
string publisherInstance2 = ((string)publisherValue2);
imageReferenceInstance.Publisher = publisherInstance2;
}
JToken offerValue = imageReferenceValue["offer"];
if (offerValue != null && offerValue.Type != JTokenType.Null)
{
string offerInstance = ((string)offerValue);
imageReferenceInstance.Offer = offerInstance;
}
JToken skuValue = imageReferenceValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
string skuInstance = ((string)skuValue);
imageReferenceInstance.Sku = skuInstance;
}
JToken versionValue = imageReferenceValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
imageReferenceInstance.Version = versionInstance;
}
}
JToken osDiskValue = storageProfileValue["osDisk"];
if (osDiskValue != null && osDiskValue.Type != JTokenType.Null)
{
OSDisk osDiskInstance = new OSDisk();
storageProfileInstance.OSDisk = osDiskInstance;
JToken osTypeValue = osDiskValue["osType"];
if (osTypeValue != null && osTypeValue.Type != JTokenType.Null)
{
string osTypeInstance = ((string)osTypeValue);
osDiskInstance.OperatingSystemType = osTypeInstance;
}
JToken nameValue2 = osDiskValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
osDiskInstance.Name = nameInstance2;
}
JToken vhdValue = osDiskValue["vhd"];
if (vhdValue != null && vhdValue.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance = new VirtualHardDisk();
osDiskInstance.VirtualHardDisk = vhdInstance;
JToken uriValue = vhdValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
vhdInstance.Uri = uriInstance;
}
}
JToken imageValue = osDiskValue["image"];
if (imageValue != null && imageValue.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance = new VirtualHardDisk();
osDiskInstance.SourceImage = imageInstance;
JToken uriValue2 = imageValue["uri"];
if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
{
string uriInstance2 = ((string)uriValue2);
imageInstance.Uri = uriInstance2;
}
}
JToken cachingValue = osDiskValue["caching"];
if (cachingValue != null && cachingValue.Type != JTokenType.Null)
{
string cachingInstance = ((string)cachingValue);
osDiskInstance.Caching = cachingInstance;
}
JToken createOptionValue = osDiskValue["createOption"];
if (createOptionValue != null && createOptionValue.Type != JTokenType.Null)
{
string createOptionInstance = ((string)createOptionValue);
osDiskInstance.CreateOption = createOptionInstance;
}
JToken diskSizeGBValue = osDiskValue["diskSizeGB"];
if (diskSizeGBValue != null && diskSizeGBValue.Type != JTokenType.Null)
{
int diskSizeGBInstance = ((int)diskSizeGBValue);
osDiskInstance.DiskSizeGB = diskSizeGBInstance;
}
}
JToken dataDisksArray = storageProfileValue["dataDisks"];
if (dataDisksArray != null && dataDisksArray.Type != JTokenType.Null)
{
foreach (JToken dataDisksValue in ((JArray)dataDisksArray))
{
DataDisk dataDiskInstance = new DataDisk();
storageProfileInstance.DataDisks.Add(dataDiskInstance);
JToken lunValue = dataDisksValue["lun"];
if (lunValue != null && lunValue.Type != JTokenType.Null)
{
int lunInstance = ((int)lunValue);
dataDiskInstance.Lun = lunInstance;
}
JToken nameValue3 = dataDisksValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dataDiskInstance.Name = nameInstance3;
}
JToken vhdValue2 = dataDisksValue["vhd"];
if (vhdValue2 != null && vhdValue2.Type != JTokenType.Null)
{
VirtualHardDisk vhdInstance2 = new VirtualHardDisk();
dataDiskInstance.VirtualHardDisk = vhdInstance2;
JToken uriValue3 = vhdValue2["uri"];
if (uriValue3 != null && uriValue3.Type != JTokenType.Null)
{
string uriInstance3 = ((string)uriValue3);
vhdInstance2.Uri = uriInstance3;
}
}
JToken imageValue2 = dataDisksValue["image"];
if (imageValue2 != null && imageValue2.Type != JTokenType.Null)
{
VirtualHardDisk imageInstance2 = new VirtualHardDisk();
dataDiskInstance.SourceImage = imageInstance2;
JToken uriValue4 = imageValue2["uri"];
if (uriValue4 != null && uriValue4.Type != JTokenType.Null)
{
string uriInstance4 = ((string)uriValue4);
imageInstance2.Uri = uriInstance4;
}
}
JToken cachingValue2 = dataDisksValue["caching"];
if (cachingValue2 != null && cachingValue2.Type != JTokenType.Null)
{
string cachingInstance2 = ((string)cachingValue2);
dataDiskInstance.Caching = cachingInstance2;
}
JToken createOptionValue2 = dataDisksValue["createOption"];
if (createOptionValue2 != null && createOptionValue2.Type != JTokenType.Null)
{
string createOptionInstance2 = ((string)createOptionValue2);
dataDiskInstance.CreateOption = createOptionInstance2;
}
JToken diskSizeGBValue2 = dataDisksValue["diskSizeGB"];
if (diskSizeGBValue2 != null && diskSizeGBValue2.Type != JTokenType.Null)
{
int diskSizeGBInstance2 = ((int)diskSizeGBValue2);
dataDiskInstance.DiskSizeGB = diskSizeGBInstance2;
}
}
}
}
JToken osProfileValue = propertiesValue["osProfile"];
if (osProfileValue != null && osProfileValue.Type != JTokenType.Null)
{
OSProfile osProfileInstance = new OSProfile();
virtualMachineJsonInstance.OSProfile = osProfileInstance;
JToken computerNameValue = osProfileValue["computerName"];
if (computerNameValue != null && computerNameValue.Type != JTokenType.Null)
{
string computerNameInstance = ((string)computerNameValue);
osProfileInstance.ComputerName = computerNameInstance;
}
JToken adminUsernameValue = osProfileValue["adminUsername"];
if (adminUsernameValue != null && adminUsernameValue.Type != JTokenType.Null)
{
string adminUsernameInstance = ((string)adminUsernameValue);
osProfileInstance.AdminUsername = adminUsernameInstance;
}
JToken adminPasswordValue = osProfileValue["adminPassword"];
if (adminPasswordValue != null && adminPasswordValue.Type != JTokenType.Null)
{
string adminPasswordInstance = ((string)adminPasswordValue);
osProfileInstance.AdminPassword = adminPasswordInstance;
}
JToken customDataValue = osProfileValue["customData"];
if (customDataValue != null && customDataValue.Type != JTokenType.Null)
{
string customDataInstance = ((string)customDataValue);
osProfileInstance.CustomData = customDataInstance;
}
JToken windowsConfigurationValue = osProfileValue["windowsConfiguration"];
if (windowsConfigurationValue != null && windowsConfigurationValue.Type != JTokenType.Null)
{
WindowsConfiguration windowsConfigurationInstance = new WindowsConfiguration();
osProfileInstance.WindowsConfiguration = windowsConfigurationInstance;
JToken provisionVMAgentValue = windowsConfigurationValue["provisionVMAgent"];
if (provisionVMAgentValue != null && provisionVMAgentValue.Type != JTokenType.Null)
{
bool provisionVMAgentInstance = ((bool)provisionVMAgentValue);
windowsConfigurationInstance.ProvisionVMAgent = provisionVMAgentInstance;
}
JToken enableAutomaticUpdatesValue = windowsConfigurationValue["enableAutomaticUpdates"];
if (enableAutomaticUpdatesValue != null && enableAutomaticUpdatesValue.Type != JTokenType.Null)
{
bool enableAutomaticUpdatesInstance = ((bool)enableAutomaticUpdatesValue);
windowsConfigurationInstance.EnableAutomaticUpdates = enableAutomaticUpdatesInstance;
}
JToken timeZoneValue = windowsConfigurationValue["timeZone"];
if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
{
string timeZoneInstance = ((string)timeZoneValue);
windowsConfigurationInstance.TimeZone = timeZoneInstance;
}
JToken additionalUnattendContentArray = windowsConfigurationValue["additionalUnattendContent"];
if (additionalUnattendContentArray != null && additionalUnattendContentArray.Type != JTokenType.Null)
{
foreach (JToken additionalUnattendContentValue in ((JArray)additionalUnattendContentArray))
{
AdditionalUnattendContent additionalUnattendContentInstance = new AdditionalUnattendContent();
windowsConfigurationInstance.AdditionalUnattendContents.Add(additionalUnattendContentInstance);
JToken passNameValue = additionalUnattendContentValue["passName"];
if (passNameValue != null && passNameValue.Type != JTokenType.Null)
{
string passNameInstance = ((string)passNameValue);
additionalUnattendContentInstance.PassName = passNameInstance;
}
JToken componentNameValue = additionalUnattendContentValue["componentName"];
if (componentNameValue != null && componentNameValue.Type != JTokenType.Null)
{
string componentNameInstance = ((string)componentNameValue);
additionalUnattendContentInstance.ComponentName = componentNameInstance;
}
JToken settingNameValue = additionalUnattendContentValue["settingName"];
if (settingNameValue != null && settingNameValue.Type != JTokenType.Null)
{
string settingNameInstance = ((string)settingNameValue);
additionalUnattendContentInstance.SettingName = settingNameInstance;
}
JToken contentValue = additionalUnattendContentValue["content"];
if (contentValue != null && contentValue.Type != JTokenType.Null)
{
string contentInstance = ((string)contentValue);
additionalUnattendContentInstance.Content = contentInstance;
}
}
}
JToken winRMValue = windowsConfigurationValue["winRM"];
if (winRMValue != null && winRMValue.Type != JTokenType.Null)
{
WinRMConfiguration winRMInstance = new WinRMConfiguration();
windowsConfigurationInstance.WinRMConfiguration = winRMInstance;
JToken listenersArray = winRMValue["listeners"];
if (listenersArray != null && listenersArray.Type != JTokenType.Null)
{
foreach (JToken listenersValue in ((JArray)listenersArray))
{
WinRMListener winRMListenerInstance = new WinRMListener();
winRMInstance.Listeners.Add(winRMListenerInstance);
JToken protocolValue = listenersValue["protocol"];
if (protocolValue != null && protocolValue.Type != JTokenType.Null)
{
string protocolInstance = ((string)protocolValue);
winRMListenerInstance.Protocol = protocolInstance;
}
JToken certificateUrlValue = listenersValue["certificateUrl"];
if (certificateUrlValue != null && certificateUrlValue.Type != JTokenType.Null)
{
Uri certificateUrlInstance = TypeConversion.TryParseUri(((string)certificateUrlValue));
winRMListenerInstance.CertificateUrl = certificateUrlInstance;
}
}
}
}
}
JToken linuxConfigurationValue = osProfileValue["linuxConfiguration"];
if (linuxConfigurationValue != null && linuxConfigurationValue.Type != JTokenType.Null)
{
LinuxConfiguration linuxConfigurationInstance = new LinuxConfiguration();
osProfileInstance.LinuxConfiguration = linuxConfigurationInstance;
JToken disablePasswordAuthenticationValue = linuxConfigurationValue["disablePasswordAuthentication"];
if (disablePasswordAuthenticationValue != null && disablePasswordAuthenticationValue.Type != JTokenType.Null)
{
bool disablePasswordAuthenticationInstance = ((bool)disablePasswordAuthenticationValue);
linuxConfigurationInstance.DisablePasswordAuthentication = disablePasswordAuthenticationInstance;
}
JToken sshValue = linuxConfigurationValue["ssh"];
if (sshValue != null && sshValue.Type != JTokenType.Null)
{
SshConfiguration sshInstance = new SshConfiguration();
linuxConfigurationInstance.SshConfiguration = sshInstance;
JToken publicKeysArray = sshValue["publicKeys"];
if (publicKeysArray != null && publicKeysArray.Type != JTokenType.Null)
{
foreach (JToken publicKeysValue in ((JArray)publicKeysArray))
{
SshPublicKey sshPublicKeyInstance = new SshPublicKey();
sshInstance.PublicKeys.Add(sshPublicKeyInstance);
JToken pathValue = publicKeysValue["path"];
if (pathValue != null && pathValue.Type != JTokenType.Null)
{
string pathInstance = ((string)pathValue);
sshPublicKeyInstance.Path = pathInstance;
}
JToken keyDataValue = publicKeysValue["keyData"];
if (keyDataValue != null && keyDataValue.Type != JTokenType.Null)
{
string keyDataInstance = ((string)keyDataValue);
sshPublicKeyInstance.KeyData = keyDataInstance;
}
}
}
}
}
JToken secretsArray = osProfileValue["secrets"];
if (secretsArray != null && secretsArray.Type != JTokenType.Null)
{
foreach (JToken secretsValue in ((JArray)secretsArray))
{
VaultSecretGroup vaultSecretGroupInstance = new VaultSecretGroup();
osProfileInstance.Secrets.Add(vaultSecretGroupInstance);
JToken sourceVaultValue = secretsValue["sourceVault"];
if (sourceVaultValue != null && sourceVaultValue.Type != JTokenType.Null)
{
SourceVaultReference sourceVaultInstance = new SourceVaultReference();
vaultSecretGroupInstance.SourceVault = sourceVaultInstance;
JToken idValue = sourceVaultValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
sourceVaultInstance.ReferenceUri = idInstance;
}
}
JToken vaultCertificatesArray = secretsValue["vaultCertificates"];
if (vaultCertificatesArray != null && vaultCertificatesArray.Type != JTokenType.Null)
{
foreach (JToken vaultCertificatesValue in ((JArray)vaultCertificatesArray))
{
VaultCertificate vaultCertificateInstance = new VaultCertificate();
vaultSecretGroupInstance.VaultCertificates.Add(vaultCertificateInstance);
JToken certificateUrlValue2 = vaultCertificatesValue["certificateUrl"];
if (certificateUrlValue2 != null && certificateUrlValue2.Type != JTokenType.Null)
{
string certificateUrlInstance2 = ((string)certificateUrlValue2);
vaultCertificateInstance.CertificateUrl = certificateUrlInstance2;
}
JToken certificateStoreValue = vaultCertificatesValue["certificateStore"];
if (certificateStoreValue != null && certificateStoreValue.Type != JTokenType.Null)
{
string certificateStoreInstance = ((string)certificateStoreValue);
vaultCertificateInstance.CertificateStore = certificateStoreInstance;
}
}
}
}
}
}
JToken networkProfileValue = propertiesValue["networkProfile"];
if (networkProfileValue != null && networkProfileValue.Type != JTokenType.Null)
{
NetworkProfile networkProfileInstance = new NetworkProfile();
virtualMachineJsonInstance.NetworkProfile = networkProfileInstance;
JToken networkInterfacesArray = networkProfileValue["networkInterfaces"];
if (networkInterfacesArray != null && networkInterfacesArray.Type != JTokenType.Null)
{
foreach (JToken networkInterfacesValue in ((JArray)networkInterfacesArray))
{
NetworkInterfaceReference networkInterfaceReferenceJsonInstance = new NetworkInterfaceReference();
networkProfileInstance.NetworkInterfaces.Add(networkInterfaceReferenceJsonInstance);
JToken propertiesValue2 = networkInterfacesValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken primaryValue = propertiesValue2["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
bool primaryInstance = ((bool)primaryValue);
networkInterfaceReferenceJsonInstance.Primary = primaryInstance;
}
}
JToken idValue2 = networkInterfacesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
networkInterfaceReferenceJsonInstance.ReferenceUri = idInstance2;
}
}
}
}
JToken availabilitySetValue = propertiesValue["availabilitySet"];
if (availabilitySetValue != null && availabilitySetValue.Type != JTokenType.Null)
{
AvailabilitySetReference availabilitySetInstance = new AvailabilitySetReference();
virtualMachineJsonInstance.AvailabilitySetReference = availabilitySetInstance;
JToken idValue3 = availabilitySetValue["id"];
if (idValue3 != null && idValue3.Type != JTokenType.Null)
{
string idInstance3 = ((string)idValue3);
availabilitySetInstance.ReferenceUri = idInstance3;
}
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
virtualMachineJsonInstance.ProvisioningState = provisioningStateInstance;
}
JToken instanceViewValue = propertiesValue["instanceView"];
if (instanceViewValue != null && instanceViewValue.Type != JTokenType.Null)
{
VirtualMachineInstanceView instanceViewInstance = new VirtualMachineInstanceView();
virtualMachineJsonInstance.InstanceView = instanceViewInstance;
JToken platformUpdateDomainValue = instanceViewValue["platformUpdateDomain"];
if (platformUpdateDomainValue != null && platformUpdateDomainValue.Type != JTokenType.Null)
{
int platformUpdateDomainInstance = ((int)platformUpdateDomainValue);
instanceViewInstance.PlatformUpdateDomain = platformUpdateDomainInstance;
}
JToken platformFaultDomainValue = instanceViewValue["platformFaultDomain"];
if (platformFaultDomainValue != null && platformFaultDomainValue.Type != JTokenType.Null)
{
int platformFaultDomainInstance = ((int)platformFaultDomainValue);
instanceViewInstance.PlatformFaultDomain = platformFaultDomainInstance;
}
JToken rdpThumbPrintValue = instanceViewValue["rdpThumbPrint"];
if (rdpThumbPrintValue != null && rdpThumbPrintValue.Type != JTokenType.Null)
{
string rdpThumbPrintInstance = ((string)rdpThumbPrintValue);
instanceViewInstance.RemoteDesktopThumbprint = rdpThumbPrintInstance;
}
JToken vmAgentValue = instanceViewValue["vmAgent"];
if (vmAgentValue != null && vmAgentValue.Type != JTokenType.Null)
{
VirtualMachineAgentInstanceView vmAgentInstance = new VirtualMachineAgentInstanceView();
instanceViewInstance.VMAgent = vmAgentInstance;
JToken vmAgentVersionValue = vmAgentValue["vmAgentVersion"];
if (vmAgentVersionValue != null && vmAgentVersionValue.Type != JTokenType.Null)
{
string vmAgentVersionInstance = ((string)vmAgentVersionValue);
vmAgentInstance.VMAgentVersion = vmAgentVersionInstance;
}
JToken extensionHandlersArray = vmAgentValue["extensionHandlers"];
if (extensionHandlersArray != null && extensionHandlersArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlersValue in ((JArray)extensionHandlersArray))
{
VirtualMachineExtensionHandlerInstanceView virtualMachineExtensionHandlerInstanceViewInstance = new VirtualMachineExtensionHandlerInstanceView();
vmAgentInstance.ExtensionHandlers.Add(virtualMachineExtensionHandlerInstanceViewInstance);
JToken typeValue = extensionHandlersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
virtualMachineExtensionHandlerInstanceViewInstance.Type = typeInstance;
}
JToken typeHandlerVersionValue = extensionHandlersValue["typeHandlerVersion"];
if (typeHandlerVersionValue != null && typeHandlerVersionValue.Type != JTokenType.Null)
{
string typeHandlerVersionInstance = ((string)typeHandlerVersionValue);
virtualMachineExtensionHandlerInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance;
}
JToken statusValue = extensionHandlersValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
InstanceViewStatus statusInstance = new InstanceViewStatus();
virtualMachineExtensionHandlerInstanceViewInstance.Status = statusInstance;
JToken codeValue = statusValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
statusInstance.Code = codeInstance;
}
JToken levelValue = statusValue["level"];
if (levelValue != null && levelValue.Type != JTokenType.Null)
{
string levelInstance = ((string)levelValue);
statusInstance.Level = levelInstance;
}
JToken displayStatusValue = statusValue["displayStatus"];
if (displayStatusValue != null && displayStatusValue.Type != JTokenType.Null)
{
string displayStatusInstance = ((string)displayStatusValue);
statusInstance.DisplayStatus = displayStatusInstance;
}
JToken messageValue = statusValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
statusInstance.Message = messageInstance;
}
JToken timeValue = statusValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
statusInstance.Time = timeInstance;
}
}
}
}
JToken statusesArray = vmAgentValue["statuses"];
if (statusesArray != null && statusesArray.Type != JTokenType.Null)
{
foreach (JToken statusesValue in ((JArray)statusesArray))
{
InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
vmAgentInstance.Statuses.Add(instanceViewStatusInstance);
JToken codeValue2 = statusesValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
instanceViewStatusInstance.Code = codeInstance2;
}
JToken levelValue2 = statusesValue["level"];
if (levelValue2 != null && levelValue2.Type != JTokenType.Null)
{
string levelInstance2 = ((string)levelValue2);
instanceViewStatusInstance.Level = levelInstance2;
}
JToken displayStatusValue2 = statusesValue["displayStatus"];
if (displayStatusValue2 != null && displayStatusValue2.Type != JTokenType.Null)
{
string displayStatusInstance2 = ((string)displayStatusValue2);
instanceViewStatusInstance.DisplayStatus = displayStatusInstance2;
}
JToken messageValue2 = statusesValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
instanceViewStatusInstance.Message = messageInstance2;
}
JToken timeValue2 = statusesValue["time"];
if (timeValue2 != null && timeValue2.Type != JTokenType.Null)
{
DateTimeOffset timeInstance2 = ((DateTimeOffset)timeValue2);
instanceViewStatusInstance.Time = timeInstance2;
}
}
}
}
JToken disksArray = instanceViewValue["disks"];
if (disksArray != null && disksArray.Type != JTokenType.Null)
{
foreach (JToken disksValue in ((JArray)disksArray))
{
DiskInstanceView diskInstanceViewInstance = new DiskInstanceView();
instanceViewInstance.Disks.Add(diskInstanceViewInstance);
JToken nameValue4 = disksValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
diskInstanceViewInstance.Name = nameInstance4;
}
JToken statusesArray2 = disksValue["statuses"];
if (statusesArray2 != null && statusesArray2.Type != JTokenType.Null)
{
foreach (JToken statusesValue2 in ((JArray)statusesArray2))
{
InstanceViewStatus instanceViewStatusInstance2 = new InstanceViewStatus();
diskInstanceViewInstance.Statuses.Add(instanceViewStatusInstance2);
JToken codeValue3 = statusesValue2["code"];
if (codeValue3 != null && codeValue3.Type != JTokenType.Null)
{
string codeInstance3 = ((string)codeValue3);
instanceViewStatusInstance2.Code = codeInstance3;
}
JToken levelValue3 = statusesValue2["level"];
if (levelValue3 != null && levelValue3.Type != JTokenType.Null)
{
string levelInstance3 = ((string)levelValue3);
instanceViewStatusInstance2.Level = levelInstance3;
}
JToken displayStatusValue3 = statusesValue2["displayStatus"];
if (displayStatusValue3 != null && displayStatusValue3.Type != JTokenType.Null)
{
string displayStatusInstance3 = ((string)displayStatusValue3);
instanceViewStatusInstance2.DisplayStatus = displayStatusInstance3;
}
JToken messageValue3 = statusesValue2["message"];
if (messageValue3 != null && messageValue3.Type != JTokenType.Null)
{
string messageInstance3 = ((string)messageValue3);
instanceViewStatusInstance2.Message = messageInstance3;
}
JToken timeValue3 = statusesValue2["time"];
if (timeValue3 != null && timeValue3.Type != JTokenType.Null)
{
DateTimeOffset timeInstance3 = ((DateTimeOffset)timeValue3);
instanceViewStatusInstance2.Time = timeInstance3;
}
}
}
}
}
JToken extensionsArray = instanceViewValue["extensions"];
if (extensionsArray != null && extensionsArray.Type != JTokenType.Null)
{
foreach (JToken extensionsValue in ((JArray)extensionsArray))
{
VirtualMachineExtensionInstanceView virtualMachineExtensionInstanceViewInstance = new VirtualMachineExtensionInstanceView();
instanceViewInstance.Extensions.Add(virtualMachineExtensionInstanceViewInstance);
JToken nameValue5 = extensionsValue["name"];
if (nameValue5 != null && nameValue5.Type != JTokenType.Null)
{
string nameInstance5 = ((string)nameValue5);
virtualMachineExtensionInstanceViewInstance.Name = nameInstance5;
}
JToken typeValue2 = extensionsValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
virtualMachineExtensionInstanceViewInstance.ExtensionType = typeInstance2;
}
JToken typeHandlerVersionValue2 = extensionsValue["typeHandlerVersion"];
if (typeHandlerVersionValue2 != null && typeHandlerVersionValue2.Type != JTokenType.Null)
{
string typeHandlerVersionInstance2 = ((string)typeHandlerVersionValue2);
virtualMachineExtensionInstanceViewInstance.TypeHandlerVersion = typeHandlerVersionInstance2;
}
JToken substatusesArray = extensionsValue["substatuses"];
if (substatusesArray != null && substatusesArray.Type != JTokenType.Null)
{
foreach (JToken substatusesValue in ((JArray)substatusesArray))
{
InstanceViewStatus instanceViewStatusInstance3 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.SubStatuses.Add(instanceViewStatusInstance3);
JToken codeValue4 = substatusesValue["code"];
if (codeValue4 != null && codeValue4.Type != JTokenType.Null)
{
string codeInstance4 = ((string)codeValue4);
instanceViewStatusInstance3.Code = codeInstance4;
}
JToken levelValue4 = substatusesValue["level"];
if (levelValue4 != null && levelValue4.Type != JTokenType.Null)
{
string levelInstance4 = ((string)levelValue4);
instanceViewStatusInstance3.Level = levelInstance4;
}
JToken displayStatusValue4 = substatusesValue["displayStatus"];
if (displayStatusValue4 != null && displayStatusValue4.Type != JTokenType.Null)
{
string displayStatusInstance4 = ((string)displayStatusValue4);
instanceViewStatusInstance3.DisplayStatus = displayStatusInstance4;
}
JToken messageValue4 = substatusesValue["message"];
if (messageValue4 != null && messageValue4.Type != JTokenType.Null)
{
string messageInstance4 = ((string)messageValue4);
instanceViewStatusInstance3.Message = messageInstance4;
}
JToken timeValue4 = substatusesValue["time"];
if (timeValue4 != null && timeValue4.Type != JTokenType.Null)
{
DateTimeOffset timeInstance4 = ((DateTimeOffset)timeValue4);
instanceViewStatusInstance3.Time = timeInstance4;
}
}
}
JToken statusesArray3 = extensionsValue["statuses"];
if (statusesArray3 != null && statusesArray3.Type != JTokenType.Null)
{
foreach (JToken statusesValue3 in ((JArray)statusesArray3))
{
InstanceViewStatus instanceViewStatusInstance4 = new InstanceViewStatus();
virtualMachineExtensionInstanceViewInstance.Statuses.Add(instanceViewStatusInstance4);
JToken codeValue5 = statusesValue3["code"];
if (codeValue5 != null && codeValue5.Type != JTokenType.Null)
{
string codeInstance5 = ((string)codeValue5);
instanceViewStatusInstance4.Code = codeInstance5;
}
JToken levelValue5 = statusesValue3["level"];
if (levelValue5 != null && levelValue5.Type != JTokenType.Null)
{
string levelInstance5 = ((string)levelValue5);
instanceViewStatusInstance4.Level = levelInstance5;
}
JToken displayStatusValue5 = statusesValue3["displayStatus"];
if (displayStatusValue5 != null && displayStatusValue5.Type != JTokenType.Null)
{
string displayStatusInstance5 = ((string)displayStatusValue5);
instanceViewStatusInstance4.DisplayStatus = displayStatusInstance5;
}
JToken messageValue5 = statusesValue3["message"];
if (messageValue5 != null && messageValue5.Type != JTokenType.Null)
{
string messageInstance5 = ((string)messageValue5);
instanceViewStatusInstance4.Message = messageInstance5;
}
JToken timeValue5 = statusesValue3["time"];
if (timeValue5 != null && timeValue5.Type != JTokenType.Null)
{
DateTimeOffset timeInstance5 = ((DateTimeOffset)timeValue5);
instanceViewStatusInstance4.Time = timeInstance5;
}
}
}
}
}
JToken statusesArray4 = instanceViewValue["statuses"];
if (statusesArray4 != null && statusesArray4.Type != JTokenType.Null)
{
foreach (JToken statusesValue4 in ((JArray)statusesArray4))
{
InstanceViewStatus instanceViewStatusInstance5 = new InstanceViewStatus();
instanceViewInstance.Statuses.Add(instanceViewStatusInstance5);
JToken codeValue6 = statusesValue4["code"];
if (codeValue6 != null && codeValue6.Type != JTokenType.Null)
{
string codeInstance6 = ((string)codeValue6);
instanceViewStatusInstance5.Code = codeInstance6;
}
JToken levelValue6 = statusesValue4["level"];
if (levelValue6 != null && levelValue6.Type != JTokenType.Null)
{
string levelInstance6 = ((string)levelValue6);
instanceViewStatusInstance5.Level = levelInstance6;
}
JToken displayStatusValue6 = statusesValue4["displayStatus"];
if (displayStatusValue6 != null && displayStatusValue6.Type != JTokenType.Null)
{
string displayStatusInstance6 = ((string)displayStatusValue6);
instanceViewStatusInstance5.DisplayStatus = displayStatusInstance6;
}
JToken messageValue6 = statusesValue4["message"];
if (messageValue6 != null && messageValue6.Type != JTokenType.Null)
{
string messageInstance6 = ((string)messageValue6);
instanceViewStatusInstance5.Message = messageInstance6;
}
JToken timeValue6 = statusesValue4["time"];
if (timeValue6 != null && timeValue6.Type != JTokenType.Null)
{
DateTimeOffset timeInstance6 = ((DateTimeOffset)timeValue6);
instanceViewStatusInstance5.Time = timeInstance6;
}
}
}
}
}
JToken resourcesArray = valueValue["resources"];
if (resourcesArray != null && resourcesArray.Type != JTokenType.Null)
{
virtualMachineJsonInstance.Extensions = new List<VirtualMachineExtension>();
foreach (JToken resourcesValue in ((JArray)resourcesArray))
{
VirtualMachineExtension virtualMachineExtensionJsonInstance = new VirtualMachineExtension();
virtualMachineJsonInstance.Extensions.Add(virtualMachineExtensionJsonInstance);
JToken propertiesValue3 = resourcesValue["properties"];
if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
{
JToken publisherValue3 = propertiesValue3["publisher"];
if (publisherValue3 != null && publisherValue3.Type != JTokenType.Null)
{
string publisherInstance3 = ((string)publisherValue3);
virtualMachineExtensionJsonInstance.Publisher = publisherInstance3;
}
JToken typeValue3 = propertiesValue3["type"];
if (typeValue3 != null && typeValue3.Type != JTokenType.Null)
{
string typeInstance3 = ((string)typeValue3);
virtualMachineExtensionJsonInstance.ExtensionType = typeInstance3;
}
JToken typeHandlerVersionValue3 = propertiesValue3["typeHandlerVersion"];
if (typeHandlerVersionValue3 != null && typeHandlerVersionValue3.Type != JTokenType.Null)
{
string typeHandlerVersionInstance3 = ((string)typeHandlerVersionValue3);
virtualMachineExtensionJsonInstance.TypeHandlerVersion = typeHandlerVersionInstance3;
}
JToken autoUpgradeMinorVersionValue = propertiesValue3["autoUpgradeMinorVersion"];
if (autoUpgradeMinorVersionValue != null && autoUpgradeMinorVersionValue.Type != JTokenType.Null)
{
bool autoUpgradeMinorVersionInstance = ((bool)autoUpgradeMinorVersionValue);
virtualMachineExtensionJsonInstance.AutoUpgradeMinorVersion = autoUpgradeMinorVersionInstance;
}
JToken settingsValue = propertiesValue3["settings"];
if (settingsValue != null && settingsValue.Type != JTokenType.Null)
{
string settingsInstance = settingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.Settings = settingsInstance;
}
JToken protectedSettingsValue = propertiesValue3["protectedSettings"];
if (protectedSettingsValue != null && protectedSettingsValue.Type != JTokenType.Null)
{
string protectedSettingsInstance = protectedSettingsValue.ToString(Newtonsoft.Json.Formatting.Indented);
virtualMachineExtensionJsonInstance.ProtectedSettings = protectedSettingsInstance;
}
JToken provisioningStateValue2 = propertiesValue3["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
virtualMachineExtensionJsonInstance.ProvisioningState = provisioningStateInstance2;
}
JToken instanceViewValue2 = propertiesValue3["instanceView"];
if (instanceViewValue2 != null && instanceViewValue2.Type != JTokenType.Null)
{
VirtualMachineExtensionInstanceView instanceViewInstance2 = new VirtualMachineExtensionInstanceView();
virtualMachineExtensionJsonInstance.InstanceView = instanceViewInstance2;
JToken nameValue6 = instanceViewValue2["name"];
if (nameValue6 != null && nameValue6.Type != JTokenType.Null)
{
string nameInstance6 = ((string)nameValue6);
instanceViewInstance2.Name = nameInstance6;
}
JToken typeValue4 = instanceViewValue2["type"];
if (typeValue4 != null && typeValue4.Type != JTokenType.Null)
{
string typeInstance4 = ((string)typeValue4);
instanceViewInstance2.ExtensionType = typeInstance4;
}
JToken typeHandlerVersionValue4 = instanceViewValue2["typeHandlerVersion"];
if (typeHandlerVersionValue4 != null && typeHandlerVersionValue4.Type != JTokenType.Null)
{
string typeHandlerVersionInstance4 = ((string)typeHandlerVersionValue4);
instanceViewInstance2.TypeHandlerVersion = typeHandlerVersionInstance4;
}
JToken substatusesArray2 = instanceViewValue2["substatuses"];
if (substatusesArray2 != null && substatusesArray2.Type != JTokenType.Null)
{
foreach (JToken substatusesValue2 in ((JArray)substatusesArray2))
{
InstanceViewStatus instanceViewStatusInstance6 = new InstanceViewStatus();
instanceViewInstance2.SubStatuses.Add(instanceViewStatusInstance6);
JToken codeValue7 = substatusesValue2["code"];
if (codeValue7 != null && codeValue7.Type != JTokenType.Null)
{
string codeInstance7 = ((string)codeValue7);
instanceViewStatusInstance6.Code = codeInstance7;
}
JToken levelValue7 = substatusesValue2["level"];
if (levelValue7 != null && levelValue7.Type != JTokenType.Null)
{
string levelInstance7 = ((string)levelValue7);
instanceViewStatusInstance6.Level = levelInstance7;
}
JToken displayStatusValue7 = substatusesValue2["displayStatus"];
if (displayStatusValue7 != null && displayStatusValue7.Type != JTokenType.Null)
{
string displayStatusInstance7 = ((string)displayStatusValue7);
instanceViewStatusInstance6.DisplayStatus = displayStatusInstance7;
}
JToken messageValue7 = substatusesValue2["message"];
if (messageValue7 != null && messageValue7.Type != JTokenType.Null)
{
string messageInstance7 = ((string)messageValue7);
instanceViewStatusInstance6.Message = messageInstance7;
}
JToken timeValue7 = substatusesValue2["time"];
if (timeValue7 != null && timeValue7.Type != JTokenType.Null)
{
DateTimeOffset timeInstance7 = ((DateTimeOffset)timeValue7);
instanceViewStatusInstance6.Time = timeInstance7;
}
}
}
JToken statusesArray5 = instanceViewValue2["statuses"];
if (statusesArray5 != null && statusesArray5.Type != JTokenType.Null)
{
foreach (JToken statusesValue5 in ((JArray)statusesArray5))
{
InstanceViewStatus instanceViewStatusInstance7 = new InstanceViewStatus();
instanceViewInstance2.Statuses.Add(instanceViewStatusInstance7);
JToken codeValue8 = statusesValue5["code"];
if (codeValue8 != null && codeValue8.Type != JTokenType.Null)
{
string codeInstance8 = ((string)codeValue8);
instanceViewStatusInstance7.Code = codeInstance8;
}
JToken levelValue8 = statusesValue5["level"];
if (levelValue8 != null && levelValue8.Type != JTokenType.Null)
{
string levelInstance8 = ((string)levelValue8);
instanceViewStatusInstance7.Level = levelInstance8;
}
JToken displayStatusValue8 = statusesValue5["displayStatus"];
if (displayStatusValue8 != null && displayStatusValue8.Type != JTokenType.Null)
{
string displayStatusInstance8 = ((string)displayStatusValue8);
instanceViewStatusInstance7.DisplayStatus = displayStatusInstance8;
}
JToken messageValue8 = statusesValue5["message"];
if (messageValue8 != null && messageValue8.Type != JTokenType.Null)
{
string messageInstance8 = ((string)messageValue8);
instanceViewStatusInstance7.Message = messageInstance8;
}
JToken timeValue8 = statusesValue5["time"];
if (timeValue8 != null && timeValue8.Type != JTokenType.Null)
{
DateTimeOffset timeInstance8 = ((DateTimeOffset)timeValue8);
instanceViewStatusInstance7.Time = timeInstance8;
}
}
}
}
}
JToken idValue4 = resourcesValue["id"];
if (idValue4 != null && idValue4.Type != JTokenType.Null)
{
string idInstance4 = ((string)idValue4);
virtualMachineExtensionJsonInstance.Id = idInstance4;
}
JToken nameValue7 = resourcesValue["name"];
if (nameValue7 != null && nameValue7.Type != JTokenType.Null)
{
string nameInstance7 = ((string)nameValue7);
virtualMachineExtensionJsonInstance.Name = nameInstance7;
}
JToken typeValue5 = resourcesValue["type"];
if (typeValue5 != null && typeValue5.Type != JTokenType.Null)
{
string typeInstance5 = ((string)typeValue5);
virtualMachineExtensionJsonInstance.Type = typeInstance5;
}
JToken locationValue = resourcesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
virtualMachineExtensionJsonInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)resourcesValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
virtualMachineExtensionJsonInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken idValue5 = valueValue["id"];
if (idValue5 != null && idValue5.Type != JTokenType.Null)
{
string idInstance5 = ((string)idValue5);
virtualMachineJsonInstance.Id = idInstance5;
}
JToken nameValue8 = valueValue["name"];
if (nameValue8 != null && nameValue8.Type != JTokenType.Null)
{
string nameInstance8 = ((string)nameValue8);
virtualMachineJsonInstance.Name = nameInstance8;
}
JToken typeValue6 = valueValue["type"];
if (typeValue6 != null && typeValue6.Type != JTokenType.Null)
{
string typeInstance6 = ((string)typeValue6);
virtualMachineJsonInstance.Type = typeInstance6;
}
JToken locationValue2 = valueValue["location"];
if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
{
string locationInstance2 = ((string)locationValue2);
virtualMachineJsonInstance.Location = locationInstance2;
}
JToken tagsSequenceElement2 = ((JToken)valueValue["tags"]);
if (tagsSequenceElement2 != null && tagsSequenceElement2.Type != JTokenType.Null)
{
foreach (JProperty property2 in tagsSequenceElement2)
{
string tagsKey2 = ((string)property2.Name);
string tagsValue2 = ((string)property2.Value);
virtualMachineJsonInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Compute service response for long-running operations.
/// </returns>
public async Task<ComputeLongRunningOperationResponse> PowerOffAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "PowerOffAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ComputeOperationResponse response = await client.VirtualMachines.BeginPoweringOffAsync(resourceGroupName, vmName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ComputeLongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Compute.Models.ComputeOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Compute service response for long-running operations.
/// </returns>
public async Task<ComputeLongRunningOperationResponse> RestartAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "RestartAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ComputeOperationResponse response = await client.VirtualMachines.BeginRestartingAsync(resourceGroupName, vmName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ComputeLongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Compute.Models.ComputeOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='vmName'>
/// Required. The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Compute service response for long-running operations.
/// </returns>
public async Task<ComputeLongRunningOperationResponse> StartAsync(string resourceGroupName, string vmName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmName", vmName);
TracingAdapter.Enter(invocationId, this, "StartAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ComputeOperationResponse response = await client.VirtualMachines.BeginStartingAsync(resourceGroupName, vmName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ComputeLongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Compute.Models.ComputeOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
}
}
| 70.057191 | 242 | 0.367218 | [
"Apache-2.0"
] | xindzhan/azure-sdk-for-net | src/ResourceManagement/Compute/ComputeManagement/Generated/VirtualMachineOperations.cs | 752,134 | C# |
#region Using
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
#endregion
namespace SmartAdmin.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
} | 30.916667 | 88 | 0.685984 | [
"Apache-2.0"
] | AlbertoGarciaArdiles/ssocloudpe-1481170344582 | src/dotnetstarter/Models/ApplicationDbContext.cs | 744 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type UnsupportedDeviceConfigurationRequest.
/// </summary>
public partial class UnsupportedDeviceConfigurationRequest : BaseRequest, IUnsupportedDeviceConfigurationRequest
{
/// <summary>
/// Constructs a new UnsupportedDeviceConfigurationRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public UnsupportedDeviceConfigurationRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified UnsupportedDeviceConfiguration using POST.
/// </summary>
/// <param name="unsupportedDeviceConfigurationToCreate">The UnsupportedDeviceConfiguration to create.</param>
/// <returns>The created UnsupportedDeviceConfiguration.</returns>
public System.Threading.Tasks.Task<UnsupportedDeviceConfiguration> CreateAsync(UnsupportedDeviceConfiguration unsupportedDeviceConfigurationToCreate)
{
return this.CreateAsync(unsupportedDeviceConfigurationToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified UnsupportedDeviceConfiguration using POST.
/// </summary>
/// <param name="unsupportedDeviceConfigurationToCreate">The UnsupportedDeviceConfiguration to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created UnsupportedDeviceConfiguration.</returns>
public async System.Threading.Tasks.Task<UnsupportedDeviceConfiguration> CreateAsync(UnsupportedDeviceConfiguration unsupportedDeviceConfigurationToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<UnsupportedDeviceConfiguration>(unsupportedDeviceConfigurationToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified UnsupportedDeviceConfiguration.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified UnsupportedDeviceConfiguration.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<UnsupportedDeviceConfiguration>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified UnsupportedDeviceConfiguration.
/// </summary>
/// <returns>The UnsupportedDeviceConfiguration.</returns>
public System.Threading.Tasks.Task<UnsupportedDeviceConfiguration> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified UnsupportedDeviceConfiguration.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The UnsupportedDeviceConfiguration.</returns>
public async System.Threading.Tasks.Task<UnsupportedDeviceConfiguration> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<UnsupportedDeviceConfiguration>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified UnsupportedDeviceConfiguration using PATCH.
/// </summary>
/// <param name="unsupportedDeviceConfigurationToUpdate">The UnsupportedDeviceConfiguration to update.</param>
/// <returns>The updated UnsupportedDeviceConfiguration.</returns>
public System.Threading.Tasks.Task<UnsupportedDeviceConfiguration> UpdateAsync(UnsupportedDeviceConfiguration unsupportedDeviceConfigurationToUpdate)
{
return this.UpdateAsync(unsupportedDeviceConfigurationToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified UnsupportedDeviceConfiguration using PATCH.
/// </summary>
/// <param name="unsupportedDeviceConfigurationToUpdate">The UnsupportedDeviceConfiguration to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated UnsupportedDeviceConfiguration.</returns>
public async System.Threading.Tasks.Task<UnsupportedDeviceConfiguration> UpdateAsync(UnsupportedDeviceConfiguration unsupportedDeviceConfigurationToUpdate, CancellationToken cancellationToken)
{
if (unsupportedDeviceConfigurationToUpdate.AdditionalData != null)
{
if (unsupportedDeviceConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
unsupportedDeviceConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, unsupportedDeviceConfigurationToUpdate.GetType().Name)
});
}
}
if (unsupportedDeviceConfigurationToUpdate.AdditionalData != null)
{
if (unsupportedDeviceConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
unsupportedDeviceConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, unsupportedDeviceConfigurationToUpdate.GetType().Name)
});
}
}
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<UnsupportedDeviceConfiguration>(unsupportedDeviceConfigurationToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IUnsupportedDeviceConfigurationRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IUnsupportedDeviceConfigurationRequest Expand(Expression<Func<UnsupportedDeviceConfiguration, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IUnsupportedDeviceConfigurationRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IUnsupportedDeviceConfigurationRequest Select(Expression<Func<UnsupportedDeviceConfiguration, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="unsupportedDeviceConfigurationToInitialize">The <see cref="UnsupportedDeviceConfiguration"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(UnsupportedDeviceConfiguration unsupportedDeviceConfigurationToInitialize)
{
}
}
}
| 47.848101 | 200 | 0.652293 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/UnsupportedDeviceConfigurationRequest.cs | 11,340 | C# |
using System;
using System.Collections.Generic;
namespace Abp.Application.Services.Dto
{
/// <summary>
/// This class can be used to return a paged list from an <see cref="IApplicationService"/> method.
/// </summary>
/// <typeparam name="T">Type of the items in the <see cref="PagedResultDto{T}.Items"/> list</typeparam>
[Serializable]
public class PagedResultOutput<T> : PagedResultDto<T>, IOutputDto
{
/// <summary>
/// Creates a new <see cref="PagedResultOutput{T}"/> object.
/// </summary>
public PagedResultOutput()
{
}
/// <summary>
/// Creates a new <see cref="PagedResultOutput{T}"/> object.
/// </summary>
/// <param name="totalCount">Total count of Items</param>
/// <param name="items">List of items in current page</param>
public PagedResultOutput(int totalCount, IReadOnlyList<T> items)
: base(totalCount, items)
{
}
}
} | 31.0625 | 107 | 0.597586 | [
"MIT"
] | FlipGitBits/aspnetboilerplate | src/Abp/Application/Services/Dto/PagedResultOutput.cs | 994 | C# |
using System.Security.Claims;
namespace ASPNETCore2JwtAuthentication.Services;
public class JwtTokensData
{
public string AccessToken { get; set; }
public string RefreshToken { get; set; }
public string RefreshTokenSerial { get; set; }
public IEnumerable<Claim> Claims { get; set; }
} | 27.545455 | 50 | 0.735974 | [
"Apache-2.0"
] | samgharcheh/ASPNETCoreJwtAuthentication | src/ASPNETCore2JwtAuthentication.Services/JwtTokensData.cs | 305 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Security.Cryptography;
namespace SocketApp.ProtocolStack.Protocol
{
public class AESProtocolOptions
{
public CipherMode Mode = CipherMode.CBC;
public int KeySize = 128;
public int BlockSize = 128;
public int FeedbackSize = 128;
public PaddingMode Padding = PaddingMode.PKCS7; // only tested this padding
public byte[] Key;
public bool Enabled = false;
}
public class AESProtocol : IProtocol
{
public event NextLowLayerEventHandler NextLowLayerEvent;
public event NextHighLayerEventHandler NextHighLayerEvent;
// two ways to update a key
// first, by SetState()
// second, by DataContent (TODO)
private AESProtocolOptions _options;
private Aes _aesAlg = Aes.Create();
public void FromHighLayerToHere(DataContent dataContent)
{
if (_options.Enabled && dataContent.Data != null)
{
byte[] encrypted = Encrypt((byte[])dataContent.Data);
dataContent.Data = encrypted;
}
NextLowLayerEvent?.Invoke(dataContent);
}
public void FromLowLayerToHere(DataContent dataContent)
{
if (_options.Enabled && dataContent.Data != null)
{
try
{
byte[] decrypted;
decrypted = Decrypt((byte[])dataContent.Data);
dataContent.Data = decrypted;
}
catch (CryptographicException)
{
dataContent.IsAesError = true;
}
}
NextHighLayerEvent?.Invoke(dataContent);
}
public void SetState(AESProtocolOptions options)
{
_options = options;
if (options.Enabled)
{
// the order is important
// set Key and IV after setting their sizes
_aesAlg.Mode = _options.Mode;
_aesAlg.KeySize = _options.KeySize;
_aesAlg.BlockSize = _options.BlockSize;
_aesAlg.FeedbackSize = _options.FeedbackSize;
_aesAlg.Padding = _options.Padding;
_aesAlg.Key = _options.Key;
}
}
private byte[] Decrypt(byte[] crypto)
{
_aesAlg.IV = crypto.Take(_aesAlg.BlockSize / 8).ToArray();
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = _aesAlg.CreateDecryptor();
return PerformCryptography(crypto.Skip(_aesAlg.BlockSize / 8).ToArray(), decryptor);
}
private byte[] Encrypt(byte[] data)
{
_aesAlg.GenerateIV();
ICryptoTransform encryptor = _aesAlg.CreateEncryptor();
byte[] encryptedData = PerformCryptography(data, encryptor);
List<byte> iv_data = new List<byte>();
iv_data.AddRange(_aesAlg.IV);
iv_data.AddRange(encryptedData);
return iv_data.ToArray();
}
private byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
{
using (var ms = new MemoryStream())
using (var cryptoStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock(); // add padding when encryption
return ms.ToArray();
}
}
public void Dispose()
{
_aesAlg.Dispose();
}
}
}
| 33.410714 | 100 | 0.563068 | [
"MIT"
] | Banyc/SocketApp | src/SocketApp.ProtocolStack/Models/Protocol/Security/AESProtocol.cs | 3,742 | C# |
using System;
namespace Anf
{
public class ComicSourceContext
{
public ComicSourceContext(string source)
{
if (string.IsNullOrEmpty(source))
{
throw new ArgumentException($"“{nameof(source)}”不能是 Null 或为空。", nameof(source));
}
Source = source;
Uri.TryCreate(source, UriKind.RelativeOrAbsolute, out var uri);
Uri = uri;
}
public ComicSourceContext(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
Source = uri.OriginalString;
}
public string Source { get; }
public Uri Uri { get; }
}
}
| 23.3 | 96 | 0.539342 | [
"BSD-3-Clause"
] | Cricle/Anf | Platforms/Anf.Engine/ComicSourceContext.cs | 719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace OpenHardwareMonitor.Software.FanControl {
internal class SoftwareFanControlGroup : IGroup {
private List<IHardware> hardware = new List<IHardware>();
public SoftwareFanControlGroup(ISettings settings) {
hardware.Add(new SoftwareFanControl(settings));
}
public IReadOnlyList<IHardware> Hardware {
get {
return hardware.ToArray();
}
}
public void Close() { }
public string GetReport() => string.Empty;
}
}
| 25.12 | 61 | 0.719745 | [
"MPL-2.0"
] | YaF3li/openhardwaremonitor | OpenHardwareMonitorLib/Software/FanControl/SoftwareFanControlGroup.cs | 630 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace BloggingPlatformBackend.Migrations
{
public partial class Second : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK__Comment__BlogPos__5629CD9C",
table: "Comment");
migrationBuilder.DropForeignKey(
name: "FK__PostTags__BlogPo__52593CB8",
table: "PostTags");
migrationBuilder.DropForeignKey(
name: "FK__PostTags__TagID__534D60F1",
table: "PostTags");
migrationBuilder.DropIndex(
name: "UQ__PostTags__657CFA4D988AFF33",
table: "PostTags");
migrationBuilder.AlterColumn<string>(
name: "Body",
table: "BlogPost",
maxLength: 4000,
nullable: false,
oldClrType: typeof(string));
migrationBuilder.CreateIndex(
name: "UQ__Tag__BDE0FD1DF380243B",
table: "Tag",
column: "TagName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_PostTags_TagID",
table: "PostTags",
column: "TagID");
migrationBuilder.AddForeignKey(
name: "FK__Comment__BlogPos__5629CD9C",
table: "Comment",
column: "BlogPostID",
principalTable: "BlogPost",
principalColumn: "BlogPostID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK__PostTags__BlogPo__60A75C0F",
table: "PostTags",
column: "BlogPostID",
principalTable: "BlogPost",
principalColumn: "BlogPostID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK__PostTags__TagID__619B8048",
table: "PostTags",
column: "TagID",
principalTable: "Tag",
principalColumn: "TagID",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK__Comment__BlogPos__5629CD9C",
table: "Comment");
migrationBuilder.DropForeignKey(
name: "FK__PostTags__BlogPo__60A75C0F",
table: "PostTags");
migrationBuilder.DropForeignKey(
name: "FK__PostTags__TagID__619B8048",
table: "PostTags");
migrationBuilder.DropIndex(
name: "UQ__Tag__BDE0FD1DF380243B",
table: "Tag");
migrationBuilder.DropIndex(
name: "IX_PostTags_TagID",
table: "PostTags");
migrationBuilder.AlterColumn<string>(
name: "Body",
table: "BlogPost",
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 4000);
migrationBuilder.CreateIndex(
name: "UQ__PostTags__657CFA4D988AFF33",
table: "PostTags",
column: "TagID",
unique: true);
migrationBuilder.AddForeignKey(
name: "FK__Comment__BlogPos__5629CD9C",
table: "Comment",
column: "BlogPostID",
principalTable: "BlogPost",
principalColumn: "BlogPostID",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK__PostTags__BlogPo__52593CB8",
table: "PostTags",
column: "BlogPostID",
principalTable: "BlogPost",
principalColumn: "BlogPostID",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK__PostTags__TagID__534D60F1",
table: "PostTags",
column: "TagID",
principalTable: "Tag",
principalColumn: "TagID",
onDelete: ReferentialAction.Restrict);
}
}
}
| 34.263566 | 71 | 0.528959 | [
"MIT"
] | SmailG/BloggingPlatformWebAPI | BloggingPlatformBackend/Migrations/20180712193408_Second.cs | 4,422 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.Psi.Visualization.Summarizers
{
using System.Collections.Generic;
using Microsoft.Psi.Visualization.Data;
/// <summary>
/// Represents a range summarizer that performs interval-based data summarization over a series of decimal values.
/// </summary>
[Summarizer]
public class DecimalSeriesRangeSummarizer : Summarizer<Dictionary<string, decimal>, Dictionary<string, decimal>>
{
/// <summary>
/// Initializes a new instance of the <see cref="DecimalSeriesRangeSummarizer"/> class.
/// </summary>
public DecimalSeriesRangeSummarizer()
: base(NumericSeriesRangeSummarizer.SeriesSummarizer, NumericSeriesRangeSummarizer.SeriesCombiner)
{
}
}
}
| 35.625 | 118 | 0.701754 | [
"MIT"
] | CMU-TBD/psi | Sources/Visualization/Microsoft.Psi.Visualization.Windows/Summarizers/Numeric/DecimalSeriesRangeSummarizer.cs | 857 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MicroserviceTwo.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace MicroserviceTwo
{
public class Startup
{
public IConfiguration Configuration { get; }
/// <summary>
/// C'tor
/// </summary>
/// <param name="configuration"></param>
public Startup( IConfiguration configuration )
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices( IServiceCollection services )
{
services.AddControllers();
services.AddSingleton<IServiceBusSubscriber, ServiceBusSubscriber>();
services.AddTransient<IProcessor, MessageProcessor>();
services.AddTransient<IServiceBusSender, ServiceBusSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure( IApplicationBuilder app, IWebHostEnvironment env )
{
if ( env.IsDevelopment() )
{
app.UseDeveloperExceptionPage();
}
app.ApplicationServices.GetService<IServiceBusSubscriber>().RegisterMessageHandler();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints( endpoints =>
{
endpoints.MapControllers();
} );
}
}
}
| 30.095238 | 106 | 0.650316 | [
"MIT"
] | mirano-galijasevic/microservices3 | TestMicro3/Microservices/Microservice2/MicroserviceTwo/Startup.cs | 1,896 | C# |
using System;
using System.Globalization;
namespace Curso
{
class Program
{
static void Main(string[] args)
{
double x = 10.35784;
int y = 32;
string z = "Maria";
char w = 'F';
Console.Write("Olá mundo!");
Console.WriteLine("Bom dia!");
Console.WriteLine("Até mais!");
Console.WriteLine();
Console.WriteLine(x);
Console.WriteLine(x.ToString("F2"));
Console.WriteLine(x.ToString("F4"));
Console.WriteLine(x.ToString("F2", CultureInfo.InvariantCulture));
Console.WriteLine();
Console.WriteLine("RESULTADO = " + x);
Console.WriteLine("O valor do troco é " + x + " reais");
Console.WriteLine("O valor do troco é " + x.ToString("F2") + " reais");
Console.WriteLine();
Console.WriteLine("A paciente " + z + " tem " + y + " anos e seu sexo é: " + w);
Console.ReadLine();
}
}
}
| 33.387097 | 92 | 0.510145 | [
"MIT"
] | GustavoBaco/ws-vs2022 | Secao15_SaidaDeDados/Secao15_SaidaDeDados/Program.cs | 1,042 | C# |
#region Copyright (C) 2020 Kevin (OSS开源系列) 公众号:osscore
/***************************************************************************
* 文件功能描述:阿里云的短信发送统一适配
*
* 创建人: Kevin
* 创建人Email:1985088337@qq.com
* 创建日期: 2020-08-14
*
*****************************************************************************/
#endregion
using System.Threading.Tasks;
using OSS.Adapter.SMS.Interface;
using OSS.Adapter.SMS.Interface.Mos;
using OSS.Clients.SMS.Ali;
using OSS.Clients.SMS.Ali.Reqs;
using OSS.Common.BasicImpls;
using OSS.Common.Resp;
namespace OSS.Adapter.SMS.Ali
{
/// <summary>
/// 阿里短信发送适配
/// </summary>
public class AliSmsAdapter : AliSmsClient, ISmsAdapter
{
/// <inheritdoc />
public AliSmsAdapter() : base(null)
{
}
/// <inheritdoc />
public AliSmsAdapter(IMetaProvider<AliSmsConfig> configProvider)
: base(configProvider)
{
}
/// <summary>
/// 发送方法
/// </summary>
/// <param name="sendMsg"></param>
/// <returns></returns>
public async Task<SendSmsResp> Send(SendSmsReq sendMsg)
{
return (await base.Send(sendMsg.ToAliSmsReq())).ToSmsResp();
}
}
public static class SendSmsReqMaps
{
public static SendAliSmsReq ToAliSmsReq(this SendSmsReq req)
{
var aliReq = new SendAliSmsReq
{
PhoneNums = req.PhoneNums,
body_paras = req.body_paras,
sign_name = req.sign_name,
template_code = req.template_code
};
return aliReq;
}
public static SendSmsResp ToSmsResp(this SendAliSmsResp aResp)
{
var resp=new SendSmsResp();
resp.WithResp(aResp);
resp.plat_msg_id = aResp.BizId;
return resp;
}
}
}
| 23.888889 | 78 | 0.510594 | [
"Apache-2.0"
] | KevinWG/OSS.Adapers | SMS/OSS.Adapter.SMS.Ali/AliSmsAdapter.cs | 2,049 | C# |
using Microsoft.AspNetCore.Components;
namespace Functional.Blazor.Components
{
/// <summary>
/// Displays different content based on whether the Option has some value or is empty.
/// </summary>
/// <typeparam name="TValue">Type of the Option's value</typeparam>
public partial class OptionMatch<TValue> : ComponentBase
{
/// <summary>
/// An Option<T>
/// </summary>
[Parameter] public Option<TValue> Option { get; set; }
/// <summary>
/// Render fragement of content to display if the Option contains some value. Context is set to the option's value.
/// </summary>
[Parameter] public RenderFragment<TValue> Some { get; set; }
/// <summary>
/// Render fragement of content to display if the Option is empty.
/// </summary>
[Parameter] public RenderFragment None { get; set; }
}
}
| 32.88 | 117 | 0.689781 | [
"MIT"
] | Justin-Cooney/Functional.Blazor | Functional.Blazor.Components/OptionMatch.razor.cs | 824 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tests")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d84c499e-08ec-4286-80fb-4a2d207e9b06")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.378378 | 84 | 0.742589 | [
"MIT"
] | Haacked/Rothko | Tests/Properties/AssemblyInfo.cs | 1,386 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using ChatLe.Repository.Identity.MySql;
namespace ChatLe.Repository.Identity.MySql.Migrations
{
[DbContext(typeof(ChatLeIdentityDbContext))]
partial class ChatLeIdentityDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.1");
modelBuilder.Entity("ChatLe.Models.Attendee<string>", b =>
{
b.Property<string>("ConversationId");
b.Property<string>("UserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<bool>("IsConnected");
b.HasKey("ConversationId", "UserId");
b.HasIndex("ConversationId");
b.ToTable("Attendees");
b.HasDiscriminator<string>("Discriminator").HasValue("Attendee<string>");
});
modelBuilder.Entity("ChatLe.Models.ChatLeUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<DateTime>("LastLoginDate");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("ChatLe.Models.Conversation<string>", b =>
{
b.Property<string>("Id");
b.Property<string>("Discriminator")
.IsRequired();
b.HasKey("Id");
b.ToTable("Conversations");
b.HasDiscriminator<string>("Discriminator").HasValue("Conversation<string>");
});
modelBuilder.Entity("ChatLe.Models.Message<string>", b =>
{
b.Property<string>("Id");
b.Property<string>("ConversationId");
b.Property<DateTime>("Date");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Text");
b.Property<string>("UserId");
b.HasKey("Id");
b.HasIndex("ConversationId");
b.ToTable("Messages");
b.HasDiscriminator<string>("Discriminator").HasValue("Message<string>");
});
modelBuilder.Entity("ChatLe.Models.NotificationConnection<string>", b =>
{
b.Property<string>("ConnectionId");
b.Property<string>("NotificationType");
b.Property<DateTime>("ConnectionDate");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("UserId");
b.HasKey("ConnectionId", "NotificationType");
b.ToTable("NotificationConnections");
b.HasDiscriminator<string>("Discriminator").HasValue("NotificationConnection<string>");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("ChatLe.Models.Attendee", b =>
{
b.HasBaseType("ChatLe.Models.Attendee<string>");
b.ToTable("Attendee");
b.HasDiscriminator().HasValue("Attendee");
});
modelBuilder.Entity("ChatLe.Models.Conversation", b =>
{
b.HasBaseType("ChatLe.Models.Conversation<string>");
b.ToTable("Conversation");
b.HasDiscriminator().HasValue("Conversation");
});
modelBuilder.Entity("ChatLe.Models.Message", b =>
{
b.HasBaseType("ChatLe.Models.Message<string>");
b.ToTable("Message");
b.HasDiscriminator().HasValue("Message");
});
modelBuilder.Entity("ChatLe.Models.NotificationConnection", b =>
{
b.HasBaseType("ChatLe.Models.NotificationConnection<string>");
b.ToTable("NotificationConnection");
b.HasDiscriminator().HasValue("NotificationConnection");
});
modelBuilder.Entity("ChatLe.Models.Attendee<string>", b =>
{
b.HasOne("ChatLe.Models.Conversation<string>", "Conversation")
.WithMany("Attendees")
.HasForeignKey("ConversationId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("ChatLe.Models.Message<string>", b =>
{
b.HasOne("ChatLe.Models.Conversation<string>", "Conversation")
.WithMany("Messages")
.HasForeignKey("ConversationId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("ChatLe.Models.ChatLeUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("ChatLe.Models.ChatLeUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("ChatLe.Models.ChatLeUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 33.310345 | 115 | 0.480072 | [
"Apache-2.0"
] | aguacongas/chatle | src/ChatLe.Repository.Identity.MySql/Migrations/ChatLeIdentityDbContextModelSnapshot.cs | 11,594 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System.Linq;
using Hl7.Fhir.Model;
using Microsoft.Health.Fhir.Tests.Common.FixtureParameters;
using Xunit;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.Health.Fhir.Tests.E2E.Rest.Search
{
[HttpIntegrationFixtureArgumentSets(DataStore.CosmosDb, Format.Json)]
public class ReferenceSearchTests : SearchTestsBase<ReferenceSearchTestFixture>
{
public ReferenceSearchTests(ReferenceSearchTestFixture fixture)
: base(fixture)
{
}
[Theory]
[InlineData("Organization/123", 0)]
[InlineData("Organization/1")]
[InlineData("organization/123")]
public async Task GivenAReferenceSearchParam_WhenSearched_ThenCorrectBundleShouldBeReturned(string valueToSearch, params int[] matchIndices)
{
string query = $"organization={valueToSearch}";
Bundle bundle = await Client.SearchAsync(ResourceType.Patient, query);
Patient[] expected = matchIndices.Select(i => Fixture.Patients[i]).ToArray();
ValidateBundle(bundle, expected);
}
}
}
| 38.368421 | 148 | 0.605624 | [
"MIT"
] | javier-alvarez/fhir-server | test/Microsoft.Health.Fhir.Tests.E2E/Rest/Search/ReferenceSearchTests.cs | 1,460 | C# |
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3
#define UNITY_LE_4_3
#endif
#if !UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3
#define UNITY_4
#endif
using UnityEngine;
using UnityEditor;
using System.Collections;
using Pathfinding;
[CustomEditor(typeof(SimpleSmoothModifier))]
public class SmoothModifierEditor : Editor {
public override void OnInspectorGUI () {
#if UNITY_LE_4_3
EditorGUI.indentLevel = 1;
#else
EditorGUI.indentLevel = 0;
#endif
SimpleSmoothModifier ob = target as SimpleSmoothModifier;
ob.smoothType = (SimpleSmoothModifier.SmoothType)EditorGUILayout.EnumPopup (new GUIContent ("Smooth Type"),ob.smoothType);
#if UNITY_LE_4_3
EditorGUIUtility.LookLikeInspector ();
#else
Undo.RecordObject (ob, "changed settings on Simple Smooth Modifier");
#endif
if (ob.smoothType == SimpleSmoothModifier.SmoothType.Simple) {
ob.uniformLength = EditorGUILayout.Toggle (new GUIContent ("Uniform Segment Length","Toggle to divide all lines in equal length segments"),ob.uniformLength);
if (ob.uniformLength) {
ob.maxSegmentLength = EditorGUILayout.FloatField (new GUIContent ("Max Segment Length","The length of each segment in the smoothed path. A high value yields rough paths and low value yields very smooth paths, but is slower"),ob.maxSegmentLength);
ob.maxSegmentLength = ob.maxSegmentLength < 0 ? 0 : ob.maxSegmentLength;
} else {
ob.subdivisions = EditorGUILayout.IntField (new GUIContent ("Subdivisions","The number of times to subdivide (divide in half) the path segments. [0...inf] (recommended [1...10])"),ob.subdivisions);
if (ob.subdivisions < 0) ob.subdivisions = 0;
}
ob.iterations = EditorGUILayout.IntField (new GUIContent ("Iterations","Number of times to apply smoothing"),ob.iterations);
ob.iterations = ob.iterations < 0 ? 0 : ob.iterations;
ob.strength = EditorGUILayout.Slider (new GUIContent ("Strength","Determines how much smoothing to apply in each smooth iteration. 0.5 usually produces the nicest looking curves"),ob.strength,0.0F,1.0F);
} else if (ob.smoothType == SimpleSmoothModifier.SmoothType.OffsetSimple) {
ob.iterations = EditorGUILayout.IntField (new GUIContent ("Iterations","Number of times to apply smoothing"),ob.iterations);
ob.iterations = ob.iterations < 0 ? 0 : ob.iterations;
ob.iterations = ob.iterations > 12 ? 12 : ob.iterations;
ob.offset = EditorGUILayout.FloatField (new GUIContent ("Offset","Offset to apply in each smoothing iteration"),ob.offset);
if (ob.offset < 0) ob.offset = 0;
} else if (ob.smoothType == SimpleSmoothModifier.SmoothType.Bezier) {
ob.subdivisions = EditorGUILayout.IntField (new GUIContent ("Subdivisions","The number of times to subdivide (divide in half) the path segments. [0...inf] (recommended [1...10])"),ob.subdivisions);
if (ob.subdivisions < 0) ob.subdivisions = 0;
ob.bezierTangentLength = EditorGUILayout.FloatField (new GUIContent ("Tangent Length","Tangent length factor"),ob.bezierTangentLength);
} else if (ob.smoothType == SimpleSmoothModifier.SmoothType.CurvedNonuniform) {
ob.maxSegmentLength = EditorGUILayout.FloatField (new GUIContent ("Max Segment Length","The length of each segment in the smoothed path. A high value yields rough paths and low value yields very smooth paths, but is slower"),ob.maxSegmentLength);
ob.factor = EditorGUILayout.FloatField (new GUIContent ("Roundness Factor","How much to smooth the path. A higher value will give a smoother path, but might take the character far off the optimal path."),ob.factor);
ob.maxSegmentLength = ob.maxSegmentLength < 0 ? 0 : ob.maxSegmentLength;
} else {
DrawDefaultInspector ();
}
//GUILayout.Space (5);
Color preCol = GUI.color;
GUI.color *= new Color (1,1,1,0.5F);
ob.Priority = EditorGUILayout.IntField (new GUIContent ("Priority","Higher priority modifiers are executed first\nAdjust this in Seeker-->Modifier Priorities"),ob.Priority);
GUI.color = preCol;
if ( ob.gameObject.GetComponent<Seeker> () == null ) {
EditorGUILayout.HelpBox ("No seeker found, modifiers are usually used together with a Seeker component", MessageType.Warning );
}
}
} | 48.436782 | 250 | 0.740389 | [
"Apache-2.0"
] | rapito/unity-basics-2d | Assets/AstarPathfindingEditor/Editor/ModifierEditors/SmoothModifierEditor.cs | 4,214 | C# |
/****************************************************************
Copyright 2021 Infosys Ltd.
Use of this source code is governed by Apache License Version 2.0 that can be found in the LICENSE file or at
http://www.apache.org/licenses/
***************************************************************/
using IMSWorkBench.Infrastructure.Interface;
using Infosys.ATR.ProcessRecorder.Views;
using Microsoft.Practices.CompositeUI.WinForms;
using IMSWorkBench.Infrastructure.Library.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.CompositeUI.EventBroker;
using System.Windows.Forms;
namespace Infosys.ATR.ProcessRecorder
{
public class ProcessRecorderWorkItem : WorkItemController
{
[EventPublication(Constants.EventTopicNames.TabHoverSet, PublicationScope.Global)]
public event EventHandler<EventArgs<String>> TabHoverSet;
[EventPublication(Constants.EventTopicNames.DisableGeneratePlaybackScript, PublicationScope.Global)]
public event EventHandler DisableGeneratePlaybackScript;
internal void exit_Click(object sender, EventArgs e)
{
closeTab_Click(sender, e);
}
internal void closeTab_Click(object sender, EventArgs e)
{
var recoDe = GetActiveTab();
IClose smartPart = recoDe as IClose;
bool close = smartPart.Close();
if (close)
this.WorkItem.SmartParts.Remove(smartPart);
DisableGeneratePlaybackScript(this, new EventArgs());
}
object GetActiveTab()
{
return this.WorkItem.Workspaces[Constants.WorkspaceNames.TabWorkSpace].ActiveSmartPart;
}
void CloseIfExists<T>(string smartPart) where T : IClose
{
var sp = this.WorkItem.SmartParts.Get<T>(smartPart);
if (sp != null)
{
sp.Close();
this.WorkItem.SmartParts.Remove(sp);
}
}
private object GetCurrentTab()
{
return this.WorkItem.Workspaces[Constants.WorkspaceNames.TabWorkSpace].ActiveSmartPart;
}
internal void RecordingView(object sender, EventArgs e)
{
AddPlaybackView("RecordingView");
}
private void AddPlaybackView(string smartpart)
{
CloseIfExists<RecordingView>("RecordingView");
var sp = this.WorkItem.SmartParts.Get<RecordingView>(smartpart);
if (sp == null)
{
var recoView = this.WorkItem.SmartParts.AddNew<RecordingView>(smartpart);
recoView.PopulateView();
if (recoView.UseCases != null)
{
WindowSmartPartInfo sp1 = new WindowSmartPartInfo();
sp1.MaximizeBox = false;
sp1.MinimizeBox = false;
sp1.Title = "Recording View";
this.WorkItem.RootWorkItem.Workspaces[Constants.WorkspaceNames.TabWorkSpace].Show(recoView, sp1);
Logger.Log("Recording", "RecordingView", "Recording View Launched");
}
else
MessageBox.Show("No Record Exists ", "IAP - Recording View", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
[EventSubscription(Constants.EventTopicNames.TabHover, ThreadOption.UserInterface)]
public void TabHover_Handler(object sender, EventArgs e)
{
var ide = GetCurrentTab();
if (ide.GetType() == typeof(Views.RecordingView))
{
var p = ide as Views.RecordingView;
if (TabHoverSet != null)
TabHoverSet(this, new EventArgs<string>("Recording View"));
}
}
public void GenerateScript_Handler(object sender, EventArgs e)
{
var ide = GetCurrentTab();
if (ide.GetType() == typeof(Views.RecordingView))
{
var p = ide as Views.RecordingView;
p.btnGenPlaybackScript_Click(sender, e);
}
}
public void ExecutePlyabackScript_Handler(object sender, EventArgs e)
{
var ide = GetCurrentTab();
if (ide.GetType() == typeof(Views.RecordingView))
{
var p = ide as Views.RecordingView;
p.RunPlaybackScript_Click(sender, e);
}
}
}
}
| 36.133858 | 147 | 0.583134 | [
"Apache-2.0"
] | Infosys/Script-Control-Center | ScriptDevelopmentTool/Infosys.ATR.ProcessRecorder/ProcessRecorderWorkItem.cs | 4,591 | C# |
using System;
using EasyAbp.Cms.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
namespace EasyAbp.Cms.Articles
{
public class ArticleRepository : EfCoreRepository<CmsDbContext, Article, Guid>, IArticleRepository
{
public ArticleRepository(IDbContextProvider<CmsDbContext> dbContextProvider) : base(dbContextProvider)
{
}
}
} | 30.428571 | 110 | 0.769953 | [
"MIT"
] | EasyAbp/Cms | src/EasyAbp.Cms.EntityFrameworkCore/EasyAbp/Cms/Articles/ArticleRepository.cs | 426 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("GTM.GHIElectronics.ReflectorR3")]
[assembly: AssemblyDescription("Driver for ReflectorR3 module made by GHI Electronics for Microsoft .NET Gadgeteer")]
[assembly: AssemblyProduct("ReflectorR3")] | 46.285714 | 117 | 0.82716 | [
"Apache-2.0"
] | ghi-electronics/NETMF-Gadgeteer | Modules/GHIElectronics/ReflectorR3/ReflectorR3_42/AssemblyInfo.cs | 326 | C# |
using MyDAL.Core.Bases;
using MyDAL.Core.Common;
using MyDAL.Core.Enums;
using MyDAL.Core.Expressions;
using MyDAL.Core.Models.Cache;
using MyDAL.Core.Models.ExpPara;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace MyDAL.Core
{
internal sealed class XExpression
{
private static CompareXEnum GetCompareType(ExpressionType nodeType, bool isR)
{
var option = CompareXEnum.None;
if (nodeType == ExpressionType.Equal)
{
option = !isR ? CompareXEnum.Equal : CompareXEnum.Equal;
}
else if (nodeType == ExpressionType.NotEqual)
{
option = !isR ? CompareXEnum.NotEqual : CompareXEnum.NotEqual;
}
else if (nodeType == ExpressionType.LessThan)
{
option = !isR ? CompareXEnum.LessThan : CompareXEnum.GreaterThan;
}
else if (nodeType == ExpressionType.LessThanOrEqual)
{
option = !isR ? CompareXEnum.LessThanOrEqual : CompareXEnum.GreaterThanOrEqual;
}
else if (nodeType == ExpressionType.GreaterThan)
{
option = !isR ? CompareXEnum.GreaterThan : CompareXEnum.LessThan;
}
else if (nodeType == ExpressionType.GreaterThanOrEqual)
{
option = !isR ? CompareXEnum.GreaterThanOrEqual : CompareXEnum.LessThanOrEqual;
}
return option;
}
private static ActionEnum GetGroupAction(ExpressionType nodeType)
{
if (nodeType == ExpressionType.AndAlso)
{
return ActionEnum.And;
}
else if (nodeType == ExpressionType.OrElse)
{
return ActionEnum.Or;
}
return ActionEnum.None;
}
/********************************************************************************************************************/
private Context DC { get; set; }
private XExpression() { }
internal XExpression(Context dc)
{
DC = dc;
}
/********************************************************************************************************************/
private bool IsBinaryExpr(ExpressionType type)
{
if (type == ExpressionType.Equal
|| type == ExpressionType.NotEqual
|| type == ExpressionType.LessThan
|| type == ExpressionType.LessThanOrEqual
|| type == ExpressionType.GreaterThan
|| type == ExpressionType.GreaterThanOrEqual)
{
return true;
}
return false;
}
private bool IsMultiExpr(ExpressionType type)
{
if (type == ExpressionType.AndAlso
|| type == ExpressionType.OrElse)
{
return true;
}
return false;
}
private bool IsNullableExpr(Expression body)
{
if (body.NodeType == ExpressionType.MemberAccess)
{
var exStr = body.ToString();
if (exStr.EndsWith(".Value")
&& exStr.LastIndexOf('.') > exStr.IndexOf('.'))
{
return true;
}
}
return false;
}
/********************************************************************************************************************/
private BinExprInfo HandBinExpr(List<string> list, BinaryExpression binExpr)
{
var binLeft = binExpr.Left;
var binRight = binExpr.Right;
var binNode = binExpr.NodeType;
//
var leftStr = binLeft.ToString();
var rightStr = binRight.ToString();
if (list.All(it => !leftStr.Contains($"{it}."))
&& list.All(it => !rightStr.Contains($"{it}.")))
{
throw XConfig.EC.Exception(XConfig.EC._049, $"查询条件中使用的[[表别名变量]]不在列表[[{string.Join(",", list)}]]中!");
}
//
if (list.Any(it => leftStr.StartsWith($"{it}.", StringComparison.Ordinal))
|| (list.Any(it => leftStr.Contains($"{it}.")) && leftStr.StartsWith($"Convert(", StringComparison.Ordinal))
|| (list.Any(it => leftStr.Contains($").{it}.")) && leftStr.StartsWith($"value(", StringComparison.Ordinal))
|| (list.Any(it => leftStr.Contains($").{it}.")) && leftStr.StartsWith($"Convert(value(", StringComparison.Ordinal)))
{
return new BinExprInfo
{
Left = binLeft,
Right = binRight,
Node = binNode,
Compare = GetCompareType(binNode, false)
};
}
else
{
return new BinExprInfo
{
Left = binRight,
Right = binLeft,
Node = binNode,
Compare = GetCompareType(binNode, true)
};
}
}
private DicParam HandBin(BinaryExpression binExpr, List<string> pres)
{
var bin = HandBinExpr(pres, binExpr);
if ((bin.Node == ExpressionType.Equal || bin.Node == ExpressionType.NotEqual)
&& bin.Right.NodeType == ExpressionType.Constant
&& (bin.Right as ConstantExpression).Value == null)
{
var cp = GetKey(bin.Left, FuncEnum.None, CompareXEnum.None);
if (bin.Node == ExpressionType.Equal)
{
DC.Option = OptionEnum.IsNull;
}
else
{
DC.Option = OptionEnum.IsNotNull;
}
return DC.DPH.IsNullDic(cp);
}
else
{
var left = default(Expression);
if (IsNullableExpr(bin.Left))
{
left = (bin.Left as MemberExpression).Expression;
}
else
{
left = bin.Left;
}
var leftStr = left.ToString();
var length = DC.CFH.IsLengthFunc(leftStr);
var tp = length ? new TrimParam { Flag = false } : DC.CFH.IsTrimFunc(leftStr);
var toString = tp.Flag ? false : DC.CFH.IsToStringFunc(leftStr);
if (length)
{
var cp = GetKey(left, FuncEnum.CharLength, CompareXEnum.None);
var val = DC.VH.ValueProcess(bin.Right, cp.ValType);
DC.Option = OptionEnum.Function;
DC.Func = FuncEnum.CharLength;
DC.Compare = bin.Compare;
return DC.DPH.CharLengthDic(cp, val);
}
else if (tp.Flag)
{
var cp = GetKey(left, tp.Trim, CompareXEnum.None);
var val = DC.VH.ValueProcess(bin.Right, cp.ValType);
DC.Option = OptionEnum.Function;
DC.Func = tp.Trim;
DC.Compare = bin.Compare;
return DC.DPH.TrimDic(cp, val);
}
else if (toString)
{
return new CsToStringExpression(DC).WhereFuncToString(left, bin);
}
else
{
var cp = GetKey(left, FuncEnum.None, CompareXEnum.None);
var val = DC.VH.ValueProcess(bin.Right, cp.ValType);
DC.Option = OptionEnum.Compare;
DC.Func = FuncEnum.None;
DC.Compare = bin.Compare;
return DC.DPH.CompareDic(cp, val);
}
}
}
/********************************************************************************************************************/
private DicParam StringLike(MethodCallExpression mcExpr, StringLikeEnum type)
{
if (mcExpr.Object == null)
{
return null;
}
else
{
var objExpr = mcExpr.Object;
var objNodeType = mcExpr.Object.NodeType;
if (objNodeType == ExpressionType.MemberAccess)
{
var memO = objExpr as MemberExpression;
var memType = objExpr.Type;
if (memType == typeof(string))
{
var cp = GetKey(memO, FuncEnum.None, CompareXEnum.None);
var valExpr = mcExpr.Arguments[0];
var val = DC.VH.ValueProcess(valExpr, cp.ValType);
val = ValueInfo.LikeVI(val, type, DC);
DC.Option = OptionEnum.Compare;
DC.Compare = CompareXEnum.Like;
DC.Func = FuncEnum.None;
return DC.DPH.LikeDic(cp, val);
}
}
}
return null;
}
private DicParam CollectionIn(ExpressionType nodeType, Expression keyExpr, Expression valExpr)
{
if (nodeType == ExpressionType.MemberAccess)
{
var cp = GetKey(keyExpr, FuncEnum.None, CompareXEnum.In);
var val = DC.VH.ValueProcess(valExpr, cp.ValType);
DC.Option = OptionEnum.Compare;
DC.Func = FuncEnum.None; // FuncEnum.In;
DC.Compare = CompareXEnum.In; // CompareXEnum.None;
return DC.DPH.InDic(cp, val);
}
else if (nodeType == ExpressionType.NewArrayInit)
{
var naExpr = valExpr as NewArrayExpression;
var cp = GetKey(keyExpr, FuncEnum.None, CompareXEnum.In);
var vals = new List<ValueInfo>();
foreach (var exp in naExpr.Expressions)
{
vals.Add(DC.VH.ValueProcess(exp, cp.ValType));
}
var val = new ValueInfo
{
Val = string.Join(",", vals.Select(it => it.Val)),
ValStr = string.Empty
};
DC.Option = OptionEnum.Compare;
DC.Func = FuncEnum.None; // FuncEnum.In;
DC.Compare = CompareXEnum.In; // CompareXEnum.None;
return DC.DPH.InDic(cp, val);
}
else if (nodeType == ExpressionType.ListInit)
{
var liExpr = valExpr as ListInitExpression;
var cp = GetKey(keyExpr, FuncEnum.None, CompareXEnum.In);
var vals = new List<ValueInfo>();
foreach (var ini in liExpr.Initializers)
{
vals.Add(DC.VH.ValueProcess(ini.Arguments[0], cp.ValType));
}
var val = new ValueInfo
{
Val = string.Join(",", vals.Select(it => it.Val)),
ValStr = string.Empty
};
DC.Option = OptionEnum.Compare;
DC.Func = FuncEnum.None; // FuncEnum.In;
DC.Compare = CompareXEnum.In; // CompareXEnum.None;
return DC.DPH.InDic(cp, val);
}
else if (nodeType == ExpressionType.MemberInit)
{
var expr = valExpr as MemberInitExpression;
if (expr.NewExpression.Arguments.Count == 0)
{
throw XConfig.EC.Exception(XConfig.EC._050, $"【{keyExpr}】 中 集合为空!!!");
}
else
{
throw XConfig.EC.Exception(XConfig.EC._019, nodeType.ToString());
}
}
else
{
throw XConfig.EC.Exception(XConfig.EC._020, nodeType.ToString());
}
}
private DicParam BoolDefaultCondition(ColumnParam cp)
{
if (cp.ValType == XConfig.CSTC.Bool
|| cp.ValType == XConfig.CSTC.BoolNull)
{
DC.Option = OptionEnum.Compare;
DC.Compare = CompareXEnum.Equal;
return DC.DPH.CompareDic(cp, new ValueInfo
{
Val = true.ToString(),
ValStr = string.Empty
});
}
return null;
}
/********************************************************************************************************************/
private DicParam NotHandle(Expression body, ParameterExpression firstParam)
{
var ue = body as UnaryExpression;
var result = BodyProcess(ue.Operand, firstParam);
if (result.Compare == CompareXEnum.Like)
{
result.Compare = CompareXEnum.NotLike;
}
else if (result.Compare == CompareXEnum.In)
{
result.Compare = CompareXEnum.NotIn;
}
else if (result.Compare == CompareXEnum.Equal)
{
result.Compare = CompareXEnum.NotEqual;
}
else if (result.Compare == CompareXEnum.NotEqual)
{
result.Compare = CompareXEnum.Equal;
}
else if (result.Compare == CompareXEnum.LessThan)
{
result.Compare = CompareXEnum.GreaterThanOrEqual;
}
else if (result.Compare == CompareXEnum.LessThanOrEqual)
{
result.Compare = CompareXEnum.GreaterThan;
}
else if (result.Compare == CompareXEnum.GreaterThan)
{
result.Compare = CompareXEnum.LessThanOrEqual;
}
else if (result.Compare == CompareXEnum.GreaterThanOrEqual)
{
result.Compare = CompareXEnum.LessThan;
}
else if (result.Option == OptionEnum.IsNull)
{
result.Option = OptionEnum.IsNotNull;
}
else if (result.Option == OptionEnum.IsNotNull)
{
result.Option = OptionEnum.IsNull;
}
else
{
throw XConfig.EC.Exception(XConfig.EC._027, body.ToString());
}
return result;
}
private DicParam CallHandle(MethodCallExpression mcExpr)
{
var clp = DC.CFH.IsContainsLikeFunc(mcExpr);
var cip = clp.Flag ? new ContainsInParam { Flag = false } : DC.CFH.IsContainsInFunc(mcExpr);
var tsp = cip.Flag || clp.Flag ? new ToStringParam { Flag = false } : DC.CFH.IsToStringFunc(mcExpr);
//
if (clp.Flag)
{
if (clp.Like == StringLikeEnum.Contains
|| clp.Like == StringLikeEnum.StartsWith
|| clp.Like == StringLikeEnum.EndsWith)
{
return StringLike(mcExpr, clp.Like);
}
}
else if (cip.Flag)
{
if (cip.Type == ExpressionType.MemberAccess
|| cip.Type == ExpressionType.NewArrayInit
|| cip.Type == ExpressionType.ListInit
|| cip.Type == ExpressionType.MemberInit)
{
return CollectionIn(cip.Type, cip.Key, cip.Val);
}
}
else if (tsp.Flag)
{
return new CsToStringExpression(DC).SelectFuncToString(mcExpr);
}
throw XConfig.EC.Exception(XConfig.EC._046, $"出现异常 -- [[{mcExpr.ToString()}]] 不能解析!!!");
}
private DicParam ConstantHandle(ConstantExpression cExpr, Type valType)
{
var val = DC.VH.ValueProcess(cExpr, valType);
if (cExpr.Type == typeof(bool))
{
DC.Option = OptionEnum.OneEqualOne;
DC.Compare = CompareXEnum.None;
return DC.DPH.OneEqualOneDic(val, valType);
}
return null;
}
internal DicParam MemberAccessHandle(MemberExpression memExpr)
{
// 原
// query where
// join where
if (DC.IsSingleTableOption()
|| DC.Crud == CrudEnum.None)
{
var cp = GetKey(memExpr, FuncEnum.None, CompareXEnum.None);
if (string.IsNullOrWhiteSpace(cp.Key))
{
throw XConfig.EC.Exception(XConfig.EC._047, "无法解析 列名 !!!");
}
if (DC.Action == ActionEnum.Select)
{
return DC.DPH.SelectColumnDic(new List<DicParam> { DC.DPH.ColumnDic(cp) });
}
else if (DC.Action == ActionEnum.Where)
{
var dp = BoolDefaultCondition(cp);
if (dp != null)
{
return dp;
}
else
{
throw XConfig.EC.Exception(XConfig.EC._040, memExpr.ToString());
}
}
else
{
return DC.DPH.ColumnDic(cp);
}
}
else if (DC.Crud == CrudEnum.Join)
{
if (DC.Action == ActionEnum.Where)
{
var cp = GetKey(memExpr, FuncEnum.None, CompareXEnum.None);
var dp = BoolDefaultCondition(cp);
if (dp != null)
{
return dp;
}
else
{
throw XConfig.EC.Exception(XConfig.EC._039, memExpr.ToString());
}
}
else
{
if (memExpr.Expression.NodeType == ExpressionType.Constant)
{
var alias = memExpr.Member.Name;
return DC.DPH.TableDic(memExpr.Type, alias);
}
else if (memExpr.Expression.NodeType == ExpressionType.MemberAccess)
{
var leftStr = memExpr.ToString();
if (DC.CFH.IsLengthFunc(leftStr))
{
var cp = GetKey(memExpr, FuncEnum.CharLength, CompareXEnum.None);
DC.Func = FuncEnum.CharLength;
DC.Compare = CompareXEnum.None;
return DC.DPH.CharLengthDic(cp, null);
}
else
{
var exp2 = memExpr.Expression as MemberExpression;
var alias = exp2.Member.Name;
var field = memExpr.Member.Name;
DC.Option = OptionEnum.Column;
if (DC.Action == ActionEnum.Select)
{
return DC.DPH.SelectColumnDic(new List<DicParam> { DC.DPH.JoinColumnDic(exp2.Type, field, alias, field) });
}
else
{
return DC.DPH.JoinColumnDic(exp2.Type, field, alias, field);
}
}
}
else
{
throw XConfig.EC.Exception(XConfig.EC._021, $"{memExpr.Expression.NodeType} - {memExpr.ToString()}");
}
}
}
else
{
throw XConfig.EC.Exception(XConfig.EC._048, $"未知的操作 -- [[{DC.Crud}]] !!!");
}
}
private DicParam NewHandle(Expression body)
{
var list = new List<DicParam>();
var nExpr = body as NewExpression;
var args = nExpr.Arguments;
var mems = nExpr.Members;
for (var i = 0; i < args.Count; i++)
{
var cp = GetKey(args[i], FuncEnum.None, CompareXEnum.None);
var colAlias = mems[i].Name;
DC.Option = OptionEnum.None;
DC.Compare = CompareXEnum.None;
list.Add(DC.DPH.SelectMemberInitDic(cp, colAlias));
}
return DC.DPH.SelectColumnDic(list);
}
private DicParam BinaryHandle(Expression body, ParameterExpression firstParam)
{
var result = default(DicParam);
if (DC.IsSingleTableOption())
{
var binExpr = body as BinaryExpression;
var pres = new List<string>
{
firstParam.Name
};
result = HandBin(binExpr, pres);
}
else if (DC.Crud == CrudEnum.Join)
{
var binExpr = body as BinaryExpression;
if (DC.Action == ActionEnum.On)
{
result = HandOnBinary(binExpr);
}
else if (DC.Action == ActionEnum.Where
|| DC.Action == ActionEnum.And
|| DC.Action == ActionEnum.Or)
{
var pres = DC.Parameters.Select(it => it.TbAlias).ToList();
result = HandBin(binExpr, pres);
}
else
{
throw XConfig.EC.Exception(XConfig.EC._029, DC.Action.ToString());
}
}
else
{
throw XConfig.EC.Exception(XConfig.EC._030, DC.Crud.ToString());
}
return result;
}
private DicParam MultiHandle(Expression body, ParameterExpression firstParam, ExpressionType nodeType)
{
var result = DC.DPH.GroupDic(GetGroupAction(nodeType));
var binExpr = body as BinaryExpression;
var left = binExpr.Left;
result.Group.Add(BodyProcess(left, firstParam));
var right = binExpr.Right;
result.Group.Add(BodyProcess(right, firstParam));
return result;
}
/********************************************************************************************************************/
private List<DicParam> HandSelectMemberInit(MemberInitExpression miExpr)
{
var result = new List<DicParam>();
foreach (var mb in miExpr.Bindings)
{
var mbEx = mb as MemberAssignment;
//var maMem = mbEx.Expression as MemberExpression;
var expStr = mbEx.Expression.ToString();
var cp = default(ColumnParam);
if (DC.CFH.IsToStringFunc(expStr))
{
//cp=
}
else
{
cp = GetKey(mbEx.Expression, FuncEnum.None, CompareXEnum.None);
}
var colAlias = mbEx.Member.Name;
result.Add(DC.DPH.SelectMemberInitDic(cp, colAlias));
}
return result;
}
/********************************************************************************************************************/
private DicParam HandOnBinary(BinaryExpression binExpr)
{
var cp1 = GetKey(binExpr.Left, FuncEnum.None, CompareXEnum.None);
var cp2 = GetKey(binExpr.Right, FuncEnum.None, CompareXEnum.None);
DC.Option = OptionEnum.Compare;
DC.Compare = GetCompareType(binExpr.NodeType, false);
return DC.DPH.OnDic(cp1, cp2);
}
/********************************************************************************************************************/
private string GetAlias(MemberExpression memExpr)
{
var alias = string.Empty;
if (memExpr.Expression != null)
{
var expr = memExpr.Expression;
if (expr.NodeType == ExpressionType.Parameter)
{
var pExpr = expr as ParameterExpression;
alias = pExpr.Name;
}
else if (expr.NodeType == ExpressionType.MemberAccess)
{
var maExpr = expr as MemberExpression;
if (maExpr.Expression != null
&& maExpr.Expression.NodeType == ExpressionType.Parameter)
{
return GetAlias(maExpr);
}
else if (maExpr.Expression != null
&& maExpr.Expression.NodeType == ExpressionType.MemberAccess)
{
var xmaExpr = maExpr.Expression as MemberExpression;
return GetAlias(xmaExpr);
}
alias = maExpr.Member.Name;
}
else if (expr.NodeType == ExpressionType.Constant)
{
alias = memExpr.Member.Name;
}
}
return alias;
}
internal ColumnParam GetKey(Expression bodyL, FuncEnum func, CompareXEnum compareX, string format = "")
{
if (bodyL.NodeType == ExpressionType.MemberAccess)
{
var leftBody = bodyL as MemberExpression;
var prop = default(PropertyInfo);
//
var mType = default(Type);
var alias = GetAlias(leftBody);
if (func == FuncEnum.CharLength
|| func == FuncEnum.ToString_CS_DateTime_Format)
{
var exp = leftBody.Expression;
if (exp is MemberExpression)
{
var clMemExpr = exp as MemberExpression;
mType = clMemExpr.Expression.Type;
prop = mType.GetProperty(clMemExpr.Member.Name);
}
else if (exp is ParameterExpression)
{
mType = leftBody.Expression.Type;
prop = mType.GetProperty(leftBody.Member.Name);
}
else
{
throw XConfig.EC.Exception(XConfig.EC._005, bodyL.ToString());
}
}
else
{
mType = leftBody.Expression.Type;
prop = mType.GetProperty(leftBody.Member.Name);
}
//
var type = prop.PropertyType;
var tbm = default(TableModelCache);
try
{
tbm = DC.XC.GetTableModel(mType);
}
catch (Exception ex)
{
if (ex.Message.Contains("004")
&& ex.Message.Contains("[XTable]"))
{
throw XConfig.EC.Exception(XConfig.EC._094, $"表达式 -- {bodyL.ToString()} -- 不能正确解析!");
}
}
var attr = tbm.PCA.FirstOrDefault(it => prop.Name.Equals(it.PropName, StringComparison.OrdinalIgnoreCase)).ColAttr;
return new ColumnParam
{
Prop = prop.Name,
Key = attr.Name,
Alias = alias,
ValType = type,
TbMType = mType,
Format = format
};
}
else if (bodyL.NodeType == ExpressionType.Convert)
{
var exp = bodyL as UnaryExpression;
var opMem = exp.Operand;
return GetKey(opMem, func, compareX);
}
else if (bodyL.NodeType == ExpressionType.Call)
{
var mcExpr = bodyL as MethodCallExpression;
if (func == FuncEnum.Trim
|| func == FuncEnum.LTrim
|| func == FuncEnum.RTrim)
{
var mem = mcExpr.Object;
return GetKey(mem, func, compareX);
}
else if (compareX == CompareXEnum.In)
{
var mem = mcExpr.Arguments[0];
return GetKey(mem, func, compareX);
}
else if (func == FuncEnum.ToString_CS_DateTime_Format)
{
var mem = mcExpr.Object;
var val = DC.VH.ValueProcess(mcExpr.Arguments[0], XConfig.CSTC.String);
return GetKey(mem, func, compareX, val.Val.ToString());
}
else if (func == FuncEnum.ToString_CS)
{
var mem = mcExpr.Object;
return GetKey(mem, func, compareX);
}
else
{
throw XConfig.EC.Exception(XConfig.EC._018, $"{bodyL.NodeType}-{func}");
}
}
else
{
throw XConfig.EC.Exception(XConfig.EC._017, bodyL.NodeType.ToString());
}
}
private DicParam BodyProcess(Expression body, ParameterExpression firstParam)
{
//
var nodeType = body.NodeType;
if (nodeType == ExpressionType.Not)
{
return NotHandle(body, firstParam);
}
else if (nodeType == ExpressionType.Call)
{
return CallHandle(body as MethodCallExpression);
}
else if (nodeType == ExpressionType.Constant)
{
var cExpr = body as ConstantExpression;
return ConstantHandle(cExpr, cExpr.Type);
}
else if (nodeType == ExpressionType.MemberAccess)
{
if (IsNullableExpr(body))
{
return MemberAccessHandle((body as MemberExpression).Expression as MemberExpression);
}
else
{
return MemberAccessHandle(body as MemberExpression);
}
}
else if (nodeType == ExpressionType.Convert)
{
var cp = GetKey(body, FuncEnum.None, CompareXEnum.None);
if (string.IsNullOrWhiteSpace(cp.Key))
{
throw XConfig.EC.Exception(XConfig.EC._052, "无法解析 列名2 !!!");
}
return DC.DPH.ColumnDic(cp);
}
else if (nodeType == ExpressionType.MemberInit)
{
var miExpr = body as MemberInitExpression;
return DC.DPH.SelectColumnDic(HandSelectMemberInit(miExpr));
}
else if (nodeType == ExpressionType.New)
{
return NewHandle(body);
}
else if (IsBinaryExpr(nodeType))
{
return BinaryHandle(body, firstParam);
}
else if (IsMultiExpr(nodeType))
{
return MultiHandle(body, firstParam, nodeType);
}
else
{
throw XConfig.EC.Exception(XConfig.EC._003, body.ToString());
}
}
/********************************************************************************************************************/
internal DicParam FuncMFExpression<M, F>(Expression<Func<M, F>> func)
where M : class
{
return BodyProcess(func.Body, null);
}
internal DicParam FuncTExpression<T>(Expression<Func<T>> func)
{
return BodyProcess(func.Body, null);
}
internal DicParam FuncMBoolExpression<M>(Expression<Func<M, bool>> func)
where M : class
{
return BodyProcess(func.Body, func.Parameters[0]);
}
internal DicParam FuncBoolExpression(Expression<Func<bool>> func)
{
return BodyProcess(func.Body, null);
}
}
}
| 38.476581 | 139 | 0.444627 | [
"Apache-2.0"
] | liumeng0403/MyDAL | MyDAL/Core/XExpression.cs | 32,981 | C# |
using TRL.Common;
using TRL.Common.Collections;
using TRL.Common.Data;
using TRL.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TRL.Logging;
using TRL.Common.Handlers;
namespace TRL.Emulation
{
public class BacktestOrderManager:IOrderManager
{
private IDataContext tradingData;
private ILogger logger;
public BacktestOrderManager(IDataContext tradingData, ILogger logger)
{
this.tradingData = tradingData;
this.logger = logger;
}
public void PlaceOrder(Order order)
{
Bar lastBar =
this.tradingData.Get<IEnumerable<Bar>>().LastOrDefault(b => b.Symbol.Equals(order.Symbol));
if (lastBar == null)
return;
Trade trade =
new Trade(order,
order.Portfolio,
order.Symbol,
lastBar.Close,
order.TradeAction == TradeAction.Buy? order.Amount:-order.Amount,
lastBar.DateTime);
order.Signal.DateTime = order.DateTime = trade.DateTime;
string logMessage = String.Format("{0:dd/MM/yyyy H:mm:ss.fff}, {1}, исполнена сделка {2}",
DateTime.Now,
this.GetType().Name,
trade.ToString());
this.logger.Log(logMessage);
this.tradingData.Get<ObservableHashSet<Trade>>().Add(trade);
}
public void MoveOrder(Order order, double price)
{
}
public void CancelOrder(Order order)
{
}
}
}
| 26.793651 | 107 | 0.575829 | [
"Apache-2.0"
] | wouldyougo/TRx | TRL.Emulation/BacktestOrderManager.cs | 1,705 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BidAuction.Hubs
{
public class ConnectionMapping<T>
{
private readonly Dictionary<T, HashSet<string>> _connections =
new Dictionary<T, HashSet<string>>();
public int Count
{
get
{
return _connections.Count;
}
}
public IList GetAllUserIds
{
get
{
lock (_connections)
{
return _connections.Keys.ToList();
}
}
}
public void Add(T key, string connectionId)
{
lock (_connections)
{
HashSet<string> connections;
if (!_connections.TryGetValue(key, out connections))
{
connections = new HashSet<string>();
_connections.Add(key, connections);
}
lock (connections)
{
connections.Add(connectionId);
}
}
}
public IEnumerable<string> GetConnections(T key)
{
HashSet<string> connections;
if (_connections.TryGetValue(key, out connections))
{
return connections;
}
return Enumerable.Empty<string>();
}
public void Remove(T key, string connectionId)
{
lock (_connections)
{
HashSet<string> connections;
if (!_connections.TryGetValue(key, out connections))
{
return;
}
lock (connections)
{
connections.Remove(connectionId);
if (connections.Count == 0)
{
_connections.Remove(key);
}
}
}
}
}
}
| 24.27907 | 70 | 0.434387 | [
"MIT"
] | berkayakcay/BidAuction | BidAuction/Hubs/ConnectionMapping.cs | 2,090 | C# |
using System.Collections.Generic;
namespace QOAM.Core.Import
{
public class JournalsImportResult
{
public int NumberOfImportedJournals { get; set; }
public List<string> UpdatedIssns { get; set; } = new List<string>();
public int NumberOfNewJournals { get; set; }
public List<string> NewIssns { get; set; } = new List<string>();
}
} | 31.416667 | 76 | 0.65252 | [
"MIT"
] | QOAM/qoam | src/Core/Import/JournalsImportResult.cs | 379 | C# |
// Copyright 2019 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Borrowed from https://github.com/CryptoManiac/Ed25519
using System;
namespace NATS.Client.NaCl.Internal.Ed25519Ref10
{
internal static partial class ScalarOperations
{
public static void sc_clamp(byte[] s, int offset)
{
s[offset + 0] &= 248;
s[offset + 31] &= 127;
s[offset + 31] |= 64;
}
}
} | 33 | 75 | 0.685475 | [
"Apache-2.0"
] | AndyPook/nats.net | src/NATS.Client/NaCl/Internal/Ed25519Ref10/sc_clamp.cs | 959 | C# |
using HomeCinema.Web.Infrastructure.Validators;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace HomeCinema.Web.Models
{
public class RegistrationViewModel : IValidatableObject
{
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validator = new RegistrationViewModelValidator();
var result = validator.Validate(this);
return result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }));
}
}
} | 35 | 118 | 0.695238 | [
"MIT"
] | 09123363503/spa-webapi-angularjs-master | HomeCinema.Web/Models/RegistrationViewModel.cs | 737 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using FakeItEasy;
using MongoDB.Driver;
using Newtonsoft.Json;
using Squidex.Infrastructure.MongoDb;
using Squidex.Infrastructure.TestHelpers;
namespace Squidex.Infrastructure.EventSourcing
{
public abstract class MongoEventStoreFixture : IDisposable
{
private readonly IMongoClient mongoClient;
private readonly IMongoDatabase mongoDatabase;
private readonly IEventNotifier notifier = A.Fake<IEventNotifier>();
public MongoEventStore EventStore { get; }
protected MongoEventStoreFixture(string connectionString)
{
mongoClient = new MongoClient(connectionString);
mongoDatabase = mongoClient.GetDatabase(TestConfig.Configuration["mongodb:database"]);
BsonJsonConvention.Register(JsonSerializer.Create(TestUtils.DefaultSettings()));
EventStore = new MongoEventStore(mongoDatabase, notifier);
EventStore.InitializeAsync(default).Wait();
}
public void Cleanup()
{
mongoClient.DropDatabase("EventStoreTest");
}
public void Dispose()
{
Cleanup();
GC.SuppressFinalize(this);
}
}
public sealed class MongoEventStoreDirectFixture : MongoEventStoreFixture
{
public MongoEventStoreDirectFixture()
: base(TestConfig.Configuration["mongodb:configuration"])
{
}
}
public sealed class MongoEventStoreReplicaSetFixture : MongoEventStoreFixture
{
public MongoEventStoreReplicaSetFixture()
: base(TestConfig.Configuration["mongodb:configurationReplica"])
{
}
}
}
| 31.765625 | 98 | 0.599606 | [
"MIT"
] | Appleseed/squidex | backend/tests/Squidex.Infrastructure.Tests/EventSourcing/MongoEventStoreFixture.cs | 2,035 | C# |
using UnityEngine;
namespace BridgePattern.Case1.Naive2 {
public class BigLightCube : BigCube {
public BigLightCube() : base() => _go.SetMaterialColor(Color.white);
}
}
| 22.25 | 72 | 0.730337 | [
"MIT"
] | enginooby-academics/unity-design-patterns-in-depth | Assets/Design Patterns/Bridge/Case Study 1 - Shape, Size & Skin/Implementation Naive 2 - Nesting Hierarchy/BigLightCube.cs | 178 | C# |
using System.Threading.Tasks;
using BibleNote.Providers.OneNote.Contracts;
using BibleNote.Providers.OneNote.Services.DocumentProvider;
using BibleNote.Services.Contracts;
using BibleNote.Tests.Mocks;
using BibleNote.Tests.TestsBase;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BibleNote.Tests
{
[TestClass]
public class MockOneNoteDocumentProviderTests : FileDocumentParserTestsBase
{
private const string TempFolderName = "MockOneNoteDocumentProviderTests";
[TestInitialize]
public void Init()
{
base.Init(TempFolderName, services => services
.AddTransient<IOneNoteDocumentConnector, MockOneNoteDocumentConnector>()
.AddTransient<IDocumentProvider, OneNoteProvider>());
}
[TestCleanup]
public override void Cleanup()
{
base.Cleanup();
}
[TestMethod]
public Task Test1()
{
return TestFileAsync(@"..\..\..\TestData\OneNote_1.html",
new string[] { "Ин 1:1" },
new string[] { "Исх 12:27" },
new string[] { "1Кор 5:7" },
new string[] { "Ис 44" },
new string[] { "Ис 44:24" },
new string[] { "Евр 1:2", "Евр 1:10" },
new string[] { "Ис 44:6" },
new string[] { "Ин 1:17" },
new string[] { "Ис 44:5" },
new string[] { "Ис 44:6" });
}
[TestMethod]
public Task Test2()
{
return TestFileAsync(@"..\..\..\TestData\OneNote_2.html",
new string[] { "Ин 1" },
new string[] { "Ин 1:5" },
new string[] { "Мк 2:5" },
new string[] { "Ин 1:6" },
new string[] { "Ин 1:7" },
new string[] { "Ин 1:8" },
new string[] { "Ин 1:9" });
}
[TestMethod]
public Task Test3()
{
return TestFileAsync(@"..\..\..\TestData\OneNote_3.html",
new string[] { "1Пет 3:3" },
new string[] { "1Пет 3:9" },
new string[] { "Мф 1:1" },
new string[] { "Мф 1:10" },
new string[] { "1Пет 4:5" },
new string[] { "1Пет 4:11" },
new string[] { "Мк 2:2" },
new string[] { "1Пет 4:12" },
new string[] { "Лк 3-4" },
new string[] { "Ин 5-6" },
new string[] { "Мк 3:3" },
new string[] { "Лк 3-4" });
}
}
}
| 33.607595 | 88 | 0.482109 | [
"MIT"
] | AlexanderDemko/BibleNote | Tests/MockOneNoteDocumentProviderTests.cs | 2,726 | C# |
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using ZendeskApi_v2;
using ZendeskApi_v2.Models.Sections;
namespace Tests.HelpCenter
{
[TestFixture]
[Category("HelpCenter")]
public class SectionTests
{
private readonly ZendeskApi api = new ZendeskApi(Settings.Site, Settings.AdminEmail, Settings.AdminPassword);
private readonly long[] safeSections = new long[] { 360002891952, 360000205286, 201010935 };
[OneTimeSetUp]
public async Task Setup()
{
var sectionsResp = await api.HelpCenter.Sections.GetSectionsAsync();
do
{
foreach (var section in sectionsResp.Sections)
{
if (!safeSections.Contains(section.Id.Value))
{
await api.HelpCenter.Sections.DeleteSectionAsync(section.Id.Value);
}
}
if (!string.IsNullOrWhiteSpace(sectionsResp.NextPage))
{
sectionsResp = await api.HelpCenter.Sections.GetSectionsAsync();
}
} while (!string.IsNullOrWhiteSpace(sectionsResp.NextPage));
}
[Test]
public void CanGetSections()
{
var res = api.HelpCenter.Sections.GetSections();
Assert.Greater(res.Count, 0);
var res1 = api.HelpCenter.Sections.GetSectionById(res.Sections[0].Id.Value);
Assert.AreEqual(res1.Section.Id, res.Sections[0].Id.Value);
}
[Test]
public void CanCreateUpdateAndDeleteSections()
{
//https://csharpapi.zendesk.com/hc/en-us/categories/200382245-Category-1
long category_id = 200382245;
var res = api.HelpCenter.Sections.CreateSection(new Section
{
Name = "My Test section",
Position = 12,
CategoryId = category_id
});
Assert.Greater(res.Section.Id, 0);
res.Section.Position = 42;
var update = api.HelpCenter.Sections.UpdateSection(res.Section);
Assert.That(update.Section.Position, Is.EqualTo(res.Section.Position));
Assert.That(api.HelpCenter.Sections.DeleteSection(res.Section.Id.Value), Is.True);
}
[Test]
public void CanGetSectionsAsync()
{
var res = api.HelpCenter.Sections.GetSectionsAsync().Result;
Assert.Greater(res.Count, 0);
var res1 = api.HelpCenter.Sections.GetSectionById(res.Sections[0].Id.Value);
Assert.AreEqual(res1.Section.Id, res.Sections[0].Id.Value);
}
[Test]
public async Task CanCreateUpdateAndDeleteSectionsAsync()
{
//https://csharpapi.zendesk.com/hc/en-us/categories/200382245-Category-1
long category_id = 200382245;
var res = await api.HelpCenter.Sections.CreateSectionAsync(new Section
{
Name = "My Test section",
Position = 12,
CategoryId = category_id
});
Assert.That(res.Section.Id, Is.GreaterThan(0));
res.Section.Position = 42;
var update = await api.HelpCenter.Sections.UpdateSectionAsync(res.Section);
Assert.That(update.Section.Position, Is.EqualTo(res.Section.Position));
Assert.That(await api.HelpCenter.Sections.DeleteSectionAsync(res.Section.Id.Value), Is.True);
}
}
}
| 35.34 | 117 | 0.587719 | [
"Apache-2.0"
] | GreenParrotGmbH/ZendeskApi_v2 | test/ZendeskApi_v2.Test/HelpCenter/SectionTests.cs | 3,536 | C# |
#if !NETSTANDARD13
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-a2i-runtime-2019-11-07.normal.json service model.
*/
using Amazon.AugmentedAIRuntime;
using Amazon.AugmentedAIRuntime.Model;
using Moq;
using System;
using System.Linq;
using AWSSDK_DotNet35.UnitTests.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AWSSDK_DotNet35.UnitTests.PaginatorTests
{
[TestClass]
public class AugmentedAIRuntimePaginatorTests
{
private static Mock<AmazonAugmentedAIRuntimeClient> _mockClient;
[ClassInitialize()]
public static void ClassInitialize(TestContext a)
{
_mockClient = new Mock<AmazonAugmentedAIRuntimeClient>("access key", "secret", Amazon.RegionEndpoint.USEast1);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("AugmentedAIRuntime")]
public void ListHumanLoopsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListHumanLoopsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListHumanLoopsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListHumanLoopsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListHumanLoops(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListHumanLoops(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("AugmentedAIRuntime")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListHumanLoopsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListHumanLoopsRequest>();
var response = InstantiateClassGenerator.Execute<ListHumanLoopsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListHumanLoops(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListHumanLoops(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
}
}
#endif | 36.795181 | 160 | 0.698756 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/test/Services/AugmentedAIRuntime/UnitTests/Generated/_bcl45+netstandard/Paginators/AugmentedAIRuntimePaginatorTests.cs | 3,054 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Network.PrivateLinkService.PrivateLinkServiceProvider;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Network
{
public abstract class PrivateEndpointConnectionBaseCmdlet : NetworkBaseCmdlet, IDynamicParameters
{
[Parameter(
Mandatory = true,
ParameterSetName = "ByResourceId",
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string ResourceId { get; set; }
[Alias("ResourceName")]
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource name.",
ParameterSetName = "ByResource")]
[ValidateNotNullOrEmpty]
[SupportsWildcards]
public virtual string Name { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.",
ParameterSetName = "ByResource")]
[ResourceGroupCompleter]
[ValidateNotNullOrEmpty]
public virtual string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The private link service name.",
ParameterSetName = "ByResource")]
[ValidateNotNullOrEmpty]
public string ServiceName { get; set; }
protected RuntimeDefinedParameterDictionary DynamicParameters;
public const string privateEndpointTypeName = "PrivateLinkResourceType";
string NamedContextParameterSet = "ByResource";
public object GetDynamicParameters()
{
var parameters = new RuntimeDefinedParameterDictionary();
RuntimeDefinedParameter namedParameter;
if (ProviderConfiguration.TryGetProvideServiceParameter(privateEndpointTypeName, NamedContextParameterSet, out namedParameter))
{
parameters.Add(privateEndpointTypeName, namedParameter);
}
DynamicParameters = parameters;
return parameters;
}
public string PrivateLinkResourceType { get; set; }
public string Subscription { get; set; }
protected IPrivateLinkProvider BuildProvider(string subscription, string privateLinkResourceType)
{
return PrivateLinkProviderFactory.CreatePrivateLinkProvder(this, subscription, privateLinkResourceType);
}
}
}
| 41.542169 | 140 | 0.635441 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Network/Network/PrivateLinkService/PrivateEndpointConnection/PrivateEndpointConnectionBaseCmdlet.cs | 3,368 | C# |
// Copyright © 2015 Stig Schmidt Nielsson. All rights reserved. Distributed under the terms of the MIT License (http://opensource.org/licenses/MIT).
using System;
using Ssn.Utils.Misc;
namespace Ssn.Utils.Extensions {
/// <summary>
/// Various DateTime utility functions.
/// </summary>
public static class DateTimeExtensions {
/// <summary>
/// Returns a new DateTime which is the given DateTime rounded down to the nearest whole TimeSpan period.
/// </summary>
/// <param name="this">The DateTime to round.</param>
/// <param name="timeSpanTicks">Length in ticks of the the period to round to.</param>
/// <param name="numberOfPeriodsToRoundTo">Optional number of periods to round down to - negative numbers also allowed.</param>
/// <returns>A new DateTime with a rounded value.</returns>
public static DateTime RoundToTimeSpanStart(this DateTime @this, long timeSpanTicks, int numberOfPeriodsToRoundTo = 0) {
return new DateTime(timeSpanTicks*(@this.Ticks/timeSpanTicks + numberOfPeriodsToRoundTo));
}
/// <summary>
/// Returns a new DateTime which is the given DateTime rounded down to the nearest whole TimeSpan period.
/// </summary>
/// <param name="this">The DateTime to round.</param>
/// <param name="timeSpanTicks">Length in ticks of the the period to round to.</param>
/// <param name="numberOfPeriodsToRoundTo">Optional number of periods to round down to - negative numbers also allowed.</param>
/// <returns>A new DateTime with a rounded value.</returns>
public static DateTime RoundToTimeSpanEnd(this DateTime @this, long timeSpanTicks, int numberOfPeriodsToRoundTo = 0) {
return RoundToTimeSpanStart(@this, timeSpanTicks, 1 + numberOfPeriodsToRoundTo);
}
/// <summary>
/// Returns a new DateTime which is the given DateTime rounded down to the nearest whole TimeSpan period.
/// </summary>
/// <param name="this">The DateTime to round.</param>
/// <param name="period">The period to round to.</param>
/// <param name="numberOfPeriodsToRoundTo">Optional number of periods to round down to - negative numbers also allowed.</param>
/// <returns>A new DateTime with a rounded value.</returns>
public static DateTime RoundToTimeSpanEnd(this DateTime @this, TimeSpan period, int numberOfPeriodsToRoundTo = 0) {
return RoundToTimeSpanStart(@this, period.Ticks, 1 + numberOfPeriodsToRoundTo);
}
/// <summary>
/// Returns a new DateTime which is the given DateTime rounded down to the nearest whole TimeSpan period.
/// </summary>
/// <param name="this">The DateTime to round.</param>
/// <param name="period">The period to round to.</param>
/// <param name="numberOfPeriodsToRoundTo">Optional number of periods to round down to - negative numbers also allowed.</param>
/// <returns>A new DateTime with a rounded value.</returns>
public static DateTime RoundToTimeSpanStart(this DateTime @this, TimeSpan period, int numberOfPeriodsToRoundTo = 0) {
return RoundToTimeSpanStart(@this, period.Ticks, numberOfPeriodsToRoundTo);
}
public static readonly DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Returns true if the given DateTime is in the future. The method to determine the value of 'now' can be customized, but defaults to System.DateTime.UtcNow.
/// </summary>
/// <param name="this">The DateTime to compare with 'now'.</param>
/// <param name="getNow">The method for getting the value of 'now', defaults to System.DateTime.UtcNow.</param>
/// <returns>True if the given DateTime is greater than 'now'.</returns>
public static bool IsInTheFuture(this DateTime @this, Func<DateTime> getNow = null) {
DateTime now = getNow == null ? DateTime.UtcNow : getNow();
return @this.Ticks > now.Ticks;
}
/// <summary>
/// Returns true if the given DateTime is in the past. The method to determine the value of 'now' can be customized, but defaults to System.DateTime.UtcNow.
/// </summary>
/// <param name="this">The DateTime to compare with 'now'.</param>
/// <param name="getNow">The method for getting the value of 'now', defaults to System.DateTime.UtcNow.</param>
/// <returns>True if the given DateTime is less than 'now'.</returns>
public static bool IsInThePast(this DateTime @this, Func<DateTime> getNow = null) {
DateTime now = getNow == null ? DateTime.UtcNow : getNow();
return @this.Ticks < now.Ticks;
}
/// <summary>
/// Returns the given DateTime converted to the number of seconds elapsed since the EPOCH of January the 1st. 1970.
/// </summary>
/// <param name="this"></param>
/// <returns>An int representing the number of elapsed seconds since January the 1st. 1970.</returns>
public static int ToUnixTime(this DateTime @this) {
return (int) (@this - EPOCH).TotalSeconds;
}
/// <summary>
/// Converts the Unix time (number of elapsed seconds since January 1st. 1970) to a DateTime with kind Utc.
/// </summary>
/// <param name="this">The Unix time (a number of seconds) to convert to an UTC DateTime.</param>
/// <returns>The DateTime represention of the Unix time. The DateTime has kind Utc.</returns>
public static DateTime FromUnixTime(this int @this) {
return EPOCH.AddSeconds(@this);
}
/// <summary>
/// Returns the given DateTime converted to the number of seconds elapsed since the EPOCH of January the 1st. 1970.
/// </summary>
/// <param name="this"></param>
/// <returns>A long representing the number of elapsed milliseconds since January the 1st. 1970.</returns>
public static long ToUnixTimeMs(this DateTime @this) {
return (long) (@this - EPOCH).TotalMilliseconds;
}
/// <summary>
/// Converts the Unix time with millisecond resolution (number of elapsed milliseconds since January 1st. 1970) to a DateTime with kind Utc.
/// </summary>
/// <param name="this">The Unix time with millisecond resolution (a number of milliseconds) to convert to an UTC DateTime.</param>
/// <returns>The DateTime represention of the Unix time with millisecond resolution. The DateTime has kind Utc.</returns>
public static DateTime FromUnixTimeMs(this long @this) {
return EPOCH.AddMilliseconds(@this);
}
public static bool NotOlderThan(this DateTime @this, TimeSpan timeSpan, DateTime now = default(DateTime)) {
if (now == default(DateTime)) now = DateTime.UtcNow;
var dateTime = now.Add(timeSpan);
return NotBefore(@this, dateTime);
}
public static bool NotOlderThan(this Date @this, TimeSpan timeSpan, DateTime now = default(DateTime)) {
if (now == default(DateTime)) now = DateTime.UtcNow;
var dateTime = now.Add(timeSpan);
return NotBefore(@this, dateTime);
}
public static bool NotBefore(this DateTime @this, DateTime dateTime) {
return @this >= dateTime;
}
public static bool NotBefore(this Date @this, DateTime dateTime) {
return @this >= dateTime;
}
public static bool IsOlderThan(this DateTime @this, TimeSpan timeSpan, DateTime now = default(DateTime)) {
if (now == default(DateTime)) now = DateTime.UtcNow;
var dateTime = now.Add(timeSpan);
return IsBefore(@this, dateTime);
}
public static bool IsOlderThan(this Date @this, TimeSpan timeSpan, DateTime now = default(DateTime)) {
if (now == default(DateTime)) now = DateTime.UtcNow;
var dateTime = now.Add(timeSpan);
return IsBefore(@this, dateTime);
}
public static bool IsBefore(this DateTime @this, DateTime dateTime) {
return @this < dateTime;
}
public static bool IsBefore(this Date @this, DateTime dateTime) {
return (DateTime) @this < dateTime;
}
}
} | 61.860294 | 166 | 0.645549 | [
"MIT"
] | snielsson/Ssn | Ssn.Utils/Extensions/DateTimeExtensions.cs | 8,416 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
// [START compute_v1_generated_Instances_SimulateMaintenanceEvent_async]
using Google.Cloud.Compute.V1;
using System.Threading.Tasks;
using lro = Google.LongRunning;
public sealed partial class GeneratedInstancesClientSnippets
{
/// <summary>Snippet for SimulateMaintenanceEventAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task SimulateMaintenanceEventRequestObjectAsync()
{
// Create client
InstancesClient instancesClient = await InstancesClient.CreateAsync();
// Initialize request argument(s)
SimulateMaintenanceEventInstanceRequest request = new SimulateMaintenanceEventInstanceRequest
{
Zone = "",
Instance = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await instancesClient.SimulateMaintenanceEventAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await instancesClient.PollOnceSimulateMaintenanceEventAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
}
}
// [END compute_v1_generated_Instances_SimulateMaintenanceEvent_async]
}
| 44.046875 | 144 | 0.678255 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/InstancesClient.SimulateMaintenanceEventRequestObjectAsyncSnippet.g.cs | 2,819 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TS_SE_Tool.Utilities;
using TS_SE_Tool.Save.DataFormat;
namespace TS_SE_Tool.Save.Items
{
class Vehicle_Sound_Accessory : SiiNBlockCore
{
internal string data_path { get; set; } = "";
internal uint refund { get; set; } = 0;
internal Vehicle_Sound_Accessory()
{ }
internal Vehicle_Sound_Accessory(string[] _input)
{
string tagLine = "", dataLine = "";
foreach (string currentLine in _input)
{
if (currentLine.Contains(':'))
{
string[] splittedLine = currentLine.Split(new char[] { ':' }, 2);
tagLine = splittedLine[0].Trim();
dataLine = splittedLine[1].Trim();
}
else
{
tagLine = currentLine.Trim();
dataLine = "";
}
try
{
switch (tagLine)
{
case "":
{
break;
}
case "data_path":
{
data_path = dataLine;
break;
}
case "refund":
{
refund = uint.Parse(dataLine);
break;
}
}
}
catch (Exception ex)
{
Utilities.IO_Utilities.ErrorLogWriter(ex.Message + Environment.NewLine + this.GetType().Name.ToLower() + " | " + tagLine + " = " + dataLine);
break;
}
}
}
internal string PrintOut(uint _version, string _nameless)
{
string returnString = "";
StringBuilder returnSB = new StringBuilder();
returnSB.AppendLine("vehicle_sound_accessory : " + _nameless + " {");
returnSB.AppendLine(" data_path: " + data_path);
returnSB.AppendLine(" refund: " + refund.ToString());
returnSB.AppendLine("}");
returnString = returnSB.ToString();
this.removeWritenBlock(_nameless);
return returnString;
}
}
} | 28.752809 | 161 | 0.423603 | [
"Apache-2.0"
] | josemurillo94/TS-SE-Tool | TS SE Tool/CustomClasses/Save/Items/Vehicle_Sound_Accessory.cs | 2,561 | C# |
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using System.Threading.Tasks;
namespace SmartHome.UI.Pages
{
public partial class Index
{
[Inject]
public AuthenticationStateProvider GetAuthenticationStateAsync { get; set; }
protected async override Task OnInitializedAsync()
{
var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
var user = authstate.User;
var name = user.Identity.Name;
}
}
}
| 29.263158 | 92 | 0.690647 | [
"MIT"
] | mrabobi/WWW | SmartHome/SmartHome.UI/Pages/PagesCode/Index.cs | 558 | C# |
// <copyright file="BingMainPage.Map.cs" company="Automate The Planet Ltd.">
// Copyright 2018 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
using HybridTestFramework.UITests.Core.Controls;
using HybridTestFramework.UITests.Core;
namespace CreateHybridTestFrameworkInterfaceContracts.HybridVersion.Pages
{
public partial class BingMainPage
{
public IElement SearchBox
{
get
{
return ElementFinder.Find<IElement>(By.Id("sb_form_q"));
}
}
public IElement GoButton
{
get
{
return ElementFinder.Find<IElement>(By.Id("sb_form_go"));
}
}
public IElement ResultsCountDiv
{
get
{
return ElementFinder.Find<IElement>(By.Id("b_tween"));
}
}
}
} | 32.521739 | 85 | 0.643717 | [
"Apache-2.0"
] | FrancielleWN/AutomateThePlanet-Learning-Series | Design-Architecture-Series/CreateHybridTestFrameworkInterfaceContracts/HybridVersion/Pages/BingMain/BingMainPage.Map.cs | 1,498 | C# |
/**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using Tup;
namespace Tup.Tars
{
/**
* Format all properties of the output tars structure,
* mainly used for debugging or logging.
*/
public class TarsDisplayer
{
private StringBuilder sb;
private int level = 0;
private void Indention(string fieldName)
{
for (int i = 0; i < level; ++i)
{
sb.Append('\t');
}
if (fieldName != null)
{
sb.Append(fieldName).Append(": ");
}
}
public TarsDisplayer(StringBuilder sb, int level)
{
this.sb = sb;
this.level = level;
}
public TarsDisplayer(StringBuilder sb)
{
this.sb = sb;
}
public TarsDisplayer Display(bool b, string fieldName)
{
Indention(fieldName);
sb.Append(b ? 'T' : 'F').Append('\n');
return this;
}
public TarsDisplayer Display(byte n, string fieldName)
{
Indention(fieldName);
sb.Append(n).Append('\n');
return this;
}
public TarsDisplayer Display(char n, string fieldName)
{
Indention(fieldName);
sb.Append(n).Append('\n');
return this;
}
public TarsDisplayer Display(short n, string fieldName)
{
Indention(fieldName);
sb.Append(n).Append('\n');
return this;
}
public TarsDisplayer Display(int n, string fieldName)
{
Indention(fieldName);
sb.Append(n).Append('\n');
return this;
}
public TarsDisplayer Display(long n, string fieldName)
{
Indention(fieldName);
sb.Append(n).Append('\n');
return this;
}
public TarsDisplayer Display(float n, string fieldName)
{
Indention(fieldName);
sb.Append(n).Append('\n');
return this;
}
public TarsDisplayer Display(double n, string fieldName)
{
Indention(fieldName);
sb.Append(n).Append('\n');
return this;
}
public TarsDisplayer Display(string str, string fieldName)
{
Indention(fieldName);
if (null == str)
{
sb.Append("null").Append('\n');
}
else
{
sb.Append(str).Append('\n');
}
return this;
}
public TarsDisplayer Display(byte[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (byte b in array)
{
jd.Display(b, null);
}
Display(']', null);
return this;
}
public TarsDisplayer Display(char[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (char c in array)
{
jd.Display(c, null);
}
Display(']', null);
return this;
}
public TarsDisplayer Display(short[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (short s in array)
{
jd.Display(s, null);
}
Display(']', null);
return this;
}
public TarsDisplayer Display(int[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (int i in array)
jd.Display(i, null);
Display(']', null);
return this;
}
public TarsDisplayer Display(long[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (long l in array)
{
jd.Display(l, null);
}
Display(']', null);
return this;
}
public TarsDisplayer Display(float[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (float f in array)
{
jd.Display(f, null);
}
Display(']', null);
return this;
}
public TarsDisplayer Display(double[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (double d in array)
{
jd.Display(d, null);
}
Display(']', null);
return this;
}
public TarsDisplayer Display<K, V>(Dictionary<K, V> map, string fieldName)
{
Indention(fieldName);
if (map == null)
{
sb.Append("null").Append('\n');
return this;
}
if (map.Count == 0)
{
sb.Append(map.Count).Append(", {}").Append('\n');
return this;
}
sb.Append(map.Count).Append(", {").Append('\n');
TarsDisplayer jd1 = new TarsDisplayer(sb, level + 1);
TarsDisplayer jd2 = new TarsDisplayer(sb, level + 2);
foreach (KeyValuePair<K, V> pair in map)
{
jd1.Display('(', null);
jd2.Display(pair.Key, null);
jd2.Display(pair.Value, null);
jd1.Display(')', null);
}
Display('}', null);
return this;
}
public TarsDisplayer Display<T>(T[] array, string fieldName)
{
Indention(fieldName);
if (array == null)
{
sb.Append("null").Append('\n');
return this;
}
if (array.Length == 0)
{
sb.Append(array.Length).Append(", []").Append('\n');
return this;
}
sb.Append(array.Length).Append(", [").Append('\n');
TarsDisplayer jd = new TarsDisplayer(sb, level + 1);
foreach (T o in array)
{
jd.Display(o, null);
}
Display(']', null);
return this;
}
public TarsDisplayer Display<T>(List<T> list, string fieldName)
{
if (list == null)
{
Indention(fieldName);
sb.Append("null").Append('\n');
return this;
}
else
{
for (int i = 0; i < list.Count; i++)
{
Display(list[i], fieldName);
}
return this;
}
}
////@SuppressWarnings("unchecked")
public TarsDisplayer Display<T>(T obj, string fieldName)
{
object oObject = obj;
if (obj == null)
{
sb.Append("null").Append('\n');
}
else if (obj is byte)
{
Display(((byte)oObject), fieldName);
}
else if (obj is bool)
{
Display(((bool)oObject), fieldName);
}
else if (obj is short)
{
Display(((short)oObject), fieldName);
}
else if (obj is int)
{
Display(((int)oObject), fieldName);
}
else if (obj is long)
{
Display(((long)oObject), fieldName);
}
else if (obj is float)
{
Display(((float)oObject), fieldName);
}
else if (obj is Double)
{
Display(((Double)oObject), fieldName);
}
else if (obj is string)
{
Display((string)oObject, fieldName);
}
else if (obj is TarsStruct)
{
Display((TarsStruct)oObject, fieldName);
}
else if (obj is byte[])
{
Display((byte[])oObject, fieldName);
}
else if (obj is bool[])
{
Display((bool[])oObject, fieldName);
}
else if (obj is short[])
{
Display((short[])oObject, fieldName);
}
else if (obj is int[])
{
Display((int[])oObject, fieldName);
}
else if (obj is long[])
{
Display((long[])oObject, fieldName);
}
else if (obj is float[])
{
Display((float[])oObject, fieldName);
}
else if (obj is double[])
{
Display((double[])oObject, fieldName);
}
else if (obj.GetType().IsArray)
{
Display((Object[])oObject, fieldName);
}
else if (obj is IList)
{
IList list = (IList)oObject;
List<object> tmplist = new List<object>();
foreach (object _obj in list)
{
tmplist.Add(_obj);
}
Display(tmplist, fieldName);
}
else
{
throw new TarsEncodeException("write object error: unsupport type.");
}
return this;
}
public TarsDisplayer Display(TarsStruct s, string fieldName)
{
Display('{', fieldName);
if (s == null)
{
sb.Append('\t').Append("null");
}
else
{
s.Display(sb, level + 1);
}
Display('}', null);
return this;
}
}
}
| 28.453027 | 93 | 0.433194 | [
"MIT"
] | Mryanxh/HuyaLiveChat_old | HuyaLiveChat/TarsTup/tars/TarsDisplayer.cs | 13,629 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Batch.V20170312.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class CreateCpmComputeEnvRequest : AbstractModel
{
/// <summary>
/// 计算环境信息
/// </summary>
[JsonProperty("ComputeEnv")]
public NamedCpmComputeEnv ComputeEnv{ get; set; }
/// <summary>
/// 位置信息
/// </summary>
[JsonProperty("Placement")]
public Placement Placement{ get; set; }
/// <summary>
/// 用于保证请求幂等性的字符串。该字符串由用户生成,需保证不同请求之间唯一,最大值不超过64个ASCII字符。若不指定该参数,则无法保证请求的幂等性。
/// </summary>
[JsonProperty("ClientToken")]
public string ClientToken{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamObj(map, prefix + "ComputeEnv.", this.ComputeEnv);
this.SetParamObj(map, prefix + "Placement.", this.Placement);
this.SetParamSimple(map, prefix + "ClientToken", this.ClientToken);
}
}
}
| 31.137931 | 85 | 0.638981 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Batch/V20170312/Models/CreateCpmComputeEnvRequest.cs | 1,980 | C# |
namespace Cesil
{
/// <summary>
/// Indicates what a writer is doing when
/// a WriteContext is created.
/// </summary>
public enum WriteContextMode : byte
{
/// <summary>
/// A writer is discovering columns for a table, used during
/// dynamic serialization to determine headers.
///
/// Neither columns nor rows are specified during this operation.
/// </summary>
DiscoveringColumns = 1,
/// <summary>
/// A writer is discovering cells in a row, used during
/// dynamic serialization to determine per-row values.
///
/// Only a row is specified during this operation.
/// </summary>
DiscoveringCells = 2,
/// <summary>
/// A writer is writing a single column.
///
/// Both a row and a column are specified during this operation.
/// </summary>
WritingColumn = 3
}
}
| 29.454545 | 73 | 0.554527 | [
"MIT"
] | Siliconrob/Cesil | Cesil/Context/WriteContextMode.cs | 974 | C# |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Common;
using Kooboo.CMS.Common.Persistence.Non_Relational;
using Kooboo.CMS.Content.Models;
using Kooboo.CMS.Content.Services;
using Kooboo.CMS.Sites;
using Kooboo.CMS.Web.Models;
using Kooboo.Globalization;
using Kooboo.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Kooboo.CMS.Web.Areas.Contents.Controllers
{
public class TextFolderController : ManagerControllerBase
{
#region .ctor
TextFolderManager Manager
{
get;
set;
}
public TextFolderController(TextFolderManager manager)
{
Manager = manager;
}
#endregion
#region Index
// Kooboo.CMS.Account.Models.Permission.Contents_ContentPermission
[Kooboo.CMS.Web.Authorizations.Authorization(AreaName = "Contents", Group = "", Name = "Content", Order = 1)]
public virtual ActionResult Index(string FolderName, string search)
{
var folders = Manager.All(Repository, search, FolderName).OrderBy(it=>it.FriendlyText).ToArray();
folders = folders
.Select(it => it.AsActual())
.Where(it => it.Visible)
.Where(it => Kooboo.CMS.Content.Services.ServiceFactory.WorkflowManager.AvailableViewContent(new TextFolder(Repository, it.FullName), User.Identity.Name)).ToArray();
return View(folders);
}
#endregion
#region Create
// Kooboo.CMS.Account.Models.Permission.Contents_FolderPermission
[Kooboo.CMS.Web.Authorizations.Authorization(AreaName = "Contents", Group = "", Name = "Folder", Order = 99)]
public virtual ActionResult Create()
{
ViewData["textFolderList"] = Manager.All(Repository, "");
return View(new TextFolder());
}
// Kooboo.CMS.Account.Models.Permission.Contents_FolderPermission
[Kooboo.CMS.Web.Authorizations.Authorization(AreaName = "Contents", Group = "", Name = "Folder", Order = 99)]
[HttpPost]
public virtual ActionResult Create(TextFolder model, string folderName, string @return)
{
//compatible with the Folder parameter changed to FolderName.
folderName = folderName ?? this.ControllerContext.RequestContext.GetRequestValue("Folder");
var data = new JsonResultData(ModelState);
if (ModelState.IsValid)
{
data.RunWithTry((resultData) =>
{
Folder parent = null;
if (!string.IsNullOrEmpty(folderName))
{
parent = FolderHelper.Parse<TextFolder>(Repository, folderName);
}
model.Parent = parent;
model.UtcCreationDate = DateTime.UtcNow;
Manager.Add(Repository, model);
resultData.RedirectUrl = @return;
});
}
return Json(data);
}
#endregion
#region Edit
// Kooboo.CMS.Account.Models.Permission.Contents_FolderPermission
[Kooboo.CMS.Web.Authorizations.Authorization(AreaName = "Contents", Group = "", Name = "Folder", Order = 99)]
public virtual ActionResult Edit(string UUID)
{
ViewData["textFolderList"] = Manager.All(Repository, "");
return View(Manager.Get(Repository, UUID).AsActual());
}
// Kooboo.CMS.Account.Models.Permission.Contents_FolderPermission
[Kooboo.CMS.Web.Authorizations.Authorization(AreaName = "Contents", Group = "", Name = "Folder", Order = 99)]
[HttpPost]
public virtual ActionResult Edit(TextFolder model, string UUID, string successController, string @return)
{
var data = new JsonResultData(ModelState);
if (ModelState.IsValid)
{
data.RunWithTry((resultData) =>
{
UUID = string.IsNullOrEmpty(UUID) ? model.FullName : UUID;
var old = Manager.Get(Repository, UUID);
model.Parent = old.Parent;
Manager.Update(Repository, model, old);
resultData.RedirectUrl = @return;
});
}
return Json(data);
}
#endregion
#region Delete
// Kooboo.CMS.Account.Models.Permission.Contents_FolderPermission
//[Kooboo.CMS.Web.Authorizations.Authorization(AreaName = "Contents", Group = "", Name = "Folder", Order = 99)]
[HttpPost]
public virtual ActionResult Delete(TextFolder[] model)
{
ModelState.Clear();
var data = new JsonResultData(ModelState);
data.RunWithTry((resultData) =>
{
foreach (var folder in model)
{
folder.Repository = Repository;
Manager.Remove(Repository, folder);
}
resultData.ReloadPage = true;
});
return Json(data);
}
#endregion
#region Relations
public virtual ActionResult Relations(string uuid)
{
var model = Manager.Relations(new TextFolder(Repository, uuid));
return View(model);
}
#endregion
public virtual ActionResult GetSchemaFields(string schemaName)
{
var schema = new Schema(Repository, schemaName).AsActual();
if (schema == null)
{
schema = new Schema();
}
return Json(schema.AllColumns.Select(o =>
new
{
id = o.Name,
text = o.Name
}), JsonRequestBehavior.AllowGet);
}
}
}
| 33.966292 | 181 | 0.573933 | [
"BSD-3-Clause"
] | Godoy/CMS | Kooboo.CMS/Kooboo.CMS.Web/Areas/Contents/Controllers/TextFolderController.cs | 6,048 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tyrell.Hand
{
public interface IFinger
{
void Extend(int extends);
List<Bone> Joints { get; }
}
}
| 15.9375 | 34 | 0.678431 | [
"MIT"
] | sondreb/options-injection-pattern | samples/OptionsInjectionPattern/Tyrell.Hand/IFinger.cs | 257 | C# |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayPanel : BaseGui, IPanel
{
public PanelType PanelType { get { return PanelType.PLAY; } }
List<int> levels = new List<int>();
IServices services;
Transform levelsContent;
public PlayPanel(Transform content, IServices services)
{
go = content.gameObject;
levelsContent = getChild("Viewport/Content");
this.services = services;
createLevels();
}
public void Disable()
{
}
public void Enable()
{
}
void createLevels()
{
#if UNITY_EDITOR
System.IO.FileInfo[] infos = new System.IO.DirectoryInfo(Application.dataPath + "/Resources/").GetFiles();
foreach (System.IO.FileInfo info in infos)
if (info.Name.StartsWith((typeof(LevelModelComponent)).Name) && info.Name.EndsWith(".json"))
levels.Add(System.Convert.ToInt16(info.Name.Split('_')[1].Split('.')[0]));
#else
levels.Add(290);
levels.Add(323);
levels.Add(326);
levels.Add(328);
levels.Add(562);
levels.Add(1044);
levels.Add(1837);
levels.Add(1951);
levels.Add(2081);
levels.Add(2536);
#endif
for (int i = 0; i < levels.Count; i++)
{
GameObject button = services.UIFactoryService.CreatePrefab("Element/SimpleButton");
button.name = levels[i].ToString();
button.transform.SetParent(levelsContent, false);
services.UIFactoryService.AddText(button.transform, "Text", button.name);
services.UIFactoryService.AddButton(button, onLevelClicked);
}
}
void onLevelClicked()
{
int level = System.Convert.ToInt16(EventSystem.current.currentSelectedGameObject.name);
services.LoadService.PrepareAndExecute(new StartGamePhase(services.ViewService, services.GameService, level));
}
}
| 30.890625 | 119 | 0.627719 | [
"MIT"
] | kicholen/GamePrototype | Assets/Script/View/Main/Panels/PlayPanel.cs | 1,979 | C# |
using UnityEditor;
using UnityEngine;
class RenameFieldAttribute : PropertyAttribute
{
public string Name { get; }
public RenameFieldAttribute(string name) => Name = name;
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(RenameFieldAttribute))]
class FieldNameDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
string[] path = property.propertyPath.Split('.');
bool isArray = path.Length > 1 && path[1] == "Array";
if (!isArray && attribute is RenameFieldAttribute fieldName)
label.text = fieldName.Name;
EditorGUI.PropertyField(position, property, label, true);
}
}
#endif
} | 30.038462 | 97 | 0.636364 | [
"MIT"
] | Papyrustaro/UnityFishingGame | Assets/Scripts/CustomClass/RenameFieldAttribute.cs | 783 | C# |
using Microsoft.DataTransfer.Core.FactoryAdapters;
using Microsoft.DataTransfer.Extensibility;
using Microsoft.DataTransfer.TestsCommon.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.DataTransfer.Core.UnitTests.FactoryAdapters
{
[TestClass]
public class DataAdapterFactoryAdaptersTests
{
[TestMethod]
public async Task CreateAsync_DataSourceAdapter_Created()
{
const string TestDisplayName = "TestSource";
var adapterMock = Mocks.Of<IDataSourceAdapter>().First();
var adapterFactoryMock = new Mock<IDataSourceAdapterFactory<ITestAdapterConfiguration>>();
adapterFactoryMock
.Setup(f => f.CreateAsync(It.IsAny<ITestAdapterConfiguration>(), It.IsAny<IDataTransferContext>(), It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(adapterMock));
var configuration =
Mocks
.Of<ITestAdapterConfiguration>(c =>
c.Text == "Test" && c.Number == 42)
.First();
var factoryAdapter = new DataSourceAdapterFactoryAdapter<ITestAdapterConfiguration>(adapterFactoryMock.Object, TestDisplayName);
var adapter = await factoryAdapter.CreateAsync(configuration, DataTransferContextMock.Instance, CancellationToken.None);
Assert.AreEqual(TestDisplayName, factoryAdapter.DisplayName, TestResources.InvalidDataAdapter);
Assert.IsNotNull(factoryAdapter.ConfigurationType, TestResources.EmptyConfigurationType);
Assert.AreEqual(typeof(ITestAdapterConfiguration), factoryAdapter.ConfigurationType, TestResources.InvalidConfigurationType);
Assert.AreEqual(adapterMock, adapter, TestResources.InvalidDataAdapter);
}
[TestMethod]
public async Task CreateAsync_DataSinkAdapter_Created()
{
const string TestDisplayName = "TestSink";
var adapterMock = Mocks.Of<IDataSinkAdapter>().First();
var adapterFactoryMock = new Mock<IDataSinkAdapterFactory<ITestAdapterConfiguration>>();
adapterFactoryMock
.Setup(f => f.CreateAsync(It.IsAny<ITestAdapterConfiguration>(), It.IsAny<IDataTransferContext>(), It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(adapterMock));
var configuration =
Mocks
.Of<ITestAdapterConfiguration>(c =>
c.Text == "Test" && c.Number == 42)
.First();
var factoryAdapter = new DataSinkAdapterFactoryAdapter<ITestAdapterConfiguration>(adapterFactoryMock.Object, TestDisplayName);
var adapter = await factoryAdapter.CreateAsync(configuration, DataTransferContextMock.Instance, CancellationToken.None);
Assert.AreEqual(TestDisplayName, factoryAdapter.DisplayName, TestResources.InvalidDataAdapter);
Assert.IsNotNull(factoryAdapter.ConfigurationType, TestResources.EmptyConfigurationType);
Assert.AreEqual(typeof(ITestAdapterConfiguration), factoryAdapter.ConfigurationType, TestResources.InvalidConfigurationType);
Assert.AreEqual(adapterMock, adapter, TestResources.InvalidDataAdapter);
}
}
}
| 45.333333 | 146 | 0.690882 | [
"MIT"
] | Adrian-Wennberg/azure-documentdb-datamigrationtool | Core/Microsoft.DataTransfer.Core.UnitTests/FactoryAdapters/DataAdapterFactoryAdaptersTests.cs | 3,402 | C# |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace NLog
{
/// <summary>
/// Mark a parameter of a method for message templating
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class MessageTemplateFormatMethodAttribute : Attribute
{
/// <param name="parameterName">
/// Specifies which parameter of an annotated method should be treated as message-template-string
/// </param>
public MessageTemplateFormatMethodAttribute(string parameterName)
{
ParameterName = parameterName;
}
/// <summary>
/// The name of the parameter that should be as treated as message-template-string
/// </summary>
public string ParameterName { get; }
}
}
| 42.333333 | 117 | 0.725197 | [
"BSD-3-Clause"
] | AlanLiu90/NLog | src/NLog/Attributes/MessageTemplateFormatMethodAttribute.cs | 2,540 | C# |
namespace WarehouseSystem.Web.ViewModels.Manage
{
public class FactorViewModel
{
public string Purpose { get; set; }
}
}
| 17.75 | 48 | 0.661972 | [
"MIT"
] | NikitoG/WarehouseSystem | Source/Web/WarehouseSystem.Web/ViewModels/Manage/FactorViewModel.cs | 144 | C# |
using Bedrock.Shared.Configuration;
using Bedrock.Shared.Session.Interface;
namespace Bedrock.Template.Api.Domain.Validation.Service
{
public abstract class ServiceBaseDomainValidation : ServiceBaseDomain
{
#region Constructors
public ServiceBaseDomainValidation(BedrockConfiguration bedrockConfiguration, params ISessionAware[] sessionAwareDependencies) : base(bedrockConfiguration, sessionAwareDependencies) { }
#endregion
}
}
| 35.923077 | 193 | 0.79015 | [
"MIT"
] | BedrockNet/Bedrock.Template.Api | Bedrock.Template.Api.Domain/Validation/Service/ServiceBaseDomainValidation.cs | 469 | C# |
namespace Medhurst.CodeTalk.LiskovSubstitution
{
public class SportsCar : Car
{
public override void DriveFast(Driver driver)
{
base.DriveFast(driver);
// GOOD: ensure the state of this class is as you'd expect
// it after applying sub-class logic
// i.o.w. You have asserted your own logic
Guard.Post.EnsureIsNowTrue(driver.TrousersAreTight);
}
}
}
| 28 | 70 | 0.604911 | [
"Unlicense",
"MIT"
] | tommed/talk | Medhurst.CodeTalk/Medhurst.CodeTalk/LiskovSubstitution/GoodSportsCar.cs | 450 | C# |
namespace ErrorHandlingExample.Services;
public class Counter : ICounter
{
public Dictionary<string, int> UrlCounter { get; set; }
public Counter()
{
UrlCounter = new Dictionary<string, int>();
}
public void IncrementRequestPathCount(string requestPath)
{
if (UrlCounter.ContainsKey(requestPath))
{
UrlCounter[requestPath]++;
}
else
{
UrlCounter.Add(requestPath, 1);
}
}
}
| 19.44 | 61 | 0.58642 | [
"MIT"
] | EricCote/20486D-New | Allfiles/Mod10/Democode/02_ErrorHandlingExample_end/ErrorHandlingExample/Services/Counter.cs | 488 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TicketTimer.Core.Infrastructure
{
public class JsonWorkItemStore : WorkItemStore
{
private readonly FileStore _fileStore;
private const string FileName = "timer.state";
private TimerState _state;
public JsonWorkItemStore(FileStore fileStore)
{
_fileStore = fileStore;
Load();
}
public void AddToArchive(WorkItem workItem)
{
GetState().WorkItemArchive.Add(workItem);
Save();
}
public TimerState GetState()
{
if (_state == null)
{
Load();
}
return _state;
}
public void RemoveFromArchive(string ticketNumber)
{
GetState().WorkItemArchive.RemoveAll(wi => wi.TicketNumber == ticketNumber);
Save();
}
public void RemoveRangeFromArchive(IEnumerable<string> tickets)
{
foreach (var ticketNumber in tickets)
{
RemoveFromArchive(ticketNumber);
}
}
public void Save()
{
var json = JsonConvert.SerializeObject(_state, Formatting.Indented);
_fileStore.WriteFile(json, FileName);
}
private void Load()
{
var json = _fileStore.ReadFile(FileName);
if (!string.IsNullOrEmpty(json))
{
_state = JsonConvert.DeserializeObject<TimerState>(json);
}
else
{
_state = new TimerState();
}
}
public void SetCurrent(WorkItem workItem)
{
GetState().CurrentWorkItem = workItem;
Save();
}
public void ClearArchive()
{
GetState().WorkItemArchive.Clear();
Save();
}
}
}
| 24.607595 | 88 | 0.518519 | [
"MIT"
] | n-develop/tickettimer | TicketTimer.Core/Infrastructure/JsonWorkItemStore.cs | 1,946 | C# |
namespace ME.ECS.BlackBox {
[Category("Events")]
public class CallEvent : BoxNode {
public World.GlobalEventType eventType = World.GlobalEventType.Visual;
public GlobalEvent @event;
public override void OnCreate() {
}
public override Box Execute(in Entity entity, float deltaTime) {
this.@event.Execute(in entity, this.eventType);
return this.next;
}
}
} | 20.416667 | 78 | 0.561224 | [
"MIT"
] | IgorAtorin/ecs-submodule | ECSBlackBox/Runtime/Nodes/Events/CallEvent.cs | 492 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
#if IS_WINUI
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
#else
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
#endif
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace Uno.Toolkit.Samples.Content.NestedSamples
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class NavigationBarSample_NestedPage2 : Page
{
public NavigationBarSample_NestedPage2()
{
this.InitializeComponent();
}
private void NavigateBack(object sender, RoutedEventArgs e) => Frame.GoBack();
}
}
| 28 | 95 | 0.753247 | [
"MIT"
] | Surfndez/uno.toolkit.ui | samples/Uno.Toolkit.Samples/Uno.Toolkit.Samples.Shared/Content/NestedSamples/NavigationBarSample_NestedPage2.xaml.cs | 1,234 | C# |
using Microsoft.Analytics.Interfaces;
using Microsoft.Analytics.Types.Sql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace Images
{
public static class UpdatableRowExtensions
{
public static void SetColumnIfRequested<T>(this IUpdatableRow source, string colName, Func<T> expr)
{
var colIdx = source.Schema.IndexOf(colName);
if (colIdx != -1)
{ source.Set<T>(colIdx, expr()); }
}
}
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class ImageFeatureExtractor : IExtractor
{
private int _scaleWidth, _scaleHeight;
public ImageFeatureExtractor(int scaleWidth = 150, int scaleHeight = 150)
{ _scaleWidth = scaleWidth; _scaleHeight = scaleHeight; }
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
byte[] img = ImageOps.GetByteArrayforImage(input.BaseStream);
// load image only once into memory per row
using (StreamImage inImage = new StreamImage(img))
{
output.SetColumnIfRequested("image", () => img);
output.SetColumnIfRequested("equipment_make", () => inImage.getStreamImageProperty(ImageProperties.equipment_make));
output.SetColumnIfRequested("equipment_model", () => inImage.getStreamImageProperty(ImageProperties.equipment_model));
output.SetColumnIfRequested("description", () => inImage.getStreamImageProperty(ImageProperties.description));
output.SetColumnIfRequested("copyright", () => inImage.getStreamImageProperty(ImageProperties.copyright));
output.SetColumnIfRequested("thumbnail", () => inImage.scaleStreamImageTo(this._scaleWidth, this._scaleHeight));
}
yield return output.AsReadOnly();
}
}
}
| 37.943396 | 134 | 0.67628 | [
"MIT"
] | Azure/usql | Examples/ImageApp/Image/ImageFeatureExtractor.cs | 2,013 | C# |
//
// Gendarme.Rules.Security.Cas.DoNotExposeMethodsProtectedByLinkDemandRule
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005, 2007-2008, 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security;
using System.Security.Permissions;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Gendarme.Framework;
using Gendarme.Framework.Engines;
using Gendarme.Framework.Helpers;
using Gendarme.Framework.Rocks;
namespace Gendarme.Rules.Security.Cas {
/// <summary>
/// This rule checks for visible methods that are less protected (i.e. lower security
/// requirements) than the method they call. If the called methods are protected by a
/// <c>LinkDemand</c> then the caller can be used to bypass security checks.
/// </summary>
/// <example>
/// Bad example:
/// <code>
/// public class BaseClass {
/// [SecurityPermission (SecurityAction.LinkDemand, Unrestricted = true)]
/// public virtual void VirtualMethod ()
/// {
/// }
/// }
///
/// public class Class : BaseClass {
/// // bad since a caller with only ControlAppDomain will be able to call the base method
/// [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
/// public override void VirtualMethod ()
/// {
/// base.VirtualMethod ();
/// }
/// }
/// </code>
/// </example>
/// <example>
/// Good example (InheritanceDemand):
/// <code>
/// public class BaseClass {
/// [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
/// public virtual void VirtualMethod ()
/// {
/// }
/// }
///
/// public class Class : BaseClass {
/// // ok since this permission cover the base class permission
/// [SecurityPermission (SecurityAction.LinkDemand, Unrestricted = true)]
/// public override void VirtualMethod ()
/// {
/// base.VirtualMethod ();
/// }
/// }
/// </code>
/// </example>
/// <remarks>Before Gendarme 2.2 this rule was part of Gendarme.Rules.Security and named MethodCallWithSubsetLinkDemandRule.</remarks>
[Problem ("This method is less protected than some of the methods it calls.")]
[Solution ("Ensure that the LinkDemand on this method is a superset of any LinkDemand present on called methods.")]
[EngineDependency (typeof (OpCodeEngine))]
[FxCopCompatibility ("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public class DoNotExposeMethodsProtectedByLinkDemandRule : Rule, IMethodRule {
static PermissionSet Empty = new PermissionSet (PermissionState.None);
private static PermissionSet GetLinkDemand (ISecurityDeclarationProvider method)
{
foreach (SecurityDeclaration declsec in method.SecurityDeclarations) {
switch (declsec.Action) {
case Mono.Cecil.SecurityAction.LinkDemand:
case Mono.Cecil.SecurityAction.NonCasLinkDemand:
return declsec.ToPermissionSet ();
}
}
return Empty;
}
private static bool Check (ISecurityDeclarationProvider caller, ISecurityDeclarationProvider callee)
{
// 1 - look if the callee has a LinkDemand
PermissionSet calleeLinkDemand = GetLinkDemand (callee);
if (calleeLinkDemand.Count == 0)
return true;
// 2 - Ensure the caller requires a superset (or the same) permissions
return calleeLinkDemand.IsSubsetOf (GetLinkDemand (caller));
}
public RuleResult CheckMethod (MethodDefinition method)
{
// #1 - rule apply only if the method has a body (e.g. p/invokes, icalls don't)
// otherwise we don't know what it's calling
if (!method.HasBody)
return RuleResult.DoesNotApply;
// #2 - rule apply to methods are publicly accessible
// note that the type doesn't have to be public (indirect access)
if (!method.IsVisible ())
return RuleResult.DoesNotApply;
// #3 - avoid looping if we're sure there's no call in the method
if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
return RuleResult.DoesNotApply;
// *** ok, the rule applies! ***
// #4 - look for every method we call
foreach (Instruction ins in method.Body.Instructions) {
switch (ins.OpCode.Code) {
case Code.Call:
case Code.Callvirt:
MethodDefinition callee = (ins.Operand as MethodDefinition);
if (callee == null)
continue;
// 4 - and if it has security, ensure we don't reduce it's strength
if (callee.HasSecurityDeclarations && !Check (method, callee)) {
Runner.Report (method, ins, Severity.High, Confidence.High);
}
break;
}
}
return Runner.CurrentRuleResult;
}
}
}
| 35.264151 | 135 | 0.714999 | [
"MIT"
] | VnceGd/CS451_Checkers | dev/unity-gendarme/gendarme/rules/Gendarme.Rules.Security.Cas/DoNotExposeMethodsProtectedByLinkDemandRule.cs | 5,607 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Sniper.Tests.Integration.Helpers
{
public static class RepositorySetupHelper
{
public static async Task<TreeResponse> CreateTree(this IGitHubClient client, Repository repository, IEnumerable<KeyValuePair<string, string>> treeContents)
{
var collection = new List<NewTreeItem>();
foreach (var c in treeContents)
{
var baselineBlob = new NewBlob
{
Content = c.Value,
Encoding = EncodingType.Utf8
};
var baselineBlobResult = await client.Git.Blob.Create(repository.Owner.Login, repository.Name, baselineBlob);
collection.Add(new NewTreeItem
{
Type = TreeType.Blob,
Mode = FileMode.File,
Path = c.Key,
Sha = baselineBlobResult.Sha
});
}
var newTree = new NewTree();
foreach (var item in collection)
{
newTree.Tree.Add(item);
}
return await client.Git.Tree.Create(repository.Owner.Login, repository.Name, newTree);
}
public static async Task<Commit> CreateCommit(this IGitHubClient client, Repository repository, string message, string sha, string parent)
{
var newCommit = new NewCommit(message, sha, parent);
return await client.Git.Commit.Create(repository.Owner.Login, repository.Name, newCommit);
}
public static async Task<Reference> CreateTheWorld(this IGitHubClient client, Repository repository)
{
var master = await client.Git.Reference.Get(repository.Owner.Login, repository.Name, "heads/master");
// create new commit for master branch
var newMasterTree = await client.CreateTree(repository, new Dictionary<string, string> { { "README.md", "Hello World!" } });
var newMaster = await client.CreateCommit(repository, "baseline for pull request", newMasterTree.Sha, master.Object.Sha);
// update master
await client.Git.Reference.Update(repository.Owner.Login, repository.Name, "heads/master", new ReferenceUpdate(newMaster.Sha));
// create new commit for feature branch
var featureBranchTree = await client.CreateTree(repository, new Dictionary<string, string> { { "README.md", "I am overwriting this blob with something new" } });
var featureBranchCommit = await client.CreateCommit(repository, "this is the commit to merge into the pull request", featureBranchTree.Sha, newMaster.Sha);
// create branch
return await client.Git.Reference.Create(repository.Owner.Login, repository.Name, new NewReference("refs/heads/my-branch", featureBranchCommit.Sha));
}
}
}
| 45.353846 | 173 | 0.625848 | [
"MIT"
] | amenkes/sniper | Sniper.Tests.Integration/Helpers/RepositorySetupHelper.cs | 2,950 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.