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 |
|---|---|---|---|---|---|---|---|---|
using Newtonsoft.Json.Linq;
namespace SapphireDb.Command.Create
{
public class CreateCommand : CollectionCommandBase
{
public JObject Value { get; set; }
}
}
| 18 | 54 | 0.688889 | [
"MIT"
] | greenapp-debug/SapphireDb | SapphireDb/Command/Create/CreateCommand.cs | 182 | C# |
//using Plugin.Settings;
//using Plugin.Settings.Abstractions;
namespace DPG
{
/// <summary>
/// This is the Settings static class that can be used in your Core solution or in any
/// of your client applications. All settings are laid out the same exact way with getters
/// and setters.
/// </summary>
public static class Settings
{
/*
private static ISettings AppSettings {
get
{
return CrossSettings.Current;
}
}
*/
#region Setting Constants
const string UserIdKey = "userid";
static readonly string UserIdDefault = string.Empty;
const string AuthTokenKey = "authtoken";
static readonly string AuthTokenDefault = string.Empty;
#endregion
/*
public static string AuthToken
{
get
{
return AppSettings.GetValueOrDefault(AuthTokenKey, AuthTokenDefault);
}
set
{
AppSettings.AddOrUpdateValue(AuthTokenKey, value);
}
}
*/
//public static bool IsLoggedIn => !string.IsNullOrWhiteSpace(UserId);
/*
public static string UserId
{
get
{
return AppSettings.GetValueOrDefault(UserIdKey, UserIdDefault);
}
set
{
AppSettings.AddOrUpdateValue(UserIdKey, value);
}
}
*/
}
}
| 25.45 | 94 | 0.531762 | [
"MIT"
] | lukasreuter/DPG-App | DPG/Helpers/Settings.cs | 1,529 | C# |
using Core.Domain.Validations;
using Movimentacoes.Domain.Contas.Repository;
namespace Movimentacoes.Domain.Transferencias.Specifications
{
public class ContaOrigemDevePossuirSaldoDisponivelSpecification : DomainSpecification<Transferencia>
{
private readonly IContaRepository _contaRepository;
public ContaOrigemDevePossuirSaldoDisponivelSpecification(Transferencia entidade, IContaRepository contaRepository) : base(entidade)
{
_contaRepository = contaRepository;
}
public override bool IsValid()
{
var conta = _contaRepository.ObterPorId(_entidade.ContaOrigem.Id);
if (conta == null)
return false;
return conta.SaldoDisponivel >= _entidade.Valor;
}
}
}
| 30.538462 | 140 | 0.700252 | [
"MIT"
] | alexandrebeato/bankflix | server/src/Movimentacoes.Domain/Transferencias/Specifications/ContaOrigemDevePossuirSaldoDisponivelSpecification.cs | 796 | C# |
// ******************************************************************
// /\ /| @file SiteFactionWarContention.cs
// \ V/ @brief 派系争夺战场地
// | "") @author Shadowrabbit, yingtu0401@gmail.com
// / |
// / \\ @Modified 2021-06-24 09:14:47
// *(__\_\ @Copyright Copyright (c) 2021, Shadowrabbit
// ******************************************************************
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using RimWorld;
using RimWorld.Planet;
using Verse;
using Verse.AI.Group;
namespace SR.ModRimWorld.FactionalWar
{
[UsedImplicitly]
public class SiteFactionWarContention : Site
{
private readonly IntRange _factionPoints = new IntRange(3000, 5000);
private const int TimeOutTick = 90000;
private const int Radius = 8;
/// <summary>
/// 生成时回调
/// </summary>
public override void SpawnSetup()
{
base.SpawnSetup();
var comp = GetComponent<TimeoutComp>();
if (comp == null)
{
Log.Error("[SR.ModRimWorld.FactionalWar]can't find TimeoutComp in SiteFactionWarContention");
return;
}
comp.StartTimeout(TimeOutTick);
}
/// <summary>
/// 生成地图后回调
/// </summary>
public override void PostMapGenerate()
{
bool Validator(Faction faction) =>
(faction.def.techLevel >= TechLevel.Industrial && faction.HostileTo(Faction.OfPlayer));
//生成两个相互敌对的派系 设置集群AI互相攻击并争夺资源
FactionUtil.GetHostileFactionPair(out var faction1, out var faction2, _factionPoints.min,
PawnGroupKindDefOf.Combat,
Find.FactionManager.AllFactionsVisible.ToList(), Validator);
if (faction1 == null || faction2 == null)
{
return;
}
//创建派系1的角色 空投到地图中心
var incidentParms1 = new IncidentParms
{points = _factionPoints.RandomInRange, faction = faction1, target = Map};
var pawnGroupMakerParms1 =
IncidentParmsUtility.GetDefaultPawnGroupMakerParms(PawnGroupKindDefOf.Combat, incidentParms1);
var pawnList1 = PawnGroupMakerUtility.GeneratePawns(pawnGroupMakerParms1);
PawnSpawnUtil.SpawnPawns(pawnList1, incidentParms1, Map, Radius);
ResolveLordJob(pawnList1, faction1);
//创建派系2的角色 空投到地图中心
var incidentParms2 = new IncidentParms
{points = 2 * _factionPoints.RandomInRange, faction = faction2, target = Map};
var pawnGroupMakerParms2 =
IncidentParmsUtility.GetDefaultPawnGroupMakerParms(PawnGroupKindDefOf.Combat, incidentParms2);
var pawnList2 = PawnGroupMakerUtility.GeneratePawns(pawnGroupMakerParms2);
PawnSpawnUtil.SpawnPawns(pawnList2, incidentParms2, Map, Radius);
ResolveLordJob(pawnList2, faction2);
}
/// <summary>
/// 创建集群AI
/// </summary>
/// <param name="pawns"></param>
/// <param name="faction"></param>
private void ResolveLordJob(IEnumerable<Pawn> pawns, Faction faction)
{
var lordJobFactionContention = new LordJobFactionContention(Map.Center);
LordMaker.MakeNewLord(faction, lordJobFactionContention, Map, pawns);
}
}
} | 39.337079 | 110 | 0.574407 | [
"Apache-2.0"
] | Proxyer/ModRimWorldFactionalWar | 1.2/Source/ModRimworldFactionalWar/WorldObject/Site/SiteFactionWarContention.cs | 3,653 | C# |
// <auto-generated>
// 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.
//
// For documentation on code generator please visit
// https://aka.ms/nrp-code-generation
// Please contact wanrpdev@microsoft.com if you need to make changes to this file.
// </auto-generated>
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Management.Network.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.Remove, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "LoadBalancerBackendAddressPoolConfig", SupportsShouldProcess = true), OutputType(typeof(PSLoadBalancer))]
public partial class RemoveAzureRmLoadBalancerBackendAddressPoolConfigCommand : NetworkBaseCmdlet
{
[Parameter(
Mandatory = true,
HelpMessage = "The reference of the load balancer resource.",
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
public PSLoadBalancer LoadBalancer { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "The Name of backend address pool")]
public string Name { get; set; }
public override void Execute()
{
// BackendAddressPools
if (this.LoadBalancer.BackendAddressPools == null)
{
WriteObject(this.LoadBalancer);
return;
}
var vBackendAddressPools = this.LoadBalancer.BackendAddressPools.SingleOrDefault
(e =>
string.Equals(e.Name, this.Name, System.StringComparison.CurrentCultureIgnoreCase)
);
if (vBackendAddressPools != null)
{
this.LoadBalancer.BackendAddressPools.Remove(vBackendAddressPools);
}
if (this.LoadBalancer.BackendAddressPools.Count == 0)
{
this.LoadBalancer.BackendAddressPools = null;
}
WriteObject(this.LoadBalancer, true);
}
}
}
| 36.9875 | 195 | 0.652585 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Network/Network/Generated/LoadBalancer/BackendAddressPool/RemoveAzureRmLoadBalancerBackendAddressPoolConfigCommand.cs | 2,880 | C# |
public class Solution {
public int BulbSwitch(int n) {
return (int)Math.Sqrt(n);
}
} | 20 | 34 | 0.6 | [
"MIT"
] | webigboss/Leetcode | 319. Bulb Switcher/319_Original.cs | 100 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace GuildLeader
{
public class Raid
{
public Raid()
{
Bosses = new List<Boss>();
}
public List<Boss> Bosses { get; set; }
}
}
| 16.0625 | 46 | 0.55642 | [
"MIT"
] | NevermoreDCE/GuildLeader | GuildLeader/GuildLeader/Raid.cs | 259 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public class ApplyStorageRecommendationResult : DynamicData
{
protected ManagedObjectReference _vm;
protected ApplyStorageRecommendationResult_LinkedView _linkedView;
public ManagedObjectReference Vm
{
get
{
return this._vm;
}
set
{
this._vm = value;
}
}
public ApplyStorageRecommendationResult_LinkedView LinkedView
{
get
{
return this._linkedView;
}
}
}
}
| 17.185185 | 68 | 0.726293 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/A/ApplyStorageRecommendationResult.cs | 464 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V6301 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")]
public partial class QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId : II {
private static System.Xml.Serialization.XmlSerializer serializer;
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId obj, out System.Exception exception) {
exception = null;
obj = default(QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId obj, out System.Exception exception) {
exception = null;
obj = default(QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId object
/// </summary>
public virtual QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId Clone() {
return ((QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId)(this.MemberwiseClone()));
}
#endregion
}
}
| 49.708995 | 1,358 | 0.619372 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V6301/Generated/QUPA_IN000014UK01MCCI_MT010101UK12MessageInteractionId.cs | 9,395 | C# |
using ElectronicObserver.Notifier;
using ElectronicObserver.Observer;
using ElectronicObserver.Resource;
using ElectronicObserver.Utility;
using ElectronicObserver.Utility.Storage;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ElectronicObserver.Window.Dialog
{
public partial class DialogConfiguration : Form
{
/// <summary> 司令部「任意アイテム表示」から除外するアイテムのIDリスト </summary>
private readonly HashSet<int> IgnoredItems = new HashSet<int>() { 1, 2, 3, 4, 50, 51, 66, 67, 69 };
private System.Windows.Forms.Control _UIControl;
private Dictionary<SyncBGMPlayer.SoundHandleID, SyncBGMPlayer.SoundHandle> BGMHandles;
private DateTime _shownTime;
private double _playTimeCache;
public DialogConfiguration()
{
InitializeComponent();
_shownTime = DateTime.Now;
}
public DialogConfiguration(Configuration.ConfigurationData config)
: this()
{
FromConfiguration(config);
}
private void Connection_SaveReceivedData_CheckedChanged(object sender, EventArgs e)
{
Connection_PanelSaveData.Enabled = Connection_SaveReceivedData.Checked;
}
private void Connection_SaveDataPath_TextChanged(object sender, EventArgs e)
{
if (Directory.Exists(Connection_SaveDataPath.Text))
{
Connection_SaveDataPath.BackColor = SystemColors.Window;
ToolTipInfo.SetToolTip(Connection_SaveDataPath, null);
}
else
{
Connection_SaveDataPath.BackColor = Color.MistyRose;
ToolTipInfo.SetToolTip(Connection_SaveDataPath, "指定されたフォルダは存在しません。");
}
}
/// <summary>
/// パラメータの更新をUIに適用します。
/// </summary>
internal void UpdateParameter()
{
Connection_SaveReceivedData_CheckedChanged(null, new EventArgs());
Connection_SaveDataPath_TextChanged(null, new EventArgs());
Debug_EnableDebugMenu_CheckedChanged(null, new EventArgs());
FormFleet_FixShipNameWidth_CheckedChanged(null, new EventArgs());
}
private void Connection_SaveDataPathSearch_Click(object sender, EventArgs e)
{
Connection_SaveDataPath.Text = PathHelper.ProcessFolderBrowserDialog(Connection_SaveDataPath.Text, FolderBrowser);
}
private void UI_MainFontSelect_Click(object sender, EventArgs e)
{
FontSelector.Font = UI_MainFont.Font;
if (FontSelector.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
SerializableFont font = new SerializableFont(FontSelector.Font);
UI_MainFont.Text = font.SerializeFontAttribute;
UI_MainFont.BackColor = SystemColors.Window;
UI_RenderingTest.MainFont = font.FontData;
}
}
private void UI_SubFontSelect_Click(object sender, EventArgs e)
{
FontSelector.Font = UI_SubFont.Font;
if (FontSelector.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
SerializableFont font = new SerializableFont(FontSelector.Font);
UI_SubFont.Text = font.SerializeFontAttribute;
UI_SubFont.BackColor = SystemColors.Window;
UI_RenderingTest.SubFont = font.FontData;
}
}
private void DialogConfiguration_Load(object sender, EventArgs e)
{
this.Icon = ResourceManager.ImageToIcon(ResourceManager.Instance.Icons.Images[(int)ResourceManager.IconContent.FormConfiguration]);
_UIControl = Owner;
}
private void DialogConfiguration_FormClosed(object sender, FormClosedEventArgs e)
{
ResourceManager.DestroyIcon(Icon);
}
private void UI_MainFontApply_Click(object sender, EventArgs e)
{
UI_MainFont.Font = SerializableFont.StringToFont(UI_MainFont.Text) ?? UI_MainFont.Font;
}
private void UI_SubFontApply_Click(object sender, EventArgs e)
{
UI_SubFont.Font = SerializableFont.StringToFont(UI_SubFont.Text) ?? UI_SubFont.Font;
}
//ui
private void Connection_OutputConnectionScript_Click(object sender, EventArgs e)
{
string serverAddress = APIObserver.Instance.ServerAddress;
if (serverAddress == null)
{
MessageBox.Show("艦これに接続してから操作してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
using (var dialog = new SaveFileDialog())
{
dialog.Filter = "Proxy Script|*.pac|File|*";
dialog.Title = "自動プロキシ設定スクリプトを保存する";
dialog.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
dialog.FileName = System.IO.Directory.GetCurrentDirectory() + "\\proxy.pac";
if (dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
try
{
using (StreamWriter sw = new StreamWriter(dialog.FileName))
{
sw.WriteLine("function FindProxyForURL(url, host) {");
sw.WriteLine(" if (/^" + serverAddress.Replace(".", @"\.") + "/.test(host)) {");
sw.WriteLine(" return \"PROXY localhost:{0}; DIRECT\";", (int)Connection_Port.Value);
sw.WriteLine(" }");
sw.WriteLine(" return \"DIRECT\";");
sw.WriteLine("}");
}
Clipboard.SetData(DataFormats.StringFormat, "file:///" + dialog.FileName.Replace('\\', '/'));
MessageBox.Show("自動プロキシ設定スクリプトを保存し、設定用URLをクリップボードにコピーしました。\r\n所定の位置に貼り付けてください。",
"作成完了", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
Utility.ErrorReporter.SendErrorReport(ex, "自動プロキシ設定スクリプトの保存に失敗しました。");
MessageBox.Show("自動プロキシ設定スクリプトの保存に失敗しました。\r\n" + ex.Message, "エラー",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void Notification_Expedition_Click(object sender, EventArgs e)
{
using (var dialog = new DialogConfigurationNotifier(NotifierManager.Instance.Expedition))
{
dialog.ShowDialog(this);
}
}
private void Notification_Construction_Click(object sender, EventArgs e)
{
using (var dialog = new DialogConfigurationNotifier(NotifierManager.Instance.Construction))
{
dialog.ShowDialog(this);
}
}
private void Notification_Repair_Click(object sender, EventArgs e)
{
using (var dialog = new DialogConfigurationNotifier(NotifierManager.Instance.Repair))
{
dialog.ShowDialog(this);
}
}
private void Notification_Condition_Click(object sender, EventArgs e)
{
using (var dialog = new DialogConfigurationNotifier(NotifierManager.Instance.Condition))
{
dialog.ShowDialog(this);
}
}
private void Notification_Damage_Click(object sender, EventArgs e)
{
using (var dialog = new DialogConfigurationNotifier(NotifierManager.Instance.Damage))
{
dialog.ShowDialog(this);
}
}
private void Notification_AnchorageRepair_Click(object sender, EventArgs e)
{
using (var dialog = new DialogConfigurationNotifier(NotifierManager.Instance.AnchorageRepair))
{
dialog.ShowDialog(this);
}
}
private void Life_LayoutFilePathSearch_Click(object sender, EventArgs e)
{
Life_LayoutFilePath.Text = PathHelper.ProcessOpenFileDialog(Life_LayoutFilePath.Text, LayoutFileBrowser);
}
private void Debug_APIListPathSearch_Click(object sender, EventArgs e)
{
Debug_APIListPath.Text = PathHelper.ProcessOpenFileDialog(Debug_APIListPath.Text, APIListBrowser);
}
private void Debug_EnableDebugMenu_CheckedChanged(object sender, EventArgs e)
{
Debug_SealingPanel.Visible =
Connection_UpstreamProxyAddress.Visible =
Connection_DownstreamProxy.Visible =
Connection_DownstreamProxyLabel.Visible =
SubWindow_Json_SealingPanel.Visible =
Debug_EnableDebugMenu.Checked;
}
private void FormBrowser_ScreenShotPathSearch_Click(object sender, EventArgs e)
{
FormBrowser_ScreenShotPath.Text = PathHelper.ProcessFolderBrowserDialog(FormBrowser_ScreenShotPath.Text, FolderBrowser);
}
/// <summary>
/// 設定からUIを初期化します。
/// </summary>
public void FromConfiguration(Configuration.ConfigurationData config)
{
//[通信]
Connection_Port.Value = config.Connection.Port;
Connection_SaveReceivedData.Checked = config.Connection.SaveReceivedData;
Connection_SaveDataPath.Text = config.Connection.SaveDataPath;
Connection_SaveRequest.Checked = config.Connection.SaveRequest;
Connection_SaveResponse.Checked = config.Connection.SaveResponse;
Connection_SaveOtherFile.Checked = config.Connection.SaveOtherFile;
Connection_ApplyVersion.Checked = config.Connection.ApplyVersion;
Connection_RegisterAsSystemProxy.Checked = config.Connection.RegisterAsSystemProxy;
Connection_UseUpstreamProxy.Checked = config.Connection.UseUpstreamProxy;
Connection_UpstreamProxyPort.Value = config.Connection.UpstreamProxyPort;
Connection_UpstreamProxyAddress.Text = config.Connection.UpstreamProxyAddress;
Connection_UseSystemProxy.Checked = config.Connection.UseSystemProxy;
Connection_DownstreamProxy.Text = config.Connection.DownstreamProxy;
//[UI]
UI_MainFont.Text = config.UI.MainFont.SerializeFontAttribute;
UI_SubFont.Text = config.UI.SubFont.SerializeFontAttribute;
UI_BarColorMorphing.Checked = config.UI.BarColorMorphing;
UI_IsLayoutFixed.Checked = config.UI.IsLayoutFixed;
{
UI_RenderingTest.MainFont = config.UI.MainFont.FontData;
UI_RenderingTest.SubFont = config.UI.SubFont.FontData;
UI_RenderingTest.HPBar.ColorMorphing = config.UI.BarColorMorphing;
UI_RenderingTest.HPBar.SetBarColorScheme(config.UI.BarColorScheme.Select(c => c.ColorData).ToArray());
UI_RenderingTestChanger.Maximum = UI_RenderingTest.MaximumValue;
UI_RenderingTestChanger.Value = UI_RenderingTest.Value;
}
//[ログ]
Log_LogLevel.Value = config.Log.LogLevel;
Log_SaveLogFlag.Checked = config.Log.SaveLogFlag;
Log_SaveErrorReport.Checked = config.Log.SaveErrorReport;
Log_FileEncodingID.SelectedIndex = config.Log.FileEncodingID;
Log_ShowSpoiler.Checked = config.Log.ShowSpoiler;
_playTimeCache = config.Log.PlayTime;
UpdatePlayTime();
Log_SaveBattleLog.Checked = config.Log.SaveBattleLog;
Log_SaveLogImmediately.Checked = config.Log.SaveLogImmediately;
//[動作]
Control_ConditionBorder.Value = config.Control.ConditionBorder;
Control_RecordAutoSaving.SelectedIndex = config.Control.RecordAutoSaving;
Control_UseSystemVolume.Checked = config.Control.UseSystemVolume;
Control_PowerEngagementForm.SelectedIndex = config.Control.PowerEngagementForm - 1;
Control_ShowSallyAreaAlertDialog.Checked = config.Control.ShowSallyAreaAlertDialog;
//[デバッグ]
Debug_EnableDebugMenu.Checked = config.Debug.EnableDebugMenu;
Debug_LoadAPIListOnLoad.Checked = config.Debug.LoadAPIListOnLoad;
Debug_APIListPath.Text = config.Debug.APIListPath;
Debug_AlertOnError.Checked = config.Debug.AlertOnError;
//[起動と終了]
Life_ConfirmOnClosing.Checked = config.Life.ConfirmOnClosing;
Life_TopMost.Checked = this.TopMost = config.Life.TopMost; //メインウィンドウに隠れないように
Life_LayoutFilePath.Text = config.Life.LayoutFilePath;
Life_CheckUpdateInformation.Checked = config.Life.CheckUpdateInformation;
Life_ShowStatusBar.Checked = config.Life.ShowStatusBar;
Life_ClockFormat.SelectedIndex = config.Life.ClockFormat;
Life_LockLayout.Checked = config.Life.LockLayout;
Life_CanCloseFloatWindowInLock.Checked = config.Life.CanCloseFloatWindowInLock;
//[サブウィンドウ]
FormArsenal_ShowShipName.Checked = config.FormArsenal.ShowShipName;
FormArsenal_BlinkAtCompletion.Checked = config.FormArsenal.BlinkAtCompletion;
FormArsenal_MaxShipNameWidth.Value = config.FormArsenal.MaxShipNameWidth;
FormDock_BlinkAtCompletion.Checked = config.FormDock.BlinkAtCompletion;
FormDock_MaxShipNameWidth.Value = config.FormDock.MaxShipNameWidth;
FormFleet_ShowAircraft.Checked = config.FormFleet.ShowAircraft;
FormFleet_SearchingAbilityMethod.SelectedIndex = config.FormFleet.SearchingAbilityMethod;
FormFleet_IsScrollable.Checked = config.FormFleet.IsScrollable;
FormFleet_FixShipNameWidth.Checked = config.FormFleet.FixShipNameWidth;
FormFleet_ShortenHPBar.Checked = config.FormFleet.ShortenHPBar;
FormFleet_ShowNextExp.Checked = config.FormFleet.ShowNextExp;
FormFleet_EquipmentLevelVisibility.SelectedIndex = (int)config.FormFleet.EquipmentLevelVisibility;
FormFleet_ShowAircraftLevelByNumber.Checked = config.FormFleet.ShowAircraftLevelByNumber;
FormFleet_AirSuperiorityMethod.SelectedIndex = config.FormFleet.AirSuperiorityMethod;
FormFleet_ShowAnchorageRepairingTimer.Checked = config.FormFleet.ShowAnchorageRepairingTimer;
FormFleet_BlinkAtCompletion.Checked = config.FormFleet.BlinkAtCompletion;
FormFleet_ShowConditionIcon.Checked = config.FormFleet.ShowConditionIcon;
FormFleet_FixedShipNameWidth.Value = config.FormFleet.FixedShipNameWidth;
FormFleet_ShowAirSuperiorityRange.Checked = config.FormFleet.ShowAirSuperiorityRange;
FormFleet_ReflectAnchorageRepairHealing.Checked = config.FormFleet.ReflectAnchorageRepairHealing;
FormFleet_BlinkAtDamaged.Checked = config.FormFleet.BlinkAtDamaged;
FormFleet_EmphasizesSubFleetInPort.Checked = config.FormFleet.EmphasizesSubFleetInPort;
FormFleet_FleetStateDisplayMode.SelectedIndex = config.FormFleet.FleetStateDisplayMode;
FormHeadquarters_BlinkAtMaximum.Checked = config.FormHeadquarters.BlinkAtMaximum;
FormHeadquarters_Visibility.Items.Clear();
FormHeadquarters_Visibility.Items.AddRange(FormHeadquarters.GetItemNames().ToArray());
FormHeadquarters.CheckVisibilityConfiguration();
for (int i = 0; i < FormHeadquarters_Visibility.Items.Count; i++)
{
FormHeadquarters_Visibility.SetItemChecked(i, config.FormHeadquarters.Visibility.List[i]);
}
{
FormHeadquarters_DisplayUseItemID.Items.AddRange(
ElectronicObserver.Data.KCDatabase.Instance.MasterUseItems.Values
.Where(i => i.Name.Length > 0 && i.Description.Length > 0 && !IgnoredItems.Contains(i.ItemID))
.Select(i => i.Name).ToArray());
var item = ElectronicObserver.Data.KCDatabase.Instance.MasterUseItems[config.FormHeadquarters.DisplayUseItemID];
if (item != null)
{
FormHeadquarters_DisplayUseItemID.Text = item.Name;
}
else
{
FormHeadquarters_DisplayUseItemID.Text = config.FormHeadquarters.DisplayUseItemID.ToString();
}
}
FormQuest_ShowRunningOnly.Checked = config.FormQuest.ShowRunningOnly;
FormQuest_ShowOnce.Checked = config.FormQuest.ShowOnce;
FormQuest_ShowDaily.Checked = config.FormQuest.ShowDaily;
FormQuest_ShowWeekly.Checked = config.FormQuest.ShowWeekly;
FormQuest_ShowMonthly.Checked = config.FormQuest.ShowMonthly;
FormQuest_ShowOther.Checked = config.FormQuest.ShowOther;
FormQuest_ProgressAutoSaving.SelectedIndex = config.FormQuest.ProgressAutoSaving;
FormQuest_AllowUserToSortRows.Checked = config.FormQuest.AllowUserToSortRows;
FormShipGroup_AutoUpdate.Checked = config.FormShipGroup.AutoUpdate;
FormShipGroup_ShowStatusBar.Checked = config.FormShipGroup.ShowStatusBar;
FormShipGroup_ShipNameSortMethod.SelectedIndex = config.FormShipGroup.ShipNameSortMethod;
FormBattle_IsScrollable.Checked = config.FormBattle.IsScrollable;
FormBattle_HideDuringBattle.Checked = config.FormBattle.HideDuringBattle;
FormBattle_ShowHPBar.Checked = config.FormBattle.ShowHPBar;
FormBattle_ShowShipTypeInHPBar.Checked = config.FormBattle.ShowShipTypeInHPBar;
FormBattle_Display7thAsSingleLine.Checked = config.FormBattle.Display7thAsSingleLine;
FormBrowser_IsEnabled.Checked = config.FormBrowser.IsEnabled;
FormBrowser_ZoomRate.Value = (decimal)Math.Min(Math.Max(config.FormBrowser.ZoomRate * 100, 10), 1000);
FormBrowser_ZoomFit.Checked = config.FormBrowser.ZoomFit;
FormBrowser_LogInPageURL.Text = config.FormBrowser.LogInPageURL;
FormBrowser_ScreenShotFormat_JPEG.Checked = config.FormBrowser.ScreenShotFormat == 1;
FormBrowser_ScreenShotFormat_PNG.Checked = config.FormBrowser.ScreenShotFormat == 2;
FormBrowser_ScreenShotPath.Text = config.FormBrowser.ScreenShotPath;
FormBrowser_ConfirmAtRefresh.Checked = config.FormBrowser.ConfirmAtRefresh;
FormBrowser_AppliesStyleSheet.Checked = config.FormBrowser.AppliesStyleSheet;
FormBrowser_IsDMMreloadDialogDestroyable.Checked = config.FormBrowser.IsDMMreloadDialogDestroyable;
FormBrowser_ScreenShotFormat_AvoidTwitterDeterioration.Checked = config.FormBrowser.AvoidTwitterDeterioration;
FormBrowser_ScreenShotSaveMode.SelectedIndex = config.FormBrowser.ScreenShotSaveMode - 1;
FormBrowser_HardwareAccelerationEnabled.Checked = config.FormBrowser.HardwareAccelerationEnabled;
FormBrowser_PreserveDrawingBuffer.Checked = config.FormBrowser.PreserveDrawingBuffer;
FormBrowser_ForceColorProfile.Checked = config.FormBrowser.ForceColorProfile;
if (!config.FormBrowser.IsToolMenuVisible)
FormBrowser_ToolMenuDockStyle.SelectedIndex = 4;
else
FormBrowser_ToolMenuDockStyle.SelectedIndex = (int)config.FormBrowser.ToolMenuDockStyle - 1;
FormCompass_CandidateDisplayCount.Value = config.FormCompass.CandidateDisplayCount;
FormCompass_IsScrollable.Checked = config.FormCompass.IsScrollable;
FormCompass_MaxShipNameWidth.Value = config.FormCompass.MaxShipNameWidth;
FormJson_AutoUpdate.Checked = config.FormJson.AutoUpdate;
FormJson_UpdatesTree.Checked = config.FormJson.UpdatesTree;
FormJson_AutoUpdateFilter.Text = config.FormJson.AutoUpdateFilter;
FormBaseAirCorps_ShowEventMapOnly.Checked = config.FormBaseAirCorps.ShowEventMapOnly;
//[通知]
{
bool issilenced = NotifierManager.Instance.GetNotifiers().All(no => no.IsSilenced);
Notification_Silencio.Checked = issilenced;
setSilencioConfig(issilenced);
}
//[BGM]
BGMPlayer_Enabled.Checked = config.BGMPlayer.Enabled;
BGMHandles = config.BGMPlayer.Handles.ToDictionary(h => h.HandleID);
BGMPlayer_SyncBrowserMute.Checked = config.BGMPlayer.SyncBrowserMute;
UpdateBGMPlayerUI();
//finalize
UpdateParameter();
Connection_UseSystemProxy.Checked = true;
Connection_UseSystemProxy.Enabled = false;
}
/// <summary>
/// UIをもとに設定を適用します。
/// </summary>
public void ToConfiguration(Configuration.ConfigurationData config)
{
//[通信]
{
bool changed = false;
changed |= config.Connection.Port != (ushort)Connection_Port.Value;
config.Connection.Port = (ushort)Connection_Port.Value;
config.Connection.SaveReceivedData = Connection_SaveReceivedData.Checked;
config.Connection.SaveDataPath = Connection_SaveDataPath.Text.Trim(@"\ """.ToCharArray());
config.Connection.SaveRequest = Connection_SaveRequest.Checked;
config.Connection.SaveResponse = Connection_SaveResponse.Checked;
config.Connection.SaveOtherFile = Connection_SaveOtherFile.Checked;
config.Connection.ApplyVersion = Connection_ApplyVersion.Checked;
changed |= config.Connection.RegisterAsSystemProxy != Connection_RegisterAsSystemProxy.Checked;
config.Connection.RegisterAsSystemProxy = Connection_RegisterAsSystemProxy.Checked;
changed |= config.Connection.UseUpstreamProxy != Connection_UseUpstreamProxy.Checked;
config.Connection.UseUpstreamProxy = Connection_UseUpstreamProxy.Checked;
changed |= config.Connection.UpstreamProxyPort != (ushort)Connection_UpstreamProxyPort.Value;
config.Connection.UpstreamProxyPort = (ushort)Connection_UpstreamProxyPort.Value;
changed |= config.Connection.UpstreamProxyAddress != Connection_UpstreamProxyAddress.Text;
config.Connection.UpstreamProxyAddress = Connection_UpstreamProxyAddress.Text;
changed |= config.Connection.UseSystemProxy != Connection_UseSystemProxy.Checked;
config.Connection.UseSystemProxy = Connection_UseSystemProxy.Checked;
changed |= config.Connection.DownstreamProxy != Connection_DownstreamProxy.Text;
config.Connection.DownstreamProxy = Connection_DownstreamProxy.Text;
if (changed)
{
APIObserver.Instance.Start(config.Connection.Port, _UIControl);
}
}
//[UI]
{
var newfont = SerializableFont.StringToFont(UI_MainFont.Text, true);
if (newfont != null)
config.UI.MainFont = newfont;
}
{
var newfont = SerializableFont.StringToFont(UI_SubFont.Text, true);
if (newfont != null)
config.UI.SubFont = newfont;
}
config.UI.BarColorMorphing = UI_BarColorMorphing.Checked;
config.UI.IsLayoutFixed = UI_IsLayoutFixed.Checked;
//[ログ]
config.Log.LogLevel = (int)Log_LogLevel.Value;
config.Log.SaveLogFlag = Log_SaveLogFlag.Checked;
config.Log.SaveErrorReport = Log_SaveErrorReport.Checked;
config.Log.FileEncodingID = Log_FileEncodingID.SelectedIndex;
config.Log.ShowSpoiler = Log_ShowSpoiler.Checked;
config.Log.SaveBattleLog = Log_SaveBattleLog.Checked;
config.Log.SaveLogImmediately = Log_SaveLogImmediately.Checked;
//[動作]
config.Control.ConditionBorder = (int)Control_ConditionBorder.Value;
config.Control.RecordAutoSaving = Control_RecordAutoSaving.SelectedIndex;
config.Control.UseSystemVolume = Control_UseSystemVolume.Checked;
config.Control.PowerEngagementForm = Control_PowerEngagementForm.SelectedIndex + 1;
config.Control.ShowSallyAreaAlertDialog = Control_ShowSallyAreaAlertDialog.Checked;
//[デバッグ]
config.Debug.EnableDebugMenu = Debug_EnableDebugMenu.Checked;
config.Debug.LoadAPIListOnLoad = Debug_LoadAPIListOnLoad.Checked;
config.Debug.APIListPath = Debug_APIListPath.Text;
config.Debug.AlertOnError = Debug_AlertOnError.Checked;
//[起動と終了]
config.Life.ConfirmOnClosing = Life_ConfirmOnClosing.Checked;
config.Life.TopMost = Life_TopMost.Checked;
config.Life.LayoutFilePath = Life_LayoutFilePath.Text;
config.Life.CheckUpdateInformation = Life_CheckUpdateInformation.Checked;
config.Life.ShowStatusBar = Life_ShowStatusBar.Checked;
config.Life.ClockFormat = Life_ClockFormat.SelectedIndex;
config.Life.LockLayout = Life_LockLayout.Checked;
config.Life.CanCloseFloatWindowInLock = Life_CanCloseFloatWindowInLock.Checked;
//[サブウィンドウ]
config.FormArsenal.ShowShipName = FormArsenal_ShowShipName.Checked;
config.FormArsenal.BlinkAtCompletion = FormArsenal_BlinkAtCompletion.Checked;
config.FormArsenal.MaxShipNameWidth = (int)FormArsenal_MaxShipNameWidth.Value;
config.FormDock.BlinkAtCompletion = FormDock_BlinkAtCompletion.Checked;
config.FormDock.MaxShipNameWidth = (int)FormDock_MaxShipNameWidth.Value;
config.FormFleet.ShowAircraft = FormFleet_ShowAircraft.Checked;
config.FormFleet.SearchingAbilityMethod = FormFleet_SearchingAbilityMethod.SelectedIndex;
config.FormFleet.IsScrollable = FormFleet_IsScrollable.Checked;
config.FormFleet.FixShipNameWidth = FormFleet_FixShipNameWidth.Checked;
config.FormFleet.ShortenHPBar = FormFleet_ShortenHPBar.Checked;
config.FormFleet.ShowNextExp = FormFleet_ShowNextExp.Checked;
config.FormFleet.EquipmentLevelVisibility = (Window.Control.ShipStatusEquipment.LevelVisibilityFlag)FormFleet_EquipmentLevelVisibility.SelectedIndex;
config.FormFleet.ShowAircraftLevelByNumber = FormFleet_ShowAircraftLevelByNumber.Checked;
config.FormFleet.AirSuperiorityMethod = FormFleet_AirSuperiorityMethod.SelectedIndex;
config.FormFleet.ShowAnchorageRepairingTimer = FormFleet_ShowAnchorageRepairingTimer.Checked;
config.FormFleet.BlinkAtCompletion = FormFleet_BlinkAtCompletion.Checked;
config.FormFleet.ShowConditionIcon = FormFleet_ShowConditionIcon.Checked;
config.FormFleet.FixedShipNameWidth = (int)FormFleet_FixedShipNameWidth.Value;
config.FormFleet.ShowAirSuperiorityRange = FormFleet_ShowAirSuperiorityRange.Checked;
config.FormFleet.ReflectAnchorageRepairHealing = FormFleet_ReflectAnchorageRepairHealing.Checked;
config.FormFleet.BlinkAtDamaged = FormFleet_BlinkAtDamaged.Checked;
config.FormFleet.EmphasizesSubFleetInPort = FormFleet_EmphasizesSubFleetInPort.Checked;
config.FormFleet.FleetStateDisplayMode = FormFleet_FleetStateDisplayMode.SelectedIndex;
config.FormHeadquarters.BlinkAtMaximum = FormHeadquarters_BlinkAtMaximum.Checked;
{
var list = new List<bool>();
for (int i = 0; i < FormHeadquarters_Visibility.Items.Count; i++)
list.Add(FormHeadquarters_Visibility.GetItemChecked(i));
config.FormHeadquarters.Visibility.List = list;
}
{
string name = FormHeadquarters_DisplayUseItemID.Text;
if (string.IsNullOrEmpty(name))
{
config.FormHeadquarters.DisplayUseItemID = -1;
}
else
{
var item = ElectronicObserver.Data.KCDatabase.Instance.MasterUseItems.Values.FirstOrDefault(p => p.Name == name);
if (item != null)
{
config.FormHeadquarters.DisplayUseItemID = item.ItemID;
}
else
{
if (int.TryParse(name, out int val))
config.FormHeadquarters.DisplayUseItemID = val;
else
config.FormHeadquarters.DisplayUseItemID = -1;
}
}
}
config.FormQuest.ShowRunningOnly = FormQuest_ShowRunningOnly.Checked;
config.FormQuest.ShowOnce = FormQuest_ShowOnce.Checked;
config.FormQuest.ShowDaily = FormQuest_ShowDaily.Checked;
config.FormQuest.ShowWeekly = FormQuest_ShowWeekly.Checked;
config.FormQuest.ShowMonthly = FormQuest_ShowMonthly.Checked;
config.FormQuest.ShowOther = FormQuest_ShowOther.Checked;
config.FormQuest.ProgressAutoSaving = FormQuest_ProgressAutoSaving.SelectedIndex;
config.FormQuest.AllowUserToSortRows = FormQuest_AllowUserToSortRows.Checked;
config.FormShipGroup.AutoUpdate = FormShipGroup_AutoUpdate.Checked;
config.FormShipGroup.ShowStatusBar = FormShipGroup_ShowStatusBar.Checked;
config.FormShipGroup.ShipNameSortMethod = FormShipGroup_ShipNameSortMethod.SelectedIndex;
config.FormBattle.IsScrollable = FormBattle_IsScrollable.Checked;
config.FormBattle.HideDuringBattle = FormBattle_HideDuringBattle.Checked;
config.FormBattle.ShowHPBar = FormBattle_ShowHPBar.Checked;
config.FormBattle.ShowShipTypeInHPBar = FormBattle_ShowShipTypeInHPBar.Checked;
config.FormBattle.Display7thAsSingleLine = FormBattle_Display7thAsSingleLine.Checked;
config.FormBrowser.IsEnabled = FormBrowser_IsEnabled.Checked;
config.FormBrowser.ZoomRate = (double)FormBrowser_ZoomRate.Value / 100;
config.FormBrowser.ZoomFit = FormBrowser_ZoomFit.Checked;
config.FormBrowser.LogInPageURL = FormBrowser_LogInPageURL.Text;
if (FormBrowser_ScreenShotFormat_JPEG.Checked)
config.FormBrowser.ScreenShotFormat = 1;
else
config.FormBrowser.ScreenShotFormat = 2;
config.FormBrowser.ScreenShotPath = FormBrowser_ScreenShotPath.Text;
config.FormBrowser.ConfirmAtRefresh = FormBrowser_ConfirmAtRefresh.Checked;
config.FormBrowser.AppliesStyleSheet = FormBrowser_AppliesStyleSheet.Checked;
config.FormBrowser.IsDMMreloadDialogDestroyable = FormBrowser_IsDMMreloadDialogDestroyable.Checked;
config.FormBrowser.AvoidTwitterDeterioration = FormBrowser_ScreenShotFormat_AvoidTwitterDeterioration.Checked;
config.FormBrowser.HardwareAccelerationEnabled = FormBrowser_HardwareAccelerationEnabled.Checked;
config.FormBrowser.PreserveDrawingBuffer = FormBrowser_PreserveDrawingBuffer.Checked;
config.FormBrowser.ForceColorProfile = FormBrowser_ForceColorProfile.Checked;
if (FormBrowser_ToolMenuDockStyle.SelectedIndex == 4)
{
config.FormBrowser.IsToolMenuVisible = false;
}
else
{
config.FormBrowser.IsToolMenuVisible = true;
config.FormBrowser.ToolMenuDockStyle = (DockStyle)(FormBrowser_ToolMenuDockStyle.SelectedIndex + 1);
}
config.FormBrowser.ScreenShotSaveMode = FormBrowser_ScreenShotSaveMode.SelectedIndex + 1;
config.FormCompass.CandidateDisplayCount = (int)FormCompass_CandidateDisplayCount.Value;
config.FormCompass.IsScrollable = FormCompass_IsScrollable.Checked;
config.FormCompass.MaxShipNameWidth = (int)FormCompass_MaxShipNameWidth.Value;
config.FormJson.AutoUpdate = FormJson_AutoUpdate.Checked;
config.FormJson.UpdatesTree = FormJson_UpdatesTree.Checked;
config.FormJson.AutoUpdateFilter = FormJson_AutoUpdateFilter.Text;
config.FormBaseAirCorps.ShowEventMapOnly = FormBaseAirCorps_ShowEventMapOnly.Checked;
//[通知]
setSilencioConfig(Notification_Silencio.Checked);
//[BGM]
config.BGMPlayer.Enabled = BGMPlayer_Enabled.Checked;
for (int i = 0; i < BGMPlayer_ControlGrid.Rows.Count; i++)
{
BGMHandles[(SyncBGMPlayer.SoundHandleID)BGMPlayer_ControlGrid[BGMPlayer_ColumnContent.Index, i].Value].Enabled = (bool)BGMPlayer_ControlGrid[BGMPlayer_ColumnEnabled.Index, i].Value;
}
config.BGMPlayer.Handles = new List<SyncBGMPlayer.SoundHandle>(BGMHandles.Values.ToList());
config.BGMPlayer.SyncBrowserMute = BGMPlayer_SyncBrowserMute.Checked;
}
private void UpdateBGMPlayerUI()
{
BGMPlayer_ControlGrid.Rows.Clear();
var rows = new DataGridViewRow[BGMHandles.Count];
int i = 0;
foreach (var h in BGMHandles.Values)
{
var row = new DataGridViewRow();
row.CreateCells(BGMPlayer_ControlGrid);
row.SetValues(h.Enabled, h.HandleID, h.Path);
rows[i] = row;
i++;
}
BGMPlayer_ControlGrid.Rows.AddRange(rows);
BGMPlayer_VolumeAll.Value = (int)BGMHandles.Values.Average(h => h.Volume);
}
// BGMPlayer
private void BGMPlayer_ControlGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == BGMPlayer_ColumnSetting.Index)
{
var handleID = (SyncBGMPlayer.SoundHandleID)BGMPlayer_ControlGrid[BGMPlayer_ColumnContent.Index, e.RowIndex].Value;
using (var dialog = new DialogConfigurationBGMPlayer(BGMHandles[handleID]))
{
if (dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
BGMHandles[handleID] = dialog.ResultHandle;
}
}
UpdateBGMPlayerUI();
}
}
private void BGMPlayer_ControlGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == BGMPlayer_ColumnContent.Index)
{
e.Value = SyncBGMPlayer.SoundHandleIDToString((SyncBGMPlayer.SoundHandleID)e.Value);
e.FormattingApplied = true;
}
}
//for checkbox
private void BGMPlayer_ControlGrid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (BGMPlayer_ControlGrid.Columns[BGMPlayer_ControlGrid.CurrentCellAddress.X] is DataGridViewCheckBoxColumn)
{
if (BGMPlayer_ControlGrid.IsCurrentCellDirty)
{
BGMPlayer_ControlGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
}
private void BGMPlayer_SetVolumeAll_Click(object sender, EventArgs e)
{
if (MessageBox.Show("すべてのBGMに対して音量 " + (int)BGMPlayer_VolumeAll.Value + " を適用します。\r\nよろしいですか?\r\n", "音量一括設定の確認",
MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
{
foreach (var h in BGMHandles.Values)
{
h.Volume = (int)BGMPlayer_VolumeAll.Value;
}
UpdateBGMPlayerUI();
}
}
private void setSilencioConfig(bool silenced)
{
foreach (NotifierBase no in NotifierManager.Instance.GetNotifiers())
{
no.IsSilenced = silenced;
}
}
private void UpdatePlayTime()
{
double elapsed = (DateTime.Now - _shownTime).TotalSeconds;
Log_PlayTime.Text = "プレイ時間: " + ElectronicObserver.Utility.Mathematics.DateTimeHelper.ToTimeElapsedString(TimeSpan.FromSeconds(_playTimeCache + elapsed));
}
private void PlayTimeTimer_Tick(object sender, EventArgs e)
{
UpdatePlayTime();
}
private void FormFleet_FixShipNameWidth_CheckedChanged(object sender, EventArgs e)
{
FormFleet_FixedShipNameWidth.Enabled = FormFleet_FixShipNameWidth.Checked;
}
private void FormBrowser_ScreenShotFormat_PNG_CheckedChanged(object sender, EventArgs e)
{
FormBrowser_ScreenShotFormat_AvoidTwitterDeterioration.Enabled = true;
}
private void FormBrowser_ScreenShotFormat_JPEG_CheckedChanged(object sender, EventArgs e)
{
FormBrowser_ScreenShotFormat_AvoidTwitterDeterioration.Enabled = false;
}
private void UI_MainFont_Validating(object sender, CancelEventArgs e)
{
var newfont = SerializableFont.StringToFont(UI_MainFont.Text, true);
if (newfont != null)
{
UI_RenderingTest.MainFont = newfont;
UI_MainFont.BackColor = SystemColors.Window;
}
else
{
UI_MainFont.BackColor = Color.MistyRose;
}
}
private void UI_SubFont_Validating(object sender, CancelEventArgs e)
{
var newfont = SerializableFont.StringToFont(UI_SubFont.Text, true);
if (newfont != null)
{
UI_RenderingTest.SubFont = newfont;
UI_SubFont.BackColor = SystemColors.Window;
}
else
{
UI_SubFont.BackColor = Color.MistyRose;
}
}
private void UI_BarColorMorphing_CheckedChanged(object sender, EventArgs e)
{
UI_RenderingTest.HPBar.ColorMorphing = UI_BarColorMorphing.Checked;
UI_RenderingTest.Refresh();
}
private void UI_MainFont_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
e.Handled = true;
UI_MainFont_Validating(sender, new CancelEventArgs());
}
}
private void UI_MainFont_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.IsInputKey = true; // AcceptButton の影響を回避する
}
}
private void UI_SubFont_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
e.Handled = true;
UI_SubFont_Validating(sender, new CancelEventArgs());
}
}
private void UI_SubFont_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.IsInputKey = true; // AcceptButton の影響を回避する
}
}
private void UI_RenderingTestChanger_Scroll(object sender, EventArgs e)
{
UI_RenderingTest.Value = UI_RenderingTestChanger.Value;
}
}
}
| 35.863102 | 185 | 0.780896 | [
"MIT"
] | fossabot/ElectronicObserverExtended | ElectronicObserver/Window/Dialog/DialogConfiguration.cs | 34,240 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
class TrackDownloader
{
static void Main()
{
var blackList = Console.ReadLine().Split(' ').ToList();
var fileNames = Console.ReadLine();
var result = new List<string>();
while (fileNames != "end")
{
var count = 0;
for (int i = 0; i < blackList.Count; i++)
{
if (fileNames.Contains(blackList[i]))
{
break;
}
else
{
count++;
}
}
if (count == blackList.Count)
{
result.Add(fileNames);
}
fileNames = Console.ReadLine();
}
result.Sort();
foreach (var fileName in result)
{
Console.WriteLine(fileName);
}
}
}
| 18.86 | 63 | 0.415695 | [
"MIT"
] | Sotirovgym/C---Collections---Exercises | ListExericesesExtended/2. TrackDownloader/TrackDownloader.cs | 945 | C# |
// Lucene version compatibility level 4.8.1
using YAF.Lucene.Net.Analysis.TokenAttributes;
namespace YAF.Lucene.Net.Analysis.De
{
/*
* 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.
*/
/// <summary>
/// A <see cref="TokenFilter"/> that applies <see cref="GermanLightStemmer"/> to stem German
/// words.
/// <para>
/// To prevent terms from being stemmed use an instance of
/// <see cref="Miscellaneous.SetKeywordMarkerFilter"/> or a custom <see cref="TokenFilter"/> that sets
/// the <see cref="KeywordAttribute"/> before this <see cref="TokenStream"/>.
/// </para>
/// </summary>
public sealed class GermanLightStemFilter : TokenFilter
{
private readonly GermanLightStemmer stemmer = new GermanLightStemmer();
private readonly ICharTermAttribute termAtt;
private readonly IKeywordAttribute keywordAttr;
public GermanLightStemFilter(TokenStream input)
: base(input)
{
termAtt = AddAttribute<ICharTermAttribute>();
keywordAttr = AddAttribute<IKeywordAttribute>();
}
public override bool IncrementToken()
{
if (m_input.IncrementToken())
{
if (!keywordAttr.IsKeyword)
{
int newlen = stemmer.Stem(termAtt.Buffer, termAtt.Length);
termAtt.Length = newlen;
}
return true;
}
else
{
return false;
}
}
}
} | 39.064516 | 107 | 0.607349 | [
"Apache-2.0"
] | 10by10pixel/YAFNET | yafsrc/Lucene.Net/Lucene.Net.Analysis.Common/Analysis/De/GermanLightStemFilter.cs | 2,361 | C# |
namespace Charlotte
{
partial class KeyDataDlg
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows フォーム デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(KeyDataDlg));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.txtHash = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txtRaw = new System.Windows.Forms.TextBox();
this.txtIdent = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.btnNew = new System.Windows.Forms.Button();
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnImport = new System.Windows.Forms.Button();
this.btnExport = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.txtHash);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.txtRaw);
this.groupBox1.Controls.Add(this.txtIdent);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.btnNew);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(582, 188);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "鍵";
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(16, 137);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(54, 20);
this.label3.TabIndex = 4;
this.label3.Text = "Hash:";
//
// txtHash
//
this.txtHash.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtHash.Location = new System.Drawing.Point(78, 134);
this.txtHash.Name = "txtHash";
this.txtHash.ReadOnly = true;
this.txtHash.Size = new System.Drawing.Size(376, 27);
this.txtHash.TabIndex = 5;
this.txtHash.Text = "0123456789abcdef0123456789abcdef";
this.txtHash.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtHash_KeyPress);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(16, 65);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(46, 20);
this.label2.TabIndex = 2;
this.label2.Text = "Key:";
//
// txtRaw
//
this.txtRaw.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtRaw.Location = new System.Drawing.Point(78, 62);
this.txtRaw.Multiline = true;
this.txtRaw.Name = "txtRaw";
this.txtRaw.ReadOnly = true;
this.txtRaw.Size = new System.Drawing.Size(486, 66);
this.txtRaw.TabIndex = 3;
this.txtRaw.Text = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0" +
"123456789abcdef0123456789abcdef0123456789abcdef";
this.txtRaw.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtKey_KeyPress);
//
// txtIdent
//
this.txtIdent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtIdent.Location = new System.Drawing.Point(78, 29);
this.txtIdent.Name = "txtIdent";
this.txtIdent.ReadOnly = true;
this.txtIdent.Size = new System.Drawing.Size(486, 27);
this.txtIdent.TabIndex = 1;
this.txtIdent.Text = "UnrealRemoco-Key_0123456789abcdef0123456789abcdef";
this.txtIdent.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtIdent_KeyPress);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(16, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Ident:";
//
// btnNew
//
this.btnNew.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnNew.Location = new System.Drawing.Point(460, 134);
this.btnNew.Name = "btnNew";
this.btnNew.Size = new System.Drawing.Size(116, 48);
this.btnNew.TabIndex = 6;
this.btnNew.Text = "生成";
this.btnNew.UseVisualStyleBackColor = true;
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
//
// btnOk
//
this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOk.Location = new System.Drawing.Point(356, 206);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(116, 48);
this.btnOk.TabIndex = 3;
this.btnOk.Text = "OK";
this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.Location = new System.Drawing.Point(478, 206);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(116, 48);
this.btnCancel.TabIndex = 4;
this.btnCancel.Text = "キャンセル";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnImport
//
this.btnImport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnImport.Location = new System.Drawing.Point(12, 206);
this.btnImport.Name = "btnImport";
this.btnImport.Size = new System.Drawing.Size(116, 48);
this.btnImport.TabIndex = 1;
this.btnImport.Text = "インポート";
this.btnImport.UseVisualStyleBackColor = true;
this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
//
// btnExport
//
this.btnExport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnExport.Location = new System.Drawing.Point(134, 206);
this.btnExport.Name = "btnExport";
this.btnExport.Size = new System.Drawing.Size(116, 48);
this.btnExport.TabIndex = 2;
this.btnExport.Text = "エクスポート";
this.btnExport.UseVisualStyleBackColor = true;
this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
//
// KeyDataDlg
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(606, 266);
this.Controls.Add(this.btnExport);
this.Controls.Add(this.btnImport);
this.Controls.Add(this.btnOk);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.groupBox1);
this.Font = new System.Drawing.Font("メイリオ", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "KeyDataDlg";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "鍵の設定";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.KeyDataDlg_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.KeyDataDlg_FormClosed);
this.Load += new System.EventHandler(this.KeyDataDlg_Load);
this.Shown += new System.EventHandler(this.KeyDataDlg_Shown);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnImport;
private System.Windows.Forms.Button btnExport;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtHash;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtRaw;
private System.Windows.Forms.TextBox txtIdent;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnNew;
}
}
| 42.299145 | 151 | 0.719741 | [
"MIT"
] | stackprobe/UnrealRemoco | UnrealClient/UnrealClient/KeyDataDlg.Designer.cs | 10,226 | C# |
using System;
using FplBot.Core.Helpers;
using FplBot.Tests.Helpers;
using Xunit;
using Xunit.Abstractions;
namespace FplBot.Tests
{
public class DateTimeUtilsTests
{
private readonly ITestOutputHelper _helper;
private DateTimeUtils _deadlineChecker;
public DateTimeUtilsTests(ITestOutputHelper helper)
{
_helper = helper;
_deadlineChecker = Factory.Create<DateTimeUtils>();
}
[Fact]
public void WhenDayBefore()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 24, 19, 0, 0);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.False(_deadlineChecker.IsWithinMinutesToDate(60, deadline));
}
[Fact]
public void WhenBeforeTheMinute()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 25, 19, 59, 59);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.False(_deadlineChecker.IsWithinMinutesToDate(60, deadline));
}
[Fact]
public void WhenIsAnySecondWithTheMinute()
{
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
for(var i = 0; i < 60; i++)
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 25, 19, 0, i);
var isTheMinute = _deadlineChecker.IsWithinMinutesToDate(60, deadline);
if (!isTheMinute)
{
_helper.WriteLine($"Not true for {i} - {_deadlineChecker.NowUtcOverride-deadline}");
}
Assert.True(isTheMinute);
}
}
[Fact]
public void WhenIs()
{
var deadline = new DateTime(2020, 7, 4, 10, 30, 0);
_deadlineChecker.NowUtcOverride = new DateTime(2020, 7, 4, 10, 0, 20);
var isTheMinute = _deadlineChecker.IsWithinMinutesToDate(30, deadline);
Assert.True(isTheMinute);
}
[Fact]
public void WhenPassedTheMinute()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 25, 19, 1, 0);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.False(_deadlineChecker.IsWithinMinutesToDate(60, deadline));
}
[Fact]
public void WhenAnotherHourTheSameDayButSameMinute()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 25, 20, 0, 0);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.False(_deadlineChecker.IsWithinMinutesToDate(60, deadline));
}
[Fact]
public void WhenTheDayAfterButMinute()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 26, 19, 0, 0);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.False(_deadlineChecker.IsWithinMinutesToDate(60, deadline));
}
[Fact]
public void NoOverride()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 26, 19, 0, 0);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.False(_deadlineChecker.IsWithinMinutesToDate(60, deadline));
}
[Fact]
public void When24hBefore()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 24, 20, 0, 30);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.True(_deadlineChecker.IsWithinMinutesToDate(60*24, deadline));
}
[Fact]
public void When23hBefore()
{
_deadlineChecker.NowUtcOverride = new DateTime(2005, 5, 24, 21, 0, 30);
var deadline = new DateTime(2005, 5, 25, 20, 0, 0);
Assert.False(_deadlineChecker.IsWithinMinutesToDate(60*24, deadline));
}
}
} | 35.45045 | 104 | 0.562135 | [
"MIT"
] | ehamberg/fplbot | src/FplBot.Tests/NearDeadlineTests.cs | 3,935 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace HandlebarsDotNet.Compiler
{
internal class HashParametersAccumulator : TokenConverter
{
public static IEnumerable<object> Accumulate(IEnumerable<object> sequence)
{
return new HashParametersAccumulator().ConvertTokens(sequence).ToList();
}
private HashParametersAccumulator() { }
public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence)
{
var enumerator = sequence.GetEnumerator();
while (enumerator.MoveNext())
{
var item = enumerator.Current;
if (item is HashParameterAssignmentExpression parameterAssignment)
{
bool moveNext;
var parameters = AccumulateParameters(enumerator, out moveNext);
if (parameters.Any())
{
yield return HandlebarsExpression.HashParametersExpression(parameters);
}
if (!moveNext)
{
yield break;
}
item = enumerator.Current;
}
yield return item is Expression expression ? Visit(expression) : item;
}
}
Dictionary<string, Expression> AccumulateParameters(IEnumerator<object> enumerator, out bool moveNext)
{
moveNext = true;
var parameters = new Dictionary<string, Expression>();
var item = enumerator.Current;
while (item is HashParameterAssignmentExpression parameterAssignment)
{
item = GetNext(enumerator);
if (item is Expression value)
{
parameters.Add(parameterAssignment.Name, Visit(value));
}
else
{
throw new HandlebarsCompilerException(string.Format("Unexpected token '{0}', expected an expression", item));
}
moveNext = enumerator.MoveNext();
if (!moveNext)
{
break;
}
item = enumerator.Current;
}
return parameters;
}
Expression Visit(Expression expression)
{
if (expression is HelperExpression helperExpression)
{
var originalArguments = helperExpression.Arguments.ToArray();
var arguments = ConvertTokens(originalArguments)
.Cast<Expression>()
.ToArray();
if (!arguments.SequenceEqual(originalArguments))
{
return HandlebarsExpression.Helper(
helperExpression.HelperName,
helperExpression.IsBlock,
arguments,
helperExpression.IsRaw);
}
}
if (expression is SubExpressionExpression subExpression)
{
var childExpression = Visit(subExpression.Expression);
if (childExpression != subExpression.Expression)
{
return HandlebarsExpression.SubExpression(childExpression);
}
}
return expression;
}
private static object GetNext(IEnumerator<object> enumerator)
{
enumerator.MoveNext();
return enumerator.Current;
}
}
}
| 34.036036 | 130 | 0.503176 | [
"MIT"
] | zjklee/Handlebars.CSharp | source/Handlebars/Compiler/Lexer/Converter/HashParametersAccumulator.cs | 3,778 | 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("SimpleMethod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleMethod")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("ff126330-ea50-447a-9915-6199a2fb870f")]
// 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.756757 | 84 | 0.745168 | [
"MIT"
] | rjohar1/CSharpBeginners | SimpleMethod/SimpleMethod/Properties/AssemblyInfo.cs | 1,400 | C# |
using System.Windows;
using System.Windows.Controls;
using ExampleCalculatorApp.ViewModels;
using ReactiveUI;
namespace ExampleCalculatorApp.Views
{
public partial class IntegerValueEditorView : UserControl, IViewFor<IntegerValueEditorViewModel>
{
#region ViewModel
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel),
typeof(IntegerValueEditorViewModel), typeof(IntegerValueEditorView), new PropertyMetadata(null));
public IntegerValueEditorViewModel ViewModel
{
get => (IntegerValueEditorViewModel)GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}
object IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (IntegerValueEditorViewModel)value;
}
#endregion
public IntegerValueEditorView()
{
InitializeComponent();
this.WhenActivated(d => d(
this.Bind(ViewModel, vm => vm.Value, v => v.valueUpDown.Value)
));
}
}
}
| 30.675676 | 116 | 0.649339 | [
"Apache-2.0"
] | DAud-IcI/NodeNetwork | ExampleCalculatorApp/Views/IntegerValueEditorView.xaml.cs | 1,137 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using MoreMountains.Feedbacks;
namespace MoreMountains.FeedbacksForThirdParty
{
/// <summary>
/// Add this class to a Camera with a HDRP FilmGrain post processing and it'll be able to "shake" its values by getting events
/// </summary>
[RequireComponent(typeof(Volume))]
[AddComponentMenu("More Mountains/Feedbacks/Shakers/PostProcessing/MMFilmGrainShaker_HDRP")]
public class MMFilmGrainShaker_HDRP : MMShaker
{
[Header("Intensity")]
/// whether or not to add to the initial value
[Tooltip("whether or not to add to the initial value")]
public bool RelativeIntensity = false;
/// the curve used to animate the intensity value on
[Tooltip("the curve used to animate the intensity value on")]
public AnimationCurve ShakeIntensity = new AnimationCurve(new Keyframe(0, 0), new Keyframe(0.5f, 1), new Keyframe(1, 0));
/// the value to remap the curve's 0 to
[Tooltip("the value to remap the curve's 0 to")]
[Range(0f, 1f)]
public float RemapIntensityZero = 0f;
/// the value to remap the curve's 1 to
[Tooltip("the value to remap the curve's 1 to")]
[Range(0f, 1f)]
public float RemapIntensityOne = 1f;
protected Volume _volume;
protected FilmGrain _filmGrain;
protected float _initialIntensity;
protected float _originalShakeDuration;
protected AnimationCurve _originalShakeIntensity;
protected float _originalRemapIntensityZero;
protected float _originalRemapIntensityOne;
protected bool _originalRelativeIntensity;
/// <summary>
/// On init we initialize our values
/// </summary>
protected override void Initialization()
{
base.Initialization();
_volume = this.gameObject.GetComponent<Volume>();
_volume.profile.TryGet(out _filmGrain);
}
/// <summary>
/// Shakes values over time
/// </summary>
protected override void Shake()
{
float newValue = ShakeFloat(ShakeIntensity, RemapIntensityZero, RemapIntensityOne, RelativeIntensity, _initialIntensity);
_filmGrain.intensity.Override(newValue);
}
/// <summary>
/// Collects initial values on the target
/// </summary>
protected override void GrabInitialValues()
{
_initialIntensity = _filmGrain.intensity.value;
}
/// <summary>
/// When we get the appropriate event, we trigger a shake
/// </summary>
/// <param name="intensity"></param>
/// <param name="duration"></param>
/// <param name="amplitude"></param>
/// <param name="relativeIntensity"></param>
/// <param name="attenuation"></param>
/// <param name="channel"></param>
public virtual void OnFilmGrainShakeEvent(AnimationCurve intensity, float duration, float remapMin, float remapMax, bool relativeIntensity = false,
float attenuation = 1.0f, int channel = 0, bool resetShakerValuesAfterShake = true, bool resetTargetValuesAfterShake = true, bool forwardDirection = true, TimescaleModes timescaleMode = TimescaleModes.Scaled, bool stop = false)
{
if (!CheckEventAllowed(channel) || (!Interruptible && Shaking))
{
return;
}
if (stop)
{
Stop();
return;
}
_resetShakerValuesAfterShake = resetShakerValuesAfterShake;
_resetTargetValuesAfterShake = resetTargetValuesAfterShake;
if (resetShakerValuesAfterShake)
{
_originalShakeDuration = ShakeDuration;
_originalShakeIntensity = ShakeIntensity;
_originalRemapIntensityZero = RemapIntensityZero;
_originalRemapIntensityOne = RemapIntensityOne;
_originalRelativeIntensity = RelativeIntensity;
}
TimescaleMode = timescaleMode;
ShakeDuration = duration;
ShakeIntensity = intensity;
RemapIntensityZero = remapMin * attenuation;
RemapIntensityOne = remapMax * attenuation;
RelativeIntensity = relativeIntensity;
ForwardDirection = forwardDirection;
Play();
}
/// <summary>
/// Resets the target's values
/// </summary>
protected override void ResetTargetValues()
{
base.ResetTargetValues();
_filmGrain.intensity.Override(_initialIntensity);
}
/// <summary>
/// Resets the shaker's values
/// </summary>
protected override void ResetShakerValues()
{
base.ResetShakerValues();
ShakeDuration = _originalShakeDuration;
ShakeIntensity = _originalShakeIntensity;
RemapIntensityZero = _originalRemapIntensityZero;
RemapIntensityOne = _originalRemapIntensityOne;
RelativeIntensity = _originalRelativeIntensity;
}
/// <summary>
/// Starts listening for events
/// </summary>
public override void StartListening()
{
base.StartListening();
MMFilmGrainShakeEvent_HDRP.Register(OnFilmGrainShakeEvent);
}
/// <summary>
/// Stops listening for events
/// </summary>
public override void StopListening()
{
base.StopListening();
MMFilmGrainShakeEvent_HDRP.Unregister(OnFilmGrainShakeEvent);
}
}
/// <summary>
/// An event used to trigger FilmGrain shakes
/// </summary>
public struct MMFilmGrainShakeEvent_HDRP
{
public delegate void Delegate(AnimationCurve intensity, float duration, float remapMin, float remapMax, bool relativeIntensity = false,
float attenuation = 1.0f, int channel = 0, bool resetShakerValuesAfterShake = true, bool resetTargetValuesAfterShake = true, bool forwardDirection = true, TimescaleModes timescaleMode = TimescaleModes.Scaled, bool stop = false);
static private event Delegate OnEvent;
static public void Register(Delegate callback)
{
OnEvent += callback;
}
static public void Unregister(Delegate callback)
{
OnEvent -= callback;
}
static public void Trigger(AnimationCurve intensity, float duration, float remapMin, float remapMax, bool relativeIntensity = false,
float attenuation = 1.0f, int channel = 0, bool resetShakerValuesAfterShake = true, bool resetTargetValuesAfterShake = true, bool forwardDirection = true, TimescaleModes timescaleMode = TimescaleModes.Scaled, bool stop = false)
{
OnEvent?.Invoke(intensity, duration, remapMin, remapMax, relativeIntensity, attenuation, channel, resetShakerValuesAfterShake, resetTargetValuesAfterShake, forwardDirection, timescaleMode, stop);
}
}
}
| 40.530726 | 240 | 0.632667 | [
"MIT"
] | DuLovell/Rhythm-Game | Assets/Plugins/Feel/MMFeedbacks/MMFeedbacksForThirdParty/HDRP/Shakers/MMFilmGrainShaker_HDRP.cs | 7,257 | C# |
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Ultz.Extensions.Commands.Context;
using Ultz.Extensions.Commands.Results.User;
namespace Ultz.Extensions.Commands.Attributes.Checks.Bundled.String
{
/// <summary>
/// Represents a parameter check that ensures the provided string argument matches the provided
/// <see cref="System.Text.RegularExpressions.Regex" /> pattern.
/// </summary>
public sealed class RegexAttribute : ParameterCheckAttribute
{
/// <summary>
/// Initialises a new <see cref="RegexAttribute" /> with the specified <see cref="System.Text.RegularExpressions.Regex" />
/// pattern.
/// </summary>
/// <param name="pattern"> The <see cref="System.Text.RegularExpressions.Regex" /> pattern. </param>
public RegexAttribute(string pattern)
: this(pattern, RegexOptions.Compiled)
{
}
/// <summary>
/// Initialises a new <see cref="RegexAttribute" /> with the specified <see cref="System.Text.RegularExpressions.Regex" />
/// pattern and <see cref="RegexOptions" />.
/// </summary>
/// <param name="pattern"> The <see cref="System.Text.RegularExpressions.Regex" /> pattern. </param>
/// <param name="options"> The <see cref="RegexOptions" />. </param>
public RegexAttribute(string pattern, RegexOptions options)
: base(Utilities.IsStringType)
{
Regex = new Regex(pattern, options);
}
/// <summary>
/// Gets the required <see cref="System.Text.RegularExpressions.Regex" />.
/// </summary>
public Regex Regex { get; }
/// <inheritdoc />
public override ValueTask<CheckResult> CheckAsync(object argument, CommandContext context)
=> Regex.IsMatch(argument as string)
? CheckResult.Successful
: CheckResult.Unsuccessful($"The provided argument must match the regex pattern: {Regex}.");
}
} | 42.957447 | 130 | 0.634968 | [
"MIT"
] | Ultz/Bcl | src/Ultz.Extensions.Commands/Attributes/Checks/Bundled/String/RegexCheckAttribute.cs | 2,021 | C# |
using System;
using System.Data.Common;
using grate.Configuration;
using grate.Infrastructure;
using grate.Migration;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Logging;
namespace grate.unittests.TestInfrastructure;
class SqliteGrateTestContext : TestContextBase, IGrateTestContext
{
public string AdminPassword { get; set; } = default!;
public int? Port { get; set; }
public string AdminConnectionString => $"Data Source=grate-sqlite.db";
public string ConnectionString(string database) => $"Data Source={database}.db";
public DbConnection GetDbConnection(string connectionString) => new SqliteConnection(connectionString);
public ISyntax Syntax => new SqliteSyntax();
public Type DbExceptionType => typeof(SqliteException);
public DatabaseType DatabaseType => DatabaseType.sqlite;
public bool SupportsTransaction => false;
public string DatabaseTypeName => "Sqlite";
public string MasterDatabase => "master";
public IDatabase DatabaseMigrator => new SqliteDatabase(TestConfig.LogFactory.CreateLogger<SqliteDatabase>());
public SqlStatements Sql => new()
{
SelectVersion = "SELECT sqlite_version();",
};
public string ExpectedVersionPrefix => "3.32.3";
public bool SupportsCreateDatabase => false;
} | 33.333333 | 114 | 0.747692 | [
"MIT"
] | RachelAmbler/grate | grate.unittests/TestInfrastructure/SqLiteGrateTestContext.cs | 1,302 | C# |
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace AzR.WebFw.Handlers
{
public class PreflightRequestsHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Contains("Origin") && request.Method.Method == "OPTIONS")
{
var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");
response.Headers.Add("Access-Control-Allow-Methods", "*");
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
} | 41.52 | 127 | 0.640655 | [
"MIT"
] | ashiquzzaman/azr-admin | Development/AzRAdmin/Presentations/AzR.WebFw/Handlers/PreflightRequestsHandler.cs | 1,040 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.IO;
public class Tool_MapEditor : EditorWindow
{
#region Array Icons
//Prefab Array
private GameObject[] _Prefabs = new GameObject[0];
private string[] _SearchResults = new string[0];
//Array Options
private string _SearchPrefab = "";
private bool _HideNames = true;
private float _ButtonSize = 1, _CollomLength = 4;
//Array Selection
private int _SelectedID = 99999999, _CheckSelectedID = 999999999;
#endregion
#region Options
//Options
private bool _HideOptions = true;
private int _OptionsStates = 0, _PlacementStates = 0;
//Placement Option
private float _PaintSpeed = 1, _PaintTimer = 0;
private bool _SnapPosActive = false;
//Onscene Options
private bool _ShowOptionsInScene;
private int _InScene_SelectedID;
#endregion
#region Transform
//Position
private Vector3 _MousePos, _SnapPos, _ObjectPos;
private Vector2 _GridSize = new Vector2(1, 1);
//Rotation/Size
private float _Rotation, _Size = 1;
private bool _RandomRot = false;
private Vector2 _PrevMousePos = new Vector3(0, 0, 0);
#endregion
#region Check
//Check Buttons Event
private bool _MouseDown, _ShiftDown, _CtrlDown, _ClickMenu;
#endregion
#region Other
//Placement
private GameObject _ParentObj, _ExampleObj;
//Other
private Vector2 _ScrollPos1, _ClickPos;
private Texture2D[] _PrefabIcon = new Texture2D[0];
#endregion
//Start Window
[MenuItem("Tools/Map Editor %m")]
static void Init()
{
Tool_MapEditor window = EditorWindow.GetWindow(typeof(Tool_MapEditor), false, "Tool_MapEditor") as Tool_MapEditor;
window.Show();
}
//Load Objects
private void Awake()
{
Load_Prefabs();
Load_Prefabs();
}
//Enable/Disable
void OnEnable()
{
SceneView.duringSceneGui += this.OnSceneGUI;
SceneView.duringSceneGui += this.OnScene;
}
void OnDisable()
{
SceneView.duringSceneGui -= this.OnSceneGUI;
SceneView.duringSceneGui -= this.OnScene;
DestroyImmediate(_ExampleObj);
}
//OnGUI ObjectView
void OnGUI()
{
GUILayout.BeginVertical("Box");
//Refresh/Info
GUILayout.BeginHorizontal();
if (GUILayout.Button("Refresh", GUILayout.Width(80)))
{
FixPreview();
Load_Prefabs();
}
GUILayout.Label("Loaded objects: " + _SearchResults.Length);
GUILayout.EndHorizontal();
//Windows
ObjectView_Header();
ObjectView_Objects();
ObjectView_Options();
GUILayout.EndVertical();
}
private void ObjectView_Header()
{
GUILayout.BeginHorizontal();
_OptionsStates = GUILayout.Toolbar(_OptionsStates, new string[] { "Icon", "Text" });
_ButtonSize = EditorGUILayout.Slider(_ButtonSize, 0.25f, 2);
if (!_HideNames)
{
if (GUILayout.Button("Hide Names", GUILayout.Width(100)))
_HideNames = true;
}
else
{
if (GUILayout.Button("Show Names", GUILayout.Width(100)))
_HideNames = false;
}
GUILayout.EndHorizontal();
_SearchPrefab = EditorGUILayout.TextField("Search: ", _SearchPrefab);
}
private void ObjectView_Objects()
{
Color defaultColor = GUI.backgroundColor;
GUILayout.BeginVertical("Box");
float calcWidth = 100 * _ButtonSize;
_CollomLength = position.width / calcWidth;
int x = 0;
int y = 0;
//Show/Hide Options
if (_HideOptions)
_ScrollPos1 = GUILayout.BeginScrollView(_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 109));
else
{
if (_PlacementStates == 0)
_ScrollPos1 = GUILayout.BeginScrollView(_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 235));
else
_ScrollPos1 = GUILayout.BeginScrollView(_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 253));
}
//Object Icons
for (int i = 0; i < _SearchResults.Length; i++)
{
if (_Prefabs[i] != null && _Prefabs[i].name.ToLower().Contains(_SearchPrefab.ToLower()))
{
if (_OptionsStates == 0) //Icons
{
//Select Color
if (_SelectedID == i) { GUI.backgroundColor = new Color(0, 1, 0); } else { GUI.backgroundColor = new Color(1, 0, 0); }
//Create Button
GUIContent content = new GUIContent();
content.image = _PrefabIcon[i];
GUI.skin.button.imagePosition = ImagePosition.ImageAbove;
if (!_HideNames)
content.text = _Prefabs[i].name;
if (GUI.Button(new Rect(x * 100 * _ButtonSize, y * 100 * _ButtonSize, 100 * _ButtonSize, 100 * _ButtonSize), content))
if (_SelectedID == i) { _SelectedID = 99999999; _CheckSelectedID = 99999999; DestroyImmediate(_ExampleObj); } else { _SelectedID = i; }
//Reset Button Position
x++;
if (x >= _CollomLength - 1)
{
y++;
x = 0;
}
GUI.backgroundColor = defaultColor;
}
else //Text Buttons
{
if (_SelectedID == i) { GUI.backgroundColor = new Color(0, 1, 0); } else { GUI.backgroundColor = defaultColor; }
if (GUILayout.Button(_Prefabs[i].name))
if (_SelectedID == i) { _SelectedID = 99999999; _CheckSelectedID = 99999999; DestroyImmediate(_ExampleObj); } else { _SelectedID = i; }
GUI.backgroundColor = defaultColor;
}
}
}
if (_OptionsStates == 0)
{
GUILayout.Space(y * 100 * _ButtonSize + 100);
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
}
private void ObjectView_Options()
{
GUILayout.BeginVertical("Box");
if (!_HideOptions)
{
//Paint Options
GUILayout.BeginVertical("Box");
_PlacementStates = GUILayout.Toolbar(_PlacementStates, new string[] { "Click", "Paint" });
if (_PlacementStates == 1)
_PaintSpeed = EditorGUILayout.FloatField("Paint Speed: ", _PaintSpeed);
//Parent Options
GUILayout.BeginHorizontal();
_ParentObj = (GameObject)EditorGUILayout.ObjectField("Parent Object: ", _ParentObj, typeof(GameObject), true);
if (_ParentObj != null)
if (GUILayout.Button("Clean Parent"))
CleanParent();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
//Grid Options
GUILayout.BeginVertical("Box");
_GridSize = EditorGUILayout.Vector2Field("Grid Size: ", _GridSize);
_RandomRot = EditorGUILayout.Toggle("Random Rotation: ", _RandomRot);
_SnapPosActive = EditorGUILayout.Toggle("Use Grid: ", _SnapPosActive);
GUILayout.EndVertical();
}
//Hide/Show Options
if (_HideOptions)
{
if (GUILayout.Button("Show Options"))
_HideOptions = false;
}
else
{
if (GUILayout.Button("Hide Options"))
_HideOptions = true;
}
GUILayout.EndVertical();
}
//OnSceneGUI
void OnSceneGUI(SceneView sceneView)
{
Event e = Event.current;
Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(worldRay, out hitInfo))
{
//Check MousePosition
_MousePos = hitInfo.point;
//Create Example Object
if (_SelectedID <= _Prefabs.Length)
{
if (_CheckSelectedID != _SelectedID)
{
DestroyImmediate(_ExampleObj);
_ExampleObj = Instantiate(_Prefabs[_SelectedID], hitInfo.point, Quaternion.identity);
_ExampleObj.layer = LayerMask.NameToLayer("Ignore Raycast");
for (int i = 0; i < _ExampleObj.transform.childCount; i++)
{
_ExampleObj.transform.GetChild(i).gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
for (int o = 0; o < _ExampleObj.transform.GetChild(i).childCount; o++)
{
_ExampleObj.transform.GetChild(i).GetChild(o).gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
}
}
_ExampleObj.name = "Example Object";
_CheckSelectedID = _SelectedID;
}
}
//Set Example Object Position + Rotation
if (_ExampleObj != null)
{
_ExampleObj.transform.rotation = Quaternion.Euler(0, _Rotation, 0);
_ExampleObj.transform.localScale = new Vector3(_Size, _Size, _Size);
if (!e.shift && !e.control)
{
if (!_SnapPosActive)
{ _ExampleObj.transform.position = hitInfo.point; }
else
{ _ExampleObj.transform.position = _SnapPos; }
}
}
//Check Buttons Pressed
if (!Event.current.alt && _SelectedID != 99999999)
{
if (Event.current.type == EventType.Layout)
HandleUtility.AddDefaultControl(0);
//Mouse Button 0 Pressed
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
_MouseDown = true;
_PaintTimer = _PaintSpeed;
if (e.mousePosition.y <= 20)
_ClickMenu = true;
}
//Mouse Button 0 Released
if (Event.current.type == EventType.MouseUp && Event.current.button == 0)
{
_MouseDown = false;
_ClickMenu = false;
}
//Check Shift
if (e.shift)
_ShiftDown = true;
else
_ShiftDown = false;
//Check Ctrl
if (e.control)
_CtrlDown = true;
else
_CtrlDown = false;
if (e.shift || e.control)
{
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
_ClickPos = Event.current.mousePosition;
}
//Place Object
if (!_ShiftDown && !_CtrlDown && !_ClickMenu)
{
if (_PlacementStates == 0)
{
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
CreatePrefab(hitInfo.point);
}
else
{
float timer1Final = _PaintSpeed;
if (_MouseDown)
{
_PaintTimer += 1 * Time.deltaTime;
if (_PaintTimer >= timer1Final)
{
CreatePrefab(hitInfo.point);
_PaintTimer = 0;
}
}
}
}
}
// Draw obj location
if (_SelectedID != 99999999)
{
//Draw Red Cross + Sphere on object location
Handles.color = new Color(1, 0, 0);
Handles.DrawLine(new Vector3(hitInfo.point.x - 0.3f, hitInfo.point.y, hitInfo.point.z), new Vector3(hitInfo.point.x + 0.3f, hitInfo.point.y, hitInfo.point.z));
Handles.DrawLine(new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z - 0.3f), new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z + 0.3f));
if (_SnapPosActive)
{
Handles.SphereHandleCap(1, new Vector3(_SnapPos.x, hitInfo.point.y, _SnapPos.z), Quaternion.identity, 0.1f, EventType.Repaint);
}
else
Handles.SphereHandleCap(1, new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z), Quaternion.identity, 0.1f, EventType.Repaint);
//Check Snap Position
if (_SnapPosActive)
{
Vector2 calc = new Vector2(_MousePos.x / _GridSize.x, _MousePos.z / _GridSize.y);
Vector2 calc2 = new Vector2(Mathf.RoundToInt(calc.x) * _GridSize.x, Mathf.RoundToInt(calc.y) * _GridSize.y);
_SnapPos = new Vector3(calc2.x, _MousePos.y, calc2.y);
//Draw Grid
Handles.color = new Color(0, 1, 0);
float lineLength = 0;
if (_GridSize.x > _GridSize.y)
lineLength = _GridSize.x + 1;
else
lineLength = _GridSize.y + 1;
for (int hor = 0; hor < 3; hor++)
{
Handles.DrawLine(new Vector3(calc2.x - lineLength, hitInfo.point.y, calc2.y - _GridSize.y + _GridSize.y * hor), new Vector3(calc2.x + lineLength, hitInfo.point.y, calc2.y - _GridSize.y + _GridSize.y * hor));
}
for (int ver = 0; ver < 3; ver++)
{
Handles.DrawLine(new Vector3(calc2.x - _GridSize.x + _GridSize.x * ver, hitInfo.point.y, calc2.y - lineLength), new Vector3(calc2.x - _GridSize.x + _GridSize.x * ver, hitInfo.point.y, calc2.y + lineLength));
}
}
}
}
}
//OnScene
void OnScene(SceneView sceneView)
{
//InScene Option Bar
Handles.BeginGUI();
if (_ShowOptionsInScene)
{
//Option Bar
GUI.Box(new Rect(0, 0, Screen.width, 22), GUIContent.none);
_InScene_SelectedID = GUI.Toolbar(new Rect(22, 1, Screen.width / 2 - 30, 20), _InScene_SelectedID, new string[] { "Settings", "Placement", "Transform", "Grid" });
switch (_InScene_SelectedID)
{
case 0: //Settings
GUI.Label(new Rect(Screen.width / 2 - 5, 3, 50, 20), "Parent: ");
_ParentObj = (GameObject)EditorGUI.ObjectField(new Rect(Screen.width / 2 + 50, 1, 150, 20), _ParentObj, typeof(GameObject), true);
if (GUI.Button(new Rect(Screen.width - 110, 1, 90, 20), "Clean Parent"))
{
CleanParent();
}
break;
case 1: //Placement
_PlacementStates = GUI.Toolbar(new Rect(Screen.width / 2 - 5, 1, 100, 20), _PlacementStates, new string[] { "Click", "Paint" });
_PaintSpeed = EditorGUI.FloatField(new Rect(Screen.width / 2 + 185, 1, 50, 20), _PaintSpeed);
GUI.Label(new Rect(Screen.width / 2 + 100, 3, 500, 20), "Paint speed: ");
break;
case 2: //Transform
_Size = EditorGUI.FloatField(new Rect(Screen.width / 2 + 125, 1, 100, 20), _Size);
break;
case 3: //Grid
GUI.Label(new Rect(Screen.width / 2 + 80, 3, 100, 20), "Grid Size: ");
_GridSize.x = EditorGUI.FloatField(new Rect(Screen.width / 2 + 150, 1, 50, 20), _GridSize.x);
_GridSize.y = EditorGUI.FloatField(new Rect(Screen.width / 2 + 200, 1, 50, 20), _GridSize.y);
GUI.Label(new Rect(Screen.width / 2, 3, 100, 20), "Enable: ");
_SnapPosActive = EditorGUI.Toggle(new Rect(Screen.width / 2 + 50, 3, 20, 20), _SnapPosActive);
break;
}
}
//Hotkeys Resize / Rotate
//Shift+MouseDown = Resize
Vector2 prevmove = _PrevMousePos - Event.current.mousePosition;
if (_ShiftDown && _MouseDown)
{
_Size = EditorGUI.Slider(new Rect(_ClickPos.x - 15, _ClickPos.y - 40, 50, 20), _Size, 0.01f, 1000000);
_Size -= (prevmove.x + prevmove.y) * 0.05f;
GUI.Label(new Rect(_ClickPos.x - 50, _ClickPos.y - 40, 500, 20), "Size: ");
}
//Ctrl+MouseDown = Rotate
if (_CtrlDown && _MouseDown)
{
_Rotation = EditorGUI.Slider(new Rect(_ClickPos.x - 15, _ClickPos.y - 40, 50, 20), _Rotation, -1000000, 1000000);
_Rotation += prevmove.x + prevmove.y;
GUI.Label(new Rect(_ClickPos.x - 80, _ClickPos.y - 40, 500, 20), "Rotation: ");
}
_PrevMousePos = Event.current.mousePosition;
//Inscene Show OptionButton
GUI.color = new Color(1f, 1f, 1f, 1f);
if (!_ShowOptionsInScene)
{
if (GUI.Button(new Rect(1, 1, 20, 20), " +"))
_ShowOptionsInScene = true;
}
else
{
if (GUI.Button(new Rect(1, 1, 20, 20), " -"))
_ShowOptionsInScene = false;
}
Handles.EndGUI();
}
//Load/Fix
void Load_Prefabs()
{
_SearchResults = System.IO.Directory.GetFiles("Assets/", "*.prefab", System.IO.SearchOption.AllDirectories);
_Prefabs = new GameObject[_SearchResults.Length];
_PrefabIcon = new Texture2D[_SearchResults.Length];
for (int i = 0; i < _SearchResults.Length; i++)
{
Object prefab = null;
prefab = AssetDatabase.LoadAssetAtPath(_SearchResults[i], typeof(GameObject));
_Prefabs[i] = prefab as GameObject;
_PrefabIcon[i] = AssetPreview.GetAssetPreview(_Prefabs[i]);
}
}
void FixPreview()
{
Load_Prefabs();
_SearchResults = System.IO.Directory.GetFiles("Assets/", "*.prefab", System.IO.SearchOption.AllDirectories);
for (int i = 0; i < _SearchResults.Length; i++)
{
if (_PrefabIcon[i] == null)
AssetDatabase.ImportAsset(_SearchResults[i]);
}
Load_Prefabs();
}
//Create Prefab/Clean Parent
void CreatePrefab(Vector3 createPos)
{
if (CheckPositionEmpty(true))
{
GameObject createdObj = PrefabUtility.InstantiatePrefab(_Prefabs[_SelectedID]) as GameObject;
createdObj.transform.position = createPos;
createdObj.transform.localScale = new Vector3(_Size, _Size, _Size);
if (_ParentObj == null)
{
_ParentObj = new GameObject();
_ParentObj.name = "MapEditor_Parent";
}
createdObj.transform.parent = _ParentObj.transform;
if (_SnapPosActive)
createdObj.transform.position = _SnapPos;
else
createdObj.transform.position = _MousePos;
if (_RandomRot)
createdObj.transform.rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
else
createdObj.transform.rotation = Quaternion.Euler(0, _Rotation, 0);
}
}
void CleanParent()
{
int childAmount = _ParentObj.transform.childCount;
int childCalc = childAmount - 1;
for (int i = 0; i < childAmount; i++)
{
DestroyImmediate(_ParentObj.transform.GetChild(childCalc).gameObject);
childCalc -= 1;
}
}
bool CheckPositionEmpty(bool checky)
{
if (_ParentObj != null)
{
bool check = true;
for (int i = 0; i < _ParentObj.transform.childCount; i++)
{
if (checky)
{
if (_ParentObj.transform.GetChild(i).position.x == _SnapPos.x && _ParentObj.transform.GetChild(i).position.z == _SnapPos.z)
check = false;
}
else
if (_ParentObj.transform.GetChild(i).position == _SnapPos)
check = false;
}
return check;
}
else
{
return true;
}
}
} | 38.61326 | 231 | 0.526112 | [
"MIT"
] | MarcelvanDuijnDev/Unity-Presets-Scripts-Tools | Assets/Scripts/Editor/Tool_MapEditor.cs | 20,969 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Resonance.Discovery
{
/// <summary>
/// Represents a Resonance discovery client capable of detecting and fetching information about a remote service.
/// </summary>
/// <typeparam name="TDiscoveryInfo">The type of the discovery information.</typeparam>
/// <typeparam name="TDiscoveredService">The type of the discovered service.</typeparam>
/// <seealso cref="System.IDisposable" />
public interface IResonanceDiscoveryClient<TDiscoveryInfo, TDiscoveredService> : IResonanceComponent, IDisposable, IResonanceAsyncDisposable where TDiscoveryInfo : class where TDiscoveredService : IResonanceDiscoveredService<TDiscoveryInfo>
{
/// <summary>
/// Occurs when a matching service has been discovered.
/// </summary>
event EventHandler<ResonanceDiscoveredServiceEventArgs<TDiscoveredService, TDiscoveryInfo>> ServiceDiscovered;
/// <summary>
/// Occurs when a discovered service is no longer responding.
/// </summary>
event EventHandler<ResonanceDiscoveredServiceEventArgs<TDiscoveredService, TDiscoveryInfo>> ServiceLost;
/// <summary>
/// Gets a value indicating whether this client has started.
/// </summary>
bool IsStarted { get; }
/// <summary>
/// Start discovering.
/// </summary>
Task StartAsync();
/// <summary>
/// Start discovering.
/// </summary>
void Start();
/// <summary>
/// Stop discovering.
/// </summary>
Task StopAsync();
/// <summary>
/// Start discovering.
/// </summary>
void Stop();
/// <summary>
/// Asynchronous method for collecting discovered services within the given duration.
/// </summary>
/// <param name="maxDuration">The maximum duration to perform the scan.</param>
/// <param name="maxServices">Drop the scanning after the maximum services discovered.</param>
/// <returns></returns>
Task<List<TDiscoveredService>> DiscoverAsync(TimeSpan maxDuration, int? maxServices = null);
/// <summary>
/// Asynchronous method for collecting discovered services within the given duration.
/// </summary>
/// <param name="maxDuration">The maximum duration to perform the scan.</param>
/// <param name="maxServices">Drop the scanning after the maximum services discovered.</param>
/// <returns></returns>
List<TDiscoveredService> Discover(TimeSpan maxDuration, int? maxServices = null);
}
}
| 39.705882 | 244 | 0.65 | [
"MIT"
] | royben/Resonance | source/Resonance/Discovery/IResonanceDiscoveryClient.cs | 2,702 | C# |
namespace mktool
{
class Allocation
{
public string? Name { get; set; }
public string? IpRange { get; set; }
public string? DhcpServer { get; set; }
}
}
| 19.9 | 48 | 0.527638 | [
"Unlicense"
] | AndrewSav/mktool | Models/Allocation.cs | 201 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* 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.
*
* Iotlink-Related-API
* 物联网卡服务相关API
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Core.Annotation;
using Newtonsoft.Json;
namespace JDCloudSDK.Iotlink.Apis
{
/// <summary>
/// 物联网卡停流量操作
/// </summary>
public class CloseIotFlowRequest : JdcloudRequest
{
///<summary>
/// 物联网卡号码列表(单次提交最多不超过200个号码)
///</summary>
public List<string> Iccids{ get; set; }
///<summary>
/// Region ID
///Required:true
///</summary>
[Required]
[JsonProperty("regionId")]
public string RegionIdValue{ get; set; }
}
} | 25.509091 | 76 | 0.668567 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Iotlink/Apis/CloseIotFlowRequest.cs | 1,477 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using pywebfrontend.Models;
namespace pywebfrontend.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 23.159091 | 112 | 0.593719 | [
"MIT"
] | paulyuk/docker-all-the-things | src/pywebfrontend/pywebfrontend/Controllers/HomeController.cs | 1,021 | C# |
namespace _07.InfernoInfinity.Contracts
{
public interface IRunnable
{
void Run();
}
}
| 13.375 | 40 | 0.626168 | [
"MIT"
] | anedyalkov/CSharp-OOP-Advanced | 08.Reflection and Attributes-Exercises/P07_InfernoInfinity/Contracts/IRunnable.cs | 109 | C# |
// Released under the MIT License.
//
// Copyright (c) 2018 Ntreev Soft co., Ltd.
// Copyright (c) 2020 Jeesu Choi
//
// 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.
//
// Forked from https://github.com/NtreevSoft/Crema
// Namespaces and files starting with "Ntreev" have been renamed to "JSSoft".
using JSSoft.Crema.Presentation.Controls;
using JSSoft.ModernUI.Framework;
using System;
using System.Collections.Generic;
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;
namespace JSSoft.Crema.Comparer.Types.Views
{
/// <summary>
/// TypeDocumentView.xaml에 대한 상호 작용 논리
/// </summary>
public partial class TypeDocumentView : UserControl
{
public TypeDocumentView()
{
InitializeComponent();
}
}
}
| 39.557692 | 121 | 0.753038 | [
"MIT"
] | s2quake/JSSoft.Crema | tools/JSSoft.Crema.Comparer/Types/Views/TypeDocumentView.xaml.cs | 2,077 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Zone.cs" company="HomeRun Software Systems">
// Copyright (c) 2017 Jay McLain
//
// 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.
// </copyright>
// <summary>
// Defines the Zone type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Newtonsoft.Json;
using Rachio.NET.Service.Infrastructure.Json;
namespace Rachio.NET.Service.Model
{
public class Zone : Entity
{
private const string ZoneEntity = "zone";
private const string StartAction = "start";
public int ZoneNumber { get; set; }
public string Name { get; set; }
public Uri ImageUrl { get; set; }
public bool Enabled { get; set; }
public double RootZoneDepth { get; set; }
public double AvailableWater { get; set; }
public double DepthOfWater { get; set; }
public double SaturatedDepthOfWater { get; set; }
public double Efficiency { get; set; }
public double FixedRuntime { get; set; }
public double ManagementAllowedDepletion { get; set; }
[JsonConverter(typeof(UnixEpochDateTimeJsonConverter))]
public DateTime LastWateredDate { get; set; }
[JsonConverter(typeof(UnixTimeSpanJsonConverter))]
public TimeSpan LastWateredDuration { get; set; }
[JsonConverter(typeof(UnixTimeSpanJsonConverter))]
public TimeSpan RunTime { get; set; }
[JsonConverter(typeof(UnixTimeSpanJsonConverter))]
public TimeSpan RunTimeNoMultiplier { get; set; }
[JsonConverter(typeof(UnixTimeSpanJsonConverter))]
public TimeSpan MaxRunTime { get; set; }
public bool ScheduleDataModified { get; set; }
public int YardAreaSquareFeet { get; set; }
public CustomCrop CustomCrop { get; set; }
public CustomNozzle CustomNozzle { get; set; }
public CustomShade CustomShade { get; set; }
public CustomSlope CustomSlope { get; set; }
public CustomSoil CustomSoil { get; set; }
//public WateringAdjustmentRuntimes
/// <summary>
/// Start a zone
/// </summary>
/// <param name="duration">Duration in seconds. Range is 0 to 10800 (3 hours). Default is 15 minutes.</param>
public void Start(int duration = 900)
{
ServiceProvider.PutAsync(ZoneEntity, new { id = Id, duration }, StartAction);
}
}
}
| 45.222222 | 120 | 0.629266 | [
"MIT"
] | gstar42/Rachio.NET | src/Rachio.NET.Service/Model/Zone.cs | 3,665 | C# |
using System;
using System.Linq;
using System.Web.Mvc;
using MvcGrabBag.Web.EntityFramework;
using MvcGrabBag.Web.Helpers;
using Telerik.Web.Mvc;
namespace MvcGrabBag.Web.Controllers
{
public class TelerikController : Controller
{
private readonly IDataContext _db;
public TelerikController(IDataContext db)
{
_db = db;
}
[GridAction(GridName = "Products", EnableCustomBinding = true)]
public ActionResult Index(GridCommand command)
{
var query = _db.Products;
int rowCount;
var grid = query.OrderBy(m => m.Id)
.ForGrid(serverModel =>
new
{
serverModel.Id,
ProductName = serverModel.Name,
CategoryName = serverModel.Category.Name,
serverModel.DateCreated
},
clientModel =>
new ProductDashboardModel
{
Id = clientModel.Id,
ProductName = clientModel.ProductName,
CategoryName = clientModel.CategoryName,
DaysOld = DateTime.Now.Subtract(clientModel.DateCreated.GetValueOrDefault()).Days,
},
command, new ClaimsDashboardGridPropertyMap(), out rowCount);
ViewBag.Total = rowCount;
return View(grid);
}
}
public class ProductDashboardModel
{
public int Id { get; set; }
public string CategoryName { get; set; }
public string ProductName { get; set; }
public int DaysOld { get; set; }
}
public class ClaimsDashboardGridPropertyMap : IGridPropertyMap
{
public string GetServerSidePropertyName(string clientProperty)
{
switch (clientProperty)
{
case "DaysOld":
return "DateCreated";
case "CategoryName":
return "Category.Name";
case "ProductName":
return "Name";
default:
return clientProperty;
}
}
}
} | 30.765432 | 116 | 0.470305 | [
"MIT"
] | matthidinger/MvcGrabBag | MvcGrabBag.Web/Controllers/TelerikController.cs | 2,494 | C# |
namespace Eciton
{
public class EcitonVariableNotInitializedException : EcitonException
{
}
}
| 15.285714 | 72 | 0.728972 | [
"MIT"
] | malaybaku/Eciton | Eciton/Eciton/Exceptions/EcitonVariableNotInitializedException.cs | 109 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Dynamic.Utils;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
/// <summary>
/// This type tracks "runtime" constants--live objects that appear in
/// ConstantExpression nodes and must be bound to the delegate.
/// </summary>
internal sealed class BoundConstants
{
/// <summary>
/// Constants can emit themselves as different types
/// For caching purposes, we need to treat each distinct Type as a
/// separate thing to cache. (If we have to cast it on the way out, it
/// ends up using a JIT temp and defeats the purpose of caching the
/// value in a local)
/// </summary>
private readonly struct TypedConstant : IEquatable<TypedConstant>
{
internal readonly object Value;
internal readonly Type Type;
internal TypedConstant(object value, Type type)
{
Value = value;
Type = type;
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(Value) ^ Type.GetHashCode();
}
public bool Equals(TypedConstant other)
{
return object.ReferenceEquals(Value, other.Value) && Type.Equals(other.Type);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2231:OverloadOperatorEqualsOnOverridingValueTypeEquals")]
public override bool Equals(object? obj)
{
return obj is TypedConstant typedConstant && Equals(typedConstant);
}
}
/// <summary>
/// The list of constants in the order they appear in the constant array
/// </summary>
private readonly List<object> _values = new List<object>();
/// <summary>
/// The index of each constant in the constant array
/// </summary>
private readonly Dictionary<object, int> _indexes = new Dictionary<object, int>(ReferenceEqualityComparer<object>.Instance);
/// <summary>
/// Each constant referenced within this lambda, and how often it was referenced
/// </summary>
private readonly Dictionary<TypedConstant, int> _references = new Dictionary<TypedConstant, int>();
/// <summary>
/// IL locals for storing frequently used constants
/// </summary>
private readonly Dictionary<TypedConstant, LocalBuilder> _cache = new Dictionary<TypedConstant, LocalBuilder>();
internal int Count => _values.Count;
internal object[] ToArray()
{
return _values.ToArray();
}
/// <summary>
/// Called by VariableBinder. Adds the constant to the list (if needed)
/// and increases the reference count by one
/// </summary>
internal void AddReference(object value, Type type)
{
if (_indexes.TryAdd(value, _values.Count))
{
_values.Add(value);
}
Helpers.IncrementCount(new TypedConstant(value, type), _references);
}
/// <summary>
/// Emits a live object as a constant
/// </summary>
internal void EmitConstant(LambdaCompiler lc, object value, Type type)
{
Debug.Assert(!ILGen.CanEmitConstant(value, type));
#if FEATURE_COMPILE_TO_METHODBUILDER
if (!lc.CanEmitBoundConstants)
{
throw Error.CannotCompileConstant(value);
}
#endif
if (_cache.TryGetValue(new TypedConstant(value, type), out LocalBuilder? local))
{
lc.IL.Emit(OpCodes.Ldloc, local);
return;
}
EmitConstantsArray(lc);
EmitConstantFromArray(lc, value, type);
}
/// <summary>
/// Emit code to cache frequently used constants into IL locals,
/// instead of pulling them out of the array each time
/// </summary>
internal void EmitCacheConstants(LambdaCompiler lc)
{
int count = 0;
foreach (KeyValuePair<TypedConstant, int> reference in _references)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
if (!lc.CanEmitBoundConstants)
{
throw Error.CannotCompileConstant(reference.Key.Value);
}
#endif
if (ShouldCache(reference.Value))
{
count++;
}
}
if (count == 0)
{
return;
}
EmitConstantsArray(lc);
// The same lambda can be in multiple places in the tree, so we
// need to clear any locals from last time.
_cache.Clear();
foreach (KeyValuePair<TypedConstant, int> reference in _references)
{
if (ShouldCache(reference.Value))
{
if (--count > 0)
{
// Dup array to keep it on the stack
lc.IL.Emit(OpCodes.Dup);
}
LocalBuilder local = lc.IL.DeclareLocal(reference.Key.Type);
EmitConstantFromArray(lc, reference.Key.Value, local.LocalType);
lc.IL.Emit(OpCodes.Stloc, local);
_cache.Add(reference.Key, local);
}
}
}
private static bool ShouldCache(int refCount)
{
// This caching is too aggressive in the face of conditionals and
// switch. Also, it is too conservative for variables used inside
// of loops.
return refCount > 2;
}
private static void EmitConstantsArray(LambdaCompiler lc)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
Debug.Assert(lc.CanEmitBoundConstants); // this should've been checked already
#endif
lc.EmitClosureArgument();
lc.IL.Emit(OpCodes.Ldfld, Closure_Constants);
}
private void EmitConstantFromArray(LambdaCompiler lc, object value, Type type)
{
int index;
if (!_indexes.TryGetValue(value, out index))
{
_indexes.Add(value, index = _values.Count);
_values.Add(value);
}
lc.IL.EmitPrimitive(index);
lc.IL.Emit(OpCodes.Ldelem_Ref);
if (type.IsValueType)
{
lc.IL.Emit(OpCodes.Unbox_Any, type);
}
else if (type != typeof(object))
{
lc.IL.Emit(OpCodes.Castclass, type);
}
}
}
}
| 35.019608 | 140 | 0.56355 | [
"MIT"
] | AzureMentor/runtime | src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/BoundConstants.cs | 7,144 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Shapes;
namespace WpfApplicationTM_01
{
/// <summary>
/// WindowInitialStressState.xaml 的交互逻辑
/// </summary>
public partial class WindowInitialStressState : Window
{
public WindowInitialStressState()
{
InitializeComponent();
}
private void btnConcel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnConfirm_Click(object sender, RoutedEventArgs e)
{
//FileUtil.editFileContentByRow("test.txt", 2, "哈哈哈");
string txt11 = this.txtBox11.Text;
string txt22 = this.txtBox22.Text;
string txt33 = this.txtBox33.Text;
string txt12 = this.txtBox12.Text;
string txt13 = this.txtBox13.Text;
string txt23 = this.txtBox23.Text;
string row10 = String.Format("{0} {1} {2} {3} {4} {5}", txt11, txt22, txt33, txt12, txt13, txt23);
FileUtil.editFileContentByRow("INPUT_simsand.txt", 10, row10);
MessageBox.Show("succeeded");
this.Close();
}
}
}
| 29.5625 | 110 | 0.631431 | [
"Apache-2.0"
] | BigDipper7/WPFFortranUIProject | WpfApplicationTM_01/WindowInitialStressState.xaml.cs | 1,437 | C# |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(ICT4RealsWebForms.Startup))]
namespace ICT4RealsWebForms
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 18.933333 | 67 | 0.665493 | [
"MIT"
] | marouanopen/ICT4RealsWebForms | ICT4RealsWebForms/ICT4RealsWebForms/Startup.cs | 286 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System
{
public static class Console
{
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
private static readonly object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields
private static TextReader _in;
private static TextWriter _out, _error;
private static ConsoleCancelEventHandler _cancelCallbacks;
private static ConsolePal.ControlCHandlerRegistrar _registrar;
internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class
{
lock (InternalSyncObject)
{
T result = Volatile.Read(ref field);
if (result == null)
{
result = initializer();
Volatile.Write(ref field, result);
}
return result;
}
}
public static TextReader In
{
get
{
return Volatile.Read(ref _in) ?? EnsureInitialized(ref _in, () =>
{
return ConsolePal.GetOrCreateReader();
});
}
}
public static ConsoleKeyInfo ReadKey()
{
return ConsolePal.ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept)
{
return ConsolePal.ReadKey(intercept);
}
public static TextWriter Out
{
get { return Volatile.Read(ref _out) ?? EnsureInitialized(ref _out, () => CreateOutputWriter(OpenStandardOutput())); }
}
public static TextWriter Error
{
get { return Volatile.Read(ref _error) ?? EnsureInitialized(ref _error, () => CreateOutputWriter(OpenStandardError())); }
}
private static TextWriter CreateOutputWriter(Stream outputStream)
{
return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
stream: outputStream,
encoding: ConsolePal.OutputEncoding,
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true) { AutoFlush = true });
}
private static StrongBox<bool> _isStdInRedirected;
private static StrongBox<bool> _isStdOutRedirected;
private static StrongBox<bool> _isStdErrRedirected;
public static bool IsInputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdInRedirected) ??
EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsOutputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdOutRedirected) ??
EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsErrorRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdErrRedirected) ??
EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore()));
return redirected.Value;
}
}
public static ConsoleColor BackgroundColor
{
get { return ConsolePal.BackgroundColor; }
set { ConsolePal.BackgroundColor = value; }
}
public static ConsoleColor ForegroundColor
{
get { return ConsolePal.ForegroundColor; }
set { ConsolePal.ForegroundColor = value; }
}
public static void ResetColor()
{
ConsolePal.ResetColor();
}
public static int WindowWidth
{
get
{
return ConsolePal.WindowWidth;
}
set
{
ConsolePal.WindowWidth = value;
}
}
public static bool CursorVisible
{
get
{
return ConsolePal.CursorVisible;
}
set
{
ConsolePal.CursorVisible = value;
}
}
public static event ConsoleCancelEventHandler CancelKeyPress
{
add
{
lock (InternalSyncObject)
{
_cancelCallbacks += value;
// If we haven't registered our control-C handler, do it.
if (_registrar == null)
{
_registrar = new ConsolePal.ControlCHandlerRegistrar();
_registrar.Register();
}
}
}
remove
{
lock (InternalSyncObject)
{
_cancelCallbacks -= value;
if (_registrar != null && _cancelCallbacks == null)
{
_registrar.Unregister();
_registrar = null;
}
}
}
}
public static Stream OpenStandardInput()
{
return ConsolePal.OpenStandardInput();
}
public static Stream OpenStandardOutput()
{
return ConsolePal.OpenStandardOutput();
}
public static Stream OpenStandardError()
{
return ConsolePal.OpenStandardError();
}
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, "newIn");
newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (InternalSyncObject) { _in = newIn; }
}
public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, "newOut");
newOut = SyncTextWriter.GetSynchronizedTextWriter(newOut);
lock (InternalSyncObject) { _out = newOut; }
}
public static void SetError(TextWriter newError)
{
CheckNonNull(newError, "newError");
newError = SyncTextWriter.GetSynchronizedTextWriter(newError);
lock (InternalSyncObject) { _error = newError; }
}
private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}
//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
//
// Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
// the inlined console writelines from them.
//
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Read()
{
return In.Read();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static String ReadLine()
{
return In.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine()
{
Out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer)
{
Out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg);
else
Out.WriteLine(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg);
else
Out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(bool value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer)
{
Out.Write(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(double value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(decimal value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(float value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(uint value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(ulong value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(Object value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String value)
{
Out.Write(value);
}
private sealed class ControlCDelegateData
{
private readonly ConsoleSpecialKey _controlKey;
private readonly ConsoleCancelEventHandler _cancelCallbacks;
internal bool Cancel;
internal bool DelegateStarted;
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks)
{
_controlKey = controlKey;
_cancelCallbacks = cancelCallbacks;
}
// This is the worker delegate that is called on the Threadpool thread to fire the actual events. It sets the DelegateStarted flag so
// the thread that queued the work to the threadpool knows it has started (since it does not want to block indefinitely on the task
// to start).
internal void HandleBreakEvent()
{
DelegateStarted = true;
var args = new ConsoleCancelEventArgs(_controlKey);
_cancelCallbacks(null, args);
Cancel = args.Cancel;
}
}
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey)
{
// The thread that this gets called back on has a very small stack on some systems. There is
// not enough space to handle a managed exception being caught and thrown. So, run a task
// on the threadpool for the actual event callback.
// To avoid the race condition between remove handler and raising the event
ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks;
if (cancelCallbacks == null)
{
return false;
}
var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks);
Task callBackTask = Task.Factory.StartNew(
d => ((ControlCDelegateData)d).HandleBreakEvent(),
delegateData,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Block until the delegate is done. We need to be robust in the face of the task not executing
// but we also want to get control back immediately after it is done and we don't want to give the
// handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a
// timout and a second time without if we are sure that the handler actually started.
TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds
callBackTask.Wait(controlCWaitTime);
if (!delegateData.DelegateStarted)
{
Debug.Assert(false, "The task to execute the handler did not start within 30 seconds.");
return false;
}
callBackTask.Wait();
return delegateData.Cancel;
}
}
}
| 32.759924 | 145 | 0.572245 | [
"MIT"
] | PatrickMcDonald/corefx | src/System.Console/src/System/Console.cs | 17,330 | C# |
using System;
using SubnetUtils;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
StringInput("10.1.100.1/24");
Console.WriteLine();
StringInput("10.1.100.1/255.255.255.0");
Console.WriteLine();
CidrAndByteMaskInput(new CidrBlock(10, 1, 100, 1), 24);
Console.WriteLine();
CidrAndByteMaskInput(new CidrBlock(10, 1, 100, 1), new CidrBlock(255, 255, 255, 0));
}
static void StringInput(string input)
{
Console.WriteLine($"Input: {input}");
var subnet = new Subnet(input);
Execute(subnet);
}
static void CidrAndByteMaskInput(CidrBlock address, byte mask)
{
Console.WriteLine($"Input: {address} {mask}");
var subnet = new Subnet(address, mask);
Execute(subnet);
}
static void CidrAndByteMaskInput(CidrBlock address, CidrBlock mask)
{
Console.WriteLine($"Input: {address} {mask}");
var subnet = new Subnet(address, mask);
Execute(subnet);
}
static void Execute(Subnet subnet)
{
Console.WriteLine($"Subnet: {subnet}");
Console.WriteLine($"Address: {subnet.Address}");
Console.WriteLine($"MaskCidr: {subnet.MaskCidr}");
Console.Write("Address Bit : ");
foreach (var x in subnet.Address.ToBit())
Console.Write(x);
Console.WriteLine();
Console.WriteLine($"Address ToUint32: {subnet.Address.ToUnit32()}");
Console.WriteLine($"Subnet ToUint32: {subnet.MaskCidr.ToUnit32()}");
var maskBytes = CidrBlock.GetMaskBytes(24);
Console.WriteLine($"MaskBytes: {maskBytes[0]}.{maskBytes[1]}.{maskBytes[2]}.{maskBytes[3]}");
Console.WriteLine($"Mask: {CidrBlock.FromMaskBytes(maskBytes)}");
}
}
}
| 34.684211 | 105 | 0.558422 | [
"MIT"
] | guitarrapc/CSharpPracticesLab | network/Subnet/ConsoleApp1/Program.cs | 1,977 | C# |
/*
* Copyright 2021 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : Administrator
* Summary : Represents a form for uploading configuration
*
* Author : Mikhail Shiryaev
* Created : 2018
* Modified : 2021
*/
using Scada.Admin.App.Code;
using Scada.Admin.Deployment;
using Scada.Admin.Project;
using Scada.Client;
using Scada.Forms;
using System;
using System.Windows.Forms;
namespace Scada.Admin.App.Forms.Deployment
{
/// <summary>
/// Represents a form for uploading configuration.
/// <para>Представляет форму для передачи конфигурации.</para>
/// </summary>
public partial class FrmUploadConfig : Form, IDeploymentForm
{
private readonly AppData appData; // the common data of the application
private readonly ScadaProject project; // the project under development
private readonly ProjectInstance instance; // the affected instance
private readonly string initialProfileName; // the initial instance profile name
private ConnectionOptions initialConnectionOptions; // the copy of the initial Agent connection options
private bool transferOptionsModified; // the selected upload options were modified
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private FrmUploadConfig()
{
InitializeComponent();
}
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
public FrmUploadConfig(AppData appData, ScadaProject project, ProjectInstance instance)
: this()
{
this.appData = appData ?? throw new ArgumentNullException(nameof(appData));
this.project = project ?? throw new ArgumentNullException(nameof(project));
this.instance = instance ?? throw new ArgumentNullException(nameof(instance));
initialProfileName = instance.DeploymentProfile;
initialConnectionOptions = null;
transferOptionsModified = false;
ProfileChanged = false;
ConnectionModified = false;
}
/// <summary>
/// Gets a value indicating whether the selected profile changed.
/// </summary>
public bool ProfileChanged { get; private set; }
/// <summary>
/// Gets a value indicating whether the Agent connection options were modified.
/// </summary>
public bool ConnectionModified { get; private set; }
/// <summary>
/// Saves the deployment configuration.
/// </summary>
private void SaveDeploymentConfig()
{
if (!project.DeploymentConfig.Save(out string errMsg))
appData.ErrLog.HandleError(errMsg);
}
private void FrmUploadConfig_Load(object sender, EventArgs e)
{
FormTranslator.Translate(this, GetType().FullName);
FormTranslator.Translate(ctrlProfileSelector, ctrlProfileSelector.GetType().FullName);
FormTranslator.Translate(ctrlTransferOptions, ctrlTransferOptions.GetType().FullName);
ctrlTransferOptions.Init(project.ConfigBase, true);
ctrlProfileSelector.Init(appData, project.DeploymentConfig, instance);
if (ctrlProfileSelector.SelectedProfile?.AgentConnectionOptions is ConnectionOptions connectionOptions)
initialConnectionOptions = connectionOptions.DeepClone();
}
private void FrmUploadConfig_FormClosed(object sender, FormClosedEventArgs e)
{
ConnectionModified = !ConnectionOptions.Equals(
initialConnectionOptions, ctrlProfileSelector.SelectedProfile?.AgentConnectionOptions);
}
private void ctrlProfileSelector_SelectedProfileChanged(object sender, EventArgs e)
{
// display selected upload options
DeploymentProfile deploymentProfile = ctrlProfileSelector.SelectedProfile;
if (deploymentProfile == null)
{
ctrlTransferOptions.Disable();
btnUpload.Enabled = false;
}
else
{
ctrlTransferOptions.OptionsToControls(deploymentProfile.UploadOptions);
btnUpload.Enabled = true;
}
transferOptionsModified = false;
}
private void ctrlTransferOptions_OptionsChanged(object sender, EventArgs e)
{
transferOptionsModified = true;
}
private void btnUpload_Click(object sender, EventArgs e)
{
// validate options and upload
if (ctrlProfileSelector.SelectedProfile is DeploymentProfile profile &&
ctrlTransferOptions.ValidateControls())
{
// save changed transfer options
if (transferOptionsModified)
{
ctrlTransferOptions.ControlsToOptions(profile.UploadOptions);
SaveDeploymentConfig();
}
// upload
instance.DeploymentProfile = profile.Name;
ProfileChanged = initialProfileName != profile.Name;
FrmTransfer frmTransfer = new(appData, project, instance, profile);
if (frmTransfer.UploadConfig())
DialogResult = DialogResult.OK;
}
}
}
}
| 37.141104 | 115 | 0.633465 | [
"Apache-2.0"
] | RapidScada/scada-v6 | ScadaAdmin/ScadaAdmin/ScadaAdmin/Forms/Deployment/FrmUploadConfig.cs | 6,096 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIMarker : MonoBehaviour
{
public enum MarkerTypes{
None, JumpMarker
}
void Awake()
{
AIMarkers.Markers.Add(this);
}
private void OnDestroy()
{
AIMarkers.Markers.Remove(this);
}
public virtual (bool, MarkerTypes, Vector2) ModifyAI(Vector2 pos)
{
return (false, MarkerTypes.None, Vector2.zero);
}
public static bool IsWithinBox(Vector2 point, Vector2 box_center, Vector2 box_size)
{
return (point.y < box_center.y + box_size.y / 2 &&
point.y > box_center.y - box_size.y / 2 &&
point.x < box_center.x + box_size.x / 2 &&
point.x > box_center.x - box_size.x / 2);
}
}
| 23.4 | 87 | 0.594628 | [
"MIT"
] | Airtoum/EllumiTheFireSprite | Assets/Entities/AIMarkers/AIMarker.cs | 819 | C# |
using System;
using System.Collections.Generic;
using Moq;
using MTCG;
using MTCG.Entity;
using MTCG.Interface;
using MTCG.Model;
using NUnit.Framework;
namespace UnitTest
{
[TestFixture]
public class PackageClassTests
{
[SetUp]
public void Setup()
{
}
[Test]
public void PackageModell_Created_Successful()
{
//Arrange
var cardEntity = new CardEntity {Damage = 10, CardType = CardType.MonsterCard, Race = Race.Dragon};
var list = new List<CardEntity>();
var entity = new PackageEntity {Amount = 1, Id = Guid.NewGuid().ToString("N"), CardsInPackage = list};
var database = new Mock<IDatabase>();
database.Setup(x => x.AddCardsToDatabase(It.IsAny<List<CardEntity>>())).Returns(true);
database.Setup(x => x.AddPackage(It.IsAny<PackageEntity>())).Returns(true);
//Act
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
var packageModell = new PackageModell(database.Object);
var package = packageModell.AddPackage(entity);
//Assert
Assert.That(package == 0 && packageModell.Entity.CardsInPackage.Count == list.Count);
}
[Test]
public void PackageModell_Create_Empty_Fails()
{
//Arrange
var cardEntity = new CardEntity {Damage = 10, CardType = CardType.MonsterCard, Race = Race.Dragon};
var list = new List<CardEntity>();
var entity = new PackageEntity {Amount = 1, Id = Guid.NewGuid().ToString("N"), CardsInPackage = list};
var database = new Mock<IDatabase>();
database.Setup(x => x.AddCardsToDatabase(It.IsAny<List<CardEntity>>())).Returns(true);
database.Setup(x => x.AddPackage(It.IsAny<PackageEntity>())).Returns(true);
//Act
var packageModell = new PackageModell(database.Object);
var package = packageModell.AddPackage(entity);
//Assert
Assert.That(package == 1);
}
[Test]
public void PackageModell_Create_NoType()
{
//Arrange
var cardEntity = new CardEntity {Damage = 10, Race = Race.Dragon};
var list = new List<CardEntity>();
var entity = new PackageEntity {Amount = 1, CardsInPackage = list};
var database = new Mock<IDatabase>();
database.Setup(x => x.AddCardsToDatabase(It.IsAny<List<CardEntity>>())).Returns(true);
database.Setup(x => x.AddPackage(It.IsAny<PackageEntity>())).Returns(true);
//Act
entity.CardsInPackage.Add(cardEntity);
var packageModell = new PackageModell(database.Object);
var package = packageModell.AddPackage(entity);
//Assert
Assert.That(package == 2);
}
[Test]
public void PackageModell_Create_failed()
{
//Arrange
var cardEntity = new CardEntity {Damage = 10, Race = Race.Dragon , CardType = CardType.MonsterCard};
var list = new List<CardEntity>();
var entity = new PackageEntity {Amount = 1, Id = Guid.NewGuid().ToString("N"), CardsInPackage = list};
var database = new Mock<IDatabase>();
database.Setup(x => x.AddPackage(It.IsAny<PackageEntity>())).Returns(false);
//Act
entity.CardsInPackage.Add(cardEntity);
var packageModell = new PackageModell(database.Object);
var package = packageModell.AddPackage(entity);
//Assert
Assert.That(package == 3);
}
[Test]
public void PackageModell_Open()
{
//Arrange
var cardEntity = new CardEntity {Damage = 10, CardType = CardType.MonsterCard, Race = Race.Dragon};
var list = new List<CardEntity>();
var entity = new PackageEntity {Amount = 1, Id = Guid.NewGuid().ToString("N"), CardsInPackage = list};
var database = new Mock<IDatabase>();
database.Setup(x => x.AddCardsToDatabase(It.IsAny<List<CardEntity>>())).Returns(true);
database.Setup(x => x.OpenPackage(It.IsAny<PackageEntity>(), It.IsAny<UserEntity>())).Returns(true);
var userEntity = new UserEntity
{
Coins = 30,
Token = "test-mtcgToken"
};
//Act
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
var package = new PackageModell(database.Object);
package.Entity = entity;
var result = package.Open(userEntity);
//Assert
Assert.That(result.Count == package.Entity.CardsInPackage.Count);
}
[Test]
public void PackageModell_Open_failed()
{
//Arrange
var cardEntity = new CardEntity {Damage = 10, CardType = CardType.MonsterCard, Race = Race.Dragon};
var list = new List<CardEntity>();
var entity = new PackageEntity {Amount = 1, Id = Guid.NewGuid().ToString("N"), CardsInPackage = list};
var database = new Mock<IDatabase>();
database.Setup(x => x.AddCardsToDatabase(It.IsAny<List<CardEntity>>())).Returns(true);
database.Setup(x => x.OpenPackage(It.IsAny<PackageEntity>(), It.IsAny<UserEntity>())).Returns(false);
var userEntity = new UserEntity
{
Coins = 30,
Token = "test-mtcgToken"
};
//Act
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
list.Add(cardEntity);
var package = new PackageModell(database.Object);
package.Entity = entity;
var result = package.Open(userEntity);
//Assert
Assert.That(result == null);
}
}
} | 40.217949 | 114 | 0.559611 | [
"Apache-2.0"
] | Ephaltes/MTCG | UnitTest/PackageClassTests.cs | 6,276 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 組件的一般資訊是由下列的屬性集控制。
// 變更這些屬性的值即可修改組件的相關
// 資訊。
[assembly: AssemblyTitle("HermiteCurve")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HermiteCurve")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 將 ComVisible 設定為 false 會使得這個組件中的類型
// 對 COM 元件而言為不可見。如果您需要從 COM 存取這個組件中
// 的類型,請在該類型上將 ComVisible 屬性設定為 true。
[assembly: ComVisible(false)]
// 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID
[assembly: Guid("cbe2f9af-2d59-431e-a9d0-a09d5dc60025")]
// 組件的版本資訊是由下列四項值構成:
//
// 主要版本
// 次要版本
// 組建編號
// 修訂編號
//
// 您可以指定所有的值,也可以依照以下的方式,使用 '*' 將組建和修訂編號
// 指定為預設值:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 26.243243 | 56 | 0.717817 | [
"MIT"
] | yuhao-kuo/MouseHermiteCurve | simulation/HermiteCurve/Properties/AssemblyInfo.cs | 1,326 | C# |
using System.Collections.Generic;
using System.Data;
using Hikari.WPF.MVVM;
namespace DbTool.Models
{
public class PageDbFirstModel : NotificationObject
{
private string _connectionString; // 数据库连接字符串
public string ConnectionString
{
get => _connectionString;
set { _connectionString = value; NotifyPropertyChanged(); }
}
private List<string> _providerNameList;
public List<string> ProviderNameList // 数据库类型
{
get => _providerNameList;
set { _providerNameList = value; NotifyPropertyChanged(); }
}
private DataView _tableList; // 表列表
public DataView TableList
{
get => _tableList;
set { _tableList = value; NotifyPropertyChanged(); }
}
private DataView _tableFieldList; // 表字段列表
public DataView TableFieldList
{
get => _tableFieldList;
set { _tableFieldList = value; NotifyPropertyChanged(); }
}
private List<string> _primaryKeyList; // 主键列表
public List<string> PrimaryKeyList
{
get => _primaryKeyList;
set { _primaryKeyList = value; NotifyPropertyChanged(); }
}
private string _codeContent; // 代码内容
public string CodeContent
{
get => _codeContent;
set { _codeContent = value; NotifyPropertyChanged(); }
}
private string _modelPath; // 命名空间
public string ModelPath
{
get => _modelPath;
set { _modelPath = value; NotifyPropertyChanged(); }
}
private string _modelPrefix; // 前缀
public string ModelPrefix
{
get => _modelPrefix;
set { _modelPrefix = value; NotifyPropertyChanged(); }
}
private string _modelSuffix; // 后缀
public string ModelSuffix
{
get => _modelSuffix;
set { _modelSuffix = value; NotifyPropertyChanged(); }
}
}
} | 27.52 | 71 | 0.568314 | [
"MIT"
] | LoveHikari/DbTool | src/DbTool/Models/PageDbFirstModel.cs | 2,140 | C# |
using Avalonia.Markup.Xaml;
using PleasantUI.Controls.Custom;
using Regul.OlibKey.General;
namespace Regul.OlibKey.Views.Windows;
public class SearchView : PleasantDialogWindow, IMustCloseWhenLocked
{
public SearchView() => AvaloniaXamlLoader.Load(this);
} | 25.9 | 68 | 0.818533 | [
"MIT"
] | Onebeld/Regul.OlibKey | Regul.OlibKey/Views/Windows/Search/SearchView.axaml.cs | 259 | 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("WormsWorldParty")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WormsWorldParty")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("e1e37031-7f07-4faa-ac71-181038489ca6")]
// 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.783784 | 84 | 0.748927 | [
"MIT"
] | dragobaltov/Programming-Basics-And-Fundamentals | WormsWorldParty/WormsWorldParty/Properties/AssemblyInfo.cs | 1,401 | C# |
using Dynamo.Core;
using Dynamo.Extensions;
using Dynamo.Graph.Nodes;
using Dynamo.Graph.Workspaces;
using Dynamo.Models;
using Dynamo.ViewModels;
using Dynamo.Wpf.ViewModels.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
namespace WarningsViewExtension
{
public class WarningsWindowViewModel : NotificationObject, IDisposable
{
private ObservableCollection<NodeInfo> _warningNodes;
private ReadyParams _readyParams;
private DynamoViewModel _dynamoViewModel;
private NodeViewModel _displaying;
public ObservableCollection<NodeInfo> WarningNodes
{
get
{
_warningNodes = getWarningNodes();
return _warningNodes;
}
set
{
_warningNodes = value;
}
}
public ObservableCollection<NodeInfo> getWarningNodes()
{
if (_displaying != null)
{
HideTooltip(_displaying);
_displaying = null;
}
// Collect error/warning nodes, sorting by X position
// The second Select replaces the blank (0) ID with the row number
var nodeList =
(from n in _readyParams.CurrentWorkspaceModel.Nodes
where n.State != ElementState.Active && n.State != ElementState.Dead
orderby n.Rect.TopLeft.X ascending
select new NodeInfo(0, n.Name, n.GUID)).Select(
(item, index) => new NodeInfo(index + 1, item.Name, item.GUID)
);
// Return a bindable collection
return new ObservableCollection<NodeInfo>(nodeList);
}
// Construction & disposal
public WarningsWindowViewModel(ReadyParams p, DynamoViewModel dynamoVM)
{
_readyParams = p;
_dynamoViewModel = dynamoVM;
_readyParams.CurrentWorkspaceChanged +=
ReadyParams_CurrentWorkspaceChanged;
AddEventHandlers(_readyParams.CurrentWorkspaceModel);
}
public void Dispose()
{
_readyParams.CurrentWorkspaceChanged -=
ReadyParams_CurrentWorkspaceChanged;
RemoveEventHandlers(_readyParams.CurrentWorkspaceModel);
}
// Event handlers
void ReadyParams_CurrentWorkspaceChanged(
Dynamo.Graph.Workspaces.IWorkspaceModel obj
)
{
if (_readyParams != null)
{
RemoveEventHandlers(_readyParams.CurrentWorkspaceModel);
}
AddEventHandlers(obj);
RaisePropertyChanged("WarningNodes");
}
private void CurrentWorkspaceModel_NodeAdded(NodeModel node)
{
node.PropertyChanged += node_PropertyChanged;
}
private void CurrentWorkspaceModel_NodeRemoved(NodeModel node)
{
node.PropertyChanged -= node_PropertyChanged;
}
private void CurrentWorkspaceModel_NodesCleared()
{
foreach (var node in _readyParams.CurrentWorkspaceModel.Nodes)
{
node.PropertyChanged -= node_PropertyChanged;
}
RaisePropertyChanged("WarningNodes");
}
private void node_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "State")
{
RaisePropertyChanged("WarningNodes");
}
}
// Attach and remove handlers
private void AddEventHandlers(IWorkspaceModel model)
{
foreach (var node in model.Nodes)
{
node.PropertyChanged += node_PropertyChanged;
}
model.NodeAdded += CurrentWorkspaceModel_NodeAdded;
model.NodeRemoved += CurrentWorkspaceModel_NodeRemoved;
model.NodesCleared += CurrentWorkspaceModel_NodesCleared;
}
private void RemoveEventHandlers(IWorkspaceModel model)
{
foreach (var node in model.Nodes)
{
node.PropertyChanged -= node_PropertyChanged;
}
model.NodeAdded -= CurrentWorkspaceModel_NodeAdded;
model.NodeRemoved -= CurrentWorkspaceModel_NodeRemoved;
model.NodesCleared -= CurrentWorkspaceModel_NodesCleared;
}
public void ZoomToPosition(NodeInfo nodeInfo)
{
foreach (var node in _readyParams.CurrentWorkspaceModel.Nodes)
{
if (node.GUID == nodeInfo.GUID)
{
// node.Select();
var cmd = new DynamoModel.SelectInRegionCommand(node.Rect, false);
_readyParams.CommandExecutive.ExecuteCommand(cmd, null, null);
// Call this twice as otherwise the zoom level altertnates been close
// and far
_dynamoViewModel.FitViewCommand.Execute(null);
_dynamoViewModel.FitViewCommand.Execute(null);
// Display the error/warning message
var hsvm = (HomeWorkspaceViewModel)_dynamoViewModel.HomeSpaceViewModel;
foreach (var nodeModel in hsvm.Nodes)
{
if (nodeModel.Id == node.GUID)
{
// First hide the previously displayed one if there was one
if (_displaying != null)
{
HideTooltip(_displaying);
}
ShowTooltip(nodeModel);
_displaying = nodeModel;
break;
}
}
}
}
}
// Is the state a warning?
private bool IsWarning(ElementState state)
{
return
state == ElementState.Warning ||
state == ElementState.PersistentWarning;
}
// Expand the warning bubble for the provided NodeViewModel
private void ShowTooltip(NodeViewModel nvm)
{
var data = new InfoBubbleDataPacket();
data.Style =
IsWarning(nvm.State) ?
InfoBubbleViewModel.Style.Warning :
InfoBubbleViewModel.Style.Error;
data.ConnectingDirection = InfoBubbleViewModel.Direction.Bottom;
nvm.ErrorBubble.ShowFullContentCommand.Execute(data);
}
// Collapse he warning bubble for the provided NodeViewModel
private void HideTooltip(NodeViewModel nvm)
{
var data = new InfoBubbleDataPacket();
data.Style =
IsWarning(nvm.State) ?
InfoBubbleViewModel.Style.WarningCondensed :
InfoBubbleViewModel.Style.ErrorCondensed;
data.ConnectingDirection = InfoBubbleViewModel.Direction.Bottom;
nvm.ErrorBubble.ShowCondensedContentCommand.Execute(data);
}
}
}
| 29.182648 | 82 | 0.643874 | [
"MIT"
] | KeanW/Warnamo | src/WarningsViewExtension/WarningsWindowViewModel.cs | 6,393 | C# |
using Confluent.Kafka;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Extension.Confluent.Kafka.Client.Consumer
{
public interface IConsumeResultCallback<TKey, TValue>
{
public Task OnReceivedAsync(ReadOnlyMemory<ConsumeResult<TKey, TValue>> results, CancellationToken cancellationToken);
}
}
| 26.615385 | 126 | 0.783237 | [
"MIT"
] | ettenauer/extension-confluent-kafka-client | Source/Extension.Confluent.Kafka.Client/Consumer/IConsumeResultCallback.cs | 348 | C# |
// Copyright (c) SumTech Business Solutions, LLC. All Rights Reserved.
namespace SongList.Api.Models
{
using System;
using System.Text.RegularExpressions;
using global::SongList.Api.Repositories;
/// <summary>
/// Represents an arrangment of a song.
/// </summary>7
public class Arrangement
{
/// <summary>
/// The regular expression for finding chords in the content. Chords are found between curly braces.
/// Examples of chords: {G}, {D#m}
/// </summary>
private static Regex chordRegex = new Regex(@"\{([^\{\}]*)\}", RegexOptions.Compiled);
/// <summary>
/// The regular expression for finding headings in the content. Headings are found between square brackets.
/// Examples of chords: [Intro], [Verse], [Verse 1], [Chorus], [Bridge], [Outro]
/// </summary>
private static Regex headingRegex = new Regex(@"\[([^\[\]]*)\]");
/// <summary>
/// Initializes a new instance of the <see cref="Arrangement"/> class.
/// </summary>
public Arrangement()
{
this.Name = "Standard";
this.KeyVariation = SongKeyVariation.Natural;
}
/// <summary>
/// Gets or sets the unique identifier for the arrangement.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the song to which this arrangment is designated.
/// </summary>
public Song Song { get; set; }
/// <summary>
/// Gets or sets the unique ID for the song to which this arrangement is designed.
/// </summary>
public int SongId { get; set; }
/// <summary>
/// Gets or sets a name for the arrangment. This should be a useful identifier when there are multiple arrangements for the same song.
/// The default value will be "Standard."
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the main key in which the arrangment is written.
/// </summary>
public NaturalSongKey Key { get; set; }
/// <summary>
/// Gets or sets the indicatino of whether the key is sharp, flat, or natural.
/// </summary>
public SongKeyVariation KeyVariation { get; set; }
/// <summary>
/// Gets or sets the contents of the arrangmeent.
/// This information is in a format which is editable by a user.
/// </summary>
public string Contents { get; set; }
/// <summary>
/// Gets the contents of the arrangement with HTML tags incorporated.
/// This information is in a format which is to be interpretted by the browser.
/// </summary>
public string Chords
{
get
{
ContentsParser parser = new ChordParser();
return parser.ToHtml(this.Contents);
}
}
/// <summary>
/// Gets the lyrics for the arrangement.
/// This information is in a format which is to be interpretted by the browser.
/// </summary>
public string Lyrics
{
get
{
ContentsParser parser = new LyricParser();
return parser.ToHtml(this.Contents);
}
}
/// <summary>
/// Gets or sets any notes about the arrangment.
/// </summary>
public string Notes { get; set; }
}
}
| 33.846154 | 142 | 0.555682 | [
"MIT"
] | sumtech/song-list-api | Models/Arrangement.cs | 3,522 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Tatum.Model;
using Tatum.Model.Requests;
using System.ComponentModel.DataAnnotations;
namespace Tatum.Model.Requests
{
public class CeloBurnErc721 : BurnErc721
{
[Required]
public Currency feecurrency { get; set; }
}
} | 17.857143 | 50 | 0.661333 | [
"MIT"
] | grace43/tatum-csharp | Tatum/Model/Requests/Celo/CeloBurnErc721.cs | 377 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Threading.Tasks;
using FakeItEasy;
using NodaTime;
using Squidex.Infrastructure.TestHelpers;
using Xunit;
namespace Squidex.Infrastructure.Commands
{
public class EnrichWithTimestampCommandMiddlewareTests
{
private readonly IClock clock = A.Fake<IClock>();
private readonly ICommandBus commandBus = A.Dummy<ICommandBus>();
[Fact]
public async Task Should_set_timestamp_for_timestamp_command()
{
var utc = Instant.FromUnixTimeSeconds(1000);
var sut = new EnrichWithTimestampCommandMiddleware(clock);
A.CallTo(() => clock.GetCurrentInstant())
.Returns(utc);
var command = new MyCommand();
await sut.HandleAsync(new CommandContext(command, commandBus));
Assert.Equal(utc, command.Timestamp);
}
[Fact]
public async Task Should_do_nothing_for_normal_command()
{
var sut = new EnrichWithTimestampCommandMiddleware(clock);
await sut.HandleAsync(new CommandContext(A.Dummy<ICommand>(), commandBus));
A.CallTo(() => clock.GetCurrentInstant()).MustNotHaveHappened();
}
}
}
| 32.6875 | 87 | 0.562141 | [
"MIT"
] | BtrJay/squidex | tests/Squidex.Infrastructure.Tests/Commands/EnrichWithTimestampCommandMiddlewareTests.cs | 1,572 | C# |
// <auto-generated />
using System;
using AspnetRun.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace AspnetRun.Web.Migrations
{
[DbContext(typeof(AspnetRunContext))]
partial class AspnetRunContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AspnetRun.Core.Entities.Blog", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("ImageFile")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(80)")
.HasMaxLength(80);
b.Property<string>("Summary")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Blog");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Cart", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("UserName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Cart");
});
modelBuilder.Entity("AspnetRun.Core.Entities.CartItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int?>("CartId")
.HasColumnType("int");
b.Property<string>("Color")
.HasColumnType("nvarchar(max)");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("Quantity")
.HasColumnType("int");
b.Property<decimal>("TotalPrice")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("UnitPrice")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CartId");
b.HasIndex("ProductId");
b.ToTable("CartItem");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("ImageName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(80)")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("Category");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Compare", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("UserName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Compare");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Message")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Phone")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Contact");
});
modelBuilder.Entity("AspnetRun.Core.Entities.List", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("ImageFile")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(80)")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("List");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<decimal>("GrandTotal")
.HasColumnType("decimal(18,2)");
b.Property<int>("PaymentMethod")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<string>("UserName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Order");
});
modelBuilder.Entity("AspnetRun.Core.Entities.OrderItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Color")
.HasColumnType("nvarchar(max)");
b.Property<int?>("OrderId")
.HasColumnType("int");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("Quantity")
.HasColumnType("int");
b.Property<decimal>("TotalPrice")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("UnitPrice")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("ProductId");
b.ToTable("OrderItem");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("ImageFile")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(80)")
.HasMaxLength(80);
b.Property<string>("Slug")
.HasColumnType("nvarchar(max)");
b.Property<double>("Star")
.HasColumnType("float");
b.Property<string>("Summary")
.HasColumnType("nvarchar(max)");
b.Property<decimal>("UnitPrice")
.HasColumnType("decimal(18,2)");
b.Property<int?>("UnitsInStock")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("Product");
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductCompare", b =>
{
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("CompareId")
.HasColumnType("int");
b.HasKey("ProductId", "CompareId");
b.HasIndex("CompareId");
b.ToTable("ProductCompare");
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductList", b =>
{
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("ListId")
.HasColumnType("int");
b.HasKey("ProductId", "ListId");
b.HasIndex("ListId");
b.ToTable("ProductList");
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductRelatedProduct", b =>
{
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("RelatedProductId")
.HasColumnType("int");
b.HasKey("ProductId", "RelatedProductId");
b.HasIndex("RelatedProductId");
b.ToTable("ProductRelatedProduct");
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductWishlist", b =>
{
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("WishlistId")
.HasColumnType("int");
b.HasKey("ProductId", "WishlistId");
b.HasIndex("WishlistId");
b.ToTable("ProductWishlist");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Review", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Comment")
.HasColumnType("nvarchar(max)");
b.Property<string>("EMail")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ProductId")
.HasColumnType("int");
b.Property<double>("Star")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("Review");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Specification", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ProductId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("Specification");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Tag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ProductId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("Tag");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Wishlist", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("UserName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Wishlist");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("AspnetRun.Core.Entities.CartItem", b =>
{
b.HasOne("AspnetRun.Core.Entities.Cart", null)
.WithMany("Items")
.HasForeignKey("CartId");
b.HasOne("AspnetRun.Core.Entities.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AspnetRun.Core.Entities.OrderItem", b =>
{
b.HasOne("AspnetRun.Core.Entities.Order", null)
.WithMany("Items")
.HasForeignKey("OrderId");
b.HasOne("AspnetRun.Core.Entities.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AspnetRun.Core.Entities.Product", b =>
{
b.HasOne("AspnetRun.Core.Entities.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductCompare", b =>
{
b.HasOne("AspnetRun.Core.Entities.Compare", "Compare")
.WithMany("ProductCompares")
.HasForeignKey("CompareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AspnetRun.Core.Entities.Product", "Product")
.WithMany("ProductCompares")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductList", b =>
{
b.HasOne("AspnetRun.Core.Entities.List", "List")
.WithMany("ProductLists")
.HasForeignKey("ListId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AspnetRun.Core.Entities.Product", "Product")
.WithMany("ProductLists")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductRelatedProduct", b =>
{
b.HasOne("AspnetRun.Core.Entities.Product", "Product")
.WithMany("ProductRelatedProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("AspnetRun.Core.Entities.Product", "RelatedProduct")
.WithMany()
.HasForeignKey("RelatedProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AspnetRun.Core.Entities.ProductWishlist", b =>
{
b.HasOne("AspnetRun.Core.Entities.Product", "Product")
.WithMany("ProductWishlists")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AspnetRun.Core.Entities.Wishlist", "Wishlist")
.WithMany("ProductWishlists")
.HasForeignKey("WishlistId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AspnetRun.Core.Entities.Review", b =>
{
b.HasOne("AspnetRun.Core.Entities.Product", null)
.WithMany("Reviews")
.HasForeignKey("ProductId");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Specification", b =>
{
b.HasOne("AspnetRun.Core.Entities.Product", null)
.WithMany("Specifications")
.HasForeignKey("ProductId");
});
modelBuilder.Entity("AspnetRun.Core.Entities.Tag", b =>
{
b.HasOne("AspnetRun.Core.Entities.Product", null)
.WithMany("Tags")
.HasForeignKey("ProductId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.159204 | 125 | 0.447316 | [
"MIT"
] | 02amit1994/run-aspnetcore-realworld | src/AspnetRun.Web/Migrations/AspnetRunContextModelSnapshot.cs | 29,878 | C# |
using System;
namespace NightlyCode.Database.Fields {
/// <summary>
/// parameter for statements
/// </summary>
public class DBParameter : DBField {
internal DBParameter() { }
/// <summary>
/// creates a reference to a parameter
/// </summary>
/// <param name="index">index of parameter</param>
/// <returns>field to use in expressions</returns>
public static DBParameter Index(int index) {
throw new NotImplementedException("Method has no implementation since it is only used for typed expressions");
}
#region expression fields
/// <summary>
/// field used for lambda operations
/// </summary>
public new static object Value => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="bool"/> parameter
/// </summary>
public new static bool Bool => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="Guid"/> parameter
/// </summary>
public new static Guid Guid => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="int"/> parameter
/// </summary>
public new static int Int32 => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="long"/> parameter
/// </summary>
public new static long Int64 => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="string"/> parameter
/// </summary>
public new static string String => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="string"/> parameter
/// </summary>
public new static float Single => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="Double"/> parameter
/// </summary>
public new static double Double => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="decimal"/> parameter
/// </summary>
public new static decimal Decimal => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="DateTime"/> parameter
/// </summary>
public new static DateTime DateTime => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="TimeSpan"/> parameter
/// </summary>
public new static TimeSpan TimeSpan => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see cref="T:byte[]"/> parameter
/// </summary>
public new static byte[] Blob => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
#endregion
}
/// <summary>
/// generic parameter for specific types
/// </summary>
/// <typeparam name="T"></typeparam>
public class DBParameter<T> : DBParameter {
internal DBParameter() { }
/// <summary>
/// creates a reference to a parameter
/// </summary>
/// <param name="index">index of parameter</param>
/// <returns>field to use in expressions</returns>
public new static DBParameter<T> Index(int index)
{
throw new NotImplementedException("Method has no implementation since it is only used for typed expressions");
}
/// <summary>
/// field to use in expressions when referencing a <see typeref="T"/> parameter
/// </summary>
public T Data => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
/// <summary>
/// field to use in expressions when referencing a <see typeref="T"/> parameter
/// </summary>
public new static T Value => throw new NotImplementedException("Field has no implementation since it is only used for typed expressions");
}
} | 46.495575 | 156 | 0.646936 | [
"Unlicense"
] | telmengedar/NightlyCode.DB | Database/Fields/DBParameter.cs | 5,256 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using GameUtils;
namespace EGamePlay.Combat
{
/// <summary>
/// 逻辑时间触发组件
/// </summary>
public class ExecutionTimeTriggerComponent : Component
{
public override bool DefaultEnable { get; set; } = false;
public float TriggerTime { get; set; }
public string TimeValueExpression { get; set; }
public GameTimer TriggerTimer { get; set; }
public override void Setup()
{
}
public override void Update()
{
if (TriggerTimer != null && TriggerTimer.IsFinished == false)
{
TriggerTimer.UpdateAsFinish(Time.deltaTime, GetEntity<ExecutionEffect>().ApplyEffect);
}
}
public override void OnEnable()
{
//Log.Debug(GetEntity<LogicEntity>().Effect.Interval);
if (!string.IsNullOrEmpty(TimeValueExpression))
{
var expression = ExpressionHelper.TryEvaluate(TimeValueExpression);
TriggerTime = (int)expression.Value / 1000f;
TriggerTimer = new GameTimer(TriggerTime);
}
else if (TriggerTime > 0)
{
TriggerTimer = new GameTimer(TriggerTime);
}
else
{
}
}
}
} | 26.584906 | 102 | 0.560681 | [
"MIT"
] | m969/EGamePlay | Assets/EGamePlay/Combat/AbilityEffect/ExecutionComponents/ExecutionTimeTriggerComponent.cs | 1,427 | C# |
using System.Collections.Generic;
using BuckarooSdk.Base;
using BuckarooSdk.DataTypes.RequestBases;
using BuckarooSdk.Services;
namespace BuckarooSdk.Data
{
/// <summary>
/// General data class, to hold a Request object and a list of services
/// </summary>
public class Data
{
internal AuthenticatedRequest AuthenticatedRequest { get; set; }
internal List<Service> Services { get; set; }
internal DataBase DataRequestBase { get; private set; }
internal Data(AuthenticatedRequest authenticatedRequest)
{
authenticatedRequest.Request.Endpoint = Constants.Settings.GatewaySettings.DataRequestEndPoint;
this.AuthenticatedRequest = authenticatedRequest;
}
public ConfiguredDataRequest SetBasicFields(DataBase basicFields)
{
this.DataRequestBase = basicFields;
return new ConfiguredDataRequest(this);
}
#region "Internal methods"
/// <summary>
/// Adding a service to the datarequest.
/// </summary>
/// <param name="serviceName">The name of the service</param>
/// <param name="parameters">The list of service parameters</param>
internal void AddService(string serviceName, List<RequestParameter> parameters, string action, string version = "1")
{
var service = new Service()
{
Name = serviceName,
Action = action,
Version = version,
Parameters = parameters,
};
if(this.DataRequestBase.Services.ServiceList == null)
{
this.DataRequestBase.Services.ServiceList = new List<Service>();
}
this.DataRequestBase.Services.ServiceList.Add(service);
}
internal void AddGlobal(string serviceName, List<RequestParameter> parameters, string action, string version = "1")
{
var global = new Global()
{
Name = serviceName,
Action = action,
Version = version,
Parameters = parameters,
};
if (this.DataRequestBase.Services.ServiceList == null)
{
this.DataRequestBase.Services.ServiceList = new List<Service>();
}
this.DataRequestBase.Services.ServiceList.Add(global);
}
#endregion
}
}
| 28.554054 | 118 | 0.690014 | [
"MIT"
] | buckaroo-it/BuckarooSdk_DotNet | BuckarooSdk/Data/Data.cs | 2,115 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace IronPython.Compiler {
/// <summary>
/// When finding a yield return or yield break, this rewriter flattens out
/// containing blocks, scopes, and expressions with stack state. All
/// scopes encountered have their variables promoted to the generator's
/// closure, so they survive yields.
/// </summary>
internal sealed class GeneratorRewriter : DynamicExpressionVisitor {
private readonly Expression _body;
private readonly string _name;
private readonly StrongBox<Type> _tupleType = new StrongBox<Type>(null);
private readonly StrongBox<ParameterExpression> _tupleExpr = new StrongBox<ParameterExpression>(null);
// The one return label, or more than one if we're in a finally
private readonly Stack<LabelTarget> _returnLabels = new Stack<LabelTarget>();
private readonly ParameterExpression _gotoRouter;
private bool _inTryWithFinally;
private readonly List<YieldMarker> _yields = new List<YieldMarker>();
private readonly Dictionary<ParameterExpression, DelayedTupleExpression> _vars = new Dictionary<ParameterExpression, DelayedTupleExpression>();
private readonly List<KeyValuePair<ParameterExpression, DelayedTupleExpression>> _orderedVars = new List<KeyValuePair<ParameterExpression, DelayedTupleExpression>>();
// Possible optimization: reuse temps. Requires scoping them correctly,
// and then storing them back in a free list
private readonly List<ParameterExpression> _temps = new List<ParameterExpression>();
private Expression _state, _current;
// These two constants are used internally. They should not conflict
// with valid yield states.
private const int GotoRouterYielding = 0;
private const int GotoRouterNone = -1;
// The state of the generator before it starts and when it's done
internal const int NotStarted = -1;
internal const int Finished = 0;
internal static ParameterExpression _generatorParam = Expression.Parameter(typeof(PythonGenerator), "$generator");
internal GeneratorRewriter(string name, Expression body) {
_body = body;
_name = name;
_returnLabels.Push(Expression.Label("retLabel"));
_gotoRouter = Expression.Variable(typeof(int), "$gotoRouter");
}
internal Expression Reduce(bool shouldInterpret, bool emitDebugSymbols, int compilationThreshold,
IList<ParameterExpression> parameters, Func<Expression<Func<MutableTuple, object>>,
Expression<Func<MutableTuple, object>>> bodyConverter) {
_state = LiftVariable(Expression.Parameter(typeof(int), "state"));
_current = LiftVariable(Expression.Parameter(typeof(object), "current"));
// lift the parameters into the tuple
foreach (ParameterExpression pe in parameters) {
LiftVariable(pe);
}
DelayedTupleExpression liftedGen = LiftVariable(_generatorParam);
// Visit body
Expression body = Visit(_body);
Debug.Assert(_returnLabels.Count == 1);
// Add the switch statement to the body
int count = _yields.Count;
var cases = new SwitchCase[count + 1];
for (int i = 0; i < count; i++) {
cases[i] = Expression.SwitchCase(Expression.Goto(_yields[i].Label), AstUtils.Constant(_yields[i].State));
}
cases[count] = Expression.SwitchCase(Expression.Goto(_returnLabels.Peek()), AstUtils.Constant(Finished));
// Create the lambda for the PythonGeneratorNext, hoisting variables
// into a tuple outside the lambda
Expression[] tupleExprs = new Expression[_vars.Count];
foreach (var variable in _orderedVars) {
// first 2 are our state & out var
if (variable.Value.Index >= 2 && variable.Value.Index < (parameters.Count + 2)) {
tupleExprs[variable.Value.Index] = parameters[variable.Value.Index - 2];
} else {
tupleExprs[variable.Value.Index] = Expression.Default(variable.Key.Type);
}
}
Expression newTuple = MutableTuple.Create(tupleExprs);
Type tupleType = _tupleType.Value = newTuple.Type;
ParameterExpression tupleExpr = _tupleExpr.Value = Expression.Parameter(tupleType, "tuple");
ParameterExpression tupleArg = Expression.Parameter(typeof(MutableTuple), "tupleArg");
_temps.Add(_gotoRouter);
_temps.Add(tupleExpr);
// temps for the outer lambda
ParameterExpression tupleTmp = Expression.Parameter(tupleType, "tuple");
ParameterExpression ret = Expression.Parameter(typeof(PythonGenerator), "ret");
var innerLambda = Expression.Lambda<Func<MutableTuple, object>>(
Expression.Block(
_temps.ToArray(),
Expression.Assign(
tupleExpr,
Expression.Convert(
tupleArg,
tupleType
)
),
Expression.Switch(Expression.Assign(_gotoRouter, _state), cases),
body,
MakeAssign(_state, AstUtils.Constant(Finished)),
Expression.Label(_returnLabels.Peek()),
_current
),
_name,
new ParameterExpression[] { tupleArg }
);
// Generate a call to PythonOps.MakeGeneratorClosure(Tuple data, object generatorCode)
return Expression.Block(
new[] { tupleTmp, ret },
Expression.Assign(
ret,
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.MakeGenerator)),
parameters[0],
Expression.Assign(tupleTmp, newTuple),
emitDebugSymbols ?
(Expression)bodyConverter(innerLambda) :
(Expression)Expression.Constant(
new LazyCode<Func<MutableTuple, object>>(
bodyConverter(innerLambda),
shouldInterpret,
compilationThreshold
),
typeof(object)
)
)
),
new DelayedTupleAssign(
new DelayedTupleExpression(liftedGen.Index, new StrongBox<ParameterExpression>(tupleTmp), _tupleType, typeof(PythonGenerator)),
ret
),
ret
);
}
private YieldMarker GetYieldMarker(YieldExpression node) {
YieldMarker result = new YieldMarker(_yields.Count + 1);
_yields.Add(result);
Debug.Assert(node.YieldMarker == -1);
return result;
}
/// <summary>
/// Spills the right side into a temp, and replaces it with its temp.
/// Returns the expression that initializes the temp.
/// </summary>
private Expression ToTemp(ref Expression e) {
Debug.Assert(e != null);
var temp = LiftVariable(Expression.Variable(e.Type, "generatorTemp" + _temps.Count));
var result = MakeAssign(temp, e);
e = temp;
return result;
}
/// <summary>
/// Makes an assignment to this variable. Pushes the assignment as far
/// into the right side as possible, to allow jumps into it.
/// </summary>
private Expression MakeAssign(Expression variable, Expression value) {
// TODO: this is not complete.
// It may end up generating a bad tree if any of these nodes
// contain yield and return a value: Switch, Loop, or Goto.
// Those are not supported, but we can't throw here because we may
// end up disallowing valid uses (if some other expression contains
// yield, but not this one).
switch (value.NodeType) {
case ExpressionType.Block:
return MakeAssignBlock(variable, value);
case ExpressionType.Conditional:
return MakeAssignConditional(variable, value);
case ExpressionType.Label:
return MakeAssignLabel(variable, (LabelExpression)value);
}
return DelayedAssign(variable, value);
}
private readonly struct GotoRewriteInfo {
public readonly Expression Variable;
public readonly LabelTarget VoidTarget;
public GotoRewriteInfo(Expression variable, LabelTarget voidTarget) {
Variable = variable;
VoidTarget = voidTarget;
}
}
private Expression MakeAssignLabel(Expression variable, LabelExpression value) {
GotoRewriteInfo curVariable = new GotoRewriteInfo(variable, Expression.Label(value.Target.Name + "_voided"));
var defaultValue = new GotoRewriter(this, curVariable, value.Target).Visit(value.DefaultValue);
return MakeAssignLabel(variable, curVariable, value.Target, defaultValue);
}
private Expression MakeAssignLabel(Expression variable, GotoRewriteInfo curVariable, LabelTarget target, Expression defaultValue) {
return Expression.Label(
curVariable.VoidTarget,
MakeAssign(variable, defaultValue)
);
}
private class GotoRewriter : ExpressionVisitor {
private readonly GotoRewriteInfo _gotoInfo;
private readonly LabelTarget _target;
private readonly GeneratorRewriter _rewriter;
public GotoRewriter(GeneratorRewriter rewriter, GotoRewriteInfo gotoInfo, LabelTarget target) {
_gotoInfo = gotoInfo;
_target = target;
_rewriter = rewriter;
}
protected override Expression VisitGoto(GotoExpression node) {
if (node.Target == _target) {
return Expression.Goto(
_gotoInfo.VoidTarget,
Expression.Block(
_rewriter.MakeAssign(_gotoInfo.Variable, node.Value),
Expression.Default(typeof(void))
),
node.Type
);
}
return base.VisitGoto(node);
}
}
private Expression MakeAssignBlock(Expression variable, Expression value) {
var node = (BlockExpression)value;
var newBlock = new ReadOnlyCollectionBuilder<Expression>(node.Expressions);
Expression blockRhs = newBlock[newBlock.Count - 1];
if (blockRhs.NodeType == ExpressionType.Label) {
var label = (LabelExpression)blockRhs;
GotoRewriteInfo curVariable = new GotoRewriteInfo(variable, Expression.Label(label.Target.Name + "_voided"));
var rewriter = new GotoRewriter(this, curVariable, label.Target);
for (int i = 0; i < newBlock.Count - 1; i++) {
newBlock[i] = rewriter.Visit(newBlock[i]);
}
newBlock[newBlock.Count - 1] = MakeAssignLabel(variable, curVariable, label.Target, rewriter.Visit(label.DefaultValue));
} else {
newBlock[newBlock.Count - 1] = MakeAssign(variable, newBlock[newBlock.Count - 1]);
}
return Expression.Block(node.Variables, newBlock);
}
private Expression MakeAssignConditional(Expression variable, Expression value) {
var node = (ConditionalExpression)value;
return Expression.Condition(node.Test, MakeAssign(variable, node.IfTrue), MakeAssign(variable, node.IfFalse));
}
private BlockExpression ToTemp(ref ReadOnlyCollection<Expression> args) {
int count = args.Count;
var block = new Expression[count];
var newArgs = new Expression[count];
args.CopyTo(newArgs, 0);
for (int i = 0; i < count; i++) {
block[i] = ToTemp(ref newArgs[i]);
}
args = new ReadOnlyCollection<Expression>(newArgs);
return Expression.Block(block);
}
#region VisitTry
protected override Expression VisitTry(TryExpression node) {
int startYields = _yields.Count;
bool savedInTryWithFinally = _inTryWithFinally;
if (node.Finally != null || node.Fault != null) {
_inTryWithFinally = true;
}
Expression @try = Visit(node.Body);
int tryYields = _yields.Count;
IList<CatchBlock> handlers = Visit(node.Handlers, VisitCatchBlock);
int catchYields = _yields.Count;
// push a new return label in case the finally block yields
_returnLabels.Push(Expression.Label("tryLabel"));
// only one of these can be non-null
Expression @finally = Visit(node.Finally);
Expression fault = Visit(node.Fault);
LabelTarget finallyReturn = _returnLabels.Pop();
int finallyYields = _yields.Count;
_inTryWithFinally = savedInTryWithFinally;
if (@try == node.Body &&
handlers == node.Handlers &&
@finally == node.Finally &&
fault == node.Fault) {
return node;
}
// No yields, just return
if (startYields == _yields.Count) {
Debug.Assert(@try.Type == node.Type);
Debug.Assert(handlers == null || handlers.Count == 0 || handlers[0].Body.Type == node.Type);
return Expression.MakeTry(null, @try, @finally, fault, handlers);
}
if (fault != null && finallyYields != catchYields) {
// No one needs this yet, and it's not clear how we should get back to
// the fault
throw new NotSupportedException("yield in fault block is not supported");
}
// If try has yields, we need to build a new try body that
// dispatches to the yield labels
var tryStart = Expression.Label("tryStart");
if (tryYields != startYields) {
@try = Expression.Block(MakeYieldRouter(node.Body.Type, startYields, tryYields, tryStart), @try);
Debug.Assert(@try.Type == node.Body.Type);
}
// Transform catches with yield to deferred handlers
if (catchYields != tryYields) {
var block = new List<Expression>();
block.Add(MakeYieldRouter(node.Body.Type, tryYields, catchYields, tryStart));
block.Add(null); // empty slot to fill in later
for (int i = 0, n = handlers.Count; i < n; i++) {
CatchBlock c = handlers[i];
if (c == node.Handlers[i]) {
continue;
}
if (handlers.IsReadOnly) {
handlers = ArrayUtils.ToArray(handlers);
}
// the variable that will be scoped to the catch block
var exceptionVar = Expression.Variable(c.Test, null);
// the variable that the catch block body will use to
// access the exception. We reuse the original variable if
// the catch block had one. It needs to be hoisted because
// the catch might contain yields.
var deferredVar = c.Variable ?? Expression.Variable(c.Test, null);
LiftVariable(deferredVar);
// We need to ensure that filters can access the exception
// variable
Expression filter = c.Filter;
if (filter != null && c.Variable != null) {
filter = Expression.Block(new[] { c.Variable }, Expression.Assign(c.Variable, exceptionVar), filter);
}
// catch (ExceptionType exceptionVar) {
// deferredVar = exceptionVar;
// }
handlers[i] = Expression.Catch(
exceptionVar,
Expression.Block(
DelayedAssign(Visit(deferredVar), exceptionVar),
Expression.Default(node.Body.Type)
),
filter
);
// We need to rewrite rethrows into "throw deferredVar"
var catchBody = new RethrowRewriter { Exception = deferredVar }.Visit(c.Body);
// if (deferredVar != null) {
// ... catch body ...
// }
block.Add(
Expression.Condition(
Expression.NotEqual(Visit(deferredVar), AstUtils.Constant(null, deferredVar.Type)),
catchBody,
Expression.Default(node.Body.Type)
)
);
}
block[1] = Expression.MakeTry(null, @try, null, null, new ReadOnlyCollection<CatchBlock>(handlers));
@try = Expression.Block(block);
Debug.Assert(@try.Type == node.Body.Type);
handlers = new CatchBlock[0]; // so we don't reuse these
}
if (finallyYields != catchYields) {
// We need to add a catch block to save the exception, so we
// can rethrow in case there is a yield in the finally. Also,
// add logic for returning. It looks like this:
//
// try { ... } catch (Exception all) { saved = all; }
// finally {
// if (_finallyReturnVar) goto finallyReturn;
// ...
// if (saved != null) throw saved;
// finallyReturn:
// }
// if (_finallyReturnVar) goto _return;
// We need to add a catch(Exception), so if we have catches,
// wrap them in a try
if (handlers.Count > 0) {
@try = Expression.MakeTry(null, @try, null, null, handlers);
Debug.Assert(@try.Type == node.Body.Type);
handlers = new CatchBlock[0];
}
// NOTE: the order of these routers is important
// The first call changes the labels to all point at "tryEnd",
// so the second router will jump to "tryEnd"
var tryEnd = Expression.Label("tryEnd");
Expression inFinallyRouter = MakeYieldRouter(node.Body.Type, catchYields, finallyYields, tryEnd);
Expression inTryRouter = MakeYieldRouter(node.Body.Type, catchYields, finallyYields, tryStart);
var all = Expression.Variable(typeof(Exception), "e");
var saved = Expression.Variable(typeof(Exception), "$saved$" + _temps.Count);
LiftVariable(saved);
@try = Expression.Block(
Expression.TryCatchFinally(
Expression.Block(
inTryRouter,
@try,
DelayedAssign(Visit(saved), AstUtils.Constant(null, saved.Type)),
Expression.Label(tryEnd)
),
Expression.Block(
MakeSkipFinallyBlock(finallyReturn),
inFinallyRouter,
@finally,
Expression.Condition(
Expression.NotEqual(Visit(saved), AstUtils.Constant(null, saved.Type)),
Expression.Throw(Visit(saved)),
Utils.Empty()
),
Expression.Label(finallyReturn)
),
Expression.Catch(all, Utils.Void(DelayedAssign(Visit(saved), all)))
),
Expression.Condition(
Expression.Equal(_gotoRouter, AstUtils.Constant(GotoRouterYielding)),
Expression.Goto(_returnLabels.Peek()),
Utils.Empty()
)
);
@finally = null;
} else if (@finally != null) {
// try or catch had a yield, modify finally so we can skip over it
@finally = Expression.Block(
MakeSkipFinallyBlock(finallyReturn),
@finally,
Expression.Label(finallyReturn)
);
}
// Make the outer try, if needed
if (handlers.Count > 0 || @finally != null || fault != null) {
@try = Expression.MakeTry(null, @try, @finally, fault, handlers);
}
Debug.Assert(@try.Type == node.Body.Type);
return Expression.Block(Expression.Label(tryStart), @try);
}
private class RethrowRewriter : ExpressionVisitor {
internal Expression Exception;
protected override Expression VisitUnary(UnaryExpression node) {
if (node.NodeType == ExpressionType.Throw && node.Operand == null) {
return Expression.Throw(Exception, node.Type);
}
return base.VisitUnary(node);
}
protected override Expression VisitLambda<T>(Expression<T> node) {
return node; // don't recurse into lambdas
}
protected override Expression VisitTry(TryExpression node) {
return node; // don't recurse into other try's
}
protected override Expression VisitExtension(Expression node) {
if (node is DelayedTupleExpression) {
return node;
}
return base.VisitExtension(node);
}
}
// Skip the finally block if we are yielding, but not if we're doing a
// yield break
private Expression MakeSkipFinallyBlock(LabelTarget target) {
return Expression.Condition(
Expression.AndAlso(
Expression.Equal(_gotoRouter, AstUtils.Constant(GotoRouterYielding)),
Expression.NotEqual(_state, AstUtils.Constant(Finished))
),
Expression.Goto(target),
Utils.Empty()
);
}
// Mostly copied from the base implementation.
// - makes sure we disallow yield in filters
// - lifts exception variable
protected override CatchBlock VisitCatchBlock(CatchBlock node) {
if (node.Variable != null) {
LiftVariable(node.Variable);
}
Expression v = Visit(node.Variable);
int yields = _yields.Count;
Expression f = Visit(node.Filter);
if (yields != _yields.Count) {
// No one needs this yet, and it's not clear what it should even do
throw new NotSupportedException("yield in filter is not allowed");
}
Expression b = Visit(node.Body);
if (v == node.Variable && b == node.Body && f == node.Filter) {
return node;
}
// if we have variable and no yields in the catch block then
// we need to hoist the variable into a closure
if (v != node.Variable && yields == _yields.Count) {
return Expression.MakeCatchBlock(
node.Test,
node.Variable,
Expression.Block(
new DelayedTupleAssign(v, node.Variable),
b
),
f);
}
return Expression.MakeCatchBlock(node.Test, node.Variable, b, f);
}
#endregion
private SwitchExpression MakeYieldRouter(Type type, int start, int end, LabelTarget newTarget) {
Debug.Assert(end > start);
var cases = new SwitchCase[end - start];
for (int i = start; i < end; i++) {
YieldMarker y = _yields[i];
cases[i - start] = Expression.SwitchCase(Expression.Goto(y.Label, type), AstUtils.Constant(y.State));
// Any jumps from outer switch statements should go to the this
// router, not the original label (which they cannot legally jump to)
y.Label = newTarget;
}
return Expression.Switch(_gotoRouter, Expression.Default(type), cases);
}
protected override Expression VisitExtension(Expression node) {
if (node is YieldExpression yield) {
return VisitYield(yield);
}
if (node is FinallyFlowControlExpression ffc) {
return Visit(node.ReduceExtensions());
}
return Visit(node.ReduceExtensions());
}
private Expression VisitYield(YieldExpression node) {
var value = Visit(node.Value);
var block = new List<Expression>();
if (node.YieldMarker == -2) {
// Yield break with a return value
block.Add(MakeAssign(_current, value));
value = null;
}
if (value == null) {
// Yield break
block.Add(MakeAssign(_state, AstUtils.Constant(Finished)));
if (_inTryWithFinally) {
block.Add(Expression.Assign(_gotoRouter, AstUtils.Constant(GotoRouterYielding)));
}
block.Add(Expression.Goto(_returnLabels.Peek()));
return Expression.Block(block);
}
// Yield return
block.Add(MakeAssign(_current, value));
YieldMarker marker = GetYieldMarker(node);
block.Add(MakeAssign(_state, AstUtils.Constant(marker.State)));
if (_inTryWithFinally) {
block.Add(Expression.Assign(_gotoRouter, AstUtils.Constant(GotoRouterYielding)));
}
block.Add(Expression.Goto(_returnLabels.Peek()));
block.Add(Expression.Label(marker.Label));
block.Add(Expression.Assign(_gotoRouter, AstUtils.Constant(GotoRouterNone)));
block.Add(Utils.Empty());
return Expression.Block(block);
}
protected override Expression VisitBlock(BlockExpression node) {
// save the variables for later
// (they'll be hoisted outside of the lambda)
foreach (ParameterExpression param in node.Variables) {
LiftVariable(param);
}
int yields = _yields.Count;
var b = Visit(node.Expressions);
if (b == node.Expressions) {
return node;
}
if (yields == _yields.Count) {
return Expression.Block(node.Type, node.Variables, b);
}
// Return a new block expression with the rewritten body except for that
// all the variables are removed.
return Expression.Block(node.Type, b);
}
private DelayedTupleExpression LiftVariable(ParameterExpression param) {
DelayedTupleExpression res;
if (!_vars.TryGetValue(param, out res)) {
_vars[param] = res = new DelayedTupleExpression(_vars.Count, _tupleExpr, _tupleType, param.Type);
_orderedVars.Add(new KeyValuePair<ParameterExpression, DelayedTupleExpression>(param, res));
}
return res;
}
protected override Expression VisitParameter(ParameterExpression node) {
return _vars[node];
}
protected override Expression VisitLambda<T>(Expression<T> node) {
// don't recurse into nested lambdas
return node;
}
#region stack spilling (to permit yield in the middle of an expression)
private Expression VisitAssign(BinaryExpression node) {
int yields = _yields.Count;
Expression left = Visit(node.Left);
Expression right = Visit(node.Right);
if (left == node.Left && right == node.Right) {
return node;
}
if (yields == _yields.Count) {
if (left is DelayedTupleExpression) {
return new DelayedTupleAssign(left, right);
}
return Expression.Assign(left, right);
}
var block = new List<Expression>();
// If the left hand side did not rewrite itself, we may still need
// to rewrite to ensure proper evaluation order. Essentially, we
// want all of the left side evaluated first, then the value, then
// the assignment
if (left == node.Left) {
switch (left.NodeType) {
case ExpressionType.MemberAccess:
var member = (MemberExpression)node.Left;
Expression e = Visit(member.Expression);
block.Add(ToTemp(ref e));
left = Expression.MakeMemberAccess(e, member.Member);
break;
case ExpressionType.Index:
var index = (IndexExpression)node.Left;
Expression o = Visit(index.Object);
ReadOnlyCollection<Expression> a = Visit(index.Arguments);
if (o == index.Object && a == index.Arguments) {
return index;
}
block.Add(ToTemp(ref o));
block.Add(ToTemp(ref a));
left = Expression.MakeIndex(o, index.Indexer, a);
break;
case ExpressionType.Parameter:
// no action needed
break;
default:
// Extension should've been reduced by Visit above,
// and returned a different node
throw Assert.Unreachable;
}
} else if (left is BlockExpression) {
// Get the last expression of the rewritten left side
var leftBlock = (BlockExpression)left;
left = leftBlock.Expressions[leftBlock.Expressions.Count - 1];
block.AddRange(leftBlock.Expressions);
block.RemoveAt(block.Count - 1);
}
if (right != node.Right) {
block.Add(ToTemp(ref right));
}
if (left is DelayedTupleExpression) {
block.Add(DelayedAssign(left, right));
} else {
block.Add(Expression.Assign(left, right));
}
return Expression.Block(block);
}
protected override Expression VisitDynamic(DynamicExpression node) {
int yields = _yields.Count;
ReadOnlyCollection<Expression> a = Visit(node.Arguments);
if (a == node.Arguments) {
return node;
}
if (yields == _yields.Count) {
return DynamicExpression.MakeDynamic(node.DelegateType, node.Binder, a);
}
return Expression.Block(
ToTemp(ref a),
DynamicExpression.MakeDynamic(node.DelegateType, node.Binder, a)
);
}
protected override Expression VisitIndex(IndexExpression node) {
int yields = _yields.Count;
Expression o = Visit(node.Object);
ReadOnlyCollection<Expression> a = Visit(node.Arguments);
if (o == node.Object && a == node.Arguments) {
return node;
}
if (yields == _yields.Count) {
return Expression.MakeIndex(o, node.Indexer, a);
}
return Expression.Block(
ToTemp(ref o),
ToTemp(ref a),
Expression.MakeIndex(o, node.Indexer, a)
);
}
protected override Expression VisitInvocation(InvocationExpression node) {
int yields = _yields.Count;
Expression e = Visit(node.Expression);
ReadOnlyCollection<Expression> a = Visit(node.Arguments);
if (e == node.Expression && a == node.Arguments) {
return node;
}
if (yields == _yields.Count) {
return Expression.Invoke(e, a);
}
return Expression.Block(
ToTemp(ref e),
ToTemp(ref a),
Expression.Invoke(e, a)
);
}
protected override Expression VisitMethodCall(MethodCallExpression node) {
int yields = _yields.Count;
Expression o = Visit(node.Object);
ReadOnlyCollection<Expression> a = Visit(node.Arguments);
if (o == node.Object && a == node.Arguments) {
return node;
}
if (yields == _yields.Count) {
return Expression.Call(o, node.Method, a);
}
if (o == null) {
return Expression.Block(
ToTemp(ref a),
Expression.Call(null, node.Method, a)
);
}
return Expression.Block(
ToTemp(ref o),
ToTemp(ref a),
Expression.Call(o, node.Method, a)
);
}
protected override Expression VisitNew(NewExpression node) {
int yields = _yields.Count;
ReadOnlyCollection<Expression> a = Visit(node.Arguments);
if (a == node.Arguments) {
return node;
}
if (yields == _yields.Count) {
return (node.Members != null)
? Expression.New(node.Constructor, a, node.Members)
: Expression.New(node.Constructor, a);
}
return Expression.Block(
ToTemp(ref a),
(node.Members != null)
? Expression.New(node.Constructor, a, node.Members)
: Expression.New(node.Constructor, a)
);
}
protected override Expression VisitNewArray(NewArrayExpression node) {
int yields = _yields.Count;
ReadOnlyCollection<Expression> e = Visit(node.Expressions);
if (e == node.Expressions) {
return node;
}
if (yields == _yields.Count) {
return (node.NodeType == ExpressionType.NewArrayInit)
? Expression.NewArrayInit(node.Type.GetElementType(), e)
: Expression.NewArrayBounds(node.Type.GetElementType(), e);
}
return Expression.Block(
ToTemp(ref e),
(node.NodeType == ExpressionType.NewArrayInit)
? Expression.NewArrayInit(node.Type.GetElementType(), e)
: Expression.NewArrayBounds(node.Type.GetElementType(), e)
);
}
protected override Expression VisitMember(MemberExpression node) {
int yields = _yields.Count;
Expression e = Visit(node.Expression);
if (e == node.Expression) {
return node;
}
if (yields == _yields.Count) {
return Expression.MakeMemberAccess(e, node.Member);
}
return Expression.Block(
ToTemp(ref e),
Expression.MakeMemberAccess(e, node.Member)
);
}
protected override Expression VisitBinary(BinaryExpression node) {
if (node.NodeType == ExpressionType.Assign) {
return VisitAssign(node);
}
// For OpAssign nodes: if has a yield, we need to do the generator
// transformation on the reduced value.
if (node.CanReduce) {
return Visit(node.Reduce());
}
int yields = _yields.Count;
Expression left = Visit(node.Left);
Expression right = Visit(node.Right);
if (left == node.Left && right == node.Right) {
return node;
}
if (yields == _yields.Count) {
return Expression.MakeBinary(node.NodeType, left, right, node.IsLiftedToNull, node.Method, node.Conversion);
}
return Expression.Block(
ToTemp(ref left),
ToTemp(ref right),
Expression.MakeBinary(node.NodeType, left, right, node.IsLiftedToNull, node.Method, node.Conversion)
);
}
protected override Expression VisitTypeBinary(TypeBinaryExpression node) {
int yields = _yields.Count;
Expression e = Visit(node.Expression);
if (e == node.Expression) {
return node;
}
if (yields == _yields.Count) {
return (node.NodeType == ExpressionType.TypeIs)
? Expression.TypeIs(e, node.TypeOperand)
: Expression.TypeEqual(e, node.TypeOperand);
}
return Expression.Block(
ToTemp(ref e),
(node.NodeType == ExpressionType.TypeIs)
? Expression.TypeIs(e, node.TypeOperand)
: Expression.TypeEqual(e, node.TypeOperand)
);
}
protected override Expression VisitUnary(UnaryExpression node) {
// For OpAssign nodes: if has a yield, we need to do the generator
// transformation on the reduced value.
if (node.CanReduce) {
return Visit(node.Reduce());
}
int yields = _yields.Count;
Expression o = Visit(node.Operand);
if (o == node.Operand) {
return node;
}
// Void convert can be jumped into, no need to spill
// TODO: remove when that feature goes away.
if (yields == _yields.Count ||
(node.NodeType == ExpressionType.Convert && node.Type == typeof(void))) {
return Expression.MakeUnary(node.NodeType, o, node.Type, node.Method);
}
return Expression.Block(
ToTemp(ref o),
Expression.MakeUnary(node.NodeType, o, node.Type, node.Method)
);
}
protected override Expression VisitMemberInit(MemberInitExpression node) {
// See if anything changed
int yields = _yields.Count;
Expression e = base.VisitMemberInit(node);
if (yields == _yields.Count) {
return e;
}
// It has a yield. Reduce to basic nodes so we can jump in
return e.Reduce();
}
protected override Expression VisitListInit(ListInitExpression node) {
// See if anything changed
int yields = _yields.Count;
Expression e = base.VisitListInit(node);
if (yields == _yields.Count) {
return e;
}
// It has a yield. Reduce to basic nodes so we can jump in
return e.Reduce();
}
private static Expression DelayedAssign(Expression lhs, Expression rhs) {
return new DelayedTupleAssign(lhs, rhs);
}
#endregion
private sealed class YieldMarker {
// Note: Label can be mutated as we generate try blocks
internal LabelTarget Label = Expression.Label("yieldMarker");
internal readonly int State;
internal YieldMarker(int state) {
State = state;
}
}
}
/// <summary>
/// Accesses the property of a tuple. The node can be created first and then the tuple and index
/// type can be filled in before the tree is actually generated. This enables creation of these
/// nodes before the tuple type is actually known.
/// </summary>
internal sealed class DelayedTupleExpression : Expression {
public readonly int Index;
private readonly StrongBox<Type> _tupleType;
private readonly StrongBox<ParameterExpression> _tupleExpr;
private readonly Type _type;
public DelayedTupleExpression(int index, StrongBox<ParameterExpression> tupleExpr, StrongBox<Type> tupleType, Type type) {
Index = index;
_tupleType = tupleType;
_tupleExpr = tupleExpr;
_type = type;
}
public override Expression Reduce() {
Expression res = _tupleExpr.Value;
foreach (PropertyInfo pi in MutableTuple.GetAccessPath(_tupleType.Value, Index)) {
res = Expression.Property(res, pi);
}
return res;
}
public sealed override ExpressionType NodeType {
get { return ExpressionType.Extension; }
}
public sealed override Type/*!*/ Type {
get { return _type; }
}
public override bool CanReduce {
get {
return true;
}
}
protected override Expression VisitChildren(ExpressionVisitor visitor) {
return this;
}
}
internal sealed class DelayedTupleAssign : Expression {
private readonly Expression _lhs, _rhs;
public DelayedTupleAssign(Expression lhs, Expression rhs) {
_lhs = lhs;
_rhs = rhs;
}
public override Expression Reduce() {
// we assign to a temporary and then assign that to the tuple
// because there may be branches in the RHS which can cause
// us to not have the tuple instance
return Expression.Assign(_lhs.Reduce(), _rhs);
}
public sealed override ExpressionType NodeType {
get { return ExpressionType.Extension; }
}
public sealed override Type/*!*/ Type {
get { return _lhs.Type; }
}
public override bool CanReduce {
get {
return true;
}
}
protected override Expression VisitChildren(ExpressionVisitor visitor) {
Expression rhs = visitor.Visit(_rhs);
if (rhs != _rhs) {
return new DelayedTupleAssign(_lhs, rhs);
}
return this;
}
}
internal sealed class PythonGeneratorExpression : Expression {
private readonly LightLambdaExpression _lambda;
private readonly int _compilationThreshold;
public PythonGeneratorExpression(LightLambdaExpression lambda, int compilationThreshold) {
_lambda = lambda;
_compilationThreshold = compilationThreshold;
}
public override Expression Reduce() {
return _lambda.ToGenerator(false, true, _compilationThreshold);
}
public sealed override ExpressionType NodeType {
get { return ExpressionType.Extension; }
}
public sealed override Type/*!*/ Type {
get { return _lambda.Type; }
}
public override bool CanReduce {
get {
return true;
}
}
}
}
| 41.572084 | 174 | 0.541306 | [
"Apache-2.0"
] | Backup-eric645/ironpython3 | Src/IronPython/Compiler/GeneratorRewriter.cs | 45,274 | C# |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.Pipeline.Filters
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using GreenPipes;
using GreenPipes.Pipes;
using Observables;
using Util;
/// <summary>
/// Maintains the Publish middleware for a message type, as well as the observers for the Publish
/// </summary>
/// <typeparam name="TMessage">The message type</typeparam>
public class MessagePublishFilter<TMessage> :
IFilter<PublishContext>,
IPublishMessageObserverConnector
where TMessage : class
{
readonly PublishMessageObservable<TMessage> _messageObservers;
readonly IPipe<PublishContext<TMessage>> _outputPipe;
public MessagePublishFilter(IEnumerable<IFilter<PublishContext<TMessage>>> filters)
{
_outputPipe = BuildFilterPipe(filters.ToArray());
_messageObservers = new PublishMessageObservable<TMessage>();
}
void IProbeSite.Probe(ProbeContext context)
{
ProbeContext scope = context.CreateMessageScope(TypeMetadataCache<TMessage>.ShortName);
_outputPipe.Probe(scope);
}
public ConnectHandle ConnectPublishMessageObserver<T>(IPublishMessageObserver<T> observer)
where T : class
{
var self = _messageObservers as PublishMessageObservable<T>;
if (self == null)
throw new InvalidOperationException("The connection type is invalid: " + TypeMetadataCache<T>.ShortName);
return self.Connect(observer);
}
[DebuggerNonUserCode]
async Task IFilter<PublishContext>.Send(PublishContext context, IPipe<PublishContext> next)
{
var publishContext = context as PublishContext<TMessage>;
if (publishContext != null)
{
if (_messageObservers.Count > 0)
await _messageObservers.PrePublish(publishContext).ConfigureAwait(false);
try
{
await _outputPipe.Send(publishContext).ConfigureAwait(false);
if (_messageObservers.Count > 0)
await _messageObservers.PostPublish(publishContext).ConfigureAwait(false);
await next.Send(context).ConfigureAwait(false);
}
catch (Exception ex)
{
if (_messageObservers.Count > 0)
{
await _messageObservers.PublishFault(publishContext, ex).ConfigureAwait(false);
}
throw;
}
}
}
static IPipe<PublishContext<TMessage>> BuildFilterPipe(IFilter<PublishContext<TMessage>>[] filters)
{
if (filters.Length == 0)
throw new ArgumentException("There must be at least one filter, the output filter, for the output pipe");
IPipe<PublishContext<TMessage>> current = new LastPipe<PublishContext<TMessage>>(filters[filters.Length - 1]);
for (int i = filters.Length - 2; i >= 0; i--)
current = new FilterPipe<PublishContext<TMessage>>(filters[i], current);
return current;
}
}
} | 39.259615 | 123 | 0.612785 | [
"Apache-2.0"
] | andymac4182/MassTransit | src/MassTransit/Pipeline/Filters/MessagePublishFilter.cs | 4,083 | C# |
#if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
using System;
using System.Collections.Generic;
namespace XNetEx.Collections.Generic
{
static partial class CollectionExtensions
{
/// <summary>
/// 返回 <see cref="IEnumerable{T}"/> 的 <see cref="IAsyncEnumerable{T}"/> 包装。
/// </summary>
/// <typeparam name="T">要枚举的对象的类型。</typeparam>
/// <param name="enumerable">要包装的 <see cref="IEnumerable{T}"/> 对象。</param>
/// <returns><paramref name="enumerable"/> 的 <see cref="IAsyncEnumerable{T}"/> 包装。</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="enumerable"/> 为 <see langword="null"/>。</exception>
public static IAsyncEnumerable<T> AsAsyncEnumerable<T>(this IEnumerable<T> enumerable)
{
return new AsyncedEnumerable<T>(enumerable);
}
/// <summary>
/// 返回 <see cref="IAsyncEnumerable{T}"/> 的 <see cref="IEnumerable{T}"/> 包装。
/// </summary>
/// <typeparam name="T">要枚举的对象的类型。</typeparam>
/// <param name="asyncEnumerable">要包装的 <see cref="IAsyncEnumerable{T}"/> 对象。</param>
/// <returns><paramref name="asyncEnumerable"/> 的 <see cref="IEnumerable{T}"/> 包装。</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="asyncEnumerable"/> 为 <see langword="null"/>。</exception>
public static IEnumerable<T> AsEnumerable<T>(this IAsyncEnumerable<T> asyncEnumerable)
{
return new SyncedAsyncEnumerable<T>(asyncEnumerable);
}
}
}
#endif
| 42.837838 | 100 | 0.621451 | [
"MIT"
] | x-stars/DotNetExtensionLibrary | XNetEx.Runtime/Collections/Generic/CollectionExtensions.Async.cs | 1,703 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Threading.Tasks;
namespace SmartDisplay.Contracts
{
public interface IWeather
{
string Name { get; }
Task<GenericWeather> GetGenericWeatherAsync(double latitude, double longitude);
GenericWeather AsGenericWeather();
}
/// <summary>
/// Generic weather template, used by weatherpage.xaml.cs
/// </summary>
public class GenericWeather
{
public string Source;
public GenericCurrentObservation CurrentObservation { get; set; }
public GenericForecast Forecast { get; set; }
}
public class GenericCurrentObservation
{
public string Icon { get; set; }
public double Temperature { get; set; }
public string AdditionalInfo { get; set; }
public string WeatherDescription { get; set; }
}
public class GenericForecast
{
public GenericForecastDay[] Days { get; set; }
}
public class GenericForecastDay
{
public DateTime Date { get; set; }
public double TemperatureHigh { get; set; } = -1;
public double TemperatureLow { get; set; } = -1;
public string WeatherIcon { get; set; }
public string WeatherDescription { get; set; }
}
}
| 26.795918 | 87 | 0.639756 | [
"MIT"
] | ATM006/Windows-iotcore-samples | Samples/IoTCoreDefaultApp/CS/SmartDisplay.Contracts/Interfaces/IWeather.cs | 1,315 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ApiManagement.V20180101
{
/// <summary>
/// API details.
/// </summary>
public partial class Api : Pulumi.CustomResource
{
/// <summary>
/// Describes the Revision of the Api. If no value is provided, default revision 1 is created
/// </summary>
[Output("apiRevision")]
public Output<string?> ApiRevision { get; private set; } = null!;
/// <summary>
/// Description of the Api Revision.
/// </summary>
[Output("apiRevisionDescription")]
public Output<string?> ApiRevisionDescription { get; private set; } = null!;
/// <summary>
/// Type of API.
/// </summary>
[Output("apiType")]
public Output<string?> ApiType { get; private set; } = null!;
/// <summary>
/// Indicates the Version identifier of the API if the API is versioned
/// </summary>
[Output("apiVersion")]
public Output<string?> ApiVersion { get; private set; } = null!;
/// <summary>
/// Description of the Api Version.
/// </summary>
[Output("apiVersionDescription")]
public Output<string?> ApiVersionDescription { get; private set; } = null!;
/// <summary>
/// An API Version Set contains the common configuration for a set of API Versions relating
/// </summary>
[Output("apiVersionSet")]
public Output<Outputs.ApiVersionSetContractDetailsResponse?> ApiVersionSet { get; private set; } = null!;
/// <summary>
/// A resource identifier for the related ApiVersionSet.
/// </summary>
[Output("apiVersionSetId")]
public Output<string?> ApiVersionSetId { get; private set; } = null!;
/// <summary>
/// Collection of authentication settings included into this API.
/// </summary>
[Output("authenticationSettings")]
public Output<Outputs.AuthenticationSettingsContractResponse?> AuthenticationSettings { get; private set; } = null!;
/// <summary>
/// Description of the API. May include HTML formatting tags.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// API name.
/// </summary>
[Output("displayName")]
public Output<string?> DisplayName { get; private set; } = null!;
/// <summary>
/// Indicates if API revision is current api revision.
/// </summary>
[Output("isCurrent")]
public Output<bool> IsCurrent { get; private set; } = null!;
/// <summary>
/// Indicates if API revision is accessible via the gateway.
/// </summary>
[Output("isOnline")]
public Output<bool> IsOnline { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Relative URL uniquely identifying this API and all of its resource paths within the API Management service instance. It is appended to the API endpoint base URL specified during the service instance creation to form a public URL for this API.
/// </summary>
[Output("path")]
public Output<string> Path { get; private set; } = null!;
/// <summary>
/// Describes on which protocols the operations in this API can be invoked.
/// </summary>
[Output("protocols")]
public Output<ImmutableArray<string>> Protocols { get; private set; } = null!;
/// <summary>
/// Absolute URL of the backend service implementing this API.
/// </summary>
[Output("serviceUrl")]
public Output<string?> ServiceUrl { get; private set; } = null!;
/// <summary>
/// Protocols over which API is made available.
/// </summary>
[Output("subscriptionKeyParameterNames")]
public Output<Outputs.SubscriptionKeyParameterNamesContractResponse?> SubscriptionKeyParameterNames { get; private set; } = null!;
/// <summary>
/// Resource type for API Management resource.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Api resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Api(string name, ApiArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:apimanagement/v20180101:Api", name, args ?? new ApiArgs(), MakeResourceOptions(options, ""))
{
}
private Api(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:apimanagement/v20180101:Api", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/latest:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20160707:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20161010:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20170301:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20180601preview:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20190101:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201preview:Api"},
new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20200601preview:Api"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Api resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Api Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Api(name, id, options);
}
}
public sealed class ApiArgs : Pulumi.ResourceArgs
{
/// <summary>
/// API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
/// </summary>
[Input("apiId", required: true)]
public Input<string> ApiId { get; set; } = null!;
/// <summary>
/// Describes the Revision of the Api. If no value is provided, default revision 1 is created
/// </summary>
[Input("apiRevision")]
public Input<string>? ApiRevision { get; set; }
/// <summary>
/// Description of the Api Revision.
/// </summary>
[Input("apiRevisionDescription")]
public Input<string>? ApiRevisionDescription { get; set; }
/// <summary>
/// Type of API.
/// </summary>
[Input("apiType")]
public Input<string>? ApiType { get; set; }
/// <summary>
/// Indicates the Version identifier of the API if the API is versioned
/// </summary>
[Input("apiVersion")]
public Input<string>? ApiVersion { get; set; }
/// <summary>
/// Description of the Api Version.
/// </summary>
[Input("apiVersionDescription")]
public Input<string>? ApiVersionDescription { get; set; }
/// <summary>
/// An API Version Set contains the common configuration for a set of API Versions relating
/// </summary>
[Input("apiVersionSet")]
public Input<Inputs.ApiVersionSetContractDetailsArgs>? ApiVersionSet { get; set; }
/// <summary>
/// A resource identifier for the related ApiVersionSet.
/// </summary>
[Input("apiVersionSetId")]
public Input<string>? ApiVersionSetId { get; set; }
/// <summary>
/// Collection of authentication settings included into this API.
/// </summary>
[Input("authenticationSettings")]
public Input<Inputs.AuthenticationSettingsContractArgs>? AuthenticationSettings { get; set; }
/// <summary>
/// Format of the Content in which the API is getting imported.
/// </summary>
[Input("contentFormat")]
public Input<string>? ContentFormat { get; set; }
/// <summary>
/// Content value when Importing an API.
/// </summary>
[Input("contentValue")]
public Input<string>? ContentValue { get; set; }
/// <summary>
/// Description of the API. May include HTML formatting tags.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// API name.
/// </summary>
[Input("displayName")]
public Input<string>? DisplayName { get; set; }
/// <summary>
/// Relative URL uniquely identifying this API and all of its resource paths within the API Management service instance. It is appended to the API endpoint base URL specified during the service instance creation to form a public URL for this API.
/// </summary>
[Input("path", required: true)]
public Input<string> Path { get; set; } = null!;
[Input("protocols")]
private InputList<string>? _protocols;
/// <summary>
/// Describes on which protocols the operations in this API can be invoked.
/// </summary>
public InputList<string> Protocols
{
get => _protocols ?? (_protocols = new InputList<string>());
set => _protocols = value;
}
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the API Management service.
/// </summary>
[Input("serviceName", required: true)]
public Input<string> ServiceName { get; set; } = null!;
/// <summary>
/// Absolute URL of the backend service implementing this API.
/// </summary>
[Input("serviceUrl")]
public Input<string>? ServiceUrl { get; set; }
/// <summary>
/// Type of Api to create.
/// * `http` creates a SOAP to REST API
/// * `soap` creates a SOAP pass-through API .
/// </summary>
[Input("soapApiType")]
public Input<string>? SoapApiType { get; set; }
/// <summary>
/// Protocols over which API is made available.
/// </summary>
[Input("subscriptionKeyParameterNames")]
public Input<Inputs.SubscriptionKeyParameterNamesContractArgs>? SubscriptionKeyParameterNames { get; set; }
/// <summary>
/// Criteria to limit import of WSDL to a subset of the document.
/// </summary>
[Input("wsdlSelector")]
public Input<Inputs.ApiCreateOrUpdatePropertiesWsdlSelectorArgs>? WsdlSelector { get; set; }
public ApiArgs()
{
}
}
}
| 39.663551 | 254 | 0.588046 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ApiManagement/V20180101/Api.cs | 12,732 | C# |
//
// - DomConverter.cs -
//
// Copyright 2013 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// 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 System;
using System.Collections.Generic;
using System.Reflection;
using Carbonfrost.Commons.Core;
using Carbonfrost.Commons.Core.Runtime;
using Carbonfrost.Commons.Web.Dom;
using Carbonfrost.Commons.Html;
namespace Carbonfrost.Commons.Hxl.Compiler {
class DomConverter : HtmlNodeVisitor {
private HxlDocumentFragment _result;
private DomContainer _current;
private Action<Type> _typeUse;
private DomDocument Document {
get {
return _result.OwnerDocument;
}
}
public HxlDocumentFragment Convert(DomContainer html,
HxlDocumentFragment result,
Action<Type> typeUse) {
_result = result;
_current = _result;
_typeUse = typeUse;
Visit(html);
return _result;
}
protected override void VisitProcessingInstruction(HtmlProcessingInstruction node) {
var macro = Document.CreateProcessingInstruction(node.Target, node.Data);
// TODO Missing line numbers and positions
// TODO Enforce directives only at document level
int line = -1;
int pos = -1;
if (macro != null
&& (macro.Target == "xml" || (macro is HxlProcessingInstruction))) {
_current.Append(macro);
AddImplicitType(macro.GetType());
} else
throw HxlFailure.DirectiveNotDefined(node.Target, line, pos);
}
protected override void VisitDocument(HtmlDocument node) {
VisitRange(node.ChildNodes);
}
protected override void VisitDocumentType(DomDocumentType node) {
var docType = Document.CreateDocumentType(node.Name, node.PublicId, node.SystemId);
_current.Append(docType);
}
protected override void VisitText(HtmlText node) {
_current.Append(Document.CreateText(node.Data));
base.VisitText(node);
}
protected override void VisitElement(HtmlElement node) {
var child = Document.CreateElement(node.NodeName);
if (child == null) {
throw HxlFailure.ServerElementCannotBeCreated(node.NodeName, -1, -1);
}
var oldCurrent = _current;
AppendChild(child);
// Consolidate server attributes
var serverAttributes
= new Dictionary<string, DomAttributeWithInitializers>();
AddImplicitType(child.GetType());
foreach (var m in node.Attributes) {
if (m.Name.Contains(":")) {
var hxl = ResolveName(m.Name);
string id = hxl.Name;
DomAttributeWithInitializers withInit;
// Coalesce attribute extension syntax
if (!serverAttributes.TryGetValue(id, out withInit)) {
withInit = CreateServerDomAttribute(m, hxl.Property);
serverAttributes.Add(id, withInit);
}
if (hxl.Property == null) {
InitProperty(null, m.Value, withInit);
} else {
InitProperty(hxl.Property, m.Value, withInit);
}
} else {
CreateDomAttribute(m);
}
}
foreach (var m in serverAttributes.Values)
Activation.Initialize(m.Attribute, m.Initializers);
VisitRange(node.ChildNodes);
_current = oldCurrent;
}
void VisitRange(IEnumerable<DomNode> childNodes) {
foreach (var m in childNodes) {
Visit(m);
}
}
private DomAttribute CreateDomAttribute(DomAttribute m) {
DomAttribute attr = Document.CreateAttribute(m.Name, m.Value);
if (attr == null)
throw new NotImplementedException();
AddImplicitType(attr.GetType());
_current.Attributes.Add(attr);
return attr;
}
private DomAttributeWithInitializers CreateServerDomAttribute(DomAttribute m, string property) {
var result = new DomAttributeWithInitializers();
try {
result.Attribute = Document.CreateAttribute(m.Name);
} catch (Exception ex) {
if (Failure.IsCriticalException(ex))
throw;
else
throw HxlFailure.CannotCreateAttributeOnConversion(m.Name, ex);
}
if (result.Attribute == null)
throw HxlFailure.ServerAttributeCannotBeCreated(m.Name, -1, -1);
_current.Attributes.Add(result.Attribute);
AddImplicitType(result.Attribute.GetType());
return result;
}
private void InitProperty(string property, string value, DomAttributeWithInitializers withInit) {
PropertyInfo prop;
DomAttribute attr = withInit.Attribute;
if (property == null) {
var valueProp = HxlAttributeFragmentDefinition.ForComponent(attr).ValueProperty;
if (valueProp == null) {
valueProp = Utility.ReflectGetProperty(attr.GetType(), "Value");
}
// TODO Might not have a value property (should implement an expression around the Value property)
prop = valueProp;
} else {
// TODO Obtain line numbers
prop = Utility.ReflectGetProperty(attr.GetType(), property);
if (prop == null)
throw HxlFailure.ServerAttributePropertyNotFound(attr.GetType(), property, -1, -1);
}
if (!HxlAttributeConverter.IsExpr(value)) {
if (property == null) {
withInit.Attribute.Value = value;
}
withInit.Initializers.Add(prop.Name, value);
return;
}
var buffer = new ExpressionBuffer();
RewriteExpressionSyntax.MatchVariablesAndEmit(buffer, value);
// TODO Could allow multiple exprs
if (buffer.Parts.Count == 1) {
} else
throw new NotImplementedException("ex");
attr.AddAnnotation(new ExpressionInitializers(prop, buffer.Parts[0]));
}
private HxlQualifiedNameHelper ResolveName(string name) {
return HxlQualifiedNameHelper.Parse(name);
}
private void AddImplicitType(Type type) {
_typeUse(type);
}
private void AppendChild(DomContainer child) {
_current.Append(child);
_current = child;
}
class DomAttributeWithInitializers {
public DomAttribute Attribute;
public readonly IDictionary<string, object> Initializers = new Dictionary<string, object>();
}
}
}
| 34.065789 | 114 | 0.573066 | [
"Apache-2.0"
] | Carbonfrost/f-hxl | dotnet/src/Carbonfrost.Commons.Hxl/Compiler/DomConverter.cs | 7,767 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace AlibabaCloud.SDK.ROS.CDK.Slb
{
/// <summary>A ROS template type: `ALIYUN::SLB::BackendServerToVServerGroupAddition`.</summary>
[JsiiClass(nativeType: typeof(AlibabaCloud.SDK.ROS.CDK.Slb.RosBackendServerToVServerGroupAddition), fullyQualifiedName: "@alicloud/ros-cdk-slb.RosBackendServerToVServerGroupAddition", parametersJson: "[{\"docs\":{\"summary\":\"- scope in which this resource is defined.\"},\"name\":\"scope\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-core.Construct\"}},{\"docs\":{\"summary\":\"- scoped id of the resource.\"},\"name\":\"id\",\"type\":{\"primitive\":\"string\"}},{\"docs\":{\"summary\":\"- resource properties.\"},\"name\":\"props\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-slb.RosBackendServerToVServerGroupAdditionProps\"}},{\"name\":\"enableResourcePropertyConstraint\",\"type\":{\"primitive\":\"boolean\"}}]")]
public class RosBackendServerToVServerGroupAddition : AlibabaCloud.SDK.ROS.CDK.Core.RosResource
{
/// <summary>Create a new `ALIYUN::SLB::BackendServerToVServerGroupAddition`.</summary>
/// <param name="scope">- scope in which this resource is defined.</param>
/// <param name="id">- scoped id of the resource.</param>
/// <param name="props">- resource properties.</param>
public RosBackendServerToVServerGroupAddition(AlibabaCloud.SDK.ROS.CDK.Core.Construct scope, string id, AlibabaCloud.SDK.ROS.CDK.Slb.IRosBackendServerToVServerGroupAdditionProps props, bool enableResourcePropertyConstraint): base(new DeputyProps(new object?[]{scope, id, props, enableResourcePropertyConstraint}))
{
}
/// <summary>Used by jsii to construct an instance of this class from a Javascript-owned object reference</summary>
/// <param name="reference">The Javascript-owned object reference</param>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
protected RosBackendServerToVServerGroupAddition(ByRefValue reference): base(reference)
{
}
/// <summary>Used by jsii to construct an instance of this class from DeputyProps</summary>
/// <param name="props">The deputy props</param>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
protected RosBackendServerToVServerGroupAddition(DeputyProps props): base(props)
{
}
[JsiiMethod(name: "renderProperties", returnsJson: "{\"type\":{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}}}", parametersJson: "[{\"name\":\"props\",\"type\":{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}}}]", isOverride: true)]
protected override System.Collections.Generic.IDictionary<string, object> RenderProperties(System.Collections.Generic.IDictionary<string, object> props)
{
return InvokeInstanceMethod<System.Collections.Generic.IDictionary<string, object>>(new System.Type[]{typeof(System.Collections.Generic.IDictionary<string, object>)}, new object[]{props})!;
}
/// <summary>The resource type name for this resource class.</summary>
[JsiiProperty(name: "ROS_RESOURCE_TYPE_NAME", typeJson: "{\"primitive\":\"string\"}")]
public static string ROS_RESOURCE_TYPE_NAME
{
get;
}
= GetStaticProperty<string>(typeof(AlibabaCloud.SDK.ROS.CDK.Slb.RosBackendServerToVServerGroupAddition))!;
/// <remarks>
/// <strong>Attribute</strong>: VServerGroupId: The ID of virtual server group.
/// </remarks>
[JsiiProperty(name: "attrVServerGroupId", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}")]
public virtual AlibabaCloud.SDK.ROS.CDK.Core.IResolvable AttrVServerGroupId
{
get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Core.IResolvable>()!;
}
[JsiiProperty(name: "rosProperties", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}}")]
protected override System.Collections.Generic.IDictionary<string, object> RosProperties
{
get => GetInstanceProperty<System.Collections.Generic.IDictionary<string, object>>()!;
}
/// <remarks>
/// <strong>Property</strong>: backendServers: The list of a combination of ECS Instance-Port-Weight.Same ecs instance with different port is allowed, but same ecs instance with same port isn't.
/// </remarks>
[JsiiProperty(name: "backendServers", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-slb.RosBackendServerToVServerGroupAddition.BackendServersProperty\"}]}},\"kind\":\"array\"}}]}}")]
public virtual object BackendServers
{
get => GetInstanceProperty<object>()!;
set => SetInstanceProperty(value);
}
[JsiiProperty(name: "enableResourcePropertyConstraint", typeJson: "{\"primitive\":\"boolean\"}")]
public virtual bool EnableResourcePropertyConstraint
{
get => GetInstanceProperty<bool>()!;
set => SetInstanceProperty(value);
}
/// <remarks>
/// <strong>Property</strong>: vServerGroupId: The ID of virtual server group.
/// </remarks>
[JsiiProperty(name: "vServerGroupId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public virtual object VServerGroupId
{
get => GetInstanceProperty<object>()!;
set => SetInstanceProperty(value);
}
[JsiiInterface(nativeType: typeof(IBackendServersProperty), fullyQualifiedName: "@alicloud/ros-cdk-slb.RosBackendServerToVServerGroupAddition.BackendServersProperty")]
public interface IBackendServersProperty
{
/// <remarks>
/// <strong>Property</strong>: port: The port of backend server. From 1 to 65535.
/// </remarks>
[JsiiProperty(name: "port", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
object Port
{
get;
}
/// <remarks>
/// <strong>Property</strong>: serverId: The ID of the backend server. You can specify the ID of an Elastic Compute Service (ECS) instance,an elastic network interface (ENI) or elastic container instance (ECI).
/// </remarks>
[JsiiProperty(name: "serverId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
object ServerId
{
get;
}
/// <remarks>
/// <strong>Property</strong>: description: The description of the backend server. The description must be 1 to 80 characters in length, and can contain letters, digits, hyphens (-), forward slashes (/), periods (.), and underscores (_).
/// </remarks>
[JsiiProperty(name: "description", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? Description
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: serverIp: The IP address of an ECS instance, ENI or ECI
/// </remarks>
[JsiiProperty(name: "serverIp", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? ServerIp
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: type: The instance type of the backend server. This parameter must be set to a string. Valid values:
/// ecs: ECS instance. This is the default value.
/// eni: ENI.
/// eci: ECI.
/// </remarks>
[JsiiProperty(name: "type", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? Type
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: weight: The weight of backend server of load balancer. From 0 to 100, 0 means offline. Default is 100.
/// </remarks>
[JsiiProperty(name: "weight", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? Weight
{
get
{
return null;
}
}
[JsiiTypeProxy(nativeType: typeof(IBackendServersProperty), fullyQualifiedName: "@alicloud/ros-cdk-slb.RosBackendServerToVServerGroupAddition.BackendServersProperty")]
internal sealed class _Proxy : DeputyBase, AlibabaCloud.SDK.ROS.CDK.Slb.RosBackendServerToVServerGroupAddition.IBackendServersProperty
{
private _Proxy(ByRefValue reference): base(reference)
{
}
/// <remarks>
/// <strong>Property</strong>: port: The port of backend server. From 1 to 65535.
/// </remarks>
[JsiiProperty(name: "port", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object Port
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: serverId: The ID of the backend server. You can specify the ID of an Elastic Compute Service (ECS) instance,an elastic network interface (ENI) or elastic container instance (ECI).
/// </remarks>
[JsiiProperty(name: "serverId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object ServerId
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: description: The description of the backend server. The description must be 1 to 80 characters in length, and can contain letters, digits, hyphens (-), forward slashes (/), periods (.), and underscores (_).
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "description", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? Description
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: serverIp: The IP address of an ECS instance, ENI or ECI
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "serverIp", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? ServerIp
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: type: The instance type of the backend server. This parameter must be set to a string. Valid values:
/// ecs: ECS instance. This is the default value.
/// eni: ENI.
/// eci: ECI.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "type", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? Type
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: weight: The weight of backend server of load balancer. From 0 to 100, 0 means offline. Default is 100.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "weight", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? Weight
{
get => GetInstanceProperty<object?>();
}
}
}
#pragma warning disable CS8618
[JsiiByValue(fqn: "@alicloud/ros-cdk-slb.RosBackendServerToVServerGroupAddition.BackendServersProperty")]
public class BackendServersProperty : AlibabaCloud.SDK.ROS.CDK.Slb.RosBackendServerToVServerGroupAddition.IBackendServersProperty
{
/// <remarks>
/// <strong>Property</strong>: port: The port of backend server. From 1 to 65535.
/// </remarks>
[JsiiProperty(name: "port", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)]
public object Port
{
get;
set;
}
/// <remarks>
/// <strong>Property</strong>: serverId: The ID of the backend server. You can specify the ID of an Elastic Compute Service (ECS) instance,an elastic network interface (ENI) or elastic container instance (ECI).
/// </remarks>
[JsiiProperty(name: "serverId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)]
public object ServerId
{
get;
set;
}
/// <remarks>
/// <strong>Property</strong>: description: The description of the backend server. The description must be 1 to 80 characters in length, and can contain letters, digits, hyphens (-), forward slashes (/), periods (.), and underscores (_).
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "description", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)]
public object? Description
{
get;
set;
}
/// <remarks>
/// <strong>Property</strong>: serverIp: The IP address of an ECS instance, ENI or ECI
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "serverIp", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)]
public object? ServerIp
{
get;
set;
}
/// <remarks>
/// <strong>Property</strong>: type: The instance type of the backend server. This parameter must be set to a string. Valid values:
/// ecs: ECS instance. This is the default value.
/// eni: ENI.
/// eci: ECI.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "type", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)]
public object? Type
{
get;
set;
}
/// <remarks>
/// <strong>Property</strong>: weight: The weight of backend server of load balancer. From 0 to 100, 0 means offline. Default is 100.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "weight", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)]
public object? Weight
{
get;
set;
}
}
}
}
| 55.192182 | 711 | 0.566749 | [
"Apache-2.0"
] | aliyun/Resource-Orchestration-Service-Cloud-Development-K | multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Slb/AlibabaCloud/SDK/ROS/CDK/Slb/RosBackendServerToVServerGroupAddition.cs | 16,944 | C# |
#region License
/*
MIT License
Copyright(c) 2020 Petteri Kautonen
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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using static VPKSoft.ScintillaLexers.LexerEnumerations;
namespace VPKSoft.ScintillaLexers.LexerColors
{
/// <summary>
/// A class containing the colors for the lexers.
/// </summary>
public class LexerColors
{
/// <summary>
/// Gets or sets the colors for a given LexerType enumeration.
/// </summary>
/// <param name="lexerType">The type of the lexer.</param>
/// <returns>A list of color belonging to a specific lexer.</returns>
/// <exception cref="ArgumentOutOfRangeException">value</exception>
public List<Tuple<Color, string, bool>> this[LexerType lexerType]
{
get
{
if (lexerType == LexerType.Cpp)
{
return cppColors;
}
if (lexerType == LexerType.Nsis)
{
return nsisColors;
}
if (lexerType == LexerType.InnoSetup)
{
return innoSetupColors;
}
if (lexerType == LexerType.Cs)
{
return csColors;
}
if (lexerType == LexerType.Xml)
{
return xmlColors;
}
if (lexerType == LexerType.SQL)
{
return sqlColors;
}
if (lexerType == LexerType.Batch)
{
return batchColors;
}
if (lexerType == LexerType.Pascal)
{
return pascalColors;
}
if (lexerType == LexerType.PHP)
{
return phpColors;
}
if (lexerType == LexerType.HTML)
{
return htmlColors;
}
if (lexerType == LexerType.WindowsPowerShell)
{
return powerShellColors;
}
if (lexerType == LexerType.INI)
{
return iniColors;
}
if (lexerType == LexerType.Python)
{
return pythonColors;
}
if (lexerType == LexerType.YAML)
{
return yamlColors;
}
if (lexerType == LexerType.Java)
{
return javaColors;
}
if (lexerType == LexerType.JavaScript)
{
return javascriptColors;
}
if (lexerType == LexerType.Css)
{
return cssColors;
}
if (lexerType == LexerType.VbDotNet)
{
return vbDotNetColors;
}
if (lexerType == LexerType.Json)
{
return jsonColors;
}
return new List<Tuple<Color, string, bool>>();
}
set
{
if (lexerType == LexerType.Cpp)
{
if (value == null || value.Count != cppColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
cppColors = value;
}
else if (lexerType == LexerType.Nsis)
{
if (value == null || value.Count != nsisColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
nsisColors = value;
}
else if (lexerType == LexerType.InnoSetup)
{
if (value == null || value.Count != innoSetupColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
innoSetupColors = value;
}
else if (lexerType == LexerType.Cs)
{
if (value == null || value.Count != csColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
csColors = value;
}
else if (lexerType == LexerType.Xml)
{
if (value == null || value.Count != xmlColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
xmlColors = value;
}
else if (lexerType == LexerType.SQL)
{
if (value == null || value.Count != sqlColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
sqlColors = value;
}
else if (lexerType == LexerType.Batch)
{
if (value == null || value.Count != batchColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
batchColors = value;
}
else if (lexerType == LexerType.Pascal)
{
if (value == null || value.Count != pascalColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
pascalColors = value;
}
else if (lexerType == LexerType.PHP)
{
if (value == null || value.Count != phpColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
phpColors = value;
}
else if (lexerType == LexerType.HTML)
{
if (value == null || value.Count != htmlColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
htmlColors = value;
}
else if (lexerType == LexerType.WindowsPowerShell)
{
if (value == null || value.Count != powerShellColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
powerShellColors = value;
}
else if (lexerType == LexerType.INI)
{
if (value == null || value.Count != iniColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
iniColors = value;
}
else if (lexerType == LexerType.Python)
{
if (value == null || value.Count != pythonColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
pythonColors = value;
}
else if (lexerType == LexerType.YAML)
{
if (value == null || value.Count != yamlColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
yamlColors = value;
}
else if (lexerType == LexerType.Java)
{
if (value == null || value.Count != javaColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
javaColors = value;
}
else if (lexerType == LexerType.JavaScript)
{
if (value == null || value.Count != javascriptColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
javascriptColors = value;
}
else if (lexerType == LexerType.Css)
{
if (value == null || value.Count != cssColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
cssColors = value;
}
else if (lexerType == LexerType.VbDotNet)
{
if (value == null || value.Count != vbDotNetColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
vbDotNetColors = value;
}
else if (lexerType == LexerType.Json)
{
if (value == null || value.Count != jsonColors.Count)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
jsonColors = value;
}
}
}
/// <summary>
/// Gets or sets the color uses by the SciTE color name and a value indicating whether a foreground or a background color is requested.
/// <note type="note">URL: https://www.scintilla.org/SciTE.html</note>
/// </summary>
/// <param name="lexerType">The type of the lexer.</param>
/// <param name="colorName">The name of the color in the SciTE.</param>
/// <param name="isForeground">A flag indicating whether a foreground or a background color is requested.</param>
/// <returns>A color with the specified lexer, a specified SciTE name and a flag indicating whether the color in question is a background or a foreground color.</returns>
/// <exception cref="ArgumentOutOfRangeException">value</exception>
public Color this[LexerType lexerType, string colorName, bool isForeground]
{
get => this[lexerType][GetColorIndexBySciTEName(colorName, lexerType, isForeground)].Item1;
set
{
try
{
var tuple = this[lexerType][GetColorIndexBySciTEName(colorName, lexerType, isForeground)];
this[lexerType][GetColorIndexBySciTEName(colorName, lexerType, isForeground)] =
Tuple.Create(value, tuple.Item2, tuple.Item3);
}
catch
{
throw new ArgumentOutOfRangeException(nameof(value));
}
}
}
/// <summary>
/// Gets or sets the <see cref="Color"/> with the specified lexer type and the color's name.
/// </summary>
/// <param name="lexerType">The type of the lexer.</param>
/// <param name="colorName">The name of the color.</param>
/// <returns>A color with the specified lexer type and with a specified name.</returns>
/// <exception cref="ArgumentOutOfRangeException">value</exception>
public Color this[LexerType lexerType, string colorName]
{
get => this[lexerType][GetColorIndexByName(colorName, lexerType)].Item1;
set
{
try
{
this[lexerType][GetColorIndexByName(colorName, lexerType)] =
Tuple.Create(value, this[lexerType][GetColorIndexByName(colorName, lexerType)].Item2, this[lexerType][GetColorIndexByName(colorName, lexerType)].Item3);
}
catch
{
throw new ArgumentOutOfRangeException(nameof(value));
}
}
}
#region InternalColorList
private List<Tuple<Color, string, bool>> cppColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(128, 64, 0), "PREPROCESSOR", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "TYPE WORD", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TYPE WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "VERBATIM", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "VERBATIM", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "REGEX", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "REGEX", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT LINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT LINE DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD ERROR", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD ERROR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "PREPROCESSOR COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "PREPROCESSOR COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR COMMENT DOC", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> nsisColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENTLINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENTLINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING DOUBLE QUOTE", true), // #808080
Tuple.Create(Color.FromArgb(238, 238, 238), "STRING DOUBLE QUOTE", false), // #EEEEEE
Tuple.Create(Color.FromArgb(0, 0, 128), "STRING LEFT QUOTE", true), // #000080
Tuple.Create(Color.FromArgb(192, 192, 192), "STRING LEFT QUOTE", false), // #C0C0C0
Tuple.Create(Color.FromArgb(0, 0, 0), "STRING RIGHT QUOTE", true), // #000000
Tuple.Create(Color.FromArgb(192, 192, 192), "STRING RIGHT QUOTE", false), // #C0C0C0
Tuple.Create(Color.FromArgb(0, 0, 255), "FUNCTION", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "FUNCTION", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "VARIABLE", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "VARIABLE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "LABEL", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 128), "LABEL", false), // #FFFF80
Tuple.Create(Color.FromArgb(253, 255, 236), "USER DEFINED", true), // #FDFFEC
Tuple.Create(Color.FromArgb(255, 128, 255), "USER DEFINED", false), // #FF80FF
Tuple.Create(Color.FromArgb(0, 0, 255), "SECTION", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "SECTION", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "SUBSECTION", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "SUBSECTION", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 64), "IF DEFINE", true), // #808040
Tuple.Create(Color.FromArgb(255, 255, 255), "IF DEFINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 0), "MACRO", true), // #800000
Tuple.Create(Color.FromArgb(255, 255, 255), "MACRO", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "STRING VAR", true), // #FF8000
Tuple.Create(Color.FromArgb(239, 239, 239), "STRING VAR", false), // #EFEFEF
Tuple.Create(Color.FromArgb(255, 0, 0), "NUMBER", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "SECTION GROUP", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "SECTION GROUP", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "PAGE EX", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "PAGE EX", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "FUNCTION DEFINITIONS", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "FUNCTION DEFINITIONS", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> innoSetupColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(128, 128, 128), "DEFAULT", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "IDENTIFIER", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "IDENTIFIER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT LINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 64, 0), "PREPROCESSOR", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 64, 0), "PREPROCESSOR2", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR2", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "HEX NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "HEX NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "ASM", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "ASM", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> csColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(128, 64, 0), "PREPROCESSOR", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "TYPE WORD", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TYPE WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "VERBATIM", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "VERBATIM", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "REGEX", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "REGEX", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT LINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT LINE DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD ERROR", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD ERROR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "PREPROCESSOR COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "PREPROCESSOR COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR COMMENT DOC", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> xmlColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(255, 0, 0), "XMLSTART", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 0), "XMLSTART", false), // #FFFF00
Tuple.Create(Color.FromArgb(255, 0, 0), "XMLEND", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 0), "XMLEND", false), // #FFFF00
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "NUMBER", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "DOUBLESTRING", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "DOUBLESTRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "SINGLESTRING", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "SINGLESTRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "TAG", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TAG", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "TAGEND", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TAGEND", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "TAGUNKNOWN", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TAGUNKNOWN", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "ATTRIBUTE", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "ATTRIBUTE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "ATTRIBUTEUNKNOWN", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "ATTRIBUTEUNKNOWN", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "SGMLDEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(166, 202, 240), "SGMLDEFAULT", false), // #A6CAF0
Tuple.Create(Color.FromArgb(255, 128, 0), "CDATA", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "CDATA", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "ENTITY", true), // #000000
Tuple.Create(Color.FromArgb(254, 253, 224), "ENTITY", false) // #FEFDE0
});
private List<Tuple<Color, string, bool>> sqlColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 255), "KEYWORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "KEYWORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING2", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING2", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT LINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> batchColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "KEYWORDS", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "KEYWORDS", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "LABEL", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 128), "LABEL", false), // #FFFF80
Tuple.Create(Color.FromArgb(255, 0, 255), "HIDE SYBOL", true), // #FF00FF
Tuple.Create(Color.FromArgb(255, 255, 255), "HIDE SYBOL", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 255), "COMMAND", true), // #0080FF
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMAND", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "VARIABLE", true), // #FF8000
Tuple.Create(Color.FromArgb(252, 255, 240), "VARIABLE", false), // #FCFFF0
Tuple.Create(Color.FromArgb(255, 0, 0), "OPERATOR", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> pascalColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(128, 128, 128), "DEFAULT", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "IDENTIFIER", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "IDENTIFIER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT LINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 64, 0), "PREPROCESSOR", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 64, 0), "PREPROCESSOR2", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR2", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "HEX NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "HEX NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "ASM", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "ASM", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> phpColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(255, 0, 0), "QUESTION MARK", true), // #FF0000
Tuple.Create(Color.FromArgb(253, 248, 227), "QUESTION MARK", false), // #FDF8E3
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(254, 252, 245), "DEFAULT", false), // #FEFCF5
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(254, 252, 245), "STRING", false), // #FEFCF5
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING VARIABLE", true), // #808080
Tuple.Create(Color.FromArgb(254, 252, 245), "STRING VARIABLE", false), // #FEFCF5
Tuple.Create(Color.FromArgb(128, 128, 128), "SIMPLESTRING", true), // #808080
Tuple.Create(Color.FromArgb(254, 252, 245), "SIMPLESTRING", false), // #FEFCF5
Tuple.Create(Color.FromArgb(0, 0, 255), "WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(254, 252, 245), "WORD", false), // #FEFCF5
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(254, 252, 245), "NUMBER", false), // #FEFCF5
Tuple.Create(Color.FromArgb(0, 0, 128), "VARIABLE", true), // #000080
Tuple.Create(Color.FromArgb(254, 252, 245), "VARIABLE", false), // #FEFCF5
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(254, 252, 245), "COMMENT", false), // #FEFCF5
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENTLINE", true), // #008000
Tuple.Create(Color.FromArgb(254, 252, 245), "COMMENTLINE", false), // #FEFCF5
Tuple.Create(Color.FromArgb(128, 0, 255), "OPERATOR", true), // #8000FF
Tuple.Create(Color.FromArgb(254, 252, 245), "OPERATOR", false) // #FEFCF5
});
private List<Tuple<Color, string, bool>> htmlColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "NUMBER", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "DOUBLESTRING", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "DOUBLESTRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "SINGLESTRING", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "SINGLESTRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "TAG", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TAG", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "TAGEND", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TAGEND", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "TAGUNKNOWN", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "TAGUNKNOWN", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "ATTRIBUTE", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "ATTRIBUTE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "ATTRIBUTEUNKNOWN", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "ATTRIBUTEUNKNOWN", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "SGMLDEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(166, 202, 240), "SGMLDEFAULT", false), // #A6CAF0
Tuple.Create(Color.FromArgb(255, 128, 0), "CDATA", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "CDATA", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "VALUE", true), // #FF8000
Tuple.Create(Color.FromArgb(254, 253, 224), "VALUE", false), // #FEFDE0
Tuple.Create(Color.FromArgb(0, 0, 0), "ENTITY", true), // #000000
Tuple.Create(Color.FromArgb(254, 253, 224), "ENTITY", false) // #FEFDE0
});
private List<Tuple<Color, string, bool>> powerShellColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "VARIABLE", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "VARIABLE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "CMDLET", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "CMDLET", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 255), "ALIAS", true), // #0080FF
Tuple.Create(Color.FromArgb(255, 255, 255), "ALIAS", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT STREAM", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT STREAM", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "HERE STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "HERE STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "HERE CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "HERE CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> iniColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "SECTION", true), // #8000FF
Tuple.Create(Color.FromArgb(242, 244, 255), "SECTION", false), // #F2F4FF
Tuple.Create(Color.FromArgb(255, 0, 0), "ASSIGNMENT", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "ASSIGNMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "DEFVAL", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFVAL", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> pythonColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENTLINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENTLINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "NUMBER", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "KEYWORDS", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "KEYWORDS", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "TRIPLE", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "TRIPLE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "TRIPLEDOUBLE", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "TRIPLEDOUBLE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "CLASSNAME", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "CLASSNAME", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 255), "DEFNAME", true), // #FF00FF
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFNAME", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "IDENTIFIER", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "IDENTIFIER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENTBLOCK", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENTBLOCK", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "DECORATOR", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "DECORATOR", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> yamlColors = new List<Tuple<Color, string, bool>>(new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "IDENTIFIER", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "IDENTIFIER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 64), "NUMBER", true), // #FF8040
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 64, 0), "REFERENCE", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "REFERENCE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "DOCUMENT", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "DOCUMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "TEXT", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "TEXT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "ERROR", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "ERROR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> javaColors = new List<Tuple<Color, string, bool>>(
new[]
{
Tuple.Create(Color.FromArgb(128, 64, 0), "PREPROCESSOR", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "TYPE WORD", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TYPE WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "VERBATIM", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "VERBATIM", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "REGEX", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "REGEX", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT LINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT LINE DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD ERROR", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD ERROR", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> javascriptColors = new List<Tuple<Color, string, bool>>(
new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "INSTRUCTION WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "INSTRUCTION WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 0, 255), "TYPE WORD", true), // #8000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TYPE WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 64, 0), "WINDOW INSTRUCTION", true), // #804000
Tuple.Create(Color.FromArgb(255, 255, 255), "WINDOW INSTRUCTION", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "NUMBER", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "STRINGRAW", true), // #000080
Tuple.Create(Color.FromArgb(192, 192, 192), "STRINGRAW", false), // #C0C0C0
Tuple.Create(Color.FromArgb(128, 128, 128), "CHARACTER", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "CHARACTER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 128), "OPERATOR", true), // #000080
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "VERBATIM", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "VERBATIM", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "REGEX", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "REGEX", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT LINE", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT LINE DOC", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT LINE DOC", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 128), "COMMENT DOC KEYWORD ERROR", true), // #008080
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT DOC KEYWORD ERROR", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> cssColors = new List<Tuple<Color, string, bool>>(
new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "TAG", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "TAG", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "CLASS", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "CLASS", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 0), "PSEUDOCLASS", true), // #FF8000
Tuple.Create(Color.FromArgb(255, 255, 255), "PSEUDOCLASS", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 128, 128), "UNKNOWN_PSEUDOCLASS", true), // #FF8080
Tuple.Create(Color.FromArgb(255, 255, 255), "UNKNOWN_PSEUDOCLASS", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "OPERATOR", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 192), "IDENTIFIER", true), // #8080C0
Tuple.Create(Color.FromArgb(255, 255, 255), "IDENTIFIER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "UNKNOWN_IDENTIFIER", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "UNKNOWN_IDENTIFIER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "VALUE", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "VALUE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 255), "ID", true), // #0080FF
Tuple.Create(Color.FromArgb(255, 255, 255), "ID", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "IMPORTANT", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "IMPORTANT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 255), "DIRECTIVE", true), // #0080FF
Tuple.Create(Color.FromArgb(255, 255, 255), "DIRECTIVE", false) // #FFFFFF
});
private List<Tuple<Color, string, bool>> vbDotNetColors = new List<Tuple<Color, string, bool>>(
new[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 128, 0), "COMMENT", true), // #008000
Tuple.Create(Color.FromArgb(255, 255, 255), "COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "NUMBER", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "WORD", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "WORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 255), "WORD2", true), // #0000FF
Tuple.Create(Color.FromArgb(255, 255, 255), "WORD2", false), // #FFFFFF
Tuple.Create(Color.FromArgb(128, 128, 128), "STRING", true), // #808080
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(255, 0, 0), "PREPROCESSOR", true), // #FF0000
Tuple.Create(Color.FromArgb(255, 255, 255), "PREPROCESSOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0), "OPERATOR", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 255, 0), "DATE", true), // #00FF00
Tuple.Create(Color.FromArgb(255, 255, 255), "DATE", false), // #FFFFFF
});
List<Tuple<Color, string, bool>> jsonColors = new List<Tuple<Color, string, bool>>(new Tuple<Color, string, bool>[]
{
Tuple.Create(Color.FromArgb(0, 0, 0), "DEFAULT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "DEFAULT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0xFF, 0x80, 0), "NUMBER", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "NUMBER", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0x80, 0x80, 0x80), "STRING", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0x80, 0x80, 0x80), "UNCLOSED STRING", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "UNCLOSED STRING", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0x88, 0x0A, 0xE8), "PROPERTY NAME", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "PROPERTY NAME", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0xA5, 0x2A, 0x2A), "ESCAPE SEQUENCE", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "ESCAPE SEQUENCE", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0x80, 0), "LINE COMMENT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "LINE COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0x80, 0), "BLOCK COMMENT", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "BLOCK COMMENT", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0x80, 0, 0xFF), "OPERATOR", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "OPERATOR", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0xC7, 0x15, 0x85), "URI", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "URI", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0xD9, 0x22, 0x99), "JSON-LD COMPACT IRI", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "JSON-LD COMPACT IRI", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0x80), "JSON KEYWORD", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "JSON KEYWORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0, 0x89), "JSON-LD KEYWORD", true), // #000000
Tuple.Create(Color.FromArgb(255, 255, 255), "JSON-LD KEYWORD", false), // #FFFFFF
Tuple.Create(Color.FromArgb(0, 0x8B, 0x8B), "PARSING ERROR", true), // #000000
Tuple.Create(Color.FromArgb(0xFF, 0X45, 255), "PARSING ERROR", false), // #FFFFFF
});
#endregion
#region InteralColorIndexList
private List<KeyValuePair<int, string>> CsColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "PreprocessorFore"),
new KeyValuePair<int, string>(1, "PreprocessorBack"),
new KeyValuePair<int, string>(2, "DefaultFore"),
new KeyValuePair<int, string>(3, "DefaultBack"),
new KeyValuePair<int, string>(4, "WordFore"),
new KeyValuePair<int, string>(5, "WordBack"),
new KeyValuePair<int, string>(6, "Word2Fore"),
new KeyValuePair<int, string>(7, "Word2Back"),
new KeyValuePair<int, string>(8, "NumberFore"),
new KeyValuePair<int, string>(9, "NumberBack"),
new KeyValuePair<int, string>(10, "StringFore"),
new KeyValuePair<int, string>(11, "StringBack"),
new KeyValuePair<int, string>(12, "CharacterFore"),
new KeyValuePair<int, string>(13, "CharacterBack"),
new KeyValuePair<int, string>(14, "OperatorFore"),
new KeyValuePair<int, string>(15, "OperatorBack"),
new KeyValuePair<int, string>(16, "VerbatimFore"),
new KeyValuePair<int, string>(17, "VerbatimBack"),
new KeyValuePair<int, string>(18, "RegexFore"),
new KeyValuePair<int, string>(19, "RegexBack"),
new KeyValuePair<int, string>(20, "CommentFore"),
new KeyValuePair<int, string>(21, "CommentBack"),
new KeyValuePair<int, string>(22, "CommentLineFore"),
new KeyValuePair<int, string>(23, "CommentLineBack"),
new KeyValuePair<int, string>(24, "CommentDocFore"),
new KeyValuePair<int, string>(25, "CommentDocBack"),
new KeyValuePair<int, string>(26, "CommentLineDocFore"),
new KeyValuePair<int, string>(27, "CommentLineDocBack"),
new KeyValuePair<int, string>(28, "CommentDocKeywordFore"),
new KeyValuePair<int, string>(29, "CommentDocKeywordBack"),
new KeyValuePair<int, string>(30, "CommentDocKeywordErrorFore"),
new KeyValuePair<int, string>(31, "CommentDocKeywordErrorBack"),
new KeyValuePair<int, string>(32, "PreprocessorCommentFore"),
new KeyValuePair<int, string>(33, "PreprocessorCommentBack"),
new KeyValuePair<int, string>(34, "PreprocessorCommentDocFore"),
new KeyValuePair<int, string>(35, "PreprocessorCommentDocBack")
}
);
private List<KeyValuePair<int, string>> CppColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "PreprocessorFore"),
new KeyValuePair<int, string>(1, "PreprocessorBack"),
new KeyValuePair<int, string>(2, "DefaultFore"),
new KeyValuePair<int, string>(3, "DefaultBack"),
new KeyValuePair<int, string>(4, "WordFore"),
new KeyValuePair<int, string>(5, "WordBack"),
new KeyValuePair<int, string>(6, "Word2Fore"),
new KeyValuePair<int, string>(7, "Word2Back"),
new KeyValuePair<int, string>(8, "NumberFore"),
new KeyValuePair<int, string>(9, "NumberBack"),
new KeyValuePair<int, string>(10, "StringFore"),
new KeyValuePair<int, string>(11, "StringBack"),
new KeyValuePair<int, string>(12, "CharacterFore"),
new KeyValuePair<int, string>(13, "CharacterBack"),
new KeyValuePair<int, string>(14, "OperatorFore"),
new KeyValuePair<int, string>(15, "OperatorBack"),
new KeyValuePair<int, string>(16, "VerbatimFore"),
new KeyValuePair<int, string>(17, "VerbatimBack"),
new KeyValuePair<int, string>(18, "RegexFore"),
new KeyValuePair<int, string>(19, "RegexBack"),
new KeyValuePair<int, string>(20, "CommentFore"),
new KeyValuePair<int, string>(21, "CommentBack"),
new KeyValuePair<int, string>(22, "CommentLineFore"),
new KeyValuePair<int, string>(23, "CommentLineBack"),
new KeyValuePair<int, string>(24, "CommentDocFore"),
new KeyValuePair<int, string>(25, "CommentDocBack"),
new KeyValuePair<int, string>(26, "CommentLineDocFore"),
new KeyValuePair<int, string>(27, "CommentLineDocBack"),
new KeyValuePair<int, string>(28, "CommentDocKeywordFore"),
new KeyValuePair<int, string>(29, "CommentDocKeywordBack"),
new KeyValuePair<int, string>(30, "CommentDocKeywordErrorFore"),
new KeyValuePair<int, string>(31, "CommentDocKeywordErrorBack"),
new KeyValuePair<int, string>(32, "PreprocessorCommentFore"),
new KeyValuePair<int, string>(33, "PreprocessorCommentBack"),
new KeyValuePair<int, string>(34, "PreprocessorCommentDocFore"),
new KeyValuePair<int, string>(35, "PreprocessorCommentDocBack")
}
);
private List<KeyValuePair<int, string>> XmlColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "XmlStartFore"),
new KeyValuePair<int, string>(1, "XmlStartBack"),
new KeyValuePair<int, string>(2, "XmlEndFore"),
new KeyValuePair<int, string>(3, "XmlEndBack"),
new KeyValuePair<int, string>(4, "DefaultFore"),
new KeyValuePair<int, string>(5, "DefaultBack"),
new KeyValuePair<int, string>(6, "CommentFore"),
new KeyValuePair<int, string>(7, "CommentBack"),
new KeyValuePair<int, string>(8, "NumberFore"),
new KeyValuePair<int, string>(9, "NumberBack"),
new KeyValuePair<int, string>(10, "DoubleStringFore"),
new KeyValuePair<int, string>(11, "DoubleStringBack"),
new KeyValuePair<int, string>(12, "SingleStringFore"),
new KeyValuePair<int, string>(13, "SingleStringBack"),
new KeyValuePair<int, string>(14, "TagFore"),
new KeyValuePair<int, string>(15, "TagBack"),
new KeyValuePair<int, string>(16, "TagEndFore"),
new KeyValuePair<int, string>(17, "TagEndBack"),
new KeyValuePair<int, string>(18, "TagUnknownFore"),
new KeyValuePair<int, string>(19, "TagUnknownBack"),
new KeyValuePair<int, string>(20, "AttributeFore"),
new KeyValuePair<int, string>(21, "AttributeBack"),
new KeyValuePair<int, string>(22, "AttributeUnknownFore"),
new KeyValuePair<int, string>(23, "AttributeUnknownBack"),
new KeyValuePair<int, string>(24, "SgmlDefaultFore"),
new KeyValuePair<int, string>(25, "SgmlDefaultBack"),
new KeyValuePair<int, string>(26, "CDataFore"),
new KeyValuePair<int, string>(27, "CDataBack"),
new KeyValuePair<int, string>(28, "EntityFore"),
new KeyValuePair<int, string>(29, "EntityBack")
}
);
private List<KeyValuePair<int, string>> YamlColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "IdentifierFore"),
new KeyValuePair<int, string>(3, "IdentifierBack"),
new KeyValuePair<int, string>(4, "CommentFore"),
new KeyValuePair<int, string>(5, "CommentBack"),
new KeyValuePair<int, string>(6, "InstructionWordFore"),
new KeyValuePair<int, string>(7, "InstructionWordBack"),
new KeyValuePair<int, string>(8, "NumberFore"),
new KeyValuePair<int, string>(9, "NumberBack"),
new KeyValuePair<int, string>(10, "ReferenceFore"),
new KeyValuePair<int, string>(11, "ReferenceBack"),
new KeyValuePair<int, string>(12, "DocumentFore"),
new KeyValuePair<int, string>(13, "DocumentBack"),
new KeyValuePair<int, string>(14, "TextFore"),
new KeyValuePair<int, string>(15, "TextBack"),
new KeyValuePair<int, string>(16, "ErrorFore"),
new KeyValuePair<int, string>(17, "ErrortBack")
});
private List<KeyValuePair<int, string>> NsisColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "CommentFore"),
new KeyValuePair<int, string>(3, "CommentBack"),
new KeyValuePair<int, string>(4, "StringDoubleQuoteFore"),
new KeyValuePair<int, string>(5, "StringDoubleQuoteBack"),
new KeyValuePair<int, string>(6, "StringLeftQuoteFore"),
new KeyValuePair<int, string>(7, "StringLeftQuoteBack"),
new KeyValuePair<int, string>(8, "StringRightQuoteFore"),
new KeyValuePair<int, string>(9, "StringRightQuoteBack"),
new KeyValuePair<int, string>(10, "FunctionFore"),
new KeyValuePair<int, string>(11, "FunctionBack"),
new KeyValuePair<int, string>(12, "VariableFore"),
new KeyValuePair<int, string>(13, "VariableBack"),
new KeyValuePair<int, string>(14, "LabelFore"),
new KeyValuePair<int, string>(15, "LabelBack"),
new KeyValuePair<int, string>(16, "UserDefinedFore"),
new KeyValuePair<int, string>(17, "UserDefinedBack"),
new KeyValuePair<int, string>(18, "SectionFore"),
new KeyValuePair<int, string>(19, "SectionBack"),
new KeyValuePair<int, string>(20, "SubSectionFore"),
new KeyValuePair<int, string>(21, "SubSectionBack"),
new KeyValuePair<int, string>(22, "IfDefineFore"),
new KeyValuePair<int, string>(23, "IfDefineBack"),
new KeyValuePair<int, string>(24, "MacroFore"),
new KeyValuePair<int, string>(25, "MacroBack"),
new KeyValuePair<int, string>(26, "StringVarFore"),
new KeyValuePair<int, string>(27, "StringVarBack"),
new KeyValuePair<int, string>(28, "NumberFore"),
new KeyValuePair<int, string>(29, "NumberBack"),
new KeyValuePair<int, string>(30, "SectionGroupFore"),
new KeyValuePair<int, string>(31, "SectionGroupBack"),
new KeyValuePair<int, string>(32, "PageExFore"),
new KeyValuePair<int, string>(33, "PageExBack"),
new KeyValuePair<int, string>(34, "FunctionDefinitionsFore"),
new KeyValuePair<int, string>(35, "FunctionDefinitionsBack"),
new KeyValuePair<int, string>(36, "CommentFore"),
new KeyValuePair<int, string>(37, "CommentBack")
}
);
private List<KeyValuePair<int, string>> InnoSetupColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "IdentifierFore"),
new KeyValuePair<int, string>(3, "IdentifierBack"),
new KeyValuePair<int, string>(4, "CommentFore"),
new KeyValuePair<int, string>(5, "CommentBack"),
new KeyValuePair<int, string>(6, "Comment2Fore"),
new KeyValuePair<int, string>(7, "Comment2Back"),
new KeyValuePair<int, string>(8, "CommentLineFore"),
new KeyValuePair<int, string>(9, "CommentLineBack"),
new KeyValuePair<int, string>(10, "PreprocessorFore"),
new KeyValuePair<int, string>(11, "PreprocessorBack"),
new KeyValuePair<int, string>(12, "Preprocessor2Fore"),
new KeyValuePair<int, string>(13, "Preprocessor2Back"),
new KeyValuePair<int, string>(14, "NumberFore"),
new KeyValuePair<int, string>(15, "NumberBack"),
new KeyValuePair<int, string>(16, "HexNumberFore"),
new KeyValuePair<int, string>(17, "HexNumberBack"),
new KeyValuePair<int, string>(18, "WordFore"),
new KeyValuePair<int, string>(19, "WordBack"),
new KeyValuePair<int, string>(20, "StringFore"),
new KeyValuePair<int, string>(21, "StringBack"),
new KeyValuePair<int, string>(22, "CharacterFore"),
new KeyValuePair<int, string>(23, "CharacterBack"),
new KeyValuePair<int, string>(24, "OperatorFore"),
new KeyValuePair<int, string>(25, "OperatorBack"),
new KeyValuePair<int, string>(26, "ForeColorFore"),
new KeyValuePair<int, string>(27, "ForeColorBack")
}
);
private List<KeyValuePair<int, string>> SqlColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "WordFore"),
new KeyValuePair<int, string>(1, "WordBack"),
new KeyValuePair<int, string>(2, "NumberFore"),
new KeyValuePair<int, string>(3, "NumberBack"),
new KeyValuePair<int, string>(4, "StringFore"),
new KeyValuePair<int, string>(5, "StringBack"),
new KeyValuePair<int, string>(6, "CharacterFore"),
new KeyValuePair<int, string>(7, "CharacterBack"),
new KeyValuePair<int, string>(8, "OperatorFore"),
new KeyValuePair<int, string>(9, "OperatorBack"),
new KeyValuePair<int, string>(10, "CommentFore"),
new KeyValuePair<int, string>(11, "CommentBack"),
new KeyValuePair<int, string>(12, "CommentLineFore"),
new KeyValuePair<int, string>(13, "CommentLineBack")
}
);
private List<KeyValuePair<int, string>> BatchColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "CommentFore"),
new KeyValuePair<int, string>(3, "CommentBack"),
new KeyValuePair<int, string>(4, "WordFore"),
new KeyValuePair<int, string>(5, "WordBack"),
new KeyValuePair<int, string>(6, "LabelFore"),
new KeyValuePair<int, string>(7, "LabelBack"),
new KeyValuePair<int, string>(8, "HideFore"),
new KeyValuePair<int, string>(9, "HideBack"),
new KeyValuePair<int, string>(10, "CommandFore"),
new KeyValuePair<int, string>(11, "CommandBack"),
new KeyValuePair<int, string>(12, "IdentifierFore"),
new KeyValuePair<int, string>(13, "IdentifierBack"),
new KeyValuePair<int, string>(14, "OperatorFore"),
new KeyValuePair<int, string>(15, "OperatorBack")
}
);
private List<KeyValuePair<int, string>> PascalColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "IdentifierFore"),
new KeyValuePair<int, string>(3, "IdentifierBack"),
new KeyValuePair<int, string>(4, "CommentFore"),
new KeyValuePair<int, string>(5, "CommentBack"),
new KeyValuePair<int, string>(6, "Comment2Fore"),
new KeyValuePair<int, string>(7, "Comment2Back"),
new KeyValuePair<int, string>(8, "CommentLineFore"),
new KeyValuePair<int, string>(9, "CommentLineBack"),
new KeyValuePair<int, string>(10, "PreprocessorFore"),
new KeyValuePair<int, string>(11, "PreprocessorBack"),
new KeyValuePair<int, string>(12, "Preprocessor2Fore"),
new KeyValuePair<int, string>(13, "Preprocessor2Back"),
new KeyValuePair<int, string>(14, "NumberFore"),
new KeyValuePair<int, string>(15, "NumberBack"),
new KeyValuePair<int, string>(16, "HexNumberFore"),
new KeyValuePair<int, string>(17, "HexNumberBack"),
new KeyValuePair<int, string>(18, "WordFore"),
new KeyValuePair<int, string>(19, "WordBack"),
new KeyValuePair<int, string>(20, "StringFore"),
new KeyValuePair<int, string>(21, "StringBack"),
new KeyValuePair<int, string>(22, "CharacterFore"),
new KeyValuePair<int, string>(23, "CharacterBack"),
new KeyValuePair<int, string>(24, "OperatorFore"),
new KeyValuePair<int, string>(25, "OperatorBack"),
new KeyValuePair<int, string>(26, "ForeColorFore"),
new KeyValuePair<int, string>(27, "ForeColorBack")
}
);
private List<KeyValuePair<int, string>> PhpColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "HQuestionFore"),
new KeyValuePair<int, string>(1, "HQuestionBack"),
new KeyValuePair<int, string>(2, "DefaultFore"),
new KeyValuePair<int, string>(3, "DefaultBack"),
new KeyValuePair<int, string>(4, "HStringFore"),
new KeyValuePair<int, string>(5, "HStringBack"),
new KeyValuePair<int, string>(6, "HStringVariableFore"),
new KeyValuePair<int, string>(7, "HStringVariableBack"),
new KeyValuePair<int, string>(8, "SimpleStringFore"),
new KeyValuePair<int, string>(9, "SimpleStringBack"),
new KeyValuePair<int, string>(10, "WordFore"),
new KeyValuePair<int, string>(11, "WordBack"),
new KeyValuePair<int, string>(12, "NumberFore"),
new KeyValuePair<int, string>(13, "NumberBack"),
new KeyValuePair<int, string>(14, "VariableFore"),
new KeyValuePair<int, string>(15, "VariableBack"),
new KeyValuePair<int, string>(16, "CommentFore"),
new KeyValuePair<int, string>(17, "CommentBack"),
new KeyValuePair<int, string>(18, "CommentLineFore"),
new KeyValuePair<int, string>(19, "CommentLineBack"),
new KeyValuePair<int, string>(20, "OperatorFore"),
new KeyValuePair<int, string>(21, "OperatorBack")
}
);
private List<KeyValuePair<int, string>> HtmlColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "CommentFore"),
new KeyValuePair<int, string>(3, "CommentBack"),
new KeyValuePair<int, string>(4, "NumberFore"),
new KeyValuePair<int, string>(5, "NumberBack"),
new KeyValuePair<int, string>(6, "DoubleStringFore"),
new KeyValuePair<int, string>(7, "DoubleStringBack"),
new KeyValuePair<int, string>(8, "SingleStringFore"),
new KeyValuePair<int, string>(9, "SingleStringBack"),
new KeyValuePair<int, string>(10, "TagFore"),
new KeyValuePair<int, string>(11, "TagBack"),
new KeyValuePair<int, string>(12, "TagEndFore"),
new KeyValuePair<int, string>(13, "TagEndBack"),
new KeyValuePair<int, string>(14, "TagUnknownFore"),
new KeyValuePair<int, string>(15, "TagUnknownBack"),
new KeyValuePair<int, string>(16, "AttributeFore"),
new KeyValuePair<int, string>(17, "AttributeBack"),
new KeyValuePair<int, string>(18, "AttributeUnknownFore"),
new KeyValuePair<int, string>(19, "AttributeUnknownBack"),
new KeyValuePair<int, string>(20, "SGMDefaultFore"),
new KeyValuePair<int, string>(21, "SGMDefaultBack"),
new KeyValuePair<int, string>(22, "CDataFore"),
new KeyValuePair<int, string>(23, "CDataBack"),
new KeyValuePair<int, string>(24, "ValueFore"),
new KeyValuePair<int, string>(25, "ValueBack"),
new KeyValuePair<int, string>(26, "EntityFore"),
new KeyValuePair<int, string>(27, "EntityBack"),
new KeyValuePair<int, string>(28, "HQuestionFore"),
new KeyValuePair<int, string>(29, "HQuestionBack")
});
private List<KeyValuePair<int, string>> PowerShellColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "CommentFore"),
new KeyValuePair<int, string>(3, "CommentBack"),
new KeyValuePair<int, string>(4, "StringFore"),
new KeyValuePair<int, string>(5, "StringBack"),
new KeyValuePair<int, string>(6, "CharacterFore"),
new KeyValuePair<int, string>(7, "CharacterBack"),
new KeyValuePair<int, string>(8, "NumberFore"),
new KeyValuePair<int, string>(9, "NumberBack"),
new KeyValuePair<int, string>(10, "VariableFore"),
new KeyValuePair<int, string>(11, "VariableBack"),
new KeyValuePair<int, string>(12, "OperatorFore"),
new KeyValuePair<int, string>(13, "OperatorBack"),
new KeyValuePair<int, string>(14, "InstructionWordFore"),
new KeyValuePair<int, string>(15, "InstructionWordBack"),
new KeyValuePair<int, string>(16, "CommandletFore"),
new KeyValuePair<int, string>(17, "CommandletBack"),
new KeyValuePair<int, string>(18, "AliasFore"),
new KeyValuePair<int, string>(19, "AliasBack"),
new KeyValuePair<int, string>(20, "CommentStreamFore"),
new KeyValuePair<int, string>(21, "CommentStreamBack"),
new KeyValuePair<int, string>(22, "HereStringFore"),
new KeyValuePair<int, string>(23, "HereStringBack"),
new KeyValuePair<int, string>(24, "HereCharacterFore"),
new KeyValuePair<int, string>(25, "HereCharacterBack"),
new KeyValuePair<int, string>(26, "CommentDocKeywordFore"),
new KeyValuePair<int, string>(27, "CommentDocKeywordBack")
}
);
private List<KeyValuePair<int, string>> IniColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "CommentFore"),
new KeyValuePair<int, string>(3, "CommentBack"),
new KeyValuePair<int, string>(4, "SectionFore"),
new KeyValuePair<int, string>(5, "SectionBack"),
new KeyValuePair<int, string>(6, "AssignmentFore"),
new KeyValuePair<int, string>(7, "AssignmentBack"),
new KeyValuePair<int, string>(8, "DefValFore"),
new KeyValuePair<int, string>(9, "DefValBack")
});
private List<KeyValuePair<int, string>> PythonColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "CommentLineFore"),
new KeyValuePair<int, string>(3, "CommentLineBack"),
new KeyValuePair<int, string>(4, "NumberFore"),
new KeyValuePair<int, string>(5, "NumberBack"),
new KeyValuePair<int, string>(6, "StringFore"),
new KeyValuePair<int, string>(7, "StringBack"),
new KeyValuePair<int, string>(8, "CharacterFore"),
new KeyValuePair<int, string>(9, "CharacterBack"),
new KeyValuePair<int, string>(10, "WordFore"),
new KeyValuePair<int, string>(11, "WordBack"),
new KeyValuePair<int, string>(12, "TripleFore"),
new KeyValuePair<int, string>(13, "TripleBack"),
new KeyValuePair<int, string>(14, "TripleDoubleFore"),
new KeyValuePair<int, string>(15, "TripleDoubleBack"),
new KeyValuePair<int, string>(16, "ClassNameFore"),
new KeyValuePair<int, string>(17, "ClassNameBack"),
new KeyValuePair<int, string>(18, "DefNameFore"),
new KeyValuePair<int, string>(19, "DefNameBack"),
new KeyValuePair<int, string>(20, "OperatorFore"),
new KeyValuePair<int, string>(21, "OperatorBack"),
new KeyValuePair<int, string>(22, "IdentifierFore"),
new KeyValuePair<int, string>(23, "IdentifierBack"),
new KeyValuePair<int, string>(24, "CommentBlockFore"),
new KeyValuePair<int, string>(25, "CommentBlockBack"),
new KeyValuePair<int, string>(26, "DecoratorFore"),
new KeyValuePair<int, string>(27, "DecoratorBack")
});
private List<KeyValuePair<int, string>> JavaColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "PreprocessorFore"),
new KeyValuePair<int, string>(1, "PreprocessorBack"),
new KeyValuePair<int, string>(2, "DefaultFore"),
new KeyValuePair<int, string>(3, "DefaultBack"),
new KeyValuePair<int, string>(4, "InstructionWordFore"),
new KeyValuePair<int, string>(5, "InstructionWordBack"),
new KeyValuePair<int, string>(6, "TypeWordFore"),
new KeyValuePair<int, string>(7, "TypeWordBack"),
new KeyValuePair<int, string>(8, "NumberFore"),
new KeyValuePair<int, string>(9, "NumberBack"),
new KeyValuePair<int, string>(10, "StringFore"),
new KeyValuePair<int, string>(11, "StringBack"),
new KeyValuePair<int, string>(12, "CharacterFore"),
new KeyValuePair<int, string>(13, "CharacterBack"),
new KeyValuePair<int, string>(14, "OperatorFore"),
new KeyValuePair<int, string>(15, "OperatorBack"),
new KeyValuePair<int, string>(16, "VerbatimFore"),
new KeyValuePair<int, string>(17, "VerbatimBack"),
new KeyValuePair<int, string>(18, "RegexFore"),
new KeyValuePair<int, string>(19, "RegexBack"),
new KeyValuePair<int, string>(20, "CommentFore"),
new KeyValuePair<int, string>(21, "CommentBack"),
new KeyValuePair<int, string>(22, "CommentLineFore"),
new KeyValuePair<int, string>(23, "CommentLineBack"),
new KeyValuePair<int, string>(24, "CommentDocFore"),
new KeyValuePair<int, string>(25, "CommentDocBack"),
new KeyValuePair<int, string>(26, "CommentLineDocFore"),
new KeyValuePair<int, string>(27, "CommentLineDocBack"),
new KeyValuePair<int, string>(28, "CommentDocKeywordFore"),
new KeyValuePair<int, string>(29, "CommentDocKeywordBack"),
new KeyValuePair<int, string>(30, "CommentDocKeywordErrorFore"),
new KeyValuePair<int, string>(31, "CommentDocKeywordErrorBack")
});
private List<KeyValuePair<int, string>> JavaScriptColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "InstructionWordFore"),
new KeyValuePair<int, string>(3, "InstructionWordBack"),
new KeyValuePair<int, string>(4, "TypeWordFore"),
new KeyValuePair<int, string>(5, "TypeWordBack"),
new KeyValuePair<int, string>(6, "WindowInstructionFore"),
new KeyValuePair<int, string>(7, "WindowInstructionBack"),
new KeyValuePair<int, string>(8, "NumberFore"),
new KeyValuePair<int, string>(9, "NumberBack"),
new KeyValuePair<int, string>(10, "StringFore"),
new KeyValuePair<int, string>(11, "StringBack"),
new KeyValuePair<int, string>(12, "StringRawFore"),
new KeyValuePair<int, string>(13, "StringRawBack"),
new KeyValuePair<int, string>(14, "CharacterFore"),
new KeyValuePair<int, string>(15, "CharacterBack"),
new KeyValuePair<int, string>(16, "OperatorFore"),
new KeyValuePair<int, string>(17, "OperatorBack"),
new KeyValuePair<int, string>(18, "VerbatimFore"),
new KeyValuePair<int, string>(19, "VerbatimBack"),
new KeyValuePair<int, string>(20, "RegexFore"),
new KeyValuePair<int, string>(21, "RegexBack"),
new KeyValuePair<int, string>(22, "CommentFore"),
new KeyValuePair<int, string>(23, "CommentBack"),
new KeyValuePair<int, string>(24, "CommentLineFore"),
new KeyValuePair<int, string>(25, "CommentLineBack"),
new KeyValuePair<int, string>(26, "CommentDocFore"),
new KeyValuePair<int, string>(27, "CommentDocBack"),
new KeyValuePair<int, string>(28, "CommentLineDocFore"),
new KeyValuePair<int, string>(29, "CommentLineDocBack"),
new KeyValuePair<int, string>(30, "CommentDocKeywordFore"),
new KeyValuePair<int, string>(31, "CommentDocKeywordBack"),
new KeyValuePair<int, string>(32, "CommentDocKeywordErrorFore"),
new KeyValuePair<int, string>(33, "CommentDocKeywordErrorBack")
});
private List<KeyValuePair<int, string>> CssColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "TagFore"),
new KeyValuePair<int, string>(3, "TagBack"),
new KeyValuePair<int, string>(4, "ClassFore"),
new KeyValuePair<int, string>(5, "ClassBack"),
new KeyValuePair<int, string>(6, "PseudoClassFore"),
new KeyValuePair<int, string>(7, "PseudoClassBack"),
new KeyValuePair<int, string>(8, "UnknownPseudoClassFore"),
new KeyValuePair<int, string>(9, "UnknownPseudoClassBack"),
new KeyValuePair<int, string>(10, "OperatorFore"),
new KeyValuePair<int, string>(11, "OperatorBack"),
new KeyValuePair<int, string>(12, "IdentifierFore"),
new KeyValuePair<int, string>(13, "IdentifierBack"),
new KeyValuePair<int, string>(14, "UnknownIdentifierFore"),
new KeyValuePair<int, string>(15, "UnknownIdentifierBack"),
new KeyValuePair<int, string>(16, "ValueFore"),
new KeyValuePair<int, string>(17, "ValueBack"),
new KeyValuePair<int, string>(18, "CommentFore"),
new KeyValuePair<int, string>(19, "CommentBack"),
new KeyValuePair<int, string>(20, "IdFore"),
new KeyValuePair<int, string>(21, "IdBack"),
new KeyValuePair<int, string>(22, "ImportantFore"),
new KeyValuePair<int, string>(23, "ImportantBack"),
new KeyValuePair<int, string>(24, "DirectiveFore"),
new KeyValuePair<int, string>(25, "DirectiveBack")
});
private List<KeyValuePair<int, string>> VbDotNetColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "DefaultFore"),
new KeyValuePair<int, string>(1, "DefaultBack"),
new KeyValuePair<int, string>(2, "CommentFore"),
new KeyValuePair<int, string>(3, "CommentBack"),
new KeyValuePair<int, string>(4, "NumberFore"),
new KeyValuePair<int, string>(5, "NumberBack"),
new KeyValuePair<int, string>(6, "WordFore"),
new KeyValuePair<int, string>(7, "WordBack"),
new KeyValuePair<int, string>(8, "Word2Fore"),
new KeyValuePair<int, string>(9, "Word2Back"),
new KeyValuePair<int, string>(10, "StringFore"),
new KeyValuePair<int, string>(11, "StringBack"),
new KeyValuePair<int, string>(12, "PreprocessorFore"),
new KeyValuePair<int, string>(13, "PreprocessorBack"),
new KeyValuePair<int, string>(14, "OperatorFore"),
new KeyValuePair<int, string>(15, "OperatorBack"),
new KeyValuePair<int, string>(16, "DateFore"),
new KeyValuePair<int, string>(17, "DateBack"),
});
private List<KeyValuePair<int, string>> JsonColorIndexes { get; } =
new List<KeyValuePair<int, string>>
(
new[]
{
new KeyValuePair<int, string>(0, "JsonDefaultFore"),
new KeyValuePair<int, string>(1, "JsonDefaultBack"),
new KeyValuePair<int, string>(2, "JsonNumberFore"),
new KeyValuePair<int, string>(3, "JsonNumberBack"),
new KeyValuePair<int, string>(4, "JsonStringFore"),
new KeyValuePair<int, string>(5, "JsonStringBack"),
new KeyValuePair<int, string>(6, "JsonUnclosedStringFore"),
new KeyValuePair<int, string>(7, "JsonUnclosedStringBack"),
new KeyValuePair<int, string>(8, "JsonPropertyFore"),
new KeyValuePair<int, string>(9, "JsonPropertyBack"),
new KeyValuePair<int, string>(10, "JsonEscapeSequenceFore"),
new KeyValuePair<int, string>(11, "JsonEscapeSequenceBack"),
new KeyValuePair<int, string>(12, "JsonLineCommentFore"),
new KeyValuePair<int, string>(13, "JsonLineCommentBack"),
new KeyValuePair<int, string>(14, "JsonBlockCommentFore"),
new KeyValuePair<int, string>(15, "JsonBlockCommentBack"),
new KeyValuePair<int, string>(16, "JsonOperatorFore"),
new KeyValuePair<int, string>(17, "JsonOperatorBack"),
new KeyValuePair<int, string>(18, "JsonUriFore"),
new KeyValuePair<int, string>(19, "JsonUriBack"),
new KeyValuePair<int, string>(20, "JsonCompactIRIFore"),
new KeyValuePair<int, string>(21, "JsonCompactIRIBack"),
new KeyValuePair<int, string>(22, "JsonKeywordFore"),
new KeyValuePair<int, string>(23, "JsonKeywordBack"),
new KeyValuePair<int, string>(24, "JsonLdKeywordFore"),
new KeyValuePair<int, string>(25, "JsonLdKeywordBack"),
new KeyValuePair<int, string>(26, "JsonErrorFore"),
new KeyValuePair<int, string>(27, "JsonErrorBack"),
});
#endregion
/// <summary>
/// Saves a lexer color definition to a XML file.
/// </summary>
/// <param name="fileName">Name of the file where to save the lexer's color definitions.</param>
/// <param name="lexerType">Type of the lexer.</param>
/// <returns>True if the operation was successful; otherwise false.</returns>
public bool DescribeLexerColors(string fileName, LexerType lexerType)
{
try
{
DescribeLexerColors(lexerType).Save(fileName);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Saves a lexer color definition to a XDocument class instance.
/// </summary>
/// <param name="lexerType">Type of the lexer.</param>
/// <returns>An instance to a XDocument class containing the color definitions.</returns>
public XDocument DescribeLexerColors(LexerType lexerType)
{
// create an element for color value entries..
XElement entryElement = new XElement("Colors", new XAttribute("Lexer", lexerType.ToString()));
foreach (string colorName in GetColorNames(lexerType))
{
// add a color element to the container element..
entryElement.Add(new XElement("Color",
new XAttribute("Name", colorName),
new XAttribute("R", this[lexerType, colorName].R.ToString("X2")), // the R component of the color..
new XAttribute("G", this[lexerType, colorName].R.ToString("X2")), // the G component of the color..
new XAttribute("B", this[lexerType, colorName].R.ToString("X2")), // the B component of the color..
new XAttribute("A", this[lexerType, colorName].R.ToString("X2")), // the A component of the color..
new XAttribute("HexARGB", this[lexerType, colorName].ToArgb().ToString("X8")))); // The color as ARGB hex string..
}
// create a XDocument for the color definitions..
XDocument document = new XDocument(
new XDeclaration("1.0", "utf-8", ""),
entryElement);
// return the created document..
return document;
}
/// <summary>
/// Loads the lexer color definition from a XDocument class instance.
/// </summary>
/// <param name="document">The document containing the lexer's color definitions.</param>
/// <param name="lexerType">Type of the lexer.</param>
/// <returns>True if the operation was successful; otherwise false.</returns>
public bool LoadDescribedLexerColorsFromXml(XDocument document, LexerType lexerType)
{
try
{
// loop through the color definition elements..
if (document.Root != null)
{
foreach (XElement element in document.Root.Elements("Color"))
{
if (element.Attribute("Name").Value != null)
{
// assign the color for lexer..
this[lexerType, element.Attribute("Name").Value] =
Color.FromArgb(int.Parse(element.Attribute("HexARGB").Value, NumberStyles.HexNumber));
}
}
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Loads the lexer color definition from a XML file.
/// </summary>
/// <param name="fileName">Name of the file from where to load the lexer color definitions.</param>
/// <param name="lexerType">Type of the lexer.</param>
/// <returns>True if the operation was successful; otherwise false.</returns>
public bool LoadDescribedLexerColorsFromXml(string fileName, LexerType lexerType)
{
if (File.Exists(fileName)) // the file must exist..
{
try
{
// try to load the color definitions..
XDocument document = XDocument.Load(fileName);
return LoadDescribedLexerColorsFromXml(document, lexerType);
}
catch
{
// an error occurred so return false..
return false;
}
}
// the file wasn't found..
return false;
}
/// <summary>
/// Gets the color uses by the SciTE color name and a value indicating whether a foreground or a background color is requested.
/// <note type="note">URL: https://www.scintilla.org/SciTE.html</note>
/// </summary>
/// <param name="name">The name of the color (SciTE).</param>
/// <param name="lexerType">Type of the lexer.</param>
/// <param name="isForeground">A flag indicating whether a foreground or a background color is requested.</param>
/// <returns>An index >= 0 if successful; otherwise -1.</returns>
// ReSharper disable once InconsistentNaming
public int GetColorIndexBySciTEName(string name, LexerType lexerType, bool isForeground)
{
if (lexerType == LexerType.Cs)
{
int idx = csColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Cpp)
{
int idx = cppColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Xml)
{
int idx = xmlColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Nsis)
{
int idx = nsisColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.InnoSetup)
{
int idx = innoSetupColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.SQL)
{
int idx = sqlColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Batch)
{
int idx = batchColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Pascal)
{
int idx = pascalColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.PHP)
{
int idx = phpColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.HTML)
{
int idx = htmlColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.WindowsPowerShell)
{
int idx = powerShellColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.INI)
{
int idx = iniColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Python)
{
int idx = pythonColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.YAML)
{
int idx = yamlColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Java)
{
int idx = javaColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.JavaScript)
{
int idx = javascriptColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Css)
{
int idx = cssColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.VbDotNet)
{
int idx = vbDotNetColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
if (lexerType == LexerType.Json)
{
int idx = jsonColors.FindIndex(f => f.Item2 == name && f.Item3 == isForeground);
return idx;
}
return -1;
}
/// <summary>
/// Gets the index of the color by name.
/// </summary>
/// <param name="name">The name of the color.</param>
/// <param name="lexerType">Type of the lexer.</param>
/// <returns>An index >= 0 if successful; otherwise -1.</returns>
public int GetColorIndexByName(string name, LexerType lexerType)
{
if (lexerType == LexerType.Cs)
{
int idx = CsColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Cpp)
{
int idx = CppColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Xml)
{
int idx = XmlColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Nsis)
{
int idx = NsisColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.InnoSetup)
{
int idx = InnoSetupColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.SQL)
{
int idx = SqlColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Batch)
{
int idx = BatchColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Pascal)
{
int idx = PascalColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.PHP)
{
int idx = PhpColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.HTML)
{
int idx = HtmlColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.WindowsPowerShell)
{
int idx = PowerShellColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.INI)
{
int idx = IniColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Python)
{
int idx = PythonColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.YAML)
{
int idx = YamlColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Java)
{
int idx = JavaColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.JavaScript)
{
int idx = JavaScriptColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Css)
{
int idx = CssColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.VbDotNet)
{
int idx = VbDotNetColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
if (lexerType == LexerType.Json)
{
int idx = JsonColorIndexes.FindIndex(f => f.Value == name);
return idx;
}
return -1;
}
/// <summary>
/// Gets the color names for a given lexer type.
/// </summary>
/// <param name="lexerType">Type of the lexer.</param>
/// <returns>A collection of color names of the given lexer type if successful; otherwise an empty collection is returned.</returns>
public IEnumerable<string> GetColorNames(LexerType lexerType)
{
if (lexerType == LexerType.Cs)
{
return CsColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Cpp)
{
return CppColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Xml)
{
return XmlColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Nsis)
{
return NsisColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.InnoSetup)
{
return InnoSetupColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.SQL)
{
return SqlColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Batch)
{
return BatchColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Pascal)
{
return PascalColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.PHP)
{
return PhpColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.HTML)
{
return HtmlColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.WindowsPowerShell)
{
return PowerShellColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.INI)
{
return IniColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Python)
{
return PythonColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.YAML)
{
return YamlColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Java)
{
return JavaColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.JavaScript)
{
return JavaScriptColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Css)
{
return CssColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.VbDotNet)
{
return VbDotNetColorIndexes.Select(f => f.Value);
}
if (lexerType == LexerType.Json)
{
return JsonColorIndexes.Select(f => f.Value);
}
return new List<string>();
}
}
}
| 52.10825 | 179 | 0.51976 | [
"MIT"
] | VPKSoft/ScintillaLexers | VPKSoft.ScintillaLexers/LexerColors/LexerColors.cs | 119,382 | C# |
using blazingdocs.core.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace blazingdocs.core.Repository
{
public interface IDocumentTypeRepository
{
Task AddDocumentType(DocumentType documentType);
Task<DocumentType> GetDocumentTypeById(int id);
Task UpdateDocumentTypeValues(int id, Action<DocumentType> valueUpdater);
}
public class DocumentTypeRepository : IDocumentTypeRepository
{
private readonly DmsDbContext dmsDbContext;
private readonly IEntityPropertyUpdater<DocumentType, int> entityPropertyUpdater;
public DocumentTypeRepository(DmsDbContext dmsDbContext,
IEntityPropertyUpdater<DocumentType, int> entityPropertyUpdater)
{
this.dmsDbContext = dmsDbContext ?? throw new ArgumentNullException(nameof(dmsDbContext));
this.entityPropertyUpdater = entityPropertyUpdater ?? throw new ArgumentNullException(nameof(entityPropertyUpdater));
this.entityPropertyUpdater.EntityFactoryFunc = id => new DocumentType { DocumentTypeId = id };
}
public async Task AddDocumentType(DocumentType documentType)
{
dmsDbContext.Add<DocumentType>(documentType);
await dmsDbContext.SaveChangesAsync();
}
public async Task<DocumentType> GetDocumentTypeById(int id)
{
return await dmsDbContext.DocumentTypes.AsNoTracking()
.FirstOrDefaultAsync(_ => _.DocumentTypeId == id);
}
public async Task UpdateDocumentTypeValues(int id, Action<DocumentType> valueUpdater)
{
await entityPropertyUpdater.UpdateEntity(id, valueUpdater);
}
}
}
| 37.354167 | 129 | 0.710541 | [
"MIT"
] | kiersche/blazingdocs | old/blazingdocs.core/Repository/DocumentTypeRepository.cs | 1,795 | C# |
namespace HideCrosswalks.Utils {
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using UnityEngine;
#if !DEBUG
#if TRACE
#error TRACE is defined outside of a DEBUG build, please remove
#endif
#endif
/// <summary>
/// Log.Trace, Log.Debug, Log.Info, Log.Warning, Log.Error -- these format the message in place,
/// ✔ Cheap if there is a const string or a very simple format call with a few args.
/// ✔ Cheap if wrapped in an if (booleanValue) { ... }
/// Log.Debug and Log.Trace are optimized away if not in Debug mode
/// ⚠ Expensive if multiple $"string {interpolations}" are used (like breaking into multiple lines)
///
/// Log.DebugFormat, Log.InfoFormat, ... - these format message later, when logging. Good for
/// very-very long format strings with multiple complex arguments.
/// ✔ As they use format string literal, it can be split multiple lines without perf penalty
/// 💲 The cost incurred: bulding args array (with pointers)
/// Prevents multiple calls to string.Format as opposed to multiline $"string {interpolations}"
/// Log.DebugFormat is optimized away, others are not, so is a good idea to wrap in if (boolValue)
/// ⚠ Expensive if not wrapped in a if () condition
///
/// Log.DebugIf, Log.WarningIf, ... - these first check a condition, and then call a lambda,
/// which provides a formatted string.
/// ✔ Lambda building is just as cheap as format args building
/// 💲 The cost incurred: each captured value (pointer) is copied into lambda
/// ✔ Actual string is formatted ONLY if the condition holds true
/// Log.DebugIf is optimized away if not in Debug mode
/// ⚠ Cannot capture out and ref values
///
/// Log.NotImpl logs an error if something is not implemented and only in debug mode
/// </summary>
public static class Log {
private static readonly object LogLock = new object();
// TODO refactor log filename to configuration
private static readonly string LogFilename
= Path.Combine(Application.dataPath, "RMCrosswalks.debug.log");
private enum LogLevel {
Trace,
Debug,
Info,
Warning,
Error
}
private static Stopwatch _sw = Stopwatch.StartNew();
static Log() {
try {
if (File.Exists(LogFilename)) {
File.Delete(LogFilename);
}
}
catch (Exception) { }
}
/// <summary>
/// Will log only if debug mode
/// </summary>
/// <param name="s">The text</param>
[Conditional("DEBUG")]
public static void _Debug(string s) {
LogToFile(s, LogLevel.Debug);
}
/// <summary>
/// Will log only if debug mode, the string is prepared using string.Format
/// </summary>
/// <param name="format">The text</param>
[Conditional("DEBUG")]
public static void _DebugFormat(string format, params object[] args) {
LogToFile(string.Format(format, args), LogLevel.Debug);
}
/// <summary>
/// Will log only if debug mode is enabled and the condition is true
/// NOTE: If a lambda contains values from `out` and `ref` scope args,
/// then you can not use a lambda, instead use `if (cond) { Log._Debug }`
/// </summary>
/// <param name="cond">The condition</param>
/// <param name="s">The function which returns text to log</param>
// TODO: Add log thread and replace formatted strings with lists to perform late formatting in that thread
[Conditional("DEBUG")]
public static void _DebugIf(bool cond, Func<string> s) {
if (cond) {
LogToFile(s(), LogLevel.Debug);
}
}
[Conditional("TRACE")]
public static void _Trace(string s) {
LogToFile(s, LogLevel.Trace);
}
public static void Info(string s) {
LogToFile(s, LogLevel.Info);
}
public static void InfoFormat(string format, params object[] args) {
LogToFile(string.Format(format, args), LogLevel.Info);
}
/// <summary>
/// Will log a warning only if debug mode
/// </summary>
/// <param name="s">The text</param>
[Conditional("DEBUG")]
public static void _DebugOnlyWarning(string s) {
LogToFile(s, LogLevel.Warning);
}
/// <summary>
/// Log a warning only in debug mode if cond is true
/// NOTE: If a lambda contains values from `out` and `ref` scope args,
/// then you can not use a lambda, instead use `if (cond) { Log._DebugOnlyWarning() }`
/// </summary>
/// <param name="cond">The condition</param>
/// <param name="s">The function which returns text to log</param>
[Conditional("DEBUG")]
public static void _DebugOnlyWarningIf(bool cond, Func<string> s) {
if (cond) {
LogToFile(s(), LogLevel.Warning);
}
}
public static void Warning(string s) {
LogToFile(s, LogLevel.Warning);
}
public static void WarningFormat(string format, params object[] args) {
LogToFile(string.Format(format, args), LogLevel.Warning);
}
/// <summary>
/// Log a warning only if cond is true
/// NOTE: If a lambda contains values from `out` and `ref` scope args,
/// then you can not use a lambda, instead use `if (cond) { Log.Warning() }`
/// </summary>
/// <param name="cond">The condition</param>
/// <param name="s">The function which returns text to log</param>
public static void WarningIf(bool cond, Func<string> s) {
if (cond) {
LogToFile(s(), LogLevel.Warning);
}
}
public static void Error(string s) {
LogToFile(s, LogLevel.Error);
}
public static void ErrorFormat(string format, params object[] args) {
LogToFile(string.Format(format, args), LogLevel.Error);
}
/// <summary>
/// Log an error only if cond is true
/// NOTE: If a lambda contains values from `out` and `ref` scope args,
/// then you can not use a lambda, instead use `if (cond) { Log.Error() }`
/// </summary>
/// <param name="cond">The condition</param>
/// <param name="s">The function which returns text to log</param>
public static void ErrorIf(bool cond, Func<string> s) {
if (cond) {
LogToFile(s(), LogLevel.Error);
}
}
/// <summary>
/// Log error only in debug mode
/// </summary>
/// <param name="s">The text</param>
[Conditional("DEBUG")]
public static void _DebugOnlyError(string s) {
LogToFile(s, LogLevel.Error);
}
/// <summary>
/// Writes an Error message about something not implemented. Debug only.
/// </summary>
/// <param name="what">The hint about what is not implemented</param>
[Conditional("DEBUG")]
public static void NotImpl(string what) {
LogToFile("Not implemented: " + what, LogLevel.Error);
}
private static void LogToFile(string log, LogLevel level) {
try {
Monitor.Enter(LogLock);
using (StreamWriter w = File.AppendText(LogFilename)) {
long secs = _sw.ElapsedTicks / Stopwatch.Frequency;
long fraction = _sw.ElapsedTicks % Stopwatch.Frequency;
string m =
$"{level.ToString()} " +
$"{secs:n0}.{fraction:D7}: " +
$"{log}";
w.WriteLine(m);
if (level == LogLevel.Warning || level == LogLevel.Error) {
w.WriteLine((new System.Diagnostics.StackTrace()).ToString());
}
w.WriteLine();
}
}
finally {
Monitor.Exit(LogLock);
}
}
}
}
| 38.324201 | 114 | 0.55868 | [
"MIT"
] | aubergine10/HideCrosswalks | HideTMPECrosswalks/Utils/Log.cs | 8,415 | C# |
namespace Tests.Caliburn.Adapters.Components
{
using System;
using System.ComponentModel.Composition;
[Export(typeof(ILogger)), Export(typeof(SimpleLogger))]
public class SimpleLogger : ILogger
{
public void Log(string msg)
{
Console.WriteLine(msg);
}
}
} | 23.5 | 60 | 0.610942 | [
"MIT"
] | chrismcv/caliburn | src/Tests.Caliburn/Adapters/Components/SimpleLogger.cs | 329 | C# |
using LeetCode.Attributes;
using System;
using System.Collections.Generic;
namespace LeetCode.Exercises
{
[Exercise]
public class AllPathsFromSourceTarget
{
public static void Run()
{
var input = new[]
{
new [] { 1, 2 },
new [] { 3 },
new [] { 3 },
new int[0]
};
var ex = new AllPathsFromSourceTarget();
var output = ex.AllPathsSourceTarget(input);
}
/// <summary>
/// Input:
/// Output: [[0,1,3],[0,2,3]]
/// </summary>
/// <param name="graph"></param>
/// <returns></returns>
public IList<IList<int>> AllPathsSourceTarget(int[][] graph)
{
if (graph == null)
throw new ArgumentNullException();
if (graph.Length == 0)
return new IList<int>[0];
if (graph.Length == 1)
return new IList<int>[] { new[] { graph[0][0] } };
return AllPathsSourceTarget(graph, 0, new HashSet<int> { });
}
private IList<IList<int>> AllPathsSourceTarget(
int[][] graph,
int index,
HashSet<int> visited)
{
var nodes = graph[index];
if (index == graph.Length - 1)
{
return new[] { new List<int> { index } };
}
if (visited.Contains(index))
{
return null;
}
visited.Add(index);
var list = new List<IList<int>>();
foreach (var node in nodes)
{
var paths = AllPathsSourceTarget(graph, node, visited);
if (paths == null)
{
continue;
}
foreach (var path in paths)
{
path.Insert(0, index);
list.Add(path);
}
}
visited.Remove(index);
return list;
}
}
}
| 23.640449 | 72 | 0.419202 | [
"MIT"
] | sergioescalera/LeetCode-Exercises | src/LeetCode-Exercises/Exercises/797-AllPathsFromSourceTarget.cs | 2,106 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General information about all assemblies in this solution.
[assembly: AssemblyProduct("WIC.DotNet")]
[assembly: AssemblyCopyright("© 2020 S. Bäumlisberger")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")]
// Types in all assemblies in this solution are not exposed to COM.
[assembly: ComVisible(false)]
// Version information for all assemblies in this solution.
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 33.555556 | 67 | 0.761589 | [
"MIT"
] | sbaeumlisberger/WIC-DotNet | SharedAssemblyInfo.cs | 608 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Projeto.Presentation.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
} | 18.588235 | 44 | 0.632911 | [
"MIT"
] | ericaxv/Login-Autorization | Projeto.Presentation/Controllers/HomeController.cs | 318 | C# |
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This file is part of the Griffin+ common library suite (https://github.com/griffinplus/dotnet-libs-serialization)
// The source code is licensed under the MIT license.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Runtime.Serialization;
namespace GriffinPlus.Lib.Serialization
{
/// <summary>
/// Exception that is thrown when the serializer detects a cyclic dependency when serializing.
/// </summary>
[Serializable]
public class CyclicDependencyDetectedException : SerializationException
{
/// <summary>
/// Initializes a new instance of the <see cref="CyclicDependencyDetectedException"/> class.
/// </summary>
/// <param name="message">Message describing why the exception is thrown.</param>
public CyclicDependencyDetectedException(string message) :
base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="CyclicDependencyDetectedException"/> class (used during deserialization).
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that receives the serialized object data about the object.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected CyclicDependencyDetectedException(SerializationInfo info, StreamingContext context) :
base(info, context) { }
}
}
| 45.085714 | 140 | 0.636882 | [
"MIT"
] | GriffinPlus/dotnet-libs-serialization | src/GriffinPlus.Lib.Serialization/CyclicDependencyDetectedException.cs | 1,578 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using BizHawk.Common;
using BizHawk.Common.BufferExtensions;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions;
namespace BizHawk.Client.Common
{
public sealed class MemApi : IMem
{
[RequiredService]
private IEmulator Emulator { get; set; }
[OptionalService]
private IMemoryDomains MemoryDomainCore { get; set; }
public MemApi(Action<string> logCallback)
{
LogCallback = logCallback;
}
public MemApi() : this(Console.WriteLine) {}
private readonly Action<string> LogCallback;
private bool _isBigEndian;
private MemoryDomain _currentMemoryDomain;
private MemoryDomain Domain
{
get
{
MemoryDomain LazyInit()
{
if (MemoryDomainCore == null)
{
var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
LogCallback(error);
throw new NotImplementedException(error);
}
return MemoryDomainCore.HasSystemBus ? MemoryDomainCore.SystemBus : MemoryDomainCore.MainMemory;
}
_currentMemoryDomain ??= LazyInit();
return _currentMemoryDomain;
}
set => _currentMemoryDomain = value;
}
private IMemoryDomains DomainList
{
get
{
if (MemoryDomainCore == null)
{
var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
LogCallback(error);
throw new NotImplementedException(error);
}
return MemoryDomainCore;
}
}
private MemoryDomain NamedDomainOrCurrent(string name)
{
if (!string.IsNullOrEmpty(name))
{
try
{
var found = DomainList[name];
if (found != null) return found;
}
catch
{
// ignored
}
LogCallback($"Unable to find domain: {name}, falling back to current");
}
return Domain;
}
private uint ReadUnsignedByte(long addr, string domain = null)
{
var d = NamedDomainOrCurrent(domain);
if (addr >= d.Size)
{
LogCallback($"Warning: attempted read of {addr} outside the memory size of {d.Size}");
return default;
}
return d.PeekByte(addr);
}
private void WriteUnsignedByte(long addr, uint v, string domain = null)
{
var d = NamedDomainOrCurrent(domain);
if (!d.CanPoke())
{
LogCallback($"Error: the domain {d.Name} is not writable");
return;
}
if (addr >= d.Size)
{
LogCallback($"Warning: attempted write to {addr} outside the memory size of {d.Size}");
return;
}
d.PokeByte(addr, (byte) v);
}
private static int U2S(uint u, int size)
{
var sh = 8 * (4 - size);
return ((int) u << sh) >> sh;
}
#region Endian Handling
private uint ReadUnsignedLittle(long addr, int size, string domain = null)
{
uint v = 0;
for (var i = 0; i < size; i++) v |= ReadUnsignedByte(addr + i, domain) << (8 * i);
return v;
}
private uint ReadUnsignedBig(long addr, int size, string domain = null)
{
uint v = 0;
for (var i = 0; i < size; i++) v |= ReadUnsignedByte(addr + i, domain) << (8 * (size - 1 - i));
return v;
}
private void WriteUnsignedLittle(long addr, uint v, int size, string domain = null)
{
for (var i = 0; i < size; i++) WriteUnsignedByte(addr + i, (v >> (8 * i)) & 0xFF, domain);
}
private void WriteUnsignedBig(long addr, uint v, int size, string domain = null)
{
for (var i = 0; i < size; i++) WriteUnsignedByte(addr + i, (v >> (8 * (size - 1 - i))) & 0xFF, domain);
}
private int ReadSigned(long addr, int size, string domain = null) => U2S(ReadUnsigned(addr, size, domain), size);
private uint ReadUnsigned(long addr, int size, string domain = null) => _isBigEndian ? ReadUnsignedBig(addr, size, domain) : ReadUnsignedLittle(addr, size, domain);
private void WriteSigned(long addr, int value, int size, string domain = null) => WriteUnsigned(addr, (uint) value, size, domain);
private void WriteUnsigned(long addr, uint value, int size, string domain = null)
{
if (_isBigEndian) WriteUnsignedBig(addr, value, size, domain);
else WriteUnsignedLittle(addr, value, size, domain);
}
#endregion
#region Unique Library Methods
public void SetBigEndian(bool enabled = true) => _isBigEndian = enabled;
public List<string> GetMemoryDomainList()
{
var list = new List<string>();
foreach (var domain in DomainList) list.Add(domain.Name);
return list;
}
public uint GetMemoryDomainSize(string name = null) => (uint) NamedDomainOrCurrent(name).Size;
public string GetCurrentMemoryDomain() => Domain.Name;
public uint GetCurrentMemoryDomainSize() => (uint) Domain.Size;
public bool UseMemoryDomain(string domain)
{
try
{
var found = DomainList[domain];
if (found != null)
{
Domain = found;
return true;
}
}
catch
{
// ignored
}
LogCallback($"Unable to find domain: {domain}");
return false;
}
/// <exception cref="ArgumentOutOfRangeException">range defined by <paramref name="addr"/> and <paramref name="count"/> extends beyond the bound of <paramref name="domain"/> (or <see cref="Domain"/> if null)</exception>
public string HashRegion(long addr, int count, string domain = null)
{
var d = NamedDomainOrCurrent(domain);
if (!0L.RangeToExclusive(d.Size).Contains(addr))
{
var error = $"Address {addr} is outside the bounds of domain {d.Name}";
LogCallback(error);
throw new ArgumentOutOfRangeException(error);
}
if (addr + count > d.Size)
{
var error = $"Address {addr} + count {count} is outside the bounds of domain {d.Name}";
LogCallback(error);
throw new ArgumentOutOfRangeException(error);
}
var data = new byte[count];
for (var i = 0; i < count; i++) data[i] = d.PeekByte(addr + i);
using var hasher = SHA256.Create();
return hasher.ComputeHash(data).BytesToHexString();
}
#endregion
#region Common Special and Legacy Methods
public uint ReadByte(long addr, string domain = null) => ReadUnsignedByte(addr, domain);
public void WriteByte(long addr, uint value, string domain = null) => WriteUnsignedByte(addr, value, domain);
public List<byte> ReadByteRange(long addr, int length, string domain = null)
{
var d = NamedDomainOrCurrent(domain);
if (addr < 0) LogCallback($"Warning: Attempted reads on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(ReadByteRange)}()");
var lastReqAddr = addr + length - 1;
var indexAfterLast = Math.Min(lastReqAddr, d.Size - 1) - addr + 1;
var bytes = new byte[length];
for (var i = addr < 0 ? -addr : 0; i != indexAfterLast; i++) bytes[i] = d.PeekByte(addr + i);
if (lastReqAddr >= d.Size) LogCallback($"Warning: Attempted reads on addresses {d.Size}..{lastReqAddr} outside range of domain {d.Name} in {nameof(ReadByteRange)}()");
return bytes.ToList();
}
public void WriteByteRange(long addr, List<byte> memoryblock, string domain = null)
{
var d = NamedDomainOrCurrent(domain);
if (!d.CanPoke())
{
LogCallback($"Error: the domain {d.Name} is not writable");
return;
}
if (addr < 0) LogCallback($"Warning: Attempted reads on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(WriteByteRange)}()");
var lastReqAddr = addr + memoryblock.Count - 1;
var indexAfterLast = Math.Min(lastReqAddr, d.Size - 1) - addr + 1;
for (var i = addr < 0 ? (int) -addr : 0; i != indexAfterLast; i++) d.PokeByte(addr + i, memoryblock[i]);
if (lastReqAddr >= d.Size) LogCallback($"Warning: Attempted reads on addresses {d.Size}..{lastReqAddr} outside range of domain {d.Name} in {nameof(WriteByteRange)}()");
}
public float ReadFloat(long addr, string domain = null)
{
var d = NamedDomainOrCurrent(domain);
if (addr >= d.Size)
{
LogCallback($"Warning: Attempted read {addr} outside memory size of {d.Size}");
return default;
}
return BitConverter.ToSingle(BitConverter.GetBytes(d.PeekUint(addr, _isBigEndian)), 0);
}
public void WriteFloat(long addr, double value, string domain = null)
{
var d = NamedDomainOrCurrent(domain);
if (!d.CanPoke())
{
LogCallback($"Error: the domain {Domain.Name} is not writable");
return;
}
if (addr >= d.Size)
{
LogCallback($"Warning: Attempted write {addr} outside memory size of {d.Size}");
return;
}
d.PokeUint(addr, BitConverter.ToUInt32(BitConverter.GetBytes((float) value), 0), _isBigEndian);
}
#endregion
#region 1 Byte
public int ReadS8(long addr, string domain = null) => (sbyte) ReadUnsignedByte(addr, domain);
public uint ReadU8(long addr, string domain = null) => (byte) ReadUnsignedByte(addr, domain);
public void WriteS8(long addr, int value, string domain = null) => WriteSigned(addr, value, 1, domain);
public void WriteU8(long addr, uint value, string domain = null) => WriteUnsignedByte(addr, value, domain);
#endregion
#region 2 Byte
public int ReadS16(long addr, string domain = null) => (short) ReadSigned(addr, 2, domain);
public uint ReadU16(long addr, string domain = null) => (ushort) ReadUnsigned(addr, 2, domain);
public void WriteS16(long addr, int value, string domain = null) => WriteSigned(addr, value, 2, domain);
public void WriteU16(long addr, uint value, string domain = null) => WriteUnsigned(addr, value, 2, domain);
#endregion
#region 3 Byte
public int ReadS24(long addr, string domain = null) => ReadSigned(addr, 3, domain);
public uint ReadU24(long addr, string domain = null) => ReadUnsigned(addr, 3, domain);
public void WriteS24(long addr, int value, string domain = null) => WriteSigned(addr, value, 3, domain);
public void WriteU24(long addr, uint value, string domain = null) => WriteUnsigned(addr, value, 3, domain);
#endregion
#region 4 Byte
public int ReadS32(long addr, string domain = null) => ReadSigned(addr, 4, domain);
public uint ReadU32(long addr, string domain = null) => ReadUnsigned(addr, 4, domain);
public void WriteS32(long addr, int value, string domain = null) => WriteSigned(addr, value, 4, domain);
public void WriteU32(long addr, uint value, string domain = null) => WriteUnsigned(addr, value, 4, domain);
#endregion
}
}
| 31.072948 | 221 | 0.67397 | [
"MIT"
] | TwitchPlaysPokemon/tpp-BizHawk2 | BizHawk.Client.Common/Api/Classes/MemApi.cs | 10,225 | C# |
/**
* (C) Copyright IBM Corp. 2018, 2019.
*
* 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 System.Collections.Generic;
using Newtonsoft.Json;
namespace IBM.Watson.Discovery.v2.Model
{
/// <summary>
/// A restriction that alter the document set used for sub aggregations it precedes to nested documents found in the
/// field specified.
/// </summary>
public class QueryNestedAggregation : QueryAggregation
{
/// <summary>
/// The path to the document field to scope sub aggregations to.
/// </summary>
[JsonProperty("path", NullValueHandling = NullValueHandling.Ignore)]
public string Path { get; set; }
/// <summary>
/// Number of nested documents found in the specified field.
/// </summary>
[JsonProperty("matching_results", NullValueHandling = NullValueHandling.Ignore)]
public long? MatchingResults { get; set; }
/// <summary>
/// An array of sub aggregations.
/// </summary>
[JsonProperty("aggregations", NullValueHandling = NullValueHandling.Ignore)]
public List<QueryAggregation> Aggregations { get; set; }
}
}
| 35.723404 | 120 | 0.679571 | [
"Apache-2.0"
] | AndreiLuis/dotnet-standard-sdk | src/IBM.Watson.Discovery.v2/Model/QueryNestedAggregation.cs | 1,679 | C# |
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using Kuchen;
using Hobscure.Objects;
using Hobscure.Screens;
using Hobscure.Items;
namespace Hobscure.NPC {
public class NPCManager : MachineObject
{
public ObjectInventoryModel inventory;
public NPCModel model = new NPCModel() { name = "Tim" };
public string myName;
int commandIndex;
public NPCRouteManager routeManager;
const float RETRY_COMMAND_TIME = 1f;
private IEnumerator runCoroutine;
public bool runningCommandExecution;
void Start () {
model.name = Time.time.ToString();
inventory = new ObjectInventoryModel();
routeManager = GetComponent<NPCRouteManager>();
}
public void AddCommand(int index, ObjectInventoryManager obj, INPCCommand command)
{
model.commands.Add(new NPCCommandModel() { index = index, gameObject = obj, destinationCommand = command });
}
public void NextCommand()
{
if (commandIndex == model.commands.Count) commandIndex = 0;
model.currentCommand = model.commands.Single(c => { return (c.index == commandIndex); });
routeManager.NavigateTo(model.currentCommand.gameObject.transform.position, this.ExecuteCommand);
commandIndex++;
}
public void ExecuteCommand()
{
runCoroutine = TryCommand(this);
StartCoroutine(runCoroutine);
}
public void ContinueCommandExecution()
{
if (!runningCommandExecution) {
NextCommand();
runningCommandExecution = true;
}
}
public void PauseCommandExecution()
{
routeManager.PauseRoutes();
runningCommandExecution = false;
}
private IEnumerator TryCommand(NPCManager me)
{
while (!model.currentCommand.destinationCommand.Run(me) && runningCommandExecution)
{
yield return new WaitForSeconds(RETRY_COMMAND_TIME);
}
NextCommand();
}
}
}
| 29.423077 | 121 | 0.585185 | [
"Apache-2.0"
] | nahkranoth/DevilsTrinkets | Assets/GameWorld/World/NPCs/Scripts/Hobscure/NPC/NPCManager.cs | 2,297 | C# |
using Microsoft.EntityFrameworkCore;
namespace Message.DataAccess
{
public class MessageDbContext : DbContext
{
public MessageDbContext(DbContextOptions<MessageDbContext> options)
: base(options)
{
}
public DbSet<Models.Message> Messages { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
base.OnModelCreating(builder);
}
}
}
| 25.095238 | 77 | 0.650854 | [
"MIT"
] | TodorStamenov/GameBox | Server/Common/Message.DataAccess/MessageDbContext.cs | 529 | C# |
namespace NServiceKit.Razor.Compilation.CodeTransformers
{
internal sealed class RewriteLinePragmas : RazorCodeTransformerBase
{
private string _binRelativePath;
private string _fullPath;
/// <summary>Initializes this object.</summary>
///
/// <param name="razorHost"> The razor host.</param>
/// <param name="directives">The directives.</param>
public override void Initialize(RazorPageHost razorHost, System.Collections.Generic.IDictionary<string, string> directives)
{
_binRelativePath = @"..\.." + razorHost.File.VirtualPath;
_fullPath = razorHost.File.RealPath;
}
/// <summary>Process the output described by codeContent.</summary>
///
/// <param name="codeContent">The code content.</param>
///
/// <returns>A string.</returns>
public override string ProcessOutput(string codeContent)
{
return codeContent.Replace("\"" + _fullPath + "\"", "\"" + _binRelativePath + "\"");
}
}
}
| 37.896552 | 132 | 0.599636 | [
"BSD-3-Clause"
] | NServiceKit/NServiceKit | src/NServiceKit.Razor/Compilation/CodeTransformers/RewriteLinePragmas.cs | 1,073 | C# |
using Microsoft.AspNet.Identity.EntityFramework;
namespace VisitorDemo.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
} | 30.647059 | 176 | 0.677543 | [
"MIT"
] | TeamRenegade/billingApplication | VisitorDemo/Models/IdentityModels.cs | 523 | 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.ArtifactRegistry.V1.Snippets
{
// [START artifactregistry_v1_generated_ArtifactRegistry_UpdateProjectSettings_sync_flattened]
using Google.Cloud.ArtifactRegistry.V1;
using Google.Protobuf.WellKnownTypes;
public sealed partial class GeneratedArtifactRegistryClientSnippets
{
/// <summary>Snippet for UpdateProjectSettings</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void UpdateProjectSettings()
{
// Create client
ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create();
// Initialize request argument(s)
ProjectSettings projectSettings = new ProjectSettings();
FieldMask updateMask = new FieldMask();
// Make the request
ProjectSettings response = artifactRegistryClient.UpdateProjectSettings(projectSettings, updateMask);
}
}
// [END artifactregistry_v1_generated_ArtifactRegistry_UpdateProjectSettings_sync_flattened]
}
| 42.186047 | 113 | 0.722161 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.ArtifactRegistry.V1/Google.Cloud.ArtifactRegistry.V1.GeneratedSnippets/ArtifactRegistryClient.UpdateProjectSettingsSnippet.g.cs | 1,814 | C# |
/**
* Copyright © 2021 Push Technology 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.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using PushTechnology.ClientInterface.Client.Factories;
using PushTechnology.ClientInterface.Client.Features.Metrics;
using PushTechnology.ClientInterface.Client.Session;
using static System.Console;
using static PushTechnology.ClientInterface.Examples.Runner.Program;
namespace PushTechnology.ClientInterface.Example.Features
{
/// <summary>
/// Client implementation that demonstrates the topic metric collector.
/// </summary>
public sealed class TopicMetricCollector : IExample
{
/// <summary>
/// Runs the topic metric collector example.
/// </summary>
/// <param name="cancellationToken">A token used to end the client example.</param>
/// <param name="args">A single string should be used for the server url.</param>
public async Task Run(CancellationToken cancellationToken, string[] args)
{
string serverUrl = args[0];
var session = Diffusion.Sessions.Principal("admin").Password("password")
.CertificateValidation((cert, chain, errors) => CertificateValidationResult.ACCEPT)
.Open(serverUrl);
var metrics = session.Metrics;
ITopicMetricCollector collector = null;
string topicSelector = "selector";
try
{
WriteLine($"Adding the topic metric collector 'Test' with topic selector '{topicSelector}'.");
collector = Diffusion.NewTopicMetricCollectorBuilder()
.GroupByTopicType( true )
.Create("Test", topicSelector);
await metrics.PutTopicMetricCollectorAsync(collector);
WriteLine($"Topic metric collector '{collector.Name}' added.");
}
catch (Exception ex)
{
WriteLine($"Failed to add topic metric collector : {ex}.");
session.Close();
return;
}
try
{
WriteLine($"The following topic metric collectors exist:");
var listTopicMetricCollectors = await metrics.ListTopicMetricCollectorsAsync();
foreach (var topicMetricCollector in listTopicMetricCollectors)
{
WriteLine($"Name: '{topicMetricCollector.Name}', Topic selector: '{topicMetricCollector.TopicSelector}', Exports to Prometheus: '{GetAnswer(topicMetricCollector.ExportsToPrometheus)}', Groups by topic type: '{GetAnswer(topicMetricCollector.GroupsByTopicType)}'");
}
}
catch (Exception ex)
{
WriteLine($"Failed to list topic metric collectors : {ex}.");
session.Close();
return;
}
try
{
await metrics.RemoveTopicMetricCollectorAsync(collector.Name);
WriteLine($"Collector '{collector.Name}' removed.");
}
catch (Exception ex)
{
WriteLine($"Failed to remove topic metric collector : {ex}.");
}
// Close the session
session.Close();
}
private string GetAnswer(bool result) => result ? "Yes" : "No";
}
} | 39.019802 | 283 | 0.613296 | [
"Apache-2.0"
] | pushtechnology/diffusion-examples | dotnet/source/examples/Features/TopicMetricCollector.cs | 3,942 | C# |
using System;
namespace Vectoreyes.EyeCenters
{
/// <summary>
/// Eye center estimation class with pre-built buffers for reuse. This class is not thread-safe.
/// </summary>
public class EyeCenterEstimator
{
private readonly float[] _imageBlurred;
private readonly float[] _gradResultX;
private readonly float[] _gradResultY;
private readonly float[] _gradResult;
private readonly float[] _gradMags;
private readonly float[] _centerScores;
private readonly int _rows;
private readonly int _cols;
private readonly int _length;
internal EyeCenterEstimator(int rows, int cols)
{
var indices = rows * cols;
_imageBlurred = new float[indices];
_gradResultX = new float[indices];
_gradResultY = new float[indices];
_gradResult = new float[indices * 2];
_gradMags = new float[indices];
_centerScores = new float[indices];
_rows = rows;
_cols = cols;
_length = rows * cols;
}
/// <summary>
/// Estimates an eye center location from an image. The array passed in will be modified.
///
/// Implemented based on Timm, F. and Barth, E. (2011). "Accurate eye centre localisation by means of gradients",
/// with modifications from https://thume.ca/projects/2012/11/04/simple-accurate-eye-center-tracking-in-opencv.
/// </summary>
/// <param name="image">The image to search.</param>
/// <returns>An eye center estimate.</returns>
public unsafe EyeCenter Estimate(float[] image)
{
fixed (float* im = &image[0])
{
return Estimate(im);
}
}
/// <summary>
/// Estimates an eye center location from an image. The array passed in will be modified.
///
/// Implemented based on Timm, F. and Barth, E. (2011). "Accurate eye centre localisation by means of gradients",
/// with modifications from https://thume.ca/projects/2012/11/04/simple-accurate-eye-center-tracking-in-opencv.
/// </summary>
/// <param name="image">The image to search.</param>
/// <returns>An eye center estimate.</returns>
public unsafe EyeCenter Estimate(float* image)
{
// We can't meaningfully calculate anything on an image this small.
if (_rows < 4 && _cols < 4)
{
return new EyeCenter(-1, -1);
}
// Zero scores
for (var i = 0; i < _length; i++)
{
_centerScores[i] = 0;
}
// Blur step:
fixed (float* imageBlurred = &_imageBlurred[0])
{
// Radius chosen experimentally
GaussianBlur.Blur(image, imageBlurred, _rows, _cols, (int)Math.Sqrt(Math.Min(_rows, _cols)) / 2);
// Calculate gradients, gradient magnitude mean, and gradient magnitude std
fixed (float* gradResultX = &_gradResultX[0])
{
fixed (float* gradResultY = &_gradResultY[0])
{
CV.CentralDifferenceGradientX(imageBlurred, gradResultX, _rows, _cols);
CV.CentralDifferenceGradientY(imageBlurred, gradResultY, _rows, _cols);
fixed (float* gradResult = &_gradResult[0])
{
fixed (float* gradMags = &_gradMags[0])
{
for (var r = 0; r < _rows; r++)
{
for (var c = 0; c < _cols; c++)
{
gradMags[r * _cols + c] = (float)Math.Sqrt(gradResultX[r * _cols + c] * gradResultX[r * _cols + c] + gradResultY[r * _cols + c] * gradResultY[r * _cols + c]);
}
}
var gradMagMean = Utils.Mean2D(gradMags, _rows, _cols);
var gradMagStd = Utils.Std2D(gradMags, _rows, _cols, gradMagMean);
var gradThreshold = 0.9f * gradMagStd + gradMagMean;
for (var r = 0; r < _rows; r++)
{
for (var c = 0; c < _cols; c++)
{
var gradMag = gradMags[r * _cols + c];
// Ignore all gradients below a threshold
if (gradMag < gradThreshold)
{
continue;
}
// Scale gradients to unit length
gradResult[r * _cols + c + 1] = gradResultY[r * _cols + c] / gradMag;
gradResult[r * _cols + c] = gradResultX[r * _cols + c] / gradMag;
}
}
}
// Predict eye center:
// To save time, we only calculate the objective for every Kth column/row,
// where K is the square root of the product of the rows and columns in the
// image.
//
// This gives us a rough approximation that we can then refine by repeatedly
// square rooting the step size and calculating scores within a predicted region.
// This saves us a huge number of Score() calculations and allows us to
// calculate eye centers in high-resolution images in realistic amounts of time.
var initialStep = (int)Math.Sqrt(_rows * _cols);
fixed (float* centerScores = &_centerScores[0])
{
// Initial step scoring
for (var r = 0; r < _rows; r += initialStep)
{
for (var c = 0; c < _cols; c += initialStep)
{
centerScores[r * _cols + c] = Score(gradResult, _rows, _cols, r, c);
}
}
// Search for better and better objectives within regions with high surrounding
// objectives. We stop at a step of 2, sacrificing negligible accuracy for a
// significant speedup on larger images.
for (var lastStep = initialStep; lastStep > 2; lastStep = (int)Math.Sqrt(lastStep))
{
var (localMaxR, localMaxC) = Utils.Argmax2D(centerScores, _rows, _cols);
var localMaxVal = centerScores[localMaxR * _cols + localMaxC];
var approxThreshold = localMaxVal * 0.999999f;
var step = (int)Math.Sqrt(lastStep);
for (var r = 0; r < _rows; r += step)
{
for (var c = 0; c < _cols; c += step)
{
var scoreR = Math.Min(_rows - 1, (int)(Math.Round(r / (float)lastStep) * lastStep));
var scoreC = Math.Min(_cols - 1, (int)(Math.Round(c / (float)lastStep) * lastStep));
if (centerScores[scoreR * _cols + scoreC] > approxThreshold)
{
centerScores[r * _cols + c] = Score(gradResult, _rows, _cols, r, c);
}
}
}
}
// Calculate final estimated center
var (maxR, maxC) = Utils.Argmax2D(centerScores, _rows, _cols);
return new EyeCenter(maxC, maxR);
}
}
}
}
}
}
/// <summary>
/// Calculate an eye center score from the provided weight image, gradient image, and predicted center
/// location. The gradients provided should be calculated with the central difference gradient function.
/// The weights should come from taking the negative of the smoothed original image.
///
/// Implemented based on Timm, F. and Barth, E. (2011). "Accurate eye centre localisation by means of gradients",
/// with modifications from https://thume.ca/projects/2012/11/04/simple-accurate-eye-center-tracking-in-opencv.
/// </summary>
private static unsafe float Score(float* gradient, int rows, int cols, int centerR, int centerC)
{
var score = 0f;
for (var r = 0; r < rows; r++)
{
for (var c = 0; c < cols; c++)
{
var gY = gradient[r * cols + c + 1];
var gX = gradient[r * cols + c];
if (gX + gY == 0)
{
continue;
}
// Calculate displacement
var dX = c - centerC;
var dY = r - centerR;
if (dX + dY == 0)
{
continue;
}
var dMag = (float)Math.Sqrt(dX * dX + dY * dY);
var dXf = dX / dMag;
var dYf = dY / dMag;
// Dot product of displacement and gradient.
// https://thume.ca/projects/2012/11/04/simple-accurate-eye-center-tracking-in-opencv/#the-little-thing-that-he-didnt-mention
// (Paraphrasing for clarity)
// The central difference gradient always points towards lighter regions, so
// the gradient vectors along the iris edge always point away from the sclera.
// At the center, the gradient vectors will be pointing in the same direction
// as the displacement vector. (continues below)
var dg = Math.Max(0, dXf * gX + dYf * gY);
// In this step, we would normally just square the dot product, presumably in order
// to penalize very small intermediate results and give a bonus to very large
// intermediate results. This has the unfortunate side-effect of making very
// negative intermediate results have an outsized impact on the objective
// function, and often causing estimated centers in locations where the dot
// products along the edge of the iris should be penalizing the estimated center.
//
// To resolve this, we choose to ignore any dot products less than zero.
// The squaring step may also be removed at this point, since our dot products
// are all greater than or equal to 0. In fact, doing so appears to improve
// accuracy.
//
// I'm also choosing to remove the pixel intensity weight here, since it reduces
// accuracy when there are reflections on the iris.
score += dg;
}
}
return score / (rows * cols);
}
}
} | 51.315574 | 199 | 0.44645 | [
"MIT"
] | karashiiro/Vectoreyes | src/Vectoreyes/EyeCenters/EyeCenterEstimator.cs | 12,523 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAutoPropertyToFullProperty
{
public partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SimpleAutoPropertyTest()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExtraLineAfterProperty()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithInitialValue()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; } = 2
}
";
var expected = @"
class TestClass
{
private int goo = 2;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithCalculatedInitialValue()
{
var text = @"
class TestClass
{
const int num = 345;
public int G[||]oo { get; set; } = 2*num
}
";
var expected = @"
class TestClass
{
const int num = 345;
private int goo = 2 * num;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithPrivateSetter()
{
var text = @"
class TestClass
{
public int G[||]oo { get; private set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
private set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithFieldNameAlreadyUsed()
{
var text = @"
class TestClass
{
private int goo;
public int G[||]oo { get; private set; }
}
";
var expected = @"
class TestClass
{
private int goo;
private int goo1;
public int Goo
{
get
{
return goo1;
}
private set
{
goo1 = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithComments()
{
var text = @"
class TestClass
{
// Comments before
public int G[||]oo { get; private set; } //Comments during
//Comments after
}
";
var expected = @"
class TestClass
{
private int goo;
// Comments before
public int Goo
{
get
{
return goo;
}
private set
{
goo = value;
}
} //Comments during
//Comments after
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBody()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get => goo; set => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWhenOnSingleLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get => goo; set => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWhenOnSingleLine2()
{
var text = @"
class TestClass
{
public int G[||]oo
{
get;
set;
}
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get => goo;
set => goo = value;
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWithTrivia()
{
var text = @"
class TestClass
{
public int G[||]oo { get /* test */ ; set /* test2 */ ; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get /* test */ => goo; set /* test2 */ => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithPropertyOpenBraceOnSameLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo {
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithAccessorOpenBraceOnSameLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get {
return goo;
}
set {
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task StaticProperty()
{
var text = @"
class TestClass
{
public static int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private static int goo;
public static int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ProtectedProperty()
{
var text = @"
class TestClass
{
protected int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
protected int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InternalProperty()
{
var text = @"
class TestClass
{
internal int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
internal int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithAttributes()
{
var text = @"
class TestClass
{
[A]
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
[A]
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CommentsInAccessors()
{
var text = @"
class TestClass
{
/// <summary>
/// test stuff here
/// </summary>
public int Testg[||]oo { /* test1 */ get /* test2 */; /* test3 */ set /* test4 */; /* test5 */ } /* test6 */
}
";
var expected = @"
class TestClass
{
private int testgoo;
/// <summary>
/// test stuff here
/// </summary>
public int Testgoo
{ /* test1 */
get /* test2 */
{
return testgoo;
} /* test3 */
set /* test4 */
{
testgoo = value;
} /* test5 */
} /* test6 */
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task OverrideProperty()
{
var text = @"
class MyBaseClass
{
public virtual string Name { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string N[||]ame {get; set;}
}
";
var expected = @"
class MyBaseClass
{
public virtual string Name { get; set; }
}
class MyDerivedClass : MyBaseClass
{
private string name;
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SealedProperty()
{
var text = @"
class MyClass
{
public sealed string N[||]ame {get; set;}
}
";
var expected = @"
class MyClass
{
private string name;
public sealed string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task VirtualProperty()
{
var text = @"
class MyBaseClass
{
public virtual string N[||]ame { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
var expected = @"
class MyBaseClass
{
private string name;
public virtual string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PrivateProperty()
{
var text = @"
class MyClass
{
private string N[||]ame { get; set; }
}
";
var expected = @"
class MyClass
{
private string name;
private string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task AbstractProperty()
{
var text = @"
class MyBaseClass
{
public abstract string N[||]ame { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExternProperty()
{
var text = @"
class MyBaseClass
{
extern string N[||]ame { get; set; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task GetterOnly()
{
var text = @"
class TestClass
{
public int G[||]oo { get;}
}
";
var expected = @"
class TestClass
{
private readonly int goo;
public int Goo
{
get
{
return goo;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task GetterOnlyExpressionBodies()
{
var text = @"
class TestClass
{
public int G[||]oo { get;}
}
";
var expected = @"
class TestClass
{
private readonly int goo;
public int Goo => goo;
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SetterOnly()
{
var text = @"
class TestClass
{
public int G[||]oo
{
set {}
}
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExpressionBodiedAccessors()
{
var text = @"
class TestClass
{
private int testgoo;
public int testg[||]oo {get => testgoo; set => testgoo = value; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorAtBeginning()
{
var text = @"
class TestClass
{
[||]public int Goo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorAtEnd()
{
var text = @"
class TestClass
{
public int Goo[||] { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorOnAccessors()
{
var text = @"
class TestClass
{
public int Goo { g[||]et; set; }
}
";
await TestMissingAsync(text);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorInType()
{
var text = @"
class TestClass
{
public in[||]t Goo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SelectionWhole()
{
var text = @"
class TestClass
{
[|public int Goo { get; set; }|]
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SelectionName()
{
var text = @"
class TestClass
{
public int [|Goo|] { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task MoreThanOneGetter()
{
var text = @"
class TestClass
{
public int Goo { g[||]et; get; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task MoreThanOneSetter()
{
var text = @"
class TestClass
{
public int Goo { get; s[||]et; set; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CustomFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int testingGoo;
public int Goo
{
get
{
return testingGoo;
}
set
{
testingGoo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomFieldName);
}
[WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task UnderscorePrefixedFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int _goo;
public int Goo
{
get
{
return _goo;
}
set
{
_goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseUnderscorePrefixedFieldName);
}
[WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PropertyNameEqualsToClassNameExceptFirstCharCasingWhichCausesFieldNameCollisionByDefault()
{
var text = @"
class stranger
{
public int S[||]tranger { get; set; }
}
";
var expected = @"
class stranger
{
private int stranger;
public int Stranger { get => stranger; set => stranger = value; }
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task NonStaticPropertyWithCustomStaticFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task StaticPropertyWithCustomStaticFieldName()
{
var text = @"
class TestClass
{
public static int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private static int staticfieldtestGoo;
public static int Goo
{
get
{
return staticfieldtestGoo;
}
set
{
staticfieldtestGoo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InInterface()
{
var text = @"
interface IGoo
{
public int Goo { get; s[||]et; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InStruct()
{
var text = @"
struct goo
{
public int G[||]oo { get; set; }
}
";
var expected = @"
struct goo
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClasses()
{
var text = @"
partial class Program
{
int P { get; set; }
}
partial class Program
{
int [||]Q { get; set; }
}
";
var expected = @"
partial class Program
{
int P { get; set; }
}
partial class Program
{
private int q;
int Q { get => q; set => q = value; }
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClassInSeparateFiles1()
{
var file1 = @"
partial class Program
{
int [||]P { get; set; }
}";
var file2 = @"
partial class Program
{
int Q { get; set; }
}";
var file1AfterRefactor = @"
partial class Program
{
private int p;
int P { get => p; set => p = value; }
}";
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""file1"">{1}</Document>
<Document FilePath=""file2"">{2}</Document>
</Project>
</Workspace>", LanguageNames.CSharp, file1, file2);
using var testWorkspace = TestWorkspace.Create(xmlString);
// refactor file1 and check
var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default);
await TestActionAsync(
testWorkspace,
file1AfterRefactor,
action,
conflictSpans: ImmutableArray<TextSpan>.Empty,
renameSpans: ImmutableArray<TextSpan>.Empty,
warningSpans: ImmutableArray<TextSpan>.Empty,
navigationSpans: ImmutableArray<TextSpan>.Empty,
parameters: default);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClassInSeparateFiles2()
{
var file1 = @"
partial class Program
{
int P { get; set; }
}";
var file2 = @"
partial class Program
{
int Q[||] { get; set; }
}";
var file2AfterRefactor = @"
partial class Program
{
private int q;
int Q { get => q; set => q = value; }
}";
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""file1"">{1}</Document>
<Document FilePath=""file2"">{2}</Document>
</Project>
</Workspace>", LanguageNames.CSharp, file1, file2);
using var testWorkspace = TestWorkspace.Create(xmlString);
// refactor file2 and check
var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default);
await TestActionAsync(
testWorkspace,
file2AfterRefactor,
action,
conflictSpans: ImmutableArray<TextSpan>.Empty,
renameSpans: ImmutableArray<TextSpan>.Empty,
warningSpans: ImmutableArray<TextSpan>.Empty,
navigationSpans: ImmutableArray<TextSpan>.Empty,
parameters: default);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InvalidLocation()
{
await TestMissingAsync(@"namespace NS
{
public int G[||]oo { get; set; }
}");
await TestMissingAsync("public int G[||]oo { get; set; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task NullBackingField()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class Program
{
string? Name[||] { get; set; }
}",
@"
#nullable enable
class Program
{
private string? name;
string? Name { get => name; set => name = value; }
}");
}
}
}
| 21.892097 | 139 | 0.570392 | [
"MIT"
] | 06needhamt/roslyn | src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs | 28,812 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Lab5 {
public partial class AdminPage {
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// Table1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Table Table1;
/// <summary>
/// TextBox1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TextBox1;
/// <summary>
/// Button2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button2;
/// <summary>
/// Button1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button1;
}
}
| 32.885246 | 84 | 0.507976 | [
"MIT"
] | triod315/SysProgLabworks | Lab5/Lab5/Lab5/AdminPage.aspx.designer.cs | 2,008 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace RectangleIntersection
{
public class StartUp
{
public static void Main(string[] args)
{
List<Rectangle> rectangles = new List<Rectangle>();
int[] operations = Console.ReadLine().Split().Select(int.Parse).ToArray();
int rectanglesCount = operations[0];
int intersectCount = operations[1];
for (int i = 0; i < rectanglesCount; i++)
{
string[] input = Console.ReadLine().Split();
string name = input[0];
double width = double.Parse(input[1]);
double height = double.Parse(input[2]);
double x = double.Parse(input[3]);
double y = double.Parse(input[4]);
Rectangle rectangle = new Rectangle(name, width, height, x, y);
rectangles.Add(rectangle);
}
for (int i = 0; i < intersectCount; i++)
{
string[] input = Console.ReadLine().Split();
string firstId = input[0];
string secondId = input[1];
Rectangle firstRectangle = rectangles.FirstOrDefault(x => x.Id == firstId);
Rectangle secondRectangle = rectangles.FirstOrDefault(x => x.Id == secondId);
if (firstRectangle.Intersect(secondRectangle))
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
}
}
| 30.574074 | 93 | 0.500303 | [
"MIT"
] | Gandjurov/OOP-Basic-CSharp | 01.DefiningClasses/09.RectangleIntersection/StartUp.cs | 1,653 | C# |
using Elsa.Pipelines.WorkflowExecution;
namespace Elsa.Contracts;
public interface IWorkflowExecutionBuilder
{
public IDictionary<string, object?> Properties { get; }
IServiceProvider ApplicationServices { get; }
IWorkflowExecutionBuilder Use(Func<WorkflowMiddlewareDelegate, WorkflowMiddlewareDelegate> middleware);
public WorkflowMiddlewareDelegate Build();
} | 34.454545 | 107 | 0.812665 | [
"MIT"
] | elsa-workflows/experimental | src/core/Elsa.Core/Contracts/IWorkflowExecutionBuilder.cs | 379 | C# |
namespace eShopOnContainers.Core.Models.Orders
{
public enum OrderStatus
{
Submitted,
AwaitingValidation,
StockConfirmed,
Paid,
Shipped,
Cancelled
}
} | 17.583333 | 47 | 0.587678 | [
"MIT"
] | 07101994/eShopOnContainers | src/Mobile/eShopOnContainers/eShopOnContainers.Core/Models/Orders/OrderStatus.cs | 213 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v1/services/product_group_view_service.proto
// </auto-generated>
// Original file comments:
// Copyright 2019 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
//
// 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.
//
//
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Google.Ads.GoogleAds.V1.Services {
/// <summary>
/// Service to manage product group views.
/// </summary>
public static partial class ProductGroupViewService
{
static readonly string __ServiceName = "google.ads.googleads.v1.services.ProductGroupViewService";
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest> __Marshaller_google_ads_googleads_v1_services_GetProductGroupViewRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView> __Marshaller_google_ads_googleads_v1_resources_ProductGroupView = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest, global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView> __Method_GetProductGroupView = new grpc::Method<global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest, global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView>(
grpc::MethodType.Unary,
__ServiceName,
"GetProductGroupView",
__Marshaller_google_ads_googleads_v1_services_GetProductGroupViewRequest,
__Marshaller_google_ads_googleads_v1_resources_ProductGroupView);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Ads.GoogleAds.V1.Services.ProductGroupViewServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of ProductGroupViewService</summary>
public abstract partial class ProductGroupViewServiceBase
{
/// <summary>
/// Returns the requested product group view in full detail.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView> GetProductGroupView(global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ProductGroupViewService</summary>
public partial class ProductGroupViewServiceClient : grpc::ClientBase<ProductGroupViewServiceClient>
{
/// <summary>Creates a new client for ProductGroupViewService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public ProductGroupViewServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for ProductGroupViewService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public ProductGroupViewServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ProductGroupViewServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected ProductGroupViewServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Returns the requested product group view in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView GetProductGroupView(global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetProductGroupView(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the requested product group view in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView GetProductGroupView(global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetProductGroupView, null, options, request);
}
/// <summary>
/// Returns the requested product group view in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView> GetProductGroupViewAsync(global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetProductGroupViewAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the requested product group view in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V1.Resources.ProductGroupView> GetProductGroupViewAsync(global::Google.Ads.GoogleAds.V1.Services.GetProductGroupViewRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetProductGroupView, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override ProductGroupViewServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new ProductGroupViewServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(ProductGroupViewServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetProductGroupView, serviceImpl.GetProductGroupView).Build();
}
/// <summary>Register service method implementations with a service binder. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static void BindService(grpc::ServiceBinderBase serviceBinder, ProductGroupViewServiceBase serviceImpl)
{
serviceBinder.AddMethod(__Method_GetProductGroupView, serviceImpl.GetProductGroupView);
}
}
}
#endregion
| 60.775 | 392 | 0.740539 | [
"Apache-2.0"
] | chrisdunelm/google-ads-dotnet | src/V1/Stubs/ProductGroupViewServiceGrpc.cs | 9,724 | C# |
using System;
namespace Architecture.Domain.Core.Events
{
public abstract class Event : Message
{
public DateTime Timestamp { get; private set; }
protected Event()
{
Timestamp = DateTime.Now;
}
}
}
| 17.133333 | 55 | 0.579767 | [
"MIT"
] | brunodasilvadev/ASPNETCORE1.1 | StandardArchitecture/src/Architecture.Domain.Core/Events/Event.cs | 259 | C# |
using Xamarin.UITest;
using System.Threading.Tasks;
namespace CosmosDbSampleApp.UITests
{
public abstract class BasePage
{
protected BasePage(in IApp app, in string pageTitle)
{
App = app;
Title = pageTitle;
}
public string Title { get; }
protected IApp App { get; }
public virtual Task WaitForPageToLoad() => Task.FromResult(App.WaitForElement(Title));
}
}
| 21.380952 | 94 | 0.612472 | [
"MIT"
] | AzureAdvocateBit/CosmosDbSampleApp | CosmosDbSampleApp.UITests/Pages/BasePage.cs | 451 | C# |
using SimpleSmtpInterceptor.Data.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
namespace SimpleSmtpInterceptor.Lib.Services
{
public class AttachmentCompressor
{
private readonly IList<Attachment> _attachments;
public AttachmentCompressor(IList<Attachment> attachments)
{
_attachments = attachments;
}
public RawFile SaveAsZipArchive(string fileName)
{
var lstCleanUp = new List<string>(_attachments.Count + 1);
//If the filename does not include the zip extension add it
if (!fileName.EndsWith(".zip")) fileName += ".zip";
var obj = new RawFile
{
FileName = fileName
};
//Get a temporary path to work with
var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
//Get a separate directory so that the zip file can be created to avoid IO access exceptions
var pathZip = path + "zip";
//Create base working directory
Directory.CreateDirectory(path);
//Create directory for zip file
Directory.CreateDirectory(pathZip);
//Save to / Save as zip file
var zipFilePath = Path.Combine(pathZip, fileName);
lstCleanUp.Add(zipFilePath);
//For each attachment
foreach (var a in _attachments)
{
//Decode the base 64 string into a byte array
var bytes = Base64Decode(a.AttachmentBase64);
//Save as
var filePath = Path.Combine(path, a.Name);
//Write byte array to temp path with original name
File.WriteAllBytes(filePath, bytes);
lstCleanUp.Add(filePath);
}
//Archive everything into a zip file in the temp path
ZipFile.CreateFromDirectory(
path,
zipFilePath,
CompressionLevel.Optimal,
false);
//Create a byte array from the zip file
obj.Contents = File.ReadAllBytes(zipFilePath);
//Delete all files created
lstCleanUp.ForEach(File.Delete);
//Delete the working directories created
Directory.Delete(path);
Directory.Delete(pathZip);
return obj;
}
private static byte[] Base64Decode(string base64EncodedString)
{
var data = Convert.FromBase64String(base64EncodedString);
return data;
}
}
}
| 29.274725 | 104 | 0.5747 | [
"MIT"
] | dyslexicanaboko/simple-smtp-interceptor | SimpleSmtpInterceptor.Lib/Services/AttachmentCompressor.cs | 2,666 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EventStore.Common.Utils;
using EventStore.Core.Exceptions;
using EventStore.Core.TransactionLog;
using EventStore.Core.Util;
using EventStore.Core.Index.Hashes;
using EventStore.Core.Settings;
using EventStore.Core.TransactionLog.Checkpoint;
using EventStore.Core.TransactionLog.Chunks;
using ILogger = Serilog.ILogger;
using EventStore.Core.TransactionLog.LogRecords;
using EventStore.LogCommon;
namespace EventStore.Core.Index {
public abstract class TableIndex {
internal static readonly IndexEntry InvalidIndexEntry = new IndexEntry(0, -1, -1);
public const string IndexMapFilename = "indexmap";
public const string ForceIndexVerifyFilename = ".forceverify";
protected static readonly ILogger Log = Serilog.Log.ForContext<TableIndex>();
}
public class TableIndex<TStreamId> : TableIndex, ITableIndex<TStreamId> {
private const int MaxMemoryTables = 1;
public long CommitCheckpoint {
get { return Interlocked.Read(ref _commitCheckpoint); }
}
public long PrepareCheckpoint {
get { return Interlocked.Read(ref _prepareCheckpoint); }
}
private readonly int _maxSizeForMemory;
private readonly int _maxTablesPerLevel;
private readonly bool _additionalReclaim;
private readonly bool _inMem;
private readonly bool _skipIndexVerify;
private readonly int _indexCacheDepth;
private readonly int _initializationThreads;
private readonly byte _ptableVersion;
private readonly string _directory;
private readonly Func<IMemTable> _memTableFactory;
private readonly Func<TFReaderLease> _tfReaderFactory;
private readonly IIndexFilenameProvider _fileNameProvider;
private readonly object _awaitingTablesLock = new object();
private IndexMap _indexMap;
private List<TableItem> _awaitingMemTables;
private volatile bool _isManualMergePending;
private long _commitCheckpoint = -1;
private long _prepareCheckpoint = -1;
private volatile bool _backgroundRunning;
private readonly ManualResetEventSlim _backgroundRunningEvent = new ManualResetEventSlim(true);
private IHasher<TStreamId> _lowHasher;
private IHasher<TStreamId> _highHasher;
private readonly TStreamId _emptyStreamId;
private bool _initialized;
private readonly int _maxAutoMergeIndexLevel;
private readonly int _pTableMaxReaderCount;
public TableIndex(string directory,
IHasher<TStreamId> lowHasher,
IHasher<TStreamId> highHasher,
TStreamId emptyStreamId,
Func<IMemTable> memTableFactory,
Func<TFReaderLease> tfReaderFactory,
byte ptableVersion,
int maxAutoMergeIndexLevel,
int pTableMaxReaderCount,
int maxSizeForMemory = 1000000,
int maxTablesPerLevel = 4,
bool additionalReclaim = false,
bool inMem = false,
bool skipIndexVerify = false,
int indexCacheDepth = 16,
int initializationThreads = 1) {
Ensure.NotNullOrEmpty(directory, "directory");
Ensure.NotNull(memTableFactory, "memTableFactory");
Ensure.NotNull(lowHasher, "lowHasher");
Ensure.NotNull(highHasher, "highHasher");
Ensure.NotNull(tfReaderFactory, "tfReaderFactory");
Ensure.Positive(initializationThreads, "initializationThreads");
Ensure.Positive(pTableMaxReaderCount, "pTableMaxReaderCount");
if (maxTablesPerLevel <= 1)
throw new ArgumentOutOfRangeException("maxTablesPerLevel");
if (indexCacheDepth > 28 || indexCacheDepth < 8) throw new ArgumentOutOfRangeException("indexCacheDepth");
_directory = directory;
_memTableFactory = memTableFactory;
_tfReaderFactory = tfReaderFactory;
_fileNameProvider = new GuidFilenameProvider(directory);
_maxSizeForMemory = maxSizeForMemory;
_maxTablesPerLevel = maxTablesPerLevel;
_additionalReclaim = additionalReclaim;
_inMem = inMem;
_skipIndexVerify = ShouldForceIndexVerify() ? false : skipIndexVerify;
_indexCacheDepth = indexCacheDepth;
_initializationThreads = initializationThreads;
_ptableVersion = ptableVersion;
_awaitingMemTables = new List<TableItem> {new TableItem(_memTableFactory(), -1, -1, 0)};
_lowHasher = lowHasher;
_highHasher = highHasher;
_emptyStreamId = emptyStreamId;
_maxAutoMergeIndexLevel = maxAutoMergeIndexLevel;
_pTableMaxReaderCount = pTableMaxReaderCount;
}
public void Initialize(long chaserCheckpoint) {
Ensure.Nonnegative(chaserCheckpoint, "chaserCheckpoint");
//NOT THREAD SAFE (assumes one thread)
if (_initialized)
throw new IOException("TableIndex is already initialized.");
_initialized = true;
if (_inMem) {
_indexMap = IndexMap.CreateEmpty(_maxTablesPerLevel, int.MaxValue, _pTableMaxReaderCount);
_prepareCheckpoint = _indexMap.PrepareCheckpoint;
_commitCheckpoint = _indexMap.CommitCheckpoint;
return;
}
if (ShouldForceIndexVerify()) {
Log.Debug("Forcing verification of index files...");
}
CreateIfDoesNotExist(_directory);
var indexmapFile = Path.Combine(_directory, IndexMapFilename);
// if TableIndex's CommitCheckpoint is >= amount of written TFChunk data,
// we'll have to remove some of PTables as they point to non-existent data
// this can happen (very unlikely, though) on leader crash
try {
_indexMap = IndexMap.FromFile(indexmapFile, _maxTablesPerLevel, true, _indexCacheDepth,
_skipIndexVerify, _initializationThreads, _maxAutoMergeIndexLevel, _pTableMaxReaderCount);
if (_indexMap.CommitCheckpoint >= chaserCheckpoint) {
_indexMap.Dispose(TimeSpan.FromMilliseconds(5000));
throw new CorruptIndexException(String.Format(
"IndexMap's CommitCheckpoint ({0}) is greater than ChaserCheckpoint ({1}).",
_indexMap.CommitCheckpoint, chaserCheckpoint));
}
//verification should be completed by now
DeleteForceIndexVerifyFile();
} catch (CorruptIndexException exc) {
Log.Error(exc, "ReadIndex is corrupted...");
LogIndexMapContent(indexmapFile);
DumpAndCopyIndex();
File.SetAttributes(indexmapFile, FileAttributes.Normal);
File.Delete(indexmapFile);
DeleteForceIndexVerifyFile();
_indexMap = IndexMap.FromFile(indexmapFile, _maxTablesPerLevel, true, _indexCacheDepth,
_skipIndexVerify, _initializationThreads, _maxAutoMergeIndexLevel, _pTableMaxReaderCount);
}
_prepareCheckpoint = _indexMap.PrepareCheckpoint;
_commitCheckpoint = _indexMap.CommitCheckpoint;
// clean up all other remaining files
var indexFiles = _indexMap.InOrder().Select(x => Path.GetFileName(x.Filename))
.Union(new[] {IndexMapFilename});
var toDeleteFiles = Directory.EnumerateFiles(_directory).Select(Path.GetFileName)
.Except(indexFiles, StringComparer.OrdinalIgnoreCase);
foreach (var filePath in toDeleteFiles) {
var file = Path.Combine(_directory, filePath);
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
}
private static void LogIndexMapContent(string indexmapFile) {
try {
Log.Error("IndexMap '{indexMap}' content:\n {content}", indexmapFile,
Helper.FormatBinaryDump(File.ReadAllBytes(indexmapFile)));
} catch (Exception exc) {
Log.Error(exc, "Unexpected error while dumping IndexMap '{indexMap}'.", indexmapFile);
}
}
private void DumpAndCopyIndex() {
string dumpPath = null;
try {
dumpPath = Path.Combine(Path.GetDirectoryName(_directory),
string.Format("index-backup-{0:yyyy-MM-dd_HH-mm-ss.fff}", DateTime.UtcNow));
Log.Error("Making backup of index folder for inspection to {dumpPath}...", dumpPath);
FileUtils.DirectoryCopy(_directory, dumpPath, copySubDirs: true);
} catch (Exception exc) {
Log.Error(exc, "Unexpected error while copying index to backup dir '{dumpPath}'", dumpPath);
}
}
private static void CreateIfDoesNotExist(string directory) {
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
}
public void Add(long commitPos, TStreamId streamId, long version, long position) {
Ensure.Nonnegative(commitPos, "commitPos");
Ensure.Nonnegative(version, "version");
Ensure.Nonnegative(position, "position");
AddEntries(commitPos, new[] {CreateIndexKey(streamId, version, position)});
}
public void AddEntries(long commitPos, IList<IndexKey<TStreamId>> entries) {
//should only be called on a single thread.
var table = (IMemTable)_awaitingMemTables[0].Table; // always a memtable
var collection = entries.Select(x => CreateIndexEntry(x)).ToList();
table.AddEntries(collection);
if (table.Count >= _maxSizeForMemory) {
long prepareCheckpoint = collection[0].Position;
for (int i = 1, n = collection.Count; i < n; ++i) {
prepareCheckpoint = Math.Max(prepareCheckpoint, collection[i].Position);
}
TryProcessAwaitingTables(commitPos, prepareCheckpoint);
}
}
public Task MergeIndexes() {
TryManualMerge();
return Task.CompletedTask;
}
public bool IsBackgroundTaskRunning {
get { return _backgroundRunning; }
}
//Automerge only
private void TryProcessAwaitingTables(long commitPos, long prepareCheckpoint) {
lock (_awaitingTablesLock) {
var newTables = new List<TableItem> {new TableItem(_memTableFactory(), -1, -1, 0)};
newTables.AddRange(_awaitingMemTables.Select(
(x, i) => i == 0 ? new TableItem(x.Table, prepareCheckpoint, commitPos, x.Level) : x));
Log.Debug("Switching MemTable, currently: {awaitingMemTables} awaiting tables.", newTables.Count);
_awaitingMemTables = newTables;
if (_inMem) return;
TryProcessAwaitingTables();
if (_additionalReclaim)
ThreadPool.QueueUserWorkItem(x => ReclaimMemoryIfNeeded(_awaitingMemTables));
}
}
public void TryManualMerge() {
_isManualMergePending = true;
TryProcessAwaitingTables();
}
private void TryProcessAwaitingTables() {
lock (_awaitingTablesLock) {
if (!_backgroundRunning) {
_backgroundRunningEvent.Reset();
_backgroundRunning = true;
ThreadPool.QueueUserWorkItem(x => ReadOffQueue());
}
}
}
private void ReadOffQueue() {
try {
while (true) {
var indexmapFile = Path.Combine(_directory, IndexMapFilename);
if (_isManualMergePending) {
Log.Debug("Performing manual index merge.");
_isManualMergePending = false;
using (var reader = _tfReaderFactory()) {
var manualMergeResult = _indexMap.TryManualMerge(
(streamId, currentHash) => UpgradeHash(streamId, currentHash),
entry => reader.ExistsAt(entry.Position),
entry => ReadEntry(reader, entry.Position),
_fileNameProvider,
_ptableVersion,
_indexCacheDepth,
_skipIndexVerify);
if (manualMergeResult.HasMergedAny) {
_indexMap = manualMergeResult.MergedMap;
_indexMap.SaveToFile(indexmapFile);
manualMergeResult.ToDelete.ForEach(x => x.MarkForDestruction());
}
Log.Debug("Manual index merge completed: {numMergedPTables} PTable(s) merged.", manualMergeResult.ToDelete.Count);
}
}
TableItem tableItem;
//ISearchTable table;
lock (_awaitingTablesLock) {
Log.Debug("Awaiting tables queue size is: {awaitingMemTables}.", _awaitingMemTables.Count);
if (_awaitingMemTables.Count == 1) {
return;
}
tableItem = _awaitingMemTables[_awaitingMemTables.Count - 1];
}
PTable ptable;
var memtable = tableItem.Table as IMemTable;
if (memtable != null) {
memtable.MarkForConversion();
ptable = PTable.FromMemtable(memtable, _fileNameProvider.GetFilenameNewTable(),
ESConsts.PTableInitialReaderCount,
_pTableMaxReaderCount,
_indexCacheDepth, _skipIndexVerify);
} else
ptable = (PTable)tableItem.Table;
var addResult = _indexMap.AddPTable(ptable, tableItem.PrepareCheckpoint, tableItem.CommitCheckpoint);
_indexMap = addResult.NewMap;
_indexMap.SaveToFile(indexmapFile);
if (addResult.CanMergeAny) {
using (var reader = _tfReaderFactory()) {
MergeResult mergeResult;
do {
mergeResult = _indexMap.TryMergeOneLevel(
(streamId, currentHash) => UpgradeHash(streamId, currentHash),
entry => reader.ExistsAt(entry.Position),
entry => ReadEntry(reader, entry.Position),
_fileNameProvider,
_ptableVersion,
_indexCacheDepth,
_skipIndexVerify);
if (mergeResult.HasMergedAny) {
_indexMap = mergeResult.MergedMap;
_indexMap.SaveToFile(indexmapFile);
mergeResult.ToDelete.ForEach(x => x.MarkForDestruction());
}
} while (mergeResult.CanMergeAny);
}
}
lock (_awaitingTablesLock) {
var memTables = _awaitingMemTables.ToList();
var corrTable = memTables.First(x => x.Table.Id == ptable.Id);
memTables.Remove(corrTable);
// parallel thread could already switch table,
// so if we have another PTable instance with same ID,
// we need to kill that instance as we added ours already
if (!ReferenceEquals(corrTable.Table, ptable) && corrTable.Table is PTable)
((PTable)corrTable.Table).MarkForDestruction();
Log.Debug("There are now {awaitingMemTables} awaiting tables.", memTables.Count);
_awaitingMemTables = memTables;
}
}
} catch (FileBeingDeletedException exc) {
Log.Error(exc,
"Could not acquire chunk in TableIndex.ReadOffQueue. It is OK if node is shutting down.");
} catch (Exception exc) {
Log.Error(exc, "Error in TableIndex.ReadOffQueue");
throw;
} finally {
lock (_awaitingTablesLock) {
_backgroundRunning = false;
_backgroundRunningEvent.Set();
}
}
}
internal void WaitForBackgroundTasks() {
if (!_backgroundRunningEvent.Wait(7000)) {
throw new TimeoutException("Waiting for background tasks took too long.");
}
}
public void Scavenge(IIndexScavengerLog log, CancellationToken ct) {
GetExclusiveBackgroundTask(ct);
var sw = Stopwatch.StartNew();
try {
Log.Information("Starting scavenge of TableIndex.");
ScavengeInternal(log, ct);
} finally {
// Since scavenging indexes is the only place the ExistsAt optimization makes sense (and takes up a lot of memory), we can clear it after an index scavenge has completed.
TFChunkReaderExistsAtOptimizer.Instance.DeOptimizeAll();
lock (_awaitingTablesLock) {
_backgroundRunning = false;
_backgroundRunningEvent.Set();
TryProcessAwaitingTables();
}
Log.Information("Completed scavenge of TableIndex. Elapsed: {elapsed}", sw.Elapsed);
}
}
private void ScavengeInternal(IIndexScavengerLog log, CancellationToken ct) {
var toScavenge = _indexMap.InOrder().ToList();
foreach (var pTable in toScavenge) {
var startNew = Stopwatch.StartNew();
try {
ct.ThrowIfCancellationRequested();
using (var reader = _tfReaderFactory()) {
var indexmapFile = Path.Combine(_directory, IndexMapFilename);
var scavengeResult = _indexMap.Scavenge(pTable.Id, ct,
(streamId, currentHash) => UpgradeHash(streamId, currentHash),
entry => reader.ExistsAt(entry.Position),
entry => ReadEntry(reader, entry.Position), _fileNameProvider, _ptableVersion,
_indexCacheDepth, _skipIndexVerify);
if (scavengeResult.IsSuccess) {
_indexMap = scavengeResult.ScavengedMap;
_indexMap.SaveToFile(indexmapFile);
scavengeResult.OldTable.MarkForDestruction();
var entriesDeleted = scavengeResult.OldTable.Count - scavengeResult.NewTable.Count;
log.IndexTableScavenged(scavengeResult.Level, scavengeResult.Index, startNew.Elapsed,
entriesDeleted, scavengeResult.NewTable.Count, scavengeResult.SpaceSaved);
} else {
log.IndexTableNotScavenged(scavengeResult.Level, scavengeResult.Index, startNew.Elapsed,
pTable.Count, "");
}
}
} catch (OperationCanceledException) {
log.IndexTableNotScavenged(-1, -1, startNew.Elapsed, pTable.Count, "Scavenge cancelled");
throw;
} catch (Exception ex) {
log.IndexTableNotScavenged(-1, -1, startNew.Elapsed, pTable.Count, ex.Message);
throw;
}
}
}
private void GetExclusiveBackgroundTask(CancellationToken ct) {
while (true) {
lock (_awaitingTablesLock) {
if (!_backgroundRunning) {
_backgroundRunningEvent.Reset();
_backgroundRunning = true;
return;
}
}
Log.Information("Waiting for TableIndex background task to complete before starting scavenge.");
_backgroundRunningEvent.Wait(ct);
}
}
private Tuple<TStreamId, bool> ReadEntry(TFReaderLease reader, long position) {
RecordReadResult result = reader.TryReadAt(position);
if (!result.Success)
return new Tuple<TStreamId, bool>(_emptyStreamId, false);
if (result.LogRecord.RecordType != LogRecordType.Prepare)
throw new Exception(string.Format("Incorrect type of log record {0}, expected Prepare record.",
result.LogRecord.RecordType));
return new Tuple<TStreamId, bool>(((IPrepareLogRecord<TStreamId>)result.LogRecord).EventStreamId,
true);
}
private void ReclaimMemoryIfNeeded(List<TableItem> awaitingMemTables) {
var toPutOnDisk = awaitingMemTables.OfType<IMemTable>().Count() - MaxMemoryTables;
for (var i = awaitingMemTables.Count - 1; i >= 1 && toPutOnDisk > 0; i--) {
var memtable = awaitingMemTables[i].Table as IMemTable;
if (memtable == null || !memtable.MarkForConversion())
continue;
Log.Debug("Putting awaiting file as PTable instead of MemTable [{id}].", memtable.Id);
var ptable = PTable.FromMemtable(memtable, _fileNameProvider.GetFilenameNewTable(),
ESConsts.PTableInitialReaderCount,
_pTableMaxReaderCount,
_indexCacheDepth,
_skipIndexVerify);
var swapped = false;
lock (_awaitingTablesLock) {
for (var j = _awaitingMemTables.Count - 1; j >= 1; j--) {
var tableItem = _awaitingMemTables[j];
if (!(tableItem.Table is IMemTable) || tableItem.Table.Id != ptable.Id) continue;
swapped = true;
_awaitingMemTables[j] = new TableItem(ptable,
tableItem.PrepareCheckpoint,
tableItem.CommitCheckpoint,
tableItem.Level);
break;
}
}
if (!swapped)
ptable.MarkForDestruction();
toPutOnDisk--;
}
}
public bool TryGetOneValue(TStreamId streamId, long version, out long position) {
ulong stream = CreateHash(streamId);
int counter = 0;
while (counter < 5) {
counter++;
try {
return TryGetOneValueInternal(stream, version, out position);
} catch (FileBeingDeletedException) {
Log.Debug("File being deleted.");
} catch (MaybeCorruptIndexException) {
ForceIndexVerifyOnNextStartup();
throw;
}
}
throw new InvalidOperationException("Files are locked.");
}
private bool TryGetOneValueInternal(ulong stream, long version, out long position) {
if (version < 0)
throw new ArgumentOutOfRangeException("version");
var awaiting = _awaitingMemTables;
foreach (var tableItem in awaiting) {
if (tableItem.Table.TryGetOneValue(stream, version, out position))
return true;
}
var map = _indexMap;
foreach (var table in map.InOrder()) {
if (table.TryGetOneValue(stream, version, out position))
return true;
}
position = 0;
return false;
}
public bool TryGetLatestEntry(TStreamId streamId, out IndexEntry entry) {
ulong stream = CreateHash(streamId);
var counter = 0;
while (counter < 5) {
counter++;
try {
return TryGetLatestEntryInternal(stream, out entry);
} catch (FileBeingDeletedException) {
Log.Debug("File being deleted.");
} catch (MaybeCorruptIndexException) {
ForceIndexVerifyOnNextStartup();
throw;
}
}
throw new InvalidOperationException("Files are locked.");
}
private bool TryGetLatestEntryInternal(ulong stream, out IndexEntry entry) {
var awaiting = _awaitingMemTables;
foreach (var t in awaiting) {
if (t.Table.TryGetLatestEntry(stream, out entry))
return true;
}
var map = _indexMap;
foreach (var table in map.InOrder()) {
if (table.TryGetLatestEntry(stream, out entry))
return true;
}
entry = InvalidIndexEntry;
return false;
}
public bool TryGetOldestEntry(TStreamId streamId, out IndexEntry entry) {
ulong stream = CreateHash(streamId);
var counter = 0;
while (counter < 5) {
counter++;
try {
return TryGetOldestEntryInternal(stream, out entry);
} catch (FileBeingDeletedException) {
Log.Debug("File being deleted.");
} catch (MaybeCorruptIndexException) {
ForceIndexVerifyOnNextStartup();
throw;
}
}
throw new InvalidOperationException("Files are locked.");
}
private bool TryGetOldestEntryInternal(ulong stream, out IndexEntry entry) {
var map = _indexMap;
foreach (var table in map.InReverseOrder()) {
if (table.TryGetOldestEntry(stream, out entry))
return true;
}
var awaiting = _awaitingMemTables;
for (var index = awaiting.Count - 1; index >= 0; index--) {
if (awaiting[index].Table.TryGetOldestEntry(stream, out entry))
return true;
}
entry = InvalidIndexEntry;
return false;
}
public IEnumerable<IndexEntry> GetRange(TStreamId streamId, long startVersion, long endVersion,
int? limit = null) {
ulong hash = CreateHash(streamId);
var counter = 0;
while (counter < 5) {
counter++;
try {
return GetRangeInternal(hash, startVersion, endVersion, limit);
} catch (FileBeingDeletedException) {
Log.Debug("File being deleted.");
} catch (MaybeCorruptIndexException) {
ForceIndexVerifyOnNextStartup();
throw;
}
}
throw new InvalidOperationException("Files are locked.");
}
private IEnumerable<IndexEntry> GetRangeInternal(ulong hash, long startVersion, long endVersion,
int? limit = null) {
if (startVersion < 0)
throw new ArgumentOutOfRangeException("startVersion");
if (endVersion < 0)
throw new ArgumentOutOfRangeException("endVersion");
var candidates = new List<IEnumerator<IndexEntry>>();
var awaiting = _awaitingMemTables;
for (int index = 0; index < awaiting.Count; index++) {
var range = awaiting[index].Table.GetRange(hash, startVersion, endVersion, limit).GetEnumerator();
if (range.MoveNext())
candidates.Add(range);
}
var map = _indexMap;
foreach (var table in map.InOrder()) {
var range = table.GetRange(hash, startVersion, endVersion, limit).GetEnumerator();
if (range.MoveNext())
candidates.Add(range);
}
var last = new IndexEntry(0, 0, 0);
var first = true;
var sortedCandidates = new List<IndexEntry>();
while (candidates.Count > 0) {
var maxIdx = GetMaxOf(candidates);
var winner = candidates[maxIdx];
var best = winner.Current;
if (first || ((last.Stream != best.Stream) && (last.Version != best.Version)) ||
last.Position != best.Position) {
last = best;
sortedCandidates.Add(best);
first = false;
}
if (!winner.MoveNext())
candidates.RemoveAt(maxIdx);
}
return sortedCandidates;
}
private static int GetMaxOf(List<IEnumerator<IndexEntry>> enumerators) {
var max = new IndexEntry(ulong.MinValue, 0, long.MinValue);
int idx = 0;
for (int i = 0; i < enumerators.Count; i++) {
var cur = enumerators[i].Current;
if (cur.CompareTo(max) > 0) {
max = cur;
idx = i;
}
}
return idx;
}
public void Close(bool removeFiles = true) {
if (!_backgroundRunningEvent.Wait(7000))
throw new TimeoutException("Could not finish background thread in reasonable time.");
if (_inMem)
return;
if (_indexMap == null) return;
if (removeFiles) {
_indexMap.InOrder().ToList().ForEach(x => x.MarkForDestruction());
var fileName = Path.Combine(_directory, IndexMapFilename);
if (File.Exists(fileName)) {
File.SetAttributes(fileName, FileAttributes.Normal);
File.Delete(fileName);
}
} else {
_indexMap.InOrder().ToList().ForEach(x => x.Dispose());
}
_indexMap.InOrder().ToList().ForEach(x => x.WaitForDisposal(TimeSpan.FromMilliseconds(5000)));
}
private IndexEntry CreateIndexEntry(IndexKey<TStreamId> key) {
key = CreateIndexKey(key.StreamId, key.Version, key.Position);
return new IndexEntry(key.Hash, key.Version, key.Position);
}
private ulong UpgradeHash(TStreamId streamId, ulong lowHash) {
return lowHash << 32 | _highHasher.Hash(streamId);
}
private ulong CreateHash(TStreamId streamId) {
return (ulong)_lowHasher.Hash(streamId) << 32 | _highHasher.Hash(streamId);
}
private IndexKey<TStreamId> CreateIndexKey(TStreamId streamId, long version, long position) {
return new IndexKey<TStreamId>(streamId, version, position, CreateHash(streamId));
}
private class TableItem {
public readonly ISearchTable Table;
public readonly long PrepareCheckpoint;
public readonly long CommitCheckpoint;
public readonly int Level;
public TableItem(ISearchTable table, long prepareCheckpoint, long commitCheckpoint, int level) {
Table = table;
PrepareCheckpoint = prepareCheckpoint;
CommitCheckpoint = commitCheckpoint;
Level = level;
}
}
private void ForceIndexVerifyOnNextStartup() {
Log.Debug("Forcing index verification on next startup");
string path = Path.Combine(_directory, ForceIndexVerifyFilename);
try {
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) {
}
;
} catch {
Log.Error("Could not create force index verification file at: {path}", path);
}
return;
}
private bool ShouldForceIndexVerify() {
string path = Path.Combine(_directory, ForceIndexVerifyFilename);
return File.Exists(path);
}
private void DeleteForceIndexVerifyFile() {
string path = Path.Combine(_directory, ForceIndexVerifyFilename);
try {
if (File.Exists(path)) {
File.SetAttributes(path, FileAttributes.Normal);
File.Delete(path);
}
} catch {
Log.Error("Could not delete force index verification file at: {path}", path);
}
}
}
}
| 33.282084 | 175 | 0.711259 | [
"Apache-2.0",
"CC0-1.0"
] | riccardone/EventStore | src/EventStore.Core/Index/TableIndex.cs | 26,195 | C# |
using System.Linq;
using Adventure.GameEngine.Commands;
using Adventure.GameEngine.Core.Querys;
using Adventure.GameEngine.Systems.Components;
using CodeProject.ObjectPool.Specialized;
using EcsRx.Extensions;
using JetBrains.Annotations;
namespace Adventure.GameEngine.Systems
{
[UsedImplicitly]
public sealed class LookProcessor : CommandProcessor<LookCommand>
{
private readonly IStringBuilderPool _pool;
public LookProcessor(IStringBuilderPool pool, Game game)
: base(game)
=> _pool = pool;
protected override void ProcessCommand(LookCommand command)
{
var roomData = CurrentRoom.Value.GetComponent<RoomData>();
if (string.IsNullOrWhiteSpace(command.Target))
{
using var builder = _pool.GetObject();
foreach (var interst in roomData.Pois)
builder.StringBuilder.AppendLine(interst.Text.Format(Content));
UpdateTextContent(builder.ToString());
}
else
{
var ent = Database.GetCollection().Query(new QueryNamedItemFromRoom(command.Target, CurrentRoom.Name.Name)).FirstOrDefault();
if(ent == null) return;
UpdateTextContent(command.Responsd ?? ent.GetComponent<IngameObject>().Description.Value);
}
}
}
} | 33.5 | 141 | 0.636816 | [
"MIT"
] | Tauron1990/TextAdventure | Neu/Adventure.GameEngine/Systems/LookProcessor.cs | 1,409 | C# |
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using McMaster.Extensions.CommandLineUtils.Abstractions;
namespace McMaster.Extensions.CommandLineUtils
{
internal static class Strings
{
public const string DefaultHelpTemplate = "-?|-h|--help";
public const string DefaultHelpOptionDescription = "Show help information.";
public const string DefaultVersionTemplate = "--version";
public const string DefaultVersionOptionDescription = "Show version information.";
public const string IsEmptyArray = "value is an empty array.";
public const string PathMustNotBeRelative = "File path must not be relative.";
public const string NoValueTypesMustBeBoolean
= "Cannot specify CommandOptionType.NoValue unless the type is boolean.";
public const string AmbiguousOnExecuteMethod
= "Could not determine which 'OnExecute' or 'OnExecuteAsync' method to use. Multiple methods with this name were found.";
public const string NoOnExecuteMethodFound
= "No method named 'OnExecute' or 'OnExecuteAsync' could be found.";
public const string ConventionRequiresModel
= "This convention cannot be used on a command that does not implement " + nameof(IModelAccessor) + ".";
public static string InvalidOnExecuteReturnType(string methodName)
=> methodName + " must have a return type of int or void, or if the method is async, Task<int> or Task.";
public static string InvalidOnValidateReturnType(Type modelType)
=> $"The OnValidate method on {modelType.FullName} must return {typeof(ValidationResult).FullName}.";
public static string CannotDetermineOptionType(PropertyInfo member)
=> $"Could not automatically determine the {nameof(CommandOptionType)} for type {member.PropertyType.FullName}. " +
$"Set the {nameof(OptionAttribute.OptionType)} on the {nameof(OptionAttribute)} declaration for {member.DeclaringType.FullName}.{member.Name}.";
public static string OptionNameIsAmbiguous(string optionName, PropertyInfo first, PropertyInfo second)
=> $"Ambiguous option name. Both {first.DeclaringType.FullName}.{first.Name} and {second.DeclaringType.FullName}.{second.Name} produce a CommandOption with the name '{optionName}'.";
public static string DuplicateSubcommandName(string commandName)
=> $"The subcommand name '{commandName}' has already been been specified. Subcommand names must be unique.";
public static string BothOptionAndArgumentAttributesCannotBeSpecified(PropertyInfo prop)
=> $"Cannot specify both {nameof(OptionAttribute)} and {nameof(ArgumentAttribute)} on property {prop.DeclaringType.Name}.{prop.Name}.";
public static string BothOptionAndHelpOptionAttributesCannotBeSpecified(PropertyInfo prop)
=> $"Cannot specify both {nameof(OptionAttribute)} and {nameof(HelpOptionAttribute)} on property {prop.DeclaringType.Name}.{prop.Name}.";
public static string BothOptionAndVersionOptionAttributesCannotBeSpecified(PropertyInfo prop)
=> $"Cannot specify both {nameof(OptionAttribute)} and {nameof(VersionOptionAttribute)} on property {prop.DeclaringType.Name}.{prop.Name}.";
internal static string UnsupportedParameterTypeOnMethod(string methodName, ParameterInfo methodParam)
=> $"Unsupported type on {methodName} '{methodParam.ParameterType.FullName}' on parameter {methodParam.Name}.";
public static string BothHelpOptionAndVersionOptionAttributesCannotBeSpecified(PropertyInfo prop)
=> $"Cannot specify both {nameof(HelpOptionAttribute)} and {nameof(VersionOptionAttribute)} on property {prop.DeclaringType.Name}.{prop.Name}.";
public static string DuplicateArgumentPosition(int order, PropertyInfo first, PropertyInfo second)
=> $"Duplicate value for argument order. Both {first.DeclaringType.FullName}.{first.Name} and {second.DeclaringType.FullName}.{second.Name} have set Order = {order}.";
public static string OnlyLastArgumentCanAllowMultipleValues(string? lastArgName)
=> $"The last argument '{lastArgName}' accepts multiple values. No more argument can be added.";
public static string CannotDetermineParserType(Type type)
=> $"Could not automatically determine how to convert string values into {type.FullName}.";
public static string CannotDetermineParserType(PropertyInfo prop)
=> $"Could not automatically determine how to convert string values into {prop.PropertyType.FullName} on property {prop.DeclaringType.Name}.{prop.Name}.";
public static string MultipleValuesArgumentShouldBeCollection
= "ArgumentAttribute.MultipleValues should be true if the property type is an array or collection.";
public const string HelpOptionOnTypeAndProperty
= "Multiple HelpOptionAttributes found. HelpOptionAttribute should only be used one per type, either on one property or on the type.";
public const string MultipleHelpOptionPropertiesFound
= "Multiple HelpOptionAttributes found. HelpOptionAttribute should only be used on one property per type.";
public const string VersionOptionOnTypeAndProperty
= "Multiple VersionOptionAttributes found. VersionOptionAttribute should only be used one per type, either on one property or on the type.";
public const string MultipleVersionOptionPropertiesFound
= "Multiple VersionOptionAttributes found. VersionOptionAttribute should only be used on one property per type.";
public static string RemainingArgsPropsIsUnassignable(Type type)
=> $"The RemainingArguments property type on {type.Name} is invalid. It must be assignable from string[].";
public static string NoPropertyOrMethodFound(string memberName, Type type)
=> $"Could not find a property or method named {memberName} on type {type.FullName}.";
public static string NoParameterTypeRegistered(Type modelType, Type paramType)
=> $"The constructor of type '{modelType}' contains the parameter of type '{paramType}' is not registered, Ensure the type '{paramType}' are registered in additional services with CommandLineApplication.Conventions.UseConstructorInjection(IServiceProvider additionalServices).";
public static string NoAnyPublicConstuctorFound(Type modelType)
=> $"Could not find any public constructors of type '{modelType}'.";
public static string NoMatchedConstructorFound(Type modelType)
=> $"Could not found any matched constructors of type '{modelType}'.";
}
}
| 63.59633 | 290 | 0.734853 | [
"Apache-2.0"
] | scott-xu/CommandLineUtils | src/CommandLineUtils/Properties/Strings.cs | 6,934 | C# |
using System;
using System.IO;
using BizHawk.Common;
namespace BizHawk.Client.Common
{
public class ZipStateSaver : IDisposable
{
private readonly IZipWriter _zip;
private bool _isDisposed;
private static void WriteVersion(Stream s)
{
var sw = new StreamWriter(s);
sw.WriteLine("1"); // version 1.0.1
sw.Flush();
}
private static void WriteEmuVersion(Stream s)
{
var sw = new StreamWriter(s);
sw.WriteLine(VersionInfo.GetEmuVersion());
sw.Flush();
}
public ZipStateSaver(string path, int compressionLevel)
{
_zip = new FrameworkZipWriter(path, compressionLevel);
}
public void PutVersionLumps()
{
PutLump(BinaryStateLump.Versiontag, WriteVersion);
PutLump(BinaryStateLump.BizVersion, WriteEmuVersion);
}
public void PutLump(BinaryStateLump lump, Action<Stream> callback)
{
_zip.WriteItem(lump.WriteName, callback);
}
public void PutLump(BinaryStateLump lump, Action<BinaryWriter> callback)
{
PutLump(lump, delegate(Stream s)
{
var bw = new BinaryWriter(s);
callback(bw);
bw.Flush();
});
}
public void PutLump(BinaryStateLump lump, Action<TextWriter> callback)
{
PutLump(lump, delegate(Stream s)
{
TextWriter tw = new StreamWriter(s);
callback(tw);
tw.Flush();
});
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
if (disposing)
{
_zip.Dispose();
}
}
}
}
}
| 18.650602 | 74 | 0.671835 | [
"MIT"
] | CartoonFan/BizHawk | src/BizHawk.Client.Common/savestates/ZipStateSaver.cs | 1,550 | C# |
/*****************************************************
/* Created by Wizcas Chen (http://wizcas.me)
/* Please contact me if you have any question
/* E-mail: chen@wizcas.me
/* 2017 © All copyrights reserved by Wizcas Zhuo Chen
*****************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NUnit.Framework;
using System;
namespace Cheers
{
public class UtilityUnitTests
{
#pragma warning disable 0414
abstract class RootBase
{
public int rootPublic = 10086;
protected int rootProtected = 10010;
}
struct Nested
{
public float someValue;
}
class Root : RootBase
{
Nested rootPrivate = new Nested();
ArrayElement[] arrElements = { new ArrayElement() { nested = new Nested() }, new ArrayElement { yesOrNo = true } };
List<ArrayElement> listElements = new List<ArrayElement>
{
new ArrayElement() { nested = new Nested{ someValue = 1.25f } }, new ArrayElement { yesOrNo = true }
};
}
struct ArrayElement
{
public bool yesOrNo;
public Nested nested;
}
#pragma warning restore 0414
void AssertTypeAndValue(object obj, string path, Type expectedType, object expectedValue)
{
var fi = EditorHelper.GetObjectFieldInfo(obj.GetType(), path);
var fv = EditorHelper.GetObjectFieldValue(obj, path);
Assert.IsNotNull(fi, "failed to retrieve field info {0}/{1}", obj.GetType(), path);
Assert.IsNotNull(fv, "failed to retrieve field value {0}/{1}", obj.GetType(), path);
Assert.AreEqual(expectedType, fi.FieldType);
Assert.AreEqual(expectedValue, fv);
}
[Test]
public void TestColorName()
{
Assert.AreEqual(true, ColorNames.IsNameAvailable("maroon"));
Assert.AreEqual(false, ColorNames.IsNameAvailable("wizcas"));
}
[Test]
public void TestGetObjectFieldPlain()
{
var root = new Root();
AssertTypeAndValue(root, "rootPublic", typeof(int), 10086);
AssertTypeAndValue(root, "rootProtected", typeof(int), 10010);
AssertTypeAndValue(root, "rootPrivate", typeof(Nested), new Nested());
}
[Test]
public void TestGetObjectFieldNested()
{
var root = new Root();
AssertTypeAndValue(root, "rootPrivate.someValue", typeof(float), 0f);
}
[Test]
public void TestGetObjectFieldArrayPlain()
{
AssertTypeAndValue(new Root(), "arrElements.Array.data[0]", typeof(ArrayElement[]), new ArrayElement());
AssertTypeAndValue(new Root(), "listElements.Array.data[1]", typeof(List<ArrayElement>), new ArrayElement() { yesOrNo = true });
}
[Test]
public void TestGetObjectFieldArrayNested()
{
AssertTypeAndValue(new Root(), "arrElements.Array.data[0].yesOrNo", typeof(bool), false);
AssertTypeAndValue(new Root(), "listElements.Array.data[0].nested.someValue", typeof(float), 1.25f);
}
}
} | 34.723404 | 140 | 0.581189 | [
"MIT"
] | wizcas/cheernow-lib | Assets/CheerNowLib/Tests/Editor/UtilityUnitTests.cs | 3,267 | C# |
// <auto-generated>
// 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.
// </auto-generated>
namespace Microsoft.Azure.Management.SecurityInsights.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Tracked Resource
/// </summary>
/// <remarks>
/// The resource model definition for an Azure Resource Manager tracked top
/// level resource which has 'tags' and a 'location'
/// </remarks>
public partial class TrackedResource : Resource
{
/// <summary>
/// Initializes a new instance of the TrackedResource class.
/// </summary>
public TrackedResource()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the TrackedResource class.
/// </summary>
/// <param name="location">The geo-location where the resource
/// lives</param>
/// <param name="id">Fully qualified resource ID for the resource. Ex -
/// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}</param>
/// <param name="name">The name of the resource</param>
/// <param name="type">The type of the resource. E.g.
/// "Microsoft.Compute/virtualMachines" or
/// "Microsoft.Storage/storageAccounts"</param>
/// <param name="systemData">Azure Resource Manager metadata containing
/// createdBy and modifiedBy information.</param>
/// <param name="tags">Resource tags.</param>
public TrackedResource(string location, string id = default(string), string name = default(string), string type = default(string), SystemData systemData = default(SystemData), IDictionary<string, string> tags = default(IDictionary<string, string>))
: base(id, name, type, systemData)
{
Tags = tags;
Location = location;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets resource tags.
/// </summary>
[JsonProperty(PropertyName = "tags")]
public IDictionary<string, string> Tags { get; set; }
/// <summary>
/// Gets or sets the geo-location where the resource lives
/// </summary>
[JsonProperty(PropertyName = "location")]
public string Location { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Location");
}
}
}
}
| 36.822222 | 256 | 0.611648 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/securityinsights/Microsoft.Azure.Management.SecurityInsights/src/Generated/Models/TrackedResource.cs | 3,314 | C# |
using System;
namespace Abp.Web.Models
{
/// <summary>
/// Used to store informations about an error.
/// </summary>
[Serializable]
public class ErrorInfo
{
private static IExceptionToErrorInfoConverter _converter = new DefaultExceptionToErrorInfoConverter();
/// <summary>
/// Error code.
/// </summary>
public int Code { get; set; }
/// <summary>
/// Error message.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Error details.
/// </summary>
public string Details { get; set; }
/// <summary>
/// Validation errors if exists.
/// </summary>
public ValidationErrorInfo[] ValidationErrors { get; set; }
/// <summary>
/// Creates a new instance of <see cref="ErrorInfo"/>.
/// </summary>
public ErrorInfo()
{
}
/// <summary>
/// Creates a new instance of <see cref="ErrorInfo"/>.
/// </summary>
/// <param name="message">Error message</param>
public ErrorInfo(string message)
{
Message = message;
}
/// <summary>
/// Creates a new instance of <see cref="ErrorInfo"/>.
/// </summary>
/// <param name="code">Error code</param>
public ErrorInfo(int code)
{
Code = code;
}
/// <summary>
/// Creates a new instance of <see cref="ErrorInfo"/>.
/// </summary>
/// <param name="code">Error code</param>
/// <param name="message">Error message</param>
public ErrorInfo(int code, string message)
: this(message)
{
Code = code;
}
/// <summary>
/// Creates a new instance of <see cref="ErrorInfo"/>.
/// </summary>
/// <param name="message">Error message</param>
/// <param name="details">Error details</param>
public ErrorInfo(string message, string details)
: this(message)
{
Details = details;
}
/// <summary>
/// Creates a new instance of <see cref="ErrorInfo"/>.
/// </summary>
/// <param name="code">Error code</param>
/// <param name="message">Error message</param>
/// <param name="details">Error details</param>
public ErrorInfo(int code, string message, string details)
: this(message, details)
{
Code = code;
}
/// <summary>
/// Creates a new instance of <see cref="ErrorInfo"/> using given exception object.
/// </summary>
/// <param name="exception">Exception</param>
/// <returns>Created <see cref="ErrorInfo"/> object</returns>
public static ErrorInfo ForException(Exception exception)
{
return _converter.Convert(exception);
}
/// <summary>
/// Adds an exception converter that is used by <see cref="ForException"/> method.
/// </summary>
/// <param name="converter">Converter object</param>
public static void AddExceptionConverter(IExceptionToErrorInfoConverter converter)
{
converter.Next = _converter;
_converter = converter;
}
}
} | 29.725664 | 110 | 0.525454 | [
"MIT"
] | uQr/aspnetboilerplate | src/Abp/Framework/Abp.Web/Web/Models/ErrorInfo.cs | 3,361 | C# |
////////////////////////////////////////////////////////////////////////////////
//EF Core Provider for LCPI OLE DB.
// IBProvider and Contributors. 24.11.2020.
using System;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.Query;
namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query{
////////////////////////////////////////////////////////////////////////////////
//class LcpiOleDb__ParameterBasedSqlProcessorFactory
sealed class LcpiOleDb__ParameterBasedSqlProcessorFactory
:IRelationalParameterBasedSqlProcessorFactory
{
private const ErrSourceID
c_ErrSrcID
=ErrSourceID.LcpiOleDb__ParameterBasedSqlProcessorFactory;
//-----------------------------------------------------------------------
public LcpiOleDb__ParameterBasedSqlProcessorFactory
(RelationalParameterBasedSqlProcessorDependencies dependencies,
Core.Core_ConnectionOptions cnOptions)
{
Check.Arg_NotNull
(c_ErrSrcID,
"constructor",
nameof(dependencies),
dependencies);
Check.Arg_NotNull
(c_ErrSrcID,
"constructor",
nameof(cnOptions),
cnOptions);
//----------------------------------------
Debug.Assert(!Object.ReferenceEquals(dependencies,null));
Debug.Assert(!Object.ReferenceEquals(cnOptions,null));
m_Dependencies=dependencies;
m_CnOptions =cnOptions;
}//LcpiOleDb__ParameterBasedSqlProcessorFactory
//IRelationalParameterBasedSqlProcessorFactory interface ----------------
public RelationalParameterBasedSqlProcessor Create(bool useRelationalNulls)
{
Debug.Assert(!Object.ReferenceEquals(m_Dependencies,null));
return new LcpiOleDb__ParameterBasedSqlProcessor
(m_Dependencies,
m_CnOptions,
useRelationalNulls);
}//Create
//private data ----------------------------------------------------------
private readonly RelationalParameterBasedSqlProcessorDependencies
m_Dependencies;
private readonly Core.Core_ConnectionOptions
m_CnOptions;
};//class LcpiOleDb__ParameterBasedSqlProcessorFactory
////////////////////////////////////////////////////////////////////////////////
}//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query | 35.3125 | 83 | 0.629646 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Code/Provider/Source/Basement/EF/Root/Query/LcpiOleDb__ParameterBasedSqlProcessorFactory.cs | 2,262 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
public class UIController : MonoBehaviour
{
public TextMeshProUGUI scoreText;
public GameObject mainCanvas;
public GameObject settings;
public TMP_Dropdown dropdown;
// Start is called before the first frame update
void Start()
{
scoreText.text = "Highscore: " + PlayerPrefs.GetInt("score");
}
// Update is called once per frame
void Update()
{
}
public void play()
{
SceneManager.LoadScene(1);
}
public void quit()
{
Application.Quit();
}
public void setting()
{
mainCanvas.SetActive(false);
settings.SetActive(true);
}
public void back()
{
mainCanvas.SetActive(true);
settings.SetActive(false);
}
public void setInput()
{
Debug.Log(dropdown.value);
if(dropdown.value == 0)
{
InputManager.controller = "Mouse & Keyboard";
}
else if (dropdown.value == 1)
{
InputManager.controller = "PS4";
}
else if (dropdown.value == 2)
{
InputManager.controller = "XBOX";
}
}
}
| 19.069444 | 71 | 0.541879 | [
"Apache-2.0"
] | DerPartyPatrick/Flying-Light | Scripts/UIController.cs | 1,375 | 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("Choose_Drink_2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Choose_Drink_2")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("ea4d67df-7da2-4b8b-9322-a89c8a3a8901")]
// 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.72973 | 84 | 0.748567 | [
"MIT"
] | stepan82/Programming-Fundamentals-September-2017 | Conditionals-Loops/Choose_Drink_2/Properties/AssemblyInfo.cs | 1,399 | C# |
// ***********************************************************************
// Assembly : MPT.CSI.API
// Author : Mark Thomas
// Created : 10-08-2017
//
// Last Modified By : Mark Thomas
// Last Modified On : 10-08-2017
// ***********************************************************************
// <copyright file="eObjectType.cs" company="">
// Copyright © 2017
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.ComponentModel;
namespace MPT.CSI.API.Core.Program.ModelBehavior.Definition
{
/// <summary>
/// Objects avilable for manipulation in staged construction load cases in the application.
/// </summary>
public enum eObjectType
{
/// <summary>
/// Point Object.
/// </summary>
[Description("Point")]
Point = 1,
/// <summary>
/// Frame Object.
/// </summary>
[Description("Frame")]
Frame = 2,
/// <summary>
/// Cable Object.
/// </summary>
[Description("Cable")]
Cable = 3,
/// <summary>
/// Tendon Object.
/// </summary>
[Description("Tendon")]
Tendon = 4,
/// <summary>
/// Area Object.
/// </summary>
[Description("Area")]
Area = 5,
/// <summary>
/// Solid bject.
/// </summary>
[Description("Solid")]
Solid = 6,
/// <summary>
/// Link Object.
/// </summary>
[Description("Link")]
Link = 7,
/// <summary>
/// Group Object.
/// </summary>
[Description("Group")]
Group = 8
}
} | 24.25 | 95 | 0.413517 | [
"MIT"
] | MarkPThomas/MPT.Net | MPT/CSI/API/MPT.CSI.API/Core/Program/ModelBehavior/Definition/eObjectType.cs | 1,749 | C# |
using System.Threading.Tasks;
using WRLDCWarehouse.Data;
using WRLDCWarehouse.Core.Entities;
using WRLDCWarehouse.Core.ForiegnEntities;
using Microsoft.EntityFrameworkCore;
using WRLDCWarehouse.ETL.Enums;
using Microsoft.Extensions.Logging;
namespace WRLDCWarehouse.ETL.Loads
{
public class LoadAcTransLineCktCondType
{
public async Task<AcTransLineCkt> LoadSingleAsync(WRLDCWarehouseDbContext _context, ILogger _log, AcTransLineCktCondTypeForeign acLineCondTypeForeign, EntityWriteOption opt)
{
// get the conductor type of the entity
ConductorType condType = await _context.ConductorTypes.SingleOrDefaultAsync(ct => ct.WebUatId == acLineCondTypeForeign.CondTypeWebUatId);
// if conductor type doesnot exist, skip the import. Ideally, there should not be such case
if (condType == null)
{
_log.LogCritical($"Unable to find ConductorType with webUatId {acLineCondTypeForeign.CondTypeWebUatId} while inserting AcTransLineCktCondType with webUatId {acLineCondTypeForeign.WebUatId}");
return null;
}
// get the ac transmission line ckt of the entity
AcTransLineCkt existingAcTransLineCkt = await _context.AcTransLineCkts.SingleOrDefaultAsync(acCkt => acCkt.WebUatId == acLineCondTypeForeign.AcTransLineCktWebUatId);
// if ac transmission line ckt doesnot exist, skip the import. Ideally, there should not be such case
if (existingAcTransLineCkt == null)
{
_log.LogCritical($"Unable to find AcTransLineCkt with webUatId {acLineCondTypeForeign.AcTransLineCktWebUatId} while inserting AcTransLineCktCondType with webUatId {acLineCondTypeForeign.WebUatId}");
return null;
}
// check if we should not modify existing conductor type
if (existingAcTransLineCkt.ConductorTypeId.HasValue && opt == EntityWriteOption.DontReplace)
{
return existingAcTransLineCkt;
}
// if conductor type is not present, then insert or replace conductor type
if (!existingAcTransLineCkt.ConductorTypeId.HasValue || opt == EntityWriteOption.Replace || opt == EntityWriteOption.Modify)
{
existingAcTransLineCkt.ConductorTypeId = condType.ConductorTypeId;
await _context.SaveChangesAsync();
return existingAcTransLineCkt;
}
return null;
}
}
}
| 49.607843 | 214 | 0.6917 | [
"MIT"
] | POSOCO/wrldc_data_warehouse_csharp | WRLDCWarehouse.ETL/Loads/LoadAcTransLineCktCondType.cs | 2,532 | 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 iotsitewise-2019-12-02.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.IoTSiteWise.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoTSiteWise.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GatewayPlatform Object
/// </summary>
public class GatewayPlatformUnmarshaller : IUnmarshaller<GatewayPlatform, XmlUnmarshallerContext>, IUnmarshaller<GatewayPlatform, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
GatewayPlatform IUnmarshaller<GatewayPlatform, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public GatewayPlatform Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
GatewayPlatform unmarshalledObject = new GatewayPlatform();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("greengrass", targetDepth))
{
var unmarshaller = GreengrassUnmarshaller.Instance;
unmarshalledObject.Greengrass = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static GatewayPlatformUnmarshaller _instance = new GatewayPlatformUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static GatewayPlatformUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 33.815217 | 158 | 0.643523 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/IoTSiteWise/Generated/Model/Internal/MarshallTransformations/GatewayPlatformUnmarshaller.cs | 3,111 | C# |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The CPR Broker concept was initally developed by
* Gentofte Kommune / Municipality of Gentofte, Denmark.
* Contributor(s):
* Steen Deth
*
*
* The Initial Code for CPR Broker and related components is made in
* cooperation between Magenta, Gentofte Kommune and IT- og Telestyrelsen /
* Danish National IT and Telecom Agency
*
* Contributor(s):
* Beemen Beshara
*
* The code is currently governed by IT- og Telestyrelsen / Danish National
* IT and Telecom Agency
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CprBroker.Schemas.Part;
using NUnit.Framework;
namespace CprBroker.Tests.Schemas
{
namespace PersonRelationTypeHelperTests
{
[TestFixture(typeof(PersonFlerRelationType))]
[TestFixture(typeof(PersonRelationType))]
public class Create_CprNumber<TRelation> where TRelation : IPersonRelationType, new()
{
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Create_NullPnr_ThrowsException()
{
string pnr = null;
PersonRelationTypeHelper.Create<TRelation>(pnr, null, null);
}
[Test]
public void Create_Pnr_CorrectPnr()
{
string pnr = Utilities.RandomCprNumber();
var ret = PersonRelationTypeHelper.Create<TRelation>(pnr, null, null);
Assert.AreEqual(pnr, ret.CprNumber);
}
[Test]
public void Create_Pnr_NullReferenceID()
{
string pnr = Utilities.RandomCprNumber();
var ret = PersonRelationTypeHelper.Create<TRelation>(pnr, null, null);
Assert.Null(ret.ReferenceID);
}
}
[TestFixture(typeof(PersonFlerRelationType))]
[TestFixture(typeof(PersonRelationType))]
public class Create_Guid<TRelation> where TRelation : IPersonRelationType, new()
{
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Create_EmptyUuid_ThrowsException()
{
Guid uuid = Guid.Empty;
PersonRelationTypeHelper.Create<TRelation>(uuid, null, null);
}
[Test]
public void Create_Uuid_CorrectUuid()
{
Guid uuid = Guid.NewGuid();
var ret = PersonRelationTypeHelper.Create<TRelation>(uuid, null, null);
Assert.AreEqual(uuid.ToString(), ret.ReferenceID.Item);
}
[Test]
public void Create_Uuid_NullPnr()
{
Guid uuid = Guid.NewGuid();
var ret = PersonRelationTypeHelper.Create<TRelation>(uuid, null, null);
Assert.Null(ret.CprNumber);
}
}
}
}
| 37.373913 | 93 | 0.643555 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | OS2CPRbroker/CPRbroker | PART/Source/Core/Schemas.Tests/PersonRelationTypeHelperTests.cs | 4,300 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// This file was automatically generated. Do not edit.
#pragma warning disable IDE0016 // Null check can be simplified
#pragma warning disable IDE0017 // Variable declaration can be inlined
#pragma warning disable IDE0018 // Object initialization can be simplified
#pragma warning disable SA1402 // File may only contain a single type
#region Service
namespace Azure.Storage.Files
{
/// <summary>
/// Azure File Storage
/// </summary>
internal static partial class FileRestClient
{
#region Service operations
/// <summary>
/// Service operations for Azure File Storage
/// </summary>
public static partial class Service
{
#region Service.SetPropertiesAsync
/// <summary>
/// Sets properties for a storage account's File service endpoint, including properties for Storage Analytics metrics and CORS (Cross-Origin Resource Sharing) rules.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="properties">The StorageService properties.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response> SetPropertiesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
Azure.Storage.Files.Models.FileServiceProperties properties,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ServiceClient.SetProperties",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetPropertiesAsync_CreateMessage(
pipeline,
resourceUri,
properties,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetPropertiesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Service.SetPropertiesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="properties">The StorageService properties.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Service.SetPropertiesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetPropertiesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
Azure.Storage.Files.Models.FileServiceProperties properties,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (properties == null)
{
throw new System.ArgumentNullException(nameof(properties));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "service");
_request.Uri.AppendQuery("comp", "properties");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
// Create the body
System.Xml.Linq.XElement _body = Azure.Storage.Files.Models.FileServiceProperties.ToXml(properties, "StorageServiceProperties", "");
string _text = _body.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);
_request.Headers.SetValue("Content-Type", "application/xml");
_request.Headers.SetValue("Content-Length", _text.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
_request.Content = Azure.Core.Pipeline.HttpPipelineRequestContent.Create(System.Text.Encoding.UTF8.GetBytes(_text));
return _message;
}
/// <summary>
/// Create the Service.SetPropertiesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Service.SetPropertiesAsync Azure.Response.</returns>
internal static Azure.Response SetPropertiesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 202:
{
return response;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Service.SetPropertiesAsync
#region Service.GetPropertiesAsync
/// <summary>
/// Gets the properties of a storage account's File service, including properties for Storage Analytics metrics and CORS (Cross-Origin Resource Sharing) rules.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Storage service properties.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.FileServiceProperties>> GetPropertiesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ServiceClient.GetProperties",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetPropertiesAsync_CreateMessage(
pipeline,
resourceUri,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetPropertiesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Service.GetPropertiesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Service.GetPropertiesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetPropertiesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "service");
_request.Uri.AppendQuery("comp", "properties");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Service.GetPropertiesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Service.GetPropertiesAsync Azure.Response{Azure.Storage.Files.Models.FileServiceProperties}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.FileServiceProperties> GetPropertiesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.FileServiceProperties _value = Azure.Storage.Files.Models.FileServiceProperties.FromXml(_xml.Root);
// Create the response
Azure.Response<Azure.Storage.Files.Models.FileServiceProperties> _result =
new Azure.Response<Azure.Storage.Files.Models.FileServiceProperties>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Service.GetPropertiesAsync
#region Service.ListSharesSegmentAsync
/// <summary>
/// The List Shares Segment operation returns a list of the shares and share snapshots under the specified account.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="prefix">Filters the results to return only entries whose name begins with the specified prefix.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="include">Include this parameter to specify one or more datasets to include in the response.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>An enumeration of shares.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.SharesSegment>> ListSharesSegmentAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string prefix = default,
string marker = default,
int? maxresults = default,
System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.ListSharesIncludeType> include = default,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ServiceClient.ListSharesSegment",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = ListSharesSegmentAsync_CreateMessage(
pipeline,
resourceUri,
prefix,
marker,
maxresults,
include,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return ListSharesSegmentAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Service.ListSharesSegmentAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="prefix">Filters the results to return only entries whose name begins with the specified prefix.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="include">Include this parameter to specify one or more datasets to include in the response.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Service.ListSharesSegmentAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage ListSharesSegmentAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string prefix = default,
string marker = default,
int? maxresults = default,
System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.ListSharesIncludeType> include = default,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "list");
if (prefix != null) { _request.Uri.AppendQuery("prefix", System.Uri.EscapeDataString(prefix)); }
if (marker != null) { _request.Uri.AppendQuery("marker", System.Uri.EscapeDataString(marker)); }
if (maxresults != null) { _request.Uri.AppendQuery("maxresults", System.Uri.EscapeDataString(maxresults.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (include != null) { _request.Uri.AppendQuery("include", System.Uri.EscapeDataString(string.Join(",", System.Linq.Enumerable.Select(include, item => Azure.Storage.Files.FileRestClient.Serialization.ToString(item))))); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Service.ListSharesSegmentAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Service.ListSharesSegmentAsync Azure.Response{Azure.Storage.Files.Models.SharesSegment}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.SharesSegment> ListSharesSegmentAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.SharesSegment _value = Azure.Storage.Files.Models.SharesSegment.FromXml(_xml.Root);
// Create the response
Azure.Response<Azure.Storage.Files.Models.SharesSegment> _result =
new Azure.Response<Azure.Storage.Files.Models.SharesSegment>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Service.ListSharesSegmentAsync
}
#endregion Service operations
#region Share operations
/// <summary>
/// Share operations for Azure File Storage
/// </summary>
public static partial class Share
{
#region Share.CreateAsync
/// <summary>
/// Creates a new share under the specified account. If the share with the same name already exists, the operation fails.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="quota">Specifies the maximum size of the share, in gigabytes.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.ShareInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.ShareInfo>> CreateAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
int? quota = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.Create",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = CreateAsync_CreateMessage(
pipeline,
resourceUri,
timeout,
metadata,
quota))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return CreateAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.CreateAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="quota">Specifies the maximum size of the share, in gigabytes.</param>
/// <returns>The Share.CreateAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage CreateAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
int? quota = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
if (quota != null) { _request.Headers.SetValue("x-ms-share-quota", quota.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); }
return _message;
}
/// <summary>
/// Create the Share.CreateAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.CreateAsync Azure.Response{Azure.Storage.Files.Models.ShareInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.ShareInfo> CreateAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 201:
{
// Create the result
Azure.Storage.Files.Models.ShareInfo _value = new Azure.Storage.Files.Models.ShareInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.ShareInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.ShareInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.CreateAsync
#region Share.GetPropertiesAsync
/// <summary>
/// Returns all user-defined metadata and system properties for the specified share or share snapshot. The data returned does not include the share's list of files.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.ShareProperties}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.ShareProperties>> GetPropertiesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.GetProperties",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetPropertiesAsync_CreateMessage(
pipeline,
resourceUri,
sharesnapshot,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetPropertiesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.GetPropertiesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Share.GetPropertiesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetPropertiesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Share.GetPropertiesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.GetPropertiesAsync Azure.Response{Azure.Storage.Files.Models.ShareProperties}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.ShareProperties> GetPropertiesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.ShareProperties _value = new Azure.Storage.Files.Models.ShareProperties();
// Get response headers
string _header;
_value.Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
foreach (Azure.Core.Http.HttpHeader _headerPair in response.Headers)
{
if (_headerPair.Name.StartsWith("x-ms-meta-", System.StringComparison.InvariantCulture))
{
_value.Metadata[_headerPair.Name.Substring(10)] = _headerPair.Value;
}
}
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-share-quota", out _header))
{
_value.Quota = int.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.ShareProperties> _result =
new Azure.Response<Azure.Storage.Files.Models.ShareProperties>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.GetPropertiesAsync
#region Share.DeleteAsync
/// <summary>
/// Operation marks the specified share or share snapshot for deletion. The share or share snapshot and any files contained within it are later deleted during garbage collection.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="deleteSnapshots">Specifies the option include to delete the base share and all of its snapshots.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response> DeleteAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default,
Azure.Storage.Files.Models.DeleteSnapshotsOptionType? deleteSnapshots = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.Delete",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = DeleteAsync_CreateMessage(
pipeline,
resourceUri,
sharesnapshot,
timeout,
deleteSnapshots))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return DeleteAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.DeleteAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="deleteSnapshots">Specifies the option include to delete the base share and all of its snapshots.</param>
/// <returns>The Share.DeleteAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage DeleteAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default,
Azure.Storage.Files.Models.DeleteSnapshotsOptionType? deleteSnapshots = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Delete;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (deleteSnapshots != null) { _request.Headers.SetValue("x-ms-delete-snapshots", Azure.Storage.Files.FileRestClient.Serialization.ToString(deleteSnapshots.Value)); }
return _message;
}
/// <summary>
/// Create the Share.DeleteAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.DeleteAsync Azure.Response.</returns>
internal static Azure.Response DeleteAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 202:
{
return response;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.DeleteAsync
#region Share.CreateSnapshotAsync
/// <summary>
/// Creates a read-only snapshot of a share.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.ShareSnapshotInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.ShareSnapshotInfo>> CreateSnapshotAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.CreateSnapshot",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = CreateSnapshotAsync_CreateMessage(
pipeline,
resourceUri,
timeout,
metadata))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return CreateSnapshotAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.CreateSnapshotAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <returns>The Share.CreateSnapshotAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage CreateSnapshotAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "snapshot");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
return _message;
}
/// <summary>
/// Create the Share.CreateSnapshotAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.CreateSnapshotAsync Azure.Response{Azure.Storage.Files.Models.ShareSnapshotInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.ShareSnapshotInfo> CreateSnapshotAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 201:
{
// Create the result
Azure.Storage.Files.Models.ShareSnapshotInfo _value = new Azure.Storage.Files.Models.ShareSnapshotInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("x-ms-snapshot", out _header))
{
_value.Snapshot = _header;
}
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.ShareSnapshotInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.ShareSnapshotInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.CreateSnapshotAsync
#region Share.CreatePermissionAsync
/// <summary>
/// Create a permission (a security descriptor).
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharePermissionJson">A permission (a security descriptor) at the share level.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.PermissionInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.PermissionInfo>> CreatePermissionAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharePermissionJson,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.CreatePermission",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = CreatePermissionAsync_CreateMessage(
pipeline,
resourceUri,
sharePermissionJson,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return CreatePermissionAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.CreatePermissionAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharePermissionJson">A permission (a security descriptor) at the share level.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Share.CreatePermissionAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage CreatePermissionAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharePermissionJson,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (sharePermissionJson == null)
{
throw new System.ArgumentNullException(nameof(sharePermissionJson));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "filepermission");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
// Create the body
string _text = sharePermissionJson;
_request.Headers.SetValue("Content-Type", "application/json");
_request.Headers.SetValue("Content-Length", _text.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
_request.Content = Azure.Core.Pipeline.HttpPipelineRequestContent.Create(System.Text.Encoding.UTF8.GetBytes(_text));
return _message;
}
/// <summary>
/// Create the Share.CreatePermissionAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.CreatePermissionAsync Azure.Response{Azure.Storage.Files.Models.PermissionInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.PermissionInfo> CreatePermissionAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 201:
{
// Create the result
Azure.Storage.Files.Models.PermissionInfo _value = new Azure.Storage.Files.Models.PermissionInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.PermissionInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.PermissionInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.CreatePermissionAsync
#region Share.GetPermissionAsync
/// <summary>
/// Returns the permission (security descriptor) for a given key
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A permission (a security descriptor) at the share level.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<string>> GetPermissionAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string filePermissionKey,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.GetPermission",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetPermissionAsync_CreateMessage(
pipeline,
resourceUri,
filePermissionKey,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetPermissionAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.GetPermissionAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Share.GetPermissionAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetPermissionAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string filePermissionKey,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (filePermissionKey == null)
{
throw new System.ArgumentNullException(nameof(filePermissionKey));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "filepermission");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-file-permission-key", filePermissionKey);
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Share.GetPermissionAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.GetPermissionAsync Azure.Response{string}.</returns>
internal static Azure.Response<string> GetPermissionAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
string _value;
using (System.IO.StreamReader _streamReader = new System.IO.StreamReader(response.ContentStream))
{
_value = _streamReader.ReadToEnd();
}
// Create the response
Azure.Response<string> _result =
new Azure.Response<string>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.GetPermissionAsync
#region Share.SetQuotaAsync
/// <summary>
/// Sets quota for the specified share.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="quota">Specifies the maximum size of the share, in gigabytes.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.ShareInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.ShareInfo>> SetQuotaAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
int? quota = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.SetQuota",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetQuotaAsync_CreateMessage(
pipeline,
resourceUri,
timeout,
quota))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetQuotaAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.SetQuotaAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="quota">Specifies the maximum size of the share, in gigabytes.</param>
/// <returns>The Share.SetQuotaAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetQuotaAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
int? quota = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "properties");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (quota != null) { _request.Headers.SetValue("x-ms-share-quota", quota.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); }
return _message;
}
/// <summary>
/// Create the Share.SetQuotaAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.SetQuotaAsync Azure.Response{Azure.Storage.Files.Models.ShareInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.ShareInfo> SetQuotaAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.ShareInfo _value = new Azure.Storage.Files.Models.ShareInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.ShareInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.ShareInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.SetQuotaAsync
#region Share.SetMetadataAsync
/// <summary>
/// Sets one or more user-defined name-value pairs for the specified share.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.ShareInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.ShareInfo>> SetMetadataAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.SetMetadata",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetMetadataAsync_CreateMessage(
pipeline,
resourceUri,
timeout,
metadata))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetMetadataAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.SetMetadataAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <returns>The Share.SetMetadataAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetMetadataAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "metadata");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
return _message;
}
/// <summary>
/// Create the Share.SetMetadataAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.SetMetadataAsync Azure.Response{Azure.Storage.Files.Models.ShareInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.ShareInfo> SetMetadataAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.ShareInfo _value = new Azure.Storage.Files.Models.ShareInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.ShareInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.ShareInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.SetMetadataAsync
#region Share.GetAccessPolicyAsync
/// <summary>
/// Returns information about stored access policies specified on the share.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A collection of signed identifiers.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.SignedIdentifier>>> GetAccessPolicyAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.GetAccessPolicy",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetAccessPolicyAsync_CreateMessage(
pipeline,
resourceUri,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetAccessPolicyAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.GetAccessPolicyAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Share.GetAccessPolicyAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetAccessPolicyAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "acl");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Share.GetAccessPolicyAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.GetAccessPolicyAsync Azure.Response{System.Collections.Generic.IEnumerable{Azure.Storage.Files.Models.SignedIdentifier}}.</returns>
internal static Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.SignedIdentifier>> GetAccessPolicyAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.SignedIdentifier> _value =
System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Select(
_xml.Element(System.Xml.Linq.XName.Get("SignedIdentifiers", "")).Elements(System.Xml.Linq.XName.Get("SignedIdentifier", "")),
Azure.Storage.Files.Models.SignedIdentifier.FromXml));
// Create the response
Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.SignedIdentifier>> _result =
new Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.SignedIdentifier>>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.GetAccessPolicyAsync
#region Share.SetAccessPolicyAsync
/// <summary>
/// Sets a stored access policy for use with shared access signatures.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="permissions">The ACL for the share.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.ShareInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.ShareInfo>> SetAccessPolicyAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.SignedIdentifier> permissions = default,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.SetAccessPolicy",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetAccessPolicyAsync_CreateMessage(
pipeline,
resourceUri,
permissions,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetAccessPolicyAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.SetAccessPolicyAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="permissions">The ACL for the share.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Share.SetAccessPolicyAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetAccessPolicyAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.SignedIdentifier> permissions = default,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "acl");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
// Create the body
System.Xml.Linq.XElement _body = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("SignedIdentifiers", ""));
if (permissions != null)
{
foreach (Azure.Storage.Files.Models.SignedIdentifier _child in permissions)
{
_body.Add(Azure.Storage.Files.Models.SignedIdentifier.ToXml(_child));
}
}
string _text = _body.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);
_request.Headers.SetValue("Content-Type", "application/xml");
_request.Headers.SetValue("Content-Length", _text.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
_request.Content = Azure.Core.Pipeline.HttpPipelineRequestContent.Create(System.Text.Encoding.UTF8.GetBytes(_text));
return _message;
}
/// <summary>
/// Create the Share.SetAccessPolicyAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.SetAccessPolicyAsync Azure.Response{Azure.Storage.Files.Models.ShareInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.ShareInfo> SetAccessPolicyAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.ShareInfo _value = new Azure.Storage.Files.Models.ShareInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.ShareInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.ShareInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.SetAccessPolicyAsync
#region Share.GetStatisticsAsync
/// <summary>
/// Retrieves statistics related to the share.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Stats for the share.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.ShareStatistics>> GetStatisticsAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.ShareClient.GetStatistics",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetStatisticsAsync_CreateMessage(
pipeline,
resourceUri,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetStatisticsAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Share.GetStatisticsAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Share.GetStatisticsAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetStatisticsAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "share");
_request.Uri.AppendQuery("comp", "stats");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Share.GetStatisticsAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Share.GetStatisticsAsync Azure.Response{Azure.Storage.Files.Models.ShareStatistics}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.ShareStatistics> GetStatisticsAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.ShareStatistics _value = Azure.Storage.Files.Models.ShareStatistics.FromXml(_xml.Root);
// Create the response
Azure.Response<Azure.Storage.Files.Models.ShareStatistics> _result =
new Azure.Response<Azure.Storage.Files.Models.ShareStatistics>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Share.GetStatisticsAsync
}
#endregion Share operations
#region Directory operations
/// <summary>
/// Directory operations for Azure File Storage
/// </summary>
public static partial class Directory
{
#region Directory.CreateAsync
/// <summary>
/// Creates a new directory under the specified share or parent directory.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo>> CreateAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
string filePermission = default,
string filePermissionKey = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.Create",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = CreateAsync_CreateMessage(
pipeline,
resourceUri,
fileAttributes,
fileCreationTime,
fileLastWriteTime,
timeout,
metadata,
filePermission,
filePermissionKey))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return CreateAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.CreateAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <returns>The Directory.CreateAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage CreateAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
string filePermission = default,
string filePermissionKey = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (fileAttributes == null)
{
throw new System.ArgumentNullException(nameof(fileAttributes));
}
if (fileCreationTime == null)
{
throw new System.ArgumentNullException(nameof(fileCreationTime));
}
if (fileLastWriteTime == null)
{
throw new System.ArgumentNullException(nameof(fileLastWriteTime));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "directory");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
_request.Headers.SetValue("x-ms-file-attributes", fileAttributes);
_request.Headers.SetValue("x-ms-file-creation-time", fileCreationTime);
_request.Headers.SetValue("x-ms-file-last-write-time", fileLastWriteTime);
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
if (filePermission != null) { _request.Headers.SetValue("x-ms-file-permission", filePermission); }
if (filePermissionKey != null) { _request.Headers.SetValue("x-ms-file-permission-key", filePermissionKey); }
return _message;
}
/// <summary>
/// Create the Directory.CreateAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.CreateAsync Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo> CreateAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 201:
{
// Create the result
Azure.Storage.Files.Models.RawStorageDirectoryInfo _value = new Azure.Storage.Files.Models.RawStorageDirectoryInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.CreateAsync
#region Directory.GetPropertiesAsync
/// <summary>
/// Returns all system properties for the specified directory, and can also be used to check the existence of a directory. The data returned does not include the files in the directory or any subdirectories.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryProperties}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryProperties>> GetPropertiesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.GetProperties",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetPropertiesAsync_CreateMessage(
pipeline,
resourceUri,
sharesnapshot,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetPropertiesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.GetPropertiesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Directory.GetPropertiesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetPropertiesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "directory");
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Directory.GetPropertiesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.GetPropertiesAsync Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryProperties}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryProperties> GetPropertiesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.RawStorageDirectoryProperties _value = new Azure.Storage.Files.Models.RawStorageDirectoryProperties();
// Get response headers
string _header;
_value.Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
foreach (Azure.Core.Http.HttpHeader _headerPair in response.Headers)
{
if (_headerPair.Name.StartsWith("x-ms-meta-", System.StringComparison.InvariantCulture))
{
_value.Metadata[_headerPair.Name.Substring(10)] = _headerPair.Value;
}
}
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryProperties> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryProperties>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.GetPropertiesAsync
#region Directory.DeleteAsync
/// <summary>
/// Removes the specified empty directory. Note that the directory must be empty before it can be deleted.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response> DeleteAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.Delete",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = DeleteAsync_CreateMessage(
pipeline,
resourceUri,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return DeleteAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.DeleteAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Directory.DeleteAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage DeleteAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Delete;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "directory");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Directory.DeleteAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.DeleteAsync Azure.Response.</returns>
internal static Azure.Response DeleteAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 202:
{
return response;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.DeleteAsync
#region Directory.SetPropertiesAsync
/// <summary>
/// Sets properties on the directory.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo>> SetPropertiesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
string filePermission = default,
string filePermissionKey = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.SetProperties",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetPropertiesAsync_CreateMessage(
pipeline,
resourceUri,
fileAttributes,
fileCreationTime,
fileLastWriteTime,
timeout,
filePermission,
filePermissionKey))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetPropertiesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.SetPropertiesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <returns>The Directory.SetPropertiesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetPropertiesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
string filePermission = default,
string filePermissionKey = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (fileAttributes == null)
{
throw new System.ArgumentNullException(nameof(fileAttributes));
}
if (fileCreationTime == null)
{
throw new System.ArgumentNullException(nameof(fileCreationTime));
}
if (fileLastWriteTime == null)
{
throw new System.ArgumentNullException(nameof(fileLastWriteTime));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "directory");
_request.Uri.AppendQuery("comp", "properties");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
_request.Headers.SetValue("x-ms-file-attributes", fileAttributes);
_request.Headers.SetValue("x-ms-file-creation-time", fileCreationTime);
_request.Headers.SetValue("x-ms-file-last-write-time", fileLastWriteTime);
if (filePermission != null) { _request.Headers.SetValue("x-ms-file-permission", filePermission); }
if (filePermissionKey != null) { _request.Headers.SetValue("x-ms-file-permission-key", filePermissionKey); }
return _message;
}
/// <summary>
/// Create the Directory.SetPropertiesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.SetPropertiesAsync Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo> SetPropertiesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.RawStorageDirectoryInfo _value = new Azure.Storage.Files.Models.RawStorageDirectoryInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.SetPropertiesAsync
#region Directory.SetMetadataAsync
/// <summary>
/// Updates user defined metadata for the specified directory.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo>> SetMetadataAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.SetMetadata",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetMetadataAsync_CreateMessage(
pipeline,
resourceUri,
timeout,
metadata))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetMetadataAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.SetMetadataAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <returns>The Directory.SetMetadataAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetMetadataAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "directory");
_request.Uri.AppendQuery("comp", "metadata");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
return _message;
}
/// <summary>
/// Create the Directory.SetMetadataAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.SetMetadataAsync Azure.Response{Azure.Storage.Files.Models.RawStorageDirectoryInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo> SetMetadataAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.RawStorageDirectoryInfo _value = new Azure.Storage.Files.Models.RawStorageDirectoryInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageDirectoryInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.SetMetadataAsync
#region Directory.ListFilesAndDirectoriesSegmentAsync
/// <summary>
/// Returns a list of files or directories under the specified share or directory. It lists the contents only for a single level of the directory hierarchy.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="prefix">Filters the results to return only entries whose name begins with the specified prefix.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>An enumeration of directories and files.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.FilesAndDirectoriesSegment>> ListFilesAndDirectoriesSegmentAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string prefix = default,
string sharesnapshot = default,
string marker = default,
int? maxresults = default,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.ListFilesAndDirectoriesSegment",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = ListFilesAndDirectoriesSegmentAsync_CreateMessage(
pipeline,
resourceUri,
prefix,
sharesnapshot,
marker,
maxresults,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return ListFilesAndDirectoriesSegmentAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.ListFilesAndDirectoriesSegmentAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="prefix">Filters the results to return only entries whose name begins with the specified prefix.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The Directory.ListFilesAndDirectoriesSegmentAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage ListFilesAndDirectoriesSegmentAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string prefix = default,
string sharesnapshot = default,
string marker = default,
int? maxresults = default,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("restype", "directory");
_request.Uri.AppendQuery("comp", "list");
if (prefix != null) { _request.Uri.AppendQuery("prefix", System.Uri.EscapeDataString(prefix)); }
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
if (marker != null) { _request.Uri.AppendQuery("marker", System.Uri.EscapeDataString(marker)); }
if (maxresults != null) { _request.Uri.AppendQuery("maxresults", System.Uri.EscapeDataString(maxresults.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the Directory.ListFilesAndDirectoriesSegmentAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.ListFilesAndDirectoriesSegmentAsync Azure.Response{Azure.Storage.Files.Models.FilesAndDirectoriesSegment}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.FilesAndDirectoriesSegment> ListFilesAndDirectoriesSegmentAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.FilesAndDirectoriesSegment _value = Azure.Storage.Files.Models.FilesAndDirectoriesSegment.FromXml(_xml.Root);
// Create the response
Azure.Response<Azure.Storage.Files.Models.FilesAndDirectoriesSegment> _result =
new Azure.Response<Azure.Storage.Files.Models.FilesAndDirectoriesSegment>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.ListFilesAndDirectoriesSegmentAsync
#region Directory.ListHandlesAsync
/// <summary>
/// Lists handles for directory.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="recursive">Specifies operation should apply to the directory specified in the URI, its files, its subdirectories and their files.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>An enumeration of handles.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment>> ListHandlesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string marker = default,
int? maxresults = default,
int? timeout = default,
string sharesnapshot = default,
bool? recursive = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.ListHandles",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = ListHandlesAsync_CreateMessage(
pipeline,
resourceUri,
marker,
maxresults,
timeout,
sharesnapshot,
recursive))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return ListHandlesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.ListHandlesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="recursive">Specifies operation should apply to the directory specified in the URI, its files, its subdirectories and their files.</param>
/// <returns>The Directory.ListHandlesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage ListHandlesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string marker = default,
int? maxresults = default,
int? timeout = default,
string sharesnapshot = default,
bool? recursive = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "listhandles");
if (marker != null) { _request.Uri.AppendQuery("marker", System.Uri.EscapeDataString(marker)); }
if (maxresults != null) { _request.Uri.AppendQuery("maxresults", System.Uri.EscapeDataString(maxresults.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (recursive != null) {
#pragma warning disable CA1308 // Normalize strings to uppercase
_request.Headers.SetValue("x-ms-recursive", recursive.Value.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant());
#pragma warning restore CA1308 // Normalize strings to uppercase
}
return _message;
}
/// <summary>
/// Create the Directory.ListHandlesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.ListHandlesAsync Azure.Response{Azure.Storage.Files.Models.StorageHandlesSegment}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment> ListHandlesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageHandlesSegment _value = Azure.Storage.Files.Models.StorageHandlesSegment.FromXml(_xml.Root);
// Create the response
Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment> _result =
new Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.ListHandlesAsync
#region Directory.ForceCloseHandlesAsync
/// <summary>
/// Closes all handles open for given directory.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="handleId">Specifies handle ID opened on the file or directory to be closed. Asterix (‘*’) is a wildcard that specifies all handles.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="recursive">Specifies operation should apply to the directory specified in the URI, its files, its subdirectories and their files.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.StorageClosedHandlesSegment}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment>> ForceCloseHandlesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string handleId,
int? timeout = default,
string marker = default,
string sharesnapshot = default,
bool? recursive = default,
bool async = true,
string operationName = "Azure.Storage.Files.DirectoryClient.ForceCloseHandles",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = ForceCloseHandlesAsync_CreateMessage(
pipeline,
resourceUri,
handleId,
timeout,
marker,
sharesnapshot,
recursive))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return ForceCloseHandlesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the Directory.ForceCloseHandlesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="handleId">Specifies handle ID opened on the file or directory to be closed. Asterix (‘*’) is a wildcard that specifies all handles.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="recursive">Specifies operation should apply to the directory specified in the URI, its files, its subdirectories and their files.</param>
/// <returns>The Directory.ForceCloseHandlesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage ForceCloseHandlesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string handleId,
int? timeout = default,
string marker = default,
string sharesnapshot = default,
bool? recursive = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (handleId == null)
{
throw new System.ArgumentNullException(nameof(handleId));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "forceclosehandles");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (marker != null) { _request.Uri.AppendQuery("marker", System.Uri.EscapeDataString(marker)); }
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
// Add request headers
_request.Headers.SetValue("x-ms-handle-id", handleId);
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (recursive != null) {
#pragma warning disable CA1308 // Normalize strings to uppercase
_request.Headers.SetValue("x-ms-recursive", recursive.Value.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant());
#pragma warning restore CA1308 // Normalize strings to uppercase
}
return _message;
}
/// <summary>
/// Create the Directory.ForceCloseHandlesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The Directory.ForceCloseHandlesAsync Azure.Response{Azure.Storage.Files.Models.StorageClosedHandlesSegment}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment> ForceCloseHandlesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.StorageClosedHandlesSegment _value = new Azure.Storage.Files.Models.StorageClosedHandlesSegment();
// Get response headers
string _header;
if (response.Headers.TryGetValue("x-ms-marker", out _header))
{
_value.Marker = _header;
}
if (response.Headers.TryGetValue("x-ms-number-of-handles-closed", out _header))
{
_value.NumberOfHandlesClosed = int.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment> _result =
new Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion Directory.ForceCloseHandlesAsync
}
#endregion Directory operations
#region File operations
/// <summary>
/// File operations for Azure File Storage
/// </summary>
public static partial class File
{
#region File.CreateAsync
/// <summary>
/// Creates a new file or replaces a file. Note it only initializes the file with no content.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileContentLength">Specifies the maximum size for the file, up to 1 TB.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="fileContentType">Sets the MIME content type of the file. The default type is 'application/octet-stream'.</param>
/// <param name="fileContentEncoding">Specifies which content encodings have been applied to the file.</param>
/// <param name="fileContentLanguage">Specifies the natural languages used by this resource.</param>
/// <param name="fileCacheControl">Sets the file's cache control. The File service stores this value but does not use or modify it.</param>
/// <param name="fileContentHash">Sets the file's MD5 hash.</param>
/// <param name="fileContentDisposition">Sets the file's Content-Disposition header.</param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageFileInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo>> CreateAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
long fileContentLength,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
string fileContentType = default,
System.Collections.Generic.IEnumerable<string> fileContentEncoding = default,
System.Collections.Generic.IEnumerable<string> fileContentLanguage = default,
string fileCacheControl = default,
byte[] fileContentHash = default,
string fileContentDisposition = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
string filePermission = default,
string filePermissionKey = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.Create",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = CreateAsync_CreateMessage(
pipeline,
resourceUri,
fileContentLength,
fileAttributes,
fileCreationTime,
fileLastWriteTime,
timeout,
fileContentType,
fileContentEncoding,
fileContentLanguage,
fileCacheControl,
fileContentHash,
fileContentDisposition,
metadata,
filePermission,
filePermissionKey))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return CreateAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.CreateAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileContentLength">Specifies the maximum size for the file, up to 1 TB.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="fileContentType">Sets the MIME content type of the file. The default type is 'application/octet-stream'.</param>
/// <param name="fileContentEncoding">Specifies which content encodings have been applied to the file.</param>
/// <param name="fileContentLanguage">Specifies the natural languages used by this resource.</param>
/// <param name="fileCacheControl">Sets the file's cache control. The File service stores this value but does not use or modify it.</param>
/// <param name="fileContentHash">Sets the file's MD5 hash.</param>
/// <param name="fileContentDisposition">Sets the file's Content-Disposition header.</param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <returns>The File.CreateAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage CreateAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
long fileContentLength,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
string fileContentType = default,
System.Collections.Generic.IEnumerable<string> fileContentEncoding = default,
System.Collections.Generic.IEnumerable<string> fileContentLanguage = default,
string fileCacheControl = default,
byte[] fileContentHash = default,
string fileContentDisposition = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
string filePermission = default,
string filePermissionKey = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (fileAttributes == null)
{
throw new System.ArgumentNullException(nameof(fileAttributes));
}
if (fileCreationTime == null)
{
throw new System.ArgumentNullException(nameof(fileCreationTime));
}
if (fileLastWriteTime == null)
{
throw new System.ArgumentNullException(nameof(fileLastWriteTime));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
_request.Headers.SetValue("x-ms-content-length", fileContentLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
_request.Headers.SetValue("x-ms-type", "file");
_request.Headers.SetValue("x-ms-file-attributes", fileAttributes);
_request.Headers.SetValue("x-ms-file-creation-time", fileCreationTime);
_request.Headers.SetValue("x-ms-file-last-write-time", fileLastWriteTime);
if (fileContentType != null) { _request.Headers.SetValue("x-ms-content-type", fileContentType); }
if (fileContentEncoding != null) {
foreach (string _item in fileContentEncoding)
{
_request.Headers.SetValue("x-ms-content-encoding", _item);
}
}
if (fileContentLanguage != null) {
foreach (string _item in fileContentLanguage)
{
_request.Headers.SetValue("x-ms-content-language", _item);
}
}
if (fileCacheControl != null) { _request.Headers.SetValue("x-ms-cache-control", fileCacheControl); }
if (fileContentHash != null) { _request.Headers.SetValue("x-ms-content-md5", System.Convert.ToBase64String(fileContentHash)); }
if (fileContentDisposition != null) { _request.Headers.SetValue("x-ms-content-disposition", fileContentDisposition); }
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
if (filePermission != null) { _request.Headers.SetValue("x-ms-file-permission", filePermission); }
if (filePermissionKey != null) { _request.Headers.SetValue("x-ms-file-permission-key", filePermissionKey); }
return _message;
}
/// <summary>
/// Create the File.CreateAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.CreateAsync Azure.Response{Azure.Storage.Files.Models.RawStorageFileInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo> CreateAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 201:
{
// Create the result
Azure.Storage.Files.Models.RawStorageFileInfo _value = new Azure.Storage.Files.Models.RawStorageFileInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-request-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.CreateAsync
#region File.DownloadAsync
/// <summary>
/// Reads or downloads a file from the system, including its metadata and properties.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="range">Return file data only from the specified byte range.</param>
/// <param name="rangeGetContentHash">When this header is set to true and specified together with the Range header, the service returns the MD5 hash for the range, as long as the range is less than or equal to 4 MB in size.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.FlattenedStorageFileProperties}</returns>
public static async System.Threading.Tasks.ValueTask<(Azure.Response<Azure.Storage.Files.Models.FlattenedStorageFileProperties>, System.IO.Stream)> DownloadAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
string range = default,
bool? rangeGetContentHash = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.Download",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = DownloadAsync_CreateMessage(
pipeline,
resourceUri,
timeout,
range,
rangeGetContentHash))
{
// Avoid buffering if stream is going to be returned to the caller
_message.BufferResponse = false;
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return (DownloadAsync_CreateResponse(_response), _message.ExtractResponseContent());
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.DownloadAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="range">Return file data only from the specified byte range.</param>
/// <param name="rangeGetContentHash">When this header is set to true and specified together with the Range header, the service returns the MD5 hash for the range, as long as the range is less than or equal to 4 MB in size.</param>
/// <returns>The File.DownloadAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage DownloadAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
string range = default,
bool? rangeGetContentHash = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (range != null) { _request.Headers.SetValue("x-ms-range", range); }
if (rangeGetContentHash != null) {
#pragma warning disable CA1308 // Normalize strings to uppercase
_request.Headers.SetValue("x-ms-range-get-content-md5", rangeGetContentHash.Value.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant());
#pragma warning restore CA1308 // Normalize strings to uppercase
}
return _message;
}
/// <summary>
/// Create the File.DownloadAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.DownloadAsync Azure.Response{Azure.Storage.Files.Models.FlattenedStorageFileProperties}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.FlattenedStorageFileProperties> DownloadAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.FlattenedStorageFileProperties _value = new Azure.Storage.Files.Models.FlattenedStorageFileProperties();
_value.Content = response.ContentStream; // You should manually wrap with RetriableStream!
// Get response headers
string _header;
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
_value.Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
foreach (Azure.Core.Http.HttpHeader _headerPair in response.Headers)
{
if (_headerPair.Name.StartsWith("x-ms-meta-", System.StringComparison.InvariantCulture))
{
_value.Metadata[_headerPair.Name.Substring(10)] = _headerPair.Value;
}
}
if (response.Headers.TryGetValue("Content-Length", out _header))
{
_value.ContentLength = long.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("Content-Type", out _header))
{
_value.ContentType = _header;
}
if (response.Headers.TryGetValue("Content-Range", out _header))
{
_value.ContentRange = _header;
}
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Content-MD5", out _header))
{
_value.ContentHash = System.Convert.FromBase64String(_header);
}
if (response.Headers.TryGetValue("Content-Encoding", out _header))
{
_value.ContentEncoding = (_header ?? "").Split(',');
}
if (response.Headers.TryGetValue("Cache-Control", out _header))
{
_value.CacheControl = _header;
}
if (response.Headers.TryGetValue("Content-Disposition", out _header))
{
_value.ContentDisposition = _header;
}
if (response.Headers.TryGetValue("Content-Language", out _header))
{
_value.ContentLanguage = (_header ?? "").Split(',');
}
if (response.Headers.TryGetValue("Accept-Ranges", out _header))
{
_value.AcceptRanges = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-completion-time", out _header))
{
_value.CopyCompletionTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-copy-status-description", out _header))
{
_value.CopyStatusDescription = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-id", out _header))
{
_value.CopyId = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-progress", out _header))
{
_value.CopyProgress = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-source", out _header))
{
_value.CopySource = new System.Uri(_header);
}
if (response.Headers.TryGetValue("x-ms-copy-status", out _header))
{
_value.CopyStatus = Azure.Storage.Files.FileRestClient.Serialization.ParseCopyStatus(_header);
}
if (response.Headers.TryGetValue("x-ms-content-md5", out _header))
{
_value.FileContentHash = System.Convert.FromBase64String(_header);
}
if (response.Headers.TryGetValue("x-ms-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.FlattenedStorageFileProperties> _result =
new Azure.Response<Azure.Storage.Files.Models.FlattenedStorageFileProperties>(
response,
_value);
return _result;
}
case 206:
{
// Create the result
Azure.Storage.Files.Models.FlattenedStorageFileProperties _value = new Azure.Storage.Files.Models.FlattenedStorageFileProperties();
_value.Content = response.ContentStream; // You should manually wrap with RetriableStream!
// Get response headers
string _header;
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
_value.Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
foreach (Azure.Core.Http.HttpHeader _headerPair in response.Headers)
{
if (_headerPair.Name.StartsWith("x-ms-meta-", System.StringComparison.InvariantCulture))
{
_value.Metadata[_headerPair.Name.Substring(10)] = _headerPair.Value;
}
}
if (response.Headers.TryGetValue("Content-Length", out _header))
{
_value.ContentLength = long.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("Content-Type", out _header))
{
_value.ContentType = _header;
}
if (response.Headers.TryGetValue("Content-Range", out _header))
{
_value.ContentRange = _header;
}
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Content-MD5", out _header))
{
_value.ContentHash = System.Convert.FromBase64String(_header);
}
if (response.Headers.TryGetValue("Content-Encoding", out _header))
{
_value.ContentEncoding = (_header ?? "").Split(',');
}
if (response.Headers.TryGetValue("Cache-Control", out _header))
{
_value.CacheControl = _header;
}
if (response.Headers.TryGetValue("Content-Disposition", out _header))
{
_value.ContentDisposition = _header;
}
if (response.Headers.TryGetValue("Content-Language", out _header))
{
_value.ContentLanguage = (_header ?? "").Split(',');
}
if (response.Headers.TryGetValue("Accept-Ranges", out _header))
{
_value.AcceptRanges = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-completion-time", out _header))
{
_value.CopyCompletionTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-copy-status-description", out _header))
{
_value.CopyStatusDescription = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-id", out _header))
{
_value.CopyId = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-progress", out _header))
{
_value.CopyProgress = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-source", out _header))
{
_value.CopySource = new System.Uri(_header);
}
if (response.Headers.TryGetValue("x-ms-copy-status", out _header))
{
_value.CopyStatus = Azure.Storage.Files.FileRestClient.Serialization.ParseCopyStatus(_header);
}
if (response.Headers.TryGetValue("x-ms-content-md5", out _header))
{
_value.FileContentHash = System.Convert.FromBase64String(_header);
}
if (response.Headers.TryGetValue("x-ms-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.FlattenedStorageFileProperties> _result =
new Azure.Response<Azure.Storage.Files.Models.FlattenedStorageFileProperties>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.DownloadAsync
#region File.GetPropertiesAsync
/// <summary>
/// Returns all user-defined metadata, standard HTTP properties, and system properties for the file. It does not return the content of the file.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageFileProperties}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageFileProperties>> GetPropertiesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.GetProperties",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetPropertiesAsync_CreateMessage(
pipeline,
resourceUri,
sharesnapshot,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetPropertiesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.GetPropertiesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The File.GetPropertiesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetPropertiesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Head;
_request.Uri.Assign(resourceUri);
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the File.GetPropertiesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.GetPropertiesAsync Azure.Response{Azure.Storage.Files.Models.RawStorageFileProperties}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageFileProperties> GetPropertiesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.RawStorageFileProperties _value = new Azure.Storage.Files.Models.RawStorageFileProperties();
// Get response headers
string _header;
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
_value.Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
foreach (Azure.Core.Http.HttpHeader _headerPair in response.Headers)
{
if (_headerPair.Name.StartsWith("x-ms-meta-", System.StringComparison.InvariantCulture))
{
_value.Metadata[_headerPair.Name.Substring(10)] = _headerPair.Value;
}
}
if (response.Headers.TryGetValue("x-ms-type", out _header))
{
_value.FileType = (Azure.Storage.Files.Models.Header)System.Enum.Parse(typeof(Azure.Storage.Files.Models.Header), _header, false);
}
if (response.Headers.TryGetValue("Content-Length", out _header))
{
_value.ContentLength = long.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("Content-Type", out _header))
{
_value.ContentType = _header;
}
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Content-MD5", out _header))
{
_value.ContentHash = System.Convert.FromBase64String(_header);
}
if (response.Headers.TryGetValue("Content-Encoding", out _header))
{
_value.ContentEncoding = (_header ?? "").Split(',');
}
if (response.Headers.TryGetValue("Cache-Control", out _header))
{
_value.CacheControl = _header;
}
if (response.Headers.TryGetValue("Content-Disposition", out _header))
{
_value.ContentDisposition = _header;
}
if (response.Headers.TryGetValue("Content-Language", out _header))
{
_value.ContentLanguage = (_header ?? "").Split(',');
}
if (response.Headers.TryGetValue("x-ms-copy-completion-time", out _header))
{
_value.CopyCompletionTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-copy-status-description", out _header))
{
_value.CopyStatusDescription = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-id", out _header))
{
_value.CopyId = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-progress", out _header))
{
_value.CopyProgress = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-source", out _header))
{
_value.CopySource = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-status", out _header))
{
_value.CopyStatus = Azure.Storage.Files.FileRestClient.Serialization.ParseCopyStatus(_header);
}
if (response.Headers.TryGetValue("x-ms-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageFileProperties> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageFileProperties>(
response,
_value);
return _result;
}
default:
{
// Create the result
Azure.Storage.Files.Models.FailureNoContent _value = new Azure.Storage.Files.Models.FailureNoContent();
// Get response headers
string _header;
if (response.Headers.TryGetValue("x-ms-error-code", out _header))
{
_value.ErrorCode = _header;
}
throw _value.CreateException(response);
}
}
}
#endregion File.GetPropertiesAsync
#region File.DeleteAsync
/// <summary>
/// removes the file from the storage account.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response> DeleteAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.Delete",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = DeleteAsync_CreateMessage(
pipeline,
resourceUri,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return DeleteAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.DeleteAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The File.DeleteAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage DeleteAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Delete;
_request.Uri.Assign(resourceUri);
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the File.DeleteAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.DeleteAsync Azure.Response.</returns>
internal static Azure.Response DeleteAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 202:
{
return response;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.DeleteAsync
#region File.SetPropertiesAsync
/// <summary>
/// Sets HTTP headers on the file.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="fileContentLength">Resizes a file to the specified size. If the specified byte value is less than the current size of the file, then all ranges above the specified byte value are cleared.</param>
/// <param name="fileContentType">Sets the MIME content type of the file. The default type is 'application/octet-stream'.</param>
/// <param name="fileContentEncoding">Specifies which content encodings have been applied to the file.</param>
/// <param name="fileContentLanguage">Specifies the natural languages used by this resource.</param>
/// <param name="fileCacheControl">Sets the file's cache control. The File service stores this value but does not use or modify it.</param>
/// <param name="fileContentHash">Sets the file's MD5 hash.</param>
/// <param name="fileContentDisposition">Sets the file's Content-Disposition header.</param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageFileInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo>> SetPropertiesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
long? fileContentLength = default,
string fileContentType = default,
System.Collections.Generic.IEnumerable<string> fileContentEncoding = default,
System.Collections.Generic.IEnumerable<string> fileContentLanguage = default,
string fileCacheControl = default,
byte[] fileContentHash = default,
string fileContentDisposition = default,
string filePermission = default,
string filePermissionKey = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.SetProperties",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetPropertiesAsync_CreateMessage(
pipeline,
resourceUri,
fileAttributes,
fileCreationTime,
fileLastWriteTime,
timeout,
fileContentLength,
fileContentType,
fileContentEncoding,
fileContentLanguage,
fileCacheControl,
fileContentHash,
fileContentDisposition,
filePermission,
filePermissionKey))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetPropertiesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.SetPropertiesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="fileAttributes">If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default.</param>
/// <param name="fileCreationTime">Creation time for the file/directory. Default value: Now.</param>
/// <param name="fileLastWriteTime">Last write time for the file/directory. Default value: Now.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="fileContentLength">Resizes a file to the specified size. If the specified byte value is less than the current size of the file, then all ranges above the specified byte value are cleared.</param>
/// <param name="fileContentType">Sets the MIME content type of the file. The default type is 'application/octet-stream'.</param>
/// <param name="fileContentEncoding">Specifies which content encodings have been applied to the file.</param>
/// <param name="fileContentLanguage">Specifies the natural languages used by this resource.</param>
/// <param name="fileCacheControl">Sets the file's cache control. The File service stores this value but does not use or modify it.</param>
/// <param name="fileContentHash">Sets the file's MD5 hash.</param>
/// <param name="fileContentDisposition">Sets the file's Content-Disposition header.</param>
/// <param name="filePermission">If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <param name="filePermissionKey">Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.</param>
/// <returns>The File.SetPropertiesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetPropertiesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string fileAttributes,
string fileCreationTime,
string fileLastWriteTime,
int? timeout = default,
long? fileContentLength = default,
string fileContentType = default,
System.Collections.Generic.IEnumerable<string> fileContentEncoding = default,
System.Collections.Generic.IEnumerable<string> fileContentLanguage = default,
string fileCacheControl = default,
byte[] fileContentHash = default,
string fileContentDisposition = default,
string filePermission = default,
string filePermissionKey = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (fileAttributes == null)
{
throw new System.ArgumentNullException(nameof(fileAttributes));
}
if (fileCreationTime == null)
{
throw new System.ArgumentNullException(nameof(fileCreationTime));
}
if (fileLastWriteTime == null)
{
throw new System.ArgumentNullException(nameof(fileLastWriteTime));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "properties");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
_request.Headers.SetValue("x-ms-file-attributes", fileAttributes);
_request.Headers.SetValue("x-ms-file-creation-time", fileCreationTime);
_request.Headers.SetValue("x-ms-file-last-write-time", fileLastWriteTime);
if (fileContentLength != null) { _request.Headers.SetValue("x-ms-content-length", fileContentLength.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); }
if (fileContentType != null) { _request.Headers.SetValue("x-ms-content-type", fileContentType); }
if (fileContentEncoding != null) {
foreach (string _item in fileContentEncoding)
{
_request.Headers.SetValue("x-ms-content-encoding", _item);
}
}
if (fileContentLanguage != null) {
foreach (string _item in fileContentLanguage)
{
_request.Headers.SetValue("x-ms-content-language", _item);
}
}
if (fileCacheControl != null) { _request.Headers.SetValue("x-ms-cache-control", fileCacheControl); }
if (fileContentHash != null) { _request.Headers.SetValue("x-ms-content-md5", System.Convert.ToBase64String(fileContentHash)); }
if (fileContentDisposition != null) { _request.Headers.SetValue("x-ms-content-disposition", fileContentDisposition); }
if (filePermission != null) { _request.Headers.SetValue("x-ms-file-permission", filePermission); }
if (filePermissionKey != null) { _request.Headers.SetValue("x-ms-file-permission-key", filePermissionKey); }
return _message;
}
/// <summary>
/// Create the File.SetPropertiesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.SetPropertiesAsync Azure.Response{Azure.Storage.Files.Models.RawStorageFileInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo> SetPropertiesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.RawStorageFileInfo _value = new Azure.Storage.Files.Models.RawStorageFileInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-request-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
if (response.Headers.TryGetValue("x-ms-file-permission-key", out _header))
{
_value.FilePermissionKey = _header;
}
if (response.Headers.TryGetValue("x-ms-file-attributes", out _header))
{
_value.FileAttributes = _header;
}
if (response.Headers.TryGetValue("x-ms-file-creation-time", out _header))
{
_value.FileCreationTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-last-write-time", out _header))
{
_value.FileLastWriteTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-change-time", out _header))
{
_value.FileChangeTime = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-file-id", out _header))
{
_value.FileId = _header;
}
if (response.Headers.TryGetValue("x-ms-file-parent-id", out _header))
{
_value.FileParentId = _header;
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.SetPropertiesAsync
#region File.SetMetadataAsync
/// <summary>
/// Updates user-defined metadata for the specified file.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.RawStorageFileInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo>> SetMetadataAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.SetMetadata",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = SetMetadataAsync_CreateMessage(
pipeline,
resourceUri,
timeout,
metadata))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return SetMetadataAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.SetMetadataAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <returns>The File.SetMetadataAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage SetMetadataAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "metadata");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
return _message;
}
/// <summary>
/// Create the File.SetMetadataAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.SetMetadataAsync Azure.Response{Azure.Storage.Files.Models.RawStorageFileInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo> SetMetadataAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.RawStorageFileInfo _value = new Azure.Storage.Files.Models.RawStorageFileInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("x-ms-request-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.RawStorageFileInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.SetMetadataAsync
#region File.UploadRangeAsync
/// <summary>
/// Upload a range of bytes to a file.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="range">Specifies the range of bytes to be written. Both the start and end of the range must be specified. For an update operation, the range can be up to 4 MB in size. For a clear operation, the range can be up to the value of the file's full size. The File service accepts only a single byte range for the Range and 'x-ms-range' headers, and the byte range must be specified in the following format: bytes=startByte-endByte.</param>
/// <param name="fileRangeWrite">Specify one of the following options: - Update: Writes the bytes specified by the request body into the specified range. The Range and Content-Length headers must match to perform the update. - Clear: Clears the specified range and releases the space used in storage for that range. To clear a range, set the Content-Length header to zero, and set the Range header to a value that indicates the range to clear, up to maximum file size.</param>
/// <param name="contentLength">Specifies the number of bytes being transmitted in the request body. When the x-ms-write header is set to clear, the value of this header must be set to zero.</param>
/// <param name="optionalbody">Initial data.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="contentHash">An MD5 hash of the content. This hash is used to verify the integrity of the data during transport. When the Content-MD5 header is specified, the File service compares the hash of the content that has arrived with the header value that was sent. If the two hashes do not match, the operation will fail with error code 400 (Bad Request).</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.StorageFileUploadInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.StorageFileUploadInfo>> UploadRangeAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string range,
Azure.Storage.Files.Models.FileRangeWriteType fileRangeWrite,
long contentLength,
System.IO.Stream optionalbody = default,
int? timeout = default,
byte[] contentHash = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.UploadRange",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = UploadRangeAsync_CreateMessage(
pipeline,
resourceUri,
range,
fileRangeWrite,
contentLength,
optionalbody,
timeout,
contentHash))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return UploadRangeAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.UploadRangeAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="range">Specifies the range of bytes to be written. Both the start and end of the range must be specified. For an update operation, the range can be up to 4 MB in size. For a clear operation, the range can be up to the value of the file's full size. The File service accepts only a single byte range for the Range and 'x-ms-range' headers, and the byte range must be specified in the following format: bytes=startByte-endByte.</param>
/// <param name="fileRangeWrite">Specify one of the following options: - Update: Writes the bytes specified by the request body into the specified range. The Range and Content-Length headers must match to perform the update. - Clear: Clears the specified range and releases the space used in storage for that range. To clear a range, set the Content-Length header to zero, and set the Range header to a value that indicates the range to clear, up to maximum file size.</param>
/// <param name="contentLength">Specifies the number of bytes being transmitted in the request body. When the x-ms-write header is set to clear, the value of this header must be set to zero.</param>
/// <param name="optionalbody">Initial data.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="contentHash">An MD5 hash of the content. This hash is used to verify the integrity of the data during transport. When the Content-MD5 header is specified, the File service compares the hash of the content that has arrived with the header value that was sent. If the two hashes do not match, the operation will fail with error code 400 (Bad Request).</param>
/// <returns>The File.UploadRangeAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage UploadRangeAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string range,
Azure.Storage.Files.Models.FileRangeWriteType fileRangeWrite,
long contentLength,
System.IO.Stream optionalbody = default,
int? timeout = default,
byte[] contentHash = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (range == null)
{
throw new System.ArgumentNullException(nameof(range));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "range");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-range", range);
_request.Headers.SetValue("x-ms-write", Azure.Storage.Files.FileRestClient.Serialization.ToString(fileRangeWrite));
_request.Headers.SetValue("Content-Length", contentLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (contentHash != null) { _request.Headers.SetValue("Content-MD5", System.Convert.ToBase64String(contentHash)); }
// Create the body
_request.Content = Azure.Core.Pipeline.HttpPipelineRequestContent.Create(optionalbody);
return _message;
}
/// <summary>
/// Create the File.UploadRangeAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.UploadRangeAsync Azure.Response{Azure.Storage.Files.Models.StorageFileUploadInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.StorageFileUploadInfo> UploadRangeAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 201:
{
// Create the result
Azure.Storage.Files.Models.StorageFileUploadInfo _value = new Azure.Storage.Files.Models.StorageFileUploadInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("Content-MD5", out _header))
{
_value.ContentHash = System.Convert.FromBase64String(_header);
}
if (response.Headers.TryGetValue("x-ms-request-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.StorageFileUploadInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.StorageFileUploadInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.UploadRangeAsync
#region File.UploadRangeFromURLAsync
/// <summary>
/// Upload a range of bytes to a file where the contents are read from a URL.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="range">Writes data to the specified byte range in the file.</param>
/// <param name="copySource">Specifies the URL of the source file or blob, up to 2 KB in length. To copy a file to another file within the same storage account, you may use Shared Key to authenticate the source file. If you are copying a file from another storage account, or if you are copying a blob from the same storage account or another storage account, then you must authenticate the source file or blob using a shared access signature. If the source is a public blob, no authentication is required to perform the copy operation. A file in a share snapshot can also be specified as a copy source.</param>
/// <param name="contentLength">Specifies the number of bytes being transmitted in the request body. When the x-ms-write header is set to clear, the value of this header must be set to zero.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="sourceRange">Bytes of source data in the specified range.</param>
/// <param name="sourceContentCrc64">Specify the crc64 calculated for the range of bytes that must be read from the copy source.</param>
/// <param name="sourceIfMatchCrc64">Specify the crc64 value to operate only on range with a matching crc64 checksum.</param>
/// <param name="sourceIfNoneMatchCrc64">Specify the crc64 value to operate only on range without a matching crc64 checksum.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.FileUploadRangeFromURLResult}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.FileUploadRangeFromURLResult>> UploadRangeFromURLAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string range,
System.Uri copySource,
long contentLength,
int? timeout = default,
string sourceRange = default,
byte[] sourceContentCrc64 = default,
byte[] sourceIfMatchCrc64 = default,
byte[] sourceIfNoneMatchCrc64 = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.UploadRangeFromURL",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = UploadRangeFromURLAsync_CreateMessage(
pipeline,
resourceUri,
range,
copySource,
contentLength,
timeout,
sourceRange,
sourceContentCrc64,
sourceIfMatchCrc64,
sourceIfNoneMatchCrc64))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return UploadRangeFromURLAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.UploadRangeFromURLAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="range">Writes data to the specified byte range in the file.</param>
/// <param name="copySource">Specifies the URL of the source file or blob, up to 2 KB in length. To copy a file to another file within the same storage account, you may use Shared Key to authenticate the source file. If you are copying a file from another storage account, or if you are copying a blob from the same storage account or another storage account, then you must authenticate the source file or blob using a shared access signature. If the source is a public blob, no authentication is required to perform the copy operation. A file in a share snapshot can also be specified as a copy source.</param>
/// <param name="contentLength">Specifies the number of bytes being transmitted in the request body. When the x-ms-write header is set to clear, the value of this header must be set to zero.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="sourceRange">Bytes of source data in the specified range.</param>
/// <param name="sourceContentCrc64">Specify the crc64 calculated for the range of bytes that must be read from the copy source.</param>
/// <param name="sourceIfMatchCrc64">Specify the crc64 value to operate only on range with a matching crc64 checksum.</param>
/// <param name="sourceIfNoneMatchCrc64">Specify the crc64 value to operate only on range without a matching crc64 checksum.</param>
/// <returns>The File.UploadRangeFromURLAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage UploadRangeFromURLAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string range,
System.Uri copySource,
long contentLength,
int? timeout = default,
string sourceRange = default,
byte[] sourceContentCrc64 = default,
byte[] sourceIfMatchCrc64 = default,
byte[] sourceIfNoneMatchCrc64 = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (range == null)
{
throw new System.ArgumentNullException(nameof(range));
}
if (copySource == null)
{
throw new System.ArgumentNullException(nameof(copySource));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "range");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-range", range);
_request.Headers.SetValue("x-ms-copy-source", copySource.ToString());
_request.Headers.SetValue("x-ms-write", "update");
_request.Headers.SetValue("Content-Length", contentLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (sourceRange != null) { _request.Headers.SetValue("x-ms-source-range", sourceRange); }
if (sourceContentCrc64 != null) { _request.Headers.SetValue("x-ms-source-content-crc64", System.Convert.ToBase64String(sourceContentCrc64)); }
if (sourceIfMatchCrc64 != null) { _request.Headers.SetValue("x-ms-source-if-match-crc64", System.Convert.ToBase64String(sourceIfMatchCrc64)); }
if (sourceIfNoneMatchCrc64 != null) { _request.Headers.SetValue("x-ms-source-if-none-match-crc64", System.Convert.ToBase64String(sourceIfNoneMatchCrc64)); }
return _message;
}
/// <summary>
/// Create the File.UploadRangeFromURLAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.UploadRangeFromURLAsync Azure.Response{Azure.Storage.Files.Models.FileUploadRangeFromURLResult}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.FileUploadRangeFromURLResult> UploadRangeFromURLAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 201:
{
// Create the result
Azure.Storage.Files.Models.FileUploadRangeFromURLResult _value = new Azure.Storage.Files.Models.FileUploadRangeFromURLResult();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-content-crc64", out _header))
{
_value.XMSContentCrc64 = System.Convert.FromBase64String(_header);
}
if (response.Headers.TryGetValue("x-ms-request-server-encrypted", out _header))
{
_value.IsServerEncrypted = bool.Parse(_header);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.FileUploadRangeFromURLResult> _result =
new Azure.Response<Azure.Storage.Files.Models.FileUploadRangeFromURLResult>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.UploadRangeFromURLAsync
#region File.GetRangeListAsync
/// <summary>
/// Returns the list of valid ranges for a file.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="range">Specifies the range of bytes over which to list ranges, inclusively.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.StorageFileRangeInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.StorageFileRangeInfo>> GetRangeListAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default,
string range = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.GetRangeList",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = GetRangeListAsync_CreateMessage(
pipeline,
resourceUri,
sharesnapshot,
timeout,
range))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return GetRangeListAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.GetRangeListAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="range">Specifies the range of bytes over which to list ranges, inclusively.</param>
/// <returns>The File.GetRangeListAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage GetRangeListAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string sharesnapshot = default,
int? timeout = default,
string range = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "rangelist");
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
if (range != null) { _request.Headers.SetValue("x-ms-range", range); }
return _message;
}
/// <summary>
/// Create the File.GetRangeListAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.GetRangeListAsync Azure.Response{Azure.Storage.Files.Models.StorageFileRangeInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.StorageFileRangeInfo> GetRangeListAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageFileRangeInfo _value = new Azure.Storage.Files.Models.StorageFileRangeInfo();
_value.Ranges =
System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Select(
_xml.Element(System.Xml.Linq.XName.Get("Ranges", "")).Elements(System.Xml.Linq.XName.Get("Range", "")),
Azure.Storage.Files.Models.Range.FromXml));
// Get response headers
string _header;
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("x-ms-content-length", out _header))
{
_value.FileContentLength = long.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.StorageFileRangeInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.StorageFileRangeInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.GetRangeListAsync
#region File.StartCopyAsync
/// <summary>
/// Copies a blob or file to a destination file within the storage account.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="copySource">Specifies the URL of the source file or blob, up to 2 KB in length. To copy a file to another file within the same storage account, you may use Shared Key to authenticate the source file. If you are copying a file from another storage account, or if you are copying a blob from the same storage account or another storage account, then you must authenticate the source file or blob using a shared access signature. If the source is a public blob, no authentication is required to perform the copy operation. A file in a share snapshot can also be specified as a copy source.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.StorageFileCopyInfo}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.StorageFileCopyInfo>> StartCopyAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
System.Uri copySource,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.StartCopy",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = StartCopyAsync_CreateMessage(
pipeline,
resourceUri,
copySource,
timeout,
metadata))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return StartCopyAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.StartCopyAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="copySource">Specifies the URL of the source file or blob, up to 2 KB in length. To copy a file to another file within the same storage account, you may use Shared Key to authenticate the source file. If you are copying a file from another storage account, or if you are copying a blob from the same storage account or another storage account, then you must authenticate the source file or blob using a shared access signature. If the source is a public blob, no authentication is required to perform the copy operation. A file in a share snapshot can also be specified as a copy source.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="metadata">A name-value pair to associate with a file storage object.</param>
/// <returns>The File.StartCopyAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage StartCopyAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
System.Uri copySource,
int? timeout = default,
System.Collections.Generic.IDictionary<string, string> metadata = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (copySource == null)
{
throw new System.ArgumentNullException(nameof(copySource));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
_request.Headers.SetValue("x-ms-copy-source", copySource.ToString());
if (metadata != null) {
foreach (System.Collections.Generic.KeyValuePair<string, string> _pair in metadata)
{
_request.Headers.SetValue("x-ms-meta-" + _pair.Key, _pair.Value);
}
}
return _message;
}
/// <summary>
/// Create the File.StartCopyAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.StartCopyAsync Azure.Response{Azure.Storage.Files.Models.StorageFileCopyInfo}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.StorageFileCopyInfo> StartCopyAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 202:
{
// Create the result
Azure.Storage.Files.Models.StorageFileCopyInfo _value = new Azure.Storage.Files.Models.StorageFileCopyInfo();
// Get response headers
string _header;
if (response.Headers.TryGetValue("ETag", out _header))
{
_value.ETag = new Azure.Core.Http.ETag(_header);
}
if (response.Headers.TryGetValue("Last-Modified", out _header))
{
_value.LastModified = System.DateTimeOffset.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
if (response.Headers.TryGetValue("x-ms-copy-id", out _header))
{
_value.CopyId = _header;
}
if (response.Headers.TryGetValue("x-ms-copy-status", out _header))
{
_value.CopyStatus = Azure.Storage.Files.FileRestClient.Serialization.ParseCopyStatus(_header);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.StorageFileCopyInfo> _result =
new Azure.Response<Azure.Storage.Files.Models.StorageFileCopyInfo>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.StartCopyAsync
#region File.AbortCopyAsync
/// <summary>
/// Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="copyId">The copy identifier provided in the x-ms-copy-id header of the original Copy File operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response> AbortCopyAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string copyId,
int? timeout = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.AbortCopy",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = AbortCopyAsync_CreateMessage(
pipeline,
resourceUri,
copyId,
timeout))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return AbortCopyAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.AbortCopyAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="copyId">The copy identifier provided in the x-ms-copy-id header of the original Copy File operation.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <returns>The File.AbortCopyAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage AbortCopyAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string copyId,
int? timeout = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (copyId == null)
{
throw new System.ArgumentNullException(nameof(copyId));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "copy");
_request.Uri.AppendQuery("copyid", System.Uri.EscapeDataString(copyId));
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
// Add request headers
_request.Headers.SetValue("x-ms-copy-action", "abort");
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the File.AbortCopyAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.AbortCopyAsync Azure.Response.</returns>
internal static Azure.Response AbortCopyAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 204:
{
return response;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.AbortCopyAsync
#region File.ListHandlesAsync
/// <summary>
/// Lists handles for file
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>An enumeration of handles.</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment>> ListHandlesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string marker = default,
int? maxresults = default,
int? timeout = default,
string sharesnapshot = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.ListHandles",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = ListHandlesAsync_CreateMessage(
pipeline,
resourceUri,
marker,
maxresults,
timeout,
sharesnapshot))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return ListHandlesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.ListHandlesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="maxresults">Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <returns>The File.ListHandlesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage ListHandlesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string marker = default,
int? maxresults = default,
int? timeout = default,
string sharesnapshot = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Get;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "listhandles");
if (marker != null) { _request.Uri.AppendQuery("marker", System.Uri.EscapeDataString(marker)); }
if (maxresults != null) { _request.Uri.AppendQuery("maxresults", System.Uri.EscapeDataString(maxresults.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
// Add request headers
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the File.ListHandlesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.ListHandlesAsync Azure.Response{Azure.Storage.Files.Models.StorageHandlesSegment}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment> ListHandlesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageHandlesSegment _value = Azure.Storage.Files.Models.StorageHandlesSegment.FromXml(_xml.Root);
// Create the response
Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment> _result =
new Azure.Response<Azure.Storage.Files.Models.StorageHandlesSegment>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.ListHandlesAsync
#region File.ForceCloseHandlesAsync
/// <summary>
/// Closes all handles open for given file
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="handleId">Specifies handle ID opened on the file or directory to be closed. Asterix (‘*’) is a wildcard that specifies all handles.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param>
/// <param name="operationName">Operation name.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Azure.Response{Azure.Storage.Files.Models.StorageClosedHandlesSegment}</returns>
public static async System.Threading.Tasks.ValueTask<Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment>> ForceCloseHandlesAsync(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string handleId,
int? timeout = default,
string marker = default,
string sharesnapshot = default,
bool async = true,
string operationName = "Azure.Storage.Files.FileClient.ForceCloseHandles",
System.Threading.CancellationToken cancellationToken = default)
{
Azure.Core.Pipeline.DiagnosticScope _scope = pipeline.Diagnostics.CreateScope(operationName);
try
{
_scope.AddAttribute("url", resourceUri);
_scope.Start();
using (Azure.Core.Pipeline.HttpPipelineMessage _message = ForceCloseHandlesAsync_CreateMessage(
pipeline,
resourceUri,
handleId,
timeout,
marker,
sharesnapshot))
{
if (async)
{
// Send the request asynchronously if we're being called via an async path
await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
}
else
{
// Send the request synchronously through the API that blocks if we're being called via a sync path
// (this is safe because the Task will complete before the user can call Wait)
pipeline.Send(_message, cancellationToken);
}
Azure.Response _response = _message.Response;
cancellationToken.ThrowIfCancellationRequested();
return ForceCloseHandlesAsync_CreateResponse(_response);
}
}
catch (System.Exception ex)
{
_scope.Failed(ex);
throw;
}
finally
{
_scope.Dispose();
}
}
/// <summary>
/// Create the File.ForceCloseHandlesAsync request.
/// </summary>
/// <param name="pipeline">The pipeline used for sending requests.</param>
/// <param name="resourceUri">The URL of the service account, share, directory or file that is the target of the desired operation.</param>
/// <param name="handleId">Specifies handle ID opened on the file or directory to be closed. Asterix (‘*’) is a wildcard that specifies all handles.</param>
/// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting Timeouts for File Service Operations.</a></param>
/// <param name="marker">A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client.</param>
/// <param name="sharesnapshot">The snapshot parameter is an opaque DateTime value that, when present, specifies the share snapshot to query.</param>
/// <returns>The File.ForceCloseHandlesAsync Message.</returns>
internal static Azure.Core.Pipeline.HttpPipelineMessage ForceCloseHandlesAsync_CreateMessage(
Azure.Core.Pipeline.HttpPipeline pipeline,
System.Uri resourceUri,
string handleId,
int? timeout = default,
string marker = default,
string sharesnapshot = default)
{
// Validation
if (resourceUri == null)
{
throw new System.ArgumentNullException(nameof(resourceUri));
}
if (handleId == null)
{
throw new System.ArgumentNullException(nameof(handleId));
}
// Create the request
Azure.Core.Pipeline.HttpPipelineMessage _message = pipeline.CreateMessage();
Azure.Core.Http.Request _request = _message.Request;
// Set the endpoint
_request.Method = Azure.Core.Pipeline.RequestMethod.Put;
_request.Uri.Assign(resourceUri);
_request.Uri.AppendQuery("comp", "forceclosehandles");
if (timeout != null) { _request.Uri.AppendQuery("timeout", System.Uri.EscapeDataString(timeout.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); }
if (marker != null) { _request.Uri.AppendQuery("marker", System.Uri.EscapeDataString(marker)); }
if (sharesnapshot != null) { _request.Uri.AppendQuery("sharesnapshot", System.Uri.EscapeDataString(sharesnapshot)); }
// Add request headers
_request.Headers.SetValue("x-ms-handle-id", handleId);
_request.Headers.SetValue("x-ms-version", "2019-02-02");
return _message;
}
/// <summary>
/// Create the File.ForceCloseHandlesAsync response or throw a failure exception.
/// </summary>
/// <param name="response">The raw Response.</param>
/// <returns>The File.ForceCloseHandlesAsync Azure.Response{Azure.Storage.Files.Models.StorageClosedHandlesSegment}.</returns>
internal static Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment> ForceCloseHandlesAsync_CreateResponse(
Azure.Response response)
{
// Process the response
switch (response.Status)
{
case 200:
{
// Create the result
Azure.Storage.Files.Models.StorageClosedHandlesSegment _value = new Azure.Storage.Files.Models.StorageClosedHandlesSegment();
// Get response headers
string _header;
if (response.Headers.TryGetValue("x-ms-marker", out _header))
{
_value.Marker = _header;
}
if (response.Headers.TryGetValue("x-ms-number-of-handles-closed", out _header))
{
_value.NumberOfHandlesClosed = int.Parse(_header, System.Globalization.CultureInfo.InvariantCulture);
}
// Create the response
Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment> _result =
new Azure.Response<Azure.Storage.Files.Models.StorageClosedHandlesSegment>(
response,
_value);
return _result;
}
default:
{
// Create the result
System.Xml.Linq.XDocument _xml = System.Xml.Linq.XDocument.Load(response.ContentStream, System.Xml.Linq.LoadOptions.PreserveWhitespace);
Azure.Storage.Files.Models.StorageError _value = Azure.Storage.Files.Models.StorageError.FromXml(_xml.Root);
throw _value.CreateException(response);
}
}
}
#endregion File.ForceCloseHandlesAsync
}
#endregion File operations
}
}
#endregion Service
#region Models
#region class AccessPolicy
namespace Azure.Storage.Files.Models
{
/// <summary>
/// An Access policy.
/// </summary>
public partial class AccessPolicy
{
/// <summary>
/// The date-time the policy is active.
/// </summary>
public System.DateTimeOffset? Start { get; set; }
/// <summary>
/// The date-time the policy expires.
/// </summary>
public System.DateTimeOffset? Expiry { get; set; }
/// <summary>
/// The permissions for the ACL policy.
/// </summary>
public string Permission { get; set; }
/// <summary>
/// Prevent direct instantiation of AccessPolicy instances.
/// You can use FilesModelFactory.AccessPolicy instead.
/// </summary>
internal AccessPolicy() { }
/// <summary>
/// Serialize a AccessPolicy instance as XML.
/// </summary>
/// <param name="value">The AccessPolicy instance to serialize.</param>
/// <param name="name">An optional name to use for the root element instead of "AccessPolicy".</param>
/// <param name="ns">An optional namespace to use for the root element instead of "".</param>
/// <returns>The serialized XML element.</returns>
internal static System.Xml.Linq.XElement ToXml(Azure.Storage.Files.Models.AccessPolicy value, string name = "AccessPolicy", string ns = "")
{
System.Diagnostics.Debug.Assert(value != null);
System.Xml.Linq.XElement _element = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get(name, ns));
if (value.Start != null)
{
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Start", ""),
value.Start.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffZ", System.Globalization.CultureInfo.InvariantCulture)));
}
if (value.Expiry != null)
{
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Expiry", ""),
value.Expiry.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffZ", System.Globalization.CultureInfo.InvariantCulture)));
}
if (value.Permission != null)
{
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Permission", ""),
value.Permission));
}
return _element;
}
/// <summary>
/// Deserializes XML into a new AccessPolicy instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized AccessPolicy instance.</returns>
internal static Azure.Storage.Files.Models.AccessPolicy FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.AccessPolicy _value = new Azure.Storage.Files.Models.AccessPolicy();
_child = element.Element(System.Xml.Linq.XName.Get("Start", ""));
if (_child != null)
{
_value.Start = System.DateTimeOffset.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
_child = element.Element(System.Xml.Linq.XName.Get("Expiry", ""));
if (_child != null)
{
_value.Expiry = System.DateTimeOffset.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
_child = element.Element(System.Xml.Linq.XName.Get("Permission", ""));
if (_child != null)
{
_value.Permission = _child.Value;
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.AccessPolicy value);
}
}
#endregion class AccessPolicy
#region enum CopyStatus
namespace Azure.Storage.Files.Models
{
/// <summary>
/// State of the copy operation identified by 'x-ms-copy-id'.
/// </summary>
#pragma warning disable CA1717 // Only FlagsAttribute enums should have plural names
public enum CopyStatus
#pragma warning restore CA1717 // Only FlagsAttribute enums should have plural names
{
/// <summary>
/// pending
/// </summary>
Pending,
/// <summary>
/// success
/// </summary>
Success,
/// <summary>
/// aborted
/// </summary>
Aborted,
/// <summary>
/// failed
/// </summary>
Failed
}
}
namespace Azure.Storage.Files
{
internal static partial class FileRestClient
{
public static partial class Serialization
{
public static string ToString(Azure.Storage.Files.Models.CopyStatus value)
{
return value switch
{
Azure.Storage.Files.Models.CopyStatus.Pending => "pending",
Azure.Storage.Files.Models.CopyStatus.Success => "success",
Azure.Storage.Files.Models.CopyStatus.Aborted => "aborted",
Azure.Storage.Files.Models.CopyStatus.Failed => "failed",
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.CopyStatus value.")
};
}
public static Azure.Storage.Files.Models.CopyStatus ParseCopyStatus(string value)
{
return value switch
{
"pending" => Azure.Storage.Files.Models.CopyStatus.Pending,
"success" => Azure.Storage.Files.Models.CopyStatus.Success,
"aborted" => Azure.Storage.Files.Models.CopyStatus.Aborted,
"failed" => Azure.Storage.Files.Models.CopyStatus.Failed,
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.CopyStatus value.")
};
}
}
}
}
#endregion enum CopyStatus
#region class CorsRule
namespace Azure.Storage.Files.Models
{
/// <summary>
/// CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain.
/// </summary>
public partial class CorsRule
{
/// <summary>
/// The origin domains that are permitted to make a request against the storage service via CORS. The origin domain is the domain from which the request originates. Note that the origin must be an exact case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character '*' to allow all origin domains to make requests via CORS.
/// </summary>
public string AllowedOrigins { get; set; }
/// <summary>
/// The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated)
/// </summary>
public string AllowedMethods { get; set; }
/// <summary>
/// The request headers that the origin domain may specify on the CORS request.
/// </summary>
public string AllowedHeaders { get; set; }
/// <summary>
/// The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer.
/// </summary>
public string ExposedHeaders { get; set; }
/// <summary>
/// The maximum amount time that a browser should cache the preflight OPTIONS request.
/// </summary>
public int MaxAgeInSeconds { get; set; }
/// <summary>
/// Prevent direct instantiation of CorsRule instances.
/// You can use FilesModelFactory.CorsRule instead.
/// </summary>
internal CorsRule() { }
/// <summary>
/// Serialize a CorsRule instance as XML.
/// </summary>
/// <param name="value">The CorsRule instance to serialize.</param>
/// <param name="name">An optional name to use for the root element instead of "CorsRule".</param>
/// <param name="ns">An optional namespace to use for the root element instead of "".</param>
/// <returns>The serialized XML element.</returns>
internal static System.Xml.Linq.XElement ToXml(Azure.Storage.Files.Models.CorsRule value, string name = "CorsRule", string ns = "")
{
System.Diagnostics.Debug.Assert(value != null);
System.Xml.Linq.XElement _element = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get(name, ns));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("AllowedOrigins", ""),
value.AllowedOrigins));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("AllowedMethods", ""),
value.AllowedMethods));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("AllowedHeaders", ""),
value.AllowedHeaders));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("ExposedHeaders", ""),
value.ExposedHeaders));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("MaxAgeInSeconds", ""),
value.MaxAgeInSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture)));
return _element;
}
/// <summary>
/// Deserializes XML into a new CorsRule instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized CorsRule instance.</returns>
internal static Azure.Storage.Files.Models.CorsRule FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
Azure.Storage.Files.Models.CorsRule _value = new Azure.Storage.Files.Models.CorsRule();
_value.AllowedOrigins = element.Element(System.Xml.Linq.XName.Get("AllowedOrigins", "")).Value;
_value.AllowedMethods = element.Element(System.Xml.Linq.XName.Get("AllowedMethods", "")).Value;
_value.AllowedHeaders = element.Element(System.Xml.Linq.XName.Get("AllowedHeaders", "")).Value;
_value.ExposedHeaders = element.Element(System.Xml.Linq.XName.Get("ExposedHeaders", "")).Value;
_value.MaxAgeInSeconds = int.Parse(element.Element(System.Xml.Linq.XName.Get("MaxAgeInSeconds", "")).Value, System.Globalization.CultureInfo.InvariantCulture);
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.CorsRule value);
}
}
#endregion class CorsRule
#region enum DeleteSnapshotsOptionType
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Specifies the option include to delete the base share and all of its snapshots.
/// </summary>
public enum DeleteSnapshotsOptionType
{
/// <summary>
/// include
/// </summary>
Include
}
}
namespace Azure.Storage.Files
{
internal static partial class FileRestClient
{
public static partial class Serialization
{
public static string ToString(Azure.Storage.Files.Models.DeleteSnapshotsOptionType value)
{
return value switch
{
Azure.Storage.Files.Models.DeleteSnapshotsOptionType.Include => "include",
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.DeleteSnapshotsOptionType value.")
};
}
public static Azure.Storage.Files.Models.DeleteSnapshotsOptionType ParseDeleteSnapshotsOptionType(string value)
{
return value switch
{
"include" => Azure.Storage.Files.Models.DeleteSnapshotsOptionType.Include,
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.DeleteSnapshotsOptionType value.")
};
}
}
}
}
#endregion enum DeleteSnapshotsOptionType
#region class DirectoryItem
namespace Azure.Storage.Files.Models
{
/// <summary>
/// A listed directory item.
/// </summary>
internal partial class DirectoryItem
{
/// <summary>
/// Name
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// Prevent direct instantiation of DirectoryItem instances.
/// You can use FilesModelFactory.DirectoryItem instead.
/// </summary>
internal DirectoryItem() { }
/// <summary>
/// Deserializes XML into a new DirectoryItem instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized DirectoryItem instance.</returns>
internal static Azure.Storage.Files.Models.DirectoryItem FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
Azure.Storage.Files.Models.DirectoryItem _value = new Azure.Storage.Files.Models.DirectoryItem();
_value.Name = element.Element(System.Xml.Linq.XName.Get("Name", "")).Value;
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.DirectoryItem value);
}
}
#endregion class DirectoryItem
#region class FailureNoContent
namespace Azure.Storage.Files.Models
{
/// <summary>
/// FailureNoContent
/// </summary>
internal partial class FailureNoContent
{
/// <summary>
/// x-ms-error-code
/// </summary>
public string ErrorCode { get; internal set; }
/// <summary>
/// Prevent direct instantiation of FailureNoContent instances.
/// You can use FilesModelFactory.FailureNoContent instead.
/// </summary>
internal FailureNoContent() { }
}
}
#endregion class FailureNoContent
#region class FileUploadRangeFromURLResult
namespace Azure.Storage.Files.Models
{
/// <summary>
/// File UploadRangeFromURLResult
/// </summary>
internal partial class FileUploadRangeFromURLResult
{
/// <summary>
/// The ETag contains a value which represents the version of the file, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the directory was last modified. Any operation that modifies the share or its properties or metadata updates the last modified time. Operations on files do not affect the last modified time of the share.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// This header is returned so that the client can check for message content integrity. The value of this header is computed by the File service; it is not necessarily the same value as may have been specified in the request headers.
/// </summary>
#pragma warning disable CA1819 // Properties should not return arrays
public byte[] XMSContentCrc64 { get; internal set; }
#pragma warning restore CA1819 // Properties should not return arrays
/// <summary>
/// The value of this header is set to true if the contents of the request are successfully encrypted using the specified algorithm, and false otherwise.
/// </summary>
public bool IsServerEncrypted { get; internal set; }
/// <summary>
/// Prevent direct instantiation of FileUploadRangeFromURLResult instances.
/// You can use FilesModelFactory.FileUploadRangeFromURLResult instead.
/// </summary>
internal FileUploadRangeFromURLResult() { }
}
}
#endregion class FileUploadRangeFromURLResult
#region enum strings FileErrorCode
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Error codes returned by the service
/// </summary>
public partial struct FileErrorCode : System.IEquatable<FileErrorCode>
{
#pragma warning disable CA2211 // Non-constant fields should not be visible
/// <summary>
/// AccountAlreadyExists
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AccountAlreadyExists { get; } = @"AccountAlreadyExists";
/// <summary>
/// AccountBeingCreated
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AccountBeingCreated { get; } = @"AccountBeingCreated";
/// <summary>
/// AccountIsDisabled
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AccountIsDisabled { get; } = @"AccountIsDisabled";
/// <summary>
/// AuthenticationFailed
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AuthenticationFailed { get; } = @"AuthenticationFailed";
/// <summary>
/// AuthorizationFailure
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AuthorizationFailure { get; } = @"AuthorizationFailure";
/// <summary>
/// ConditionHeadersNotSupported
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ConditionHeadersNotSupported { get; } = @"ConditionHeadersNotSupported";
/// <summary>
/// ConditionNotMet
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ConditionNotMet { get; } = @"ConditionNotMet";
/// <summary>
/// EmptyMetadataKey
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode EmptyMetadataKey { get; } = @"EmptyMetadataKey";
/// <summary>
/// InsufficientAccountPermissions
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InsufficientAccountPermissions { get; } = @"InsufficientAccountPermissions";
/// <summary>
/// InternalError
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InternalError { get; } = @"InternalError";
/// <summary>
/// InvalidAuthenticationInfo
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidAuthenticationInfo { get; } = @"InvalidAuthenticationInfo";
/// <summary>
/// InvalidHeaderValue
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidHeaderValue { get; } = @"InvalidHeaderValue";
/// <summary>
/// InvalidHttpVerb
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidHttpVerb { get; } = @"InvalidHttpVerb";
/// <summary>
/// InvalidInput
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidInput { get; } = @"InvalidInput";
/// <summary>
/// InvalidMd5
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidMd5 { get; } = @"InvalidMd5";
/// <summary>
/// InvalidMetadata
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidMetadata { get; } = @"InvalidMetadata";
/// <summary>
/// InvalidQueryParameterValue
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidQueryParameterValue { get; } = @"InvalidQueryParameterValue";
/// <summary>
/// InvalidRange
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidRange { get; } = @"InvalidRange";
/// <summary>
/// InvalidResourceName
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidResourceName { get; } = @"InvalidResourceName";
/// <summary>
/// InvalidUri
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidUri { get; } = @"InvalidUri";
/// <summary>
/// InvalidXmlDocument
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidXmlDocument { get; } = @"InvalidXmlDocument";
/// <summary>
/// InvalidXmlNodeValue
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidXmlNodeValue { get; } = @"InvalidXmlNodeValue";
/// <summary>
/// Md5Mismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode Md5Mismatch { get; } = @"Md5Mismatch";
/// <summary>
/// MetadataTooLarge
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode MetadataTooLarge { get; } = @"MetadataTooLarge";
/// <summary>
/// MissingContentLengthHeader
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode MissingContentLengthHeader { get; } = @"MissingContentLengthHeader";
/// <summary>
/// MissingRequiredQueryParameter
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode MissingRequiredQueryParameter { get; } = @"MissingRequiredQueryParameter";
/// <summary>
/// MissingRequiredHeader
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode MissingRequiredHeader { get; } = @"MissingRequiredHeader";
/// <summary>
/// MissingRequiredXmlNode
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode MissingRequiredXmlNode { get; } = @"MissingRequiredXmlNode";
/// <summary>
/// MultipleConditionHeadersNotSupported
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode MultipleConditionHeadersNotSupported { get; } = @"MultipleConditionHeadersNotSupported";
/// <summary>
/// OperationTimedOut
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode OperationTimedOut { get; } = @"OperationTimedOut";
/// <summary>
/// OutOfRangeInput
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode OutOfRangeInput { get; } = @"OutOfRangeInput";
/// <summary>
/// OutOfRangeQueryParameterValue
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode OutOfRangeQueryParameterValue { get; } = @"OutOfRangeQueryParameterValue";
/// <summary>
/// RequestBodyTooLarge
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode RequestBodyTooLarge { get; } = @"RequestBodyTooLarge";
/// <summary>
/// ResourceTypeMismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ResourceTypeMismatch { get; } = @"ResourceTypeMismatch";
/// <summary>
/// RequestUrlFailedToParse
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode RequestUrlFailedToParse { get; } = @"RequestUrlFailedToParse";
/// <summary>
/// ResourceAlreadyExists
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ResourceAlreadyExists { get; } = @"ResourceAlreadyExists";
/// <summary>
/// ResourceNotFound
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ResourceNotFound { get; } = @"ResourceNotFound";
/// <summary>
/// ServerBusy
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ServerBusy { get; } = @"ServerBusy";
/// <summary>
/// UnsupportedHeader
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode UnsupportedHeader { get; } = @"UnsupportedHeader";
/// <summary>
/// UnsupportedXmlNode
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode UnsupportedXmlNode { get; } = @"UnsupportedXmlNode";
/// <summary>
/// UnsupportedQueryParameter
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode UnsupportedQueryParameter { get; } = @"UnsupportedQueryParameter";
/// <summary>
/// UnsupportedHttpVerb
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode UnsupportedHttpVerb { get; } = @"UnsupportedHttpVerb";
/// <summary>
/// CannotDeleteFileOrDirectory
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode CannotDeleteFileOrDirectory { get; } = @"CannotDeleteFileOrDirectory";
/// <summary>
/// ClientCacheFlushDelay
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ClientCacheFlushDelay { get; } = @"ClientCacheFlushDelay";
/// <summary>
/// DeletePending
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode DeletePending { get; } = @"DeletePending";
/// <summary>
/// DirectoryNotEmpty
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode DirectoryNotEmpty { get; } = @"DirectoryNotEmpty";
/// <summary>
/// FileLockConflict
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode FileLockConflict { get; } = @"FileLockConflict";
/// <summary>
/// InvalidFileOrDirectoryPathName
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode InvalidFileOrDirectoryPathName { get; } = @"InvalidFileOrDirectoryPathName";
/// <summary>
/// ParentNotFound
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ParentNotFound { get; } = @"ParentNotFound";
/// <summary>
/// ReadOnlyAttribute
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ReadOnlyAttribute { get; } = @"ReadOnlyAttribute";
/// <summary>
/// ShareAlreadyExists
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareAlreadyExists { get; } = @"ShareAlreadyExists";
/// <summary>
/// ShareBeingDeleted
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareBeingDeleted { get; } = @"ShareBeingDeleted";
/// <summary>
/// ShareDisabled
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareDisabled { get; } = @"ShareDisabled";
/// <summary>
/// ShareNotFound
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareNotFound { get; } = @"ShareNotFound";
/// <summary>
/// SharingViolation
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode SharingViolation { get; } = @"SharingViolation";
/// <summary>
/// ShareSnapshotInProgress
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareSnapshotInProgress { get; } = @"ShareSnapshotInProgress";
/// <summary>
/// ShareSnapshotCountExceeded
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareSnapshotCountExceeded { get; } = @"ShareSnapshotCountExceeded";
/// <summary>
/// ShareSnapshotOperationNotSupported
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareSnapshotOperationNotSupported { get; } = @"ShareSnapshotOperationNotSupported";
/// <summary>
/// ShareHasSnapshots
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ShareHasSnapshots { get; } = @"ShareHasSnapshots";
/// <summary>
/// ContainerQuotaDowngradeNotAllowed
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode ContainerQuotaDowngradeNotAllowed { get; } = @"ContainerQuotaDowngradeNotAllowed";
/// <summary>
/// AuthorizationSourceIPMismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AuthorizationSourceIPMismatch { get; } = @"AuthorizationSourceIPMismatch";
/// <summary>
/// AuthorizationProtocolMismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AuthorizationProtocolMismatch { get; } = @"AuthorizationProtocolMismatch";
/// <summary>
/// AuthorizationPermissionMismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AuthorizationPermissionMismatch { get; } = @"AuthorizationPermissionMismatch";
/// <summary>
/// AuthorizationServiceMismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AuthorizationServiceMismatch { get; } = @"AuthorizationServiceMismatch";
/// <summary>
/// AuthorizationResourceTypeMismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode AuthorizationResourceTypeMismatch { get; } = @"AuthorizationResourceTypeMismatch";
/// <summary>
/// FeatureVersionMismatch
/// </summary>
public static Azure.Storage.Files.Models.FileErrorCode FeatureVersionMismatch { get; } = @"FeatureVersionMismatch";
#pragma warning restore CA2211 // Non-constant fields should not be visible
/// <summary>
/// The FileErrorCode value.
/// </summary>
private readonly string _value;
/// <summary>
/// Creates a new FileErrorCode instance.
/// </summary>
/// <param name="value">The FileErrorCode value.</param>
private FileErrorCode(string value) { _value = value; }
/// <summary>
/// Check if two FileErrorCode instances are equal.
/// </summary>
/// <param name="other">The instance to compare to.</param>
/// <returns>True if they're equal, false otherwise.</returns>
public bool Equals(Azure.Storage.Files.Models.FileErrorCode other) => _value.Equals(other._value, System.StringComparison.InvariantCulture);
/// <summary>
/// Check if two FileErrorCode instances are equal.
/// </summary>
/// <param name="o">The instance to compare to.</param>
/// <returns>True if they're equal, false otherwise.</returns>
public override bool Equals(object o) => o is Azure.Storage.Files.Models.FileErrorCode other && Equals(other);
/// <summary>
/// Get a hash code for the FileErrorCode.
/// </summary>
/// <returns>Hash code for the FileErrorCode.</returns>
public override int GetHashCode() => _value.GetHashCode();
/// <summary>
/// Convert the FileErrorCode to a string.
/// </summary>
/// <returns>String representation of the FileErrorCode.</returns>
public override string ToString() => _value;
#pragma warning disable CA2225 // Operator overloads have named alternates
/// <summary>
/// Convert a string a FileErrorCode.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The FileErrorCode value.</returns>
public static implicit operator FileErrorCode(string value) => new Azure.Storage.Files.Models.FileErrorCode(value);
#pragma warning restore CA2225 // Operator overloads have named alternates
/// <summary>
/// Convert an FileErrorCode to a string.
/// </summary>
/// <param name="value">The FileErrorCode value.</param>
/// <returns>String representation of the FileErrorCode value.</returns>
public static implicit operator string(Azure.Storage.Files.Models.FileErrorCode value) => value._value;
/// <summary>
/// Check if two FileErrorCode instances are equal.
/// </summary>
/// <param name="left">The first instance to compare.</param>
/// <param name="right">The second instance to compare.</param>
/// <returns>True if they're equal, false otherwise.</returns>
public static bool operator ==(Azure.Storage.Files.Models.FileErrorCode left, Azure.Storage.Files.Models.FileErrorCode right) => left.Equals(right);
/// <summary>
/// Check if two FileErrorCode instances are not equal.
/// </summary>
/// <param name="left">The first instance to compare.</param>
/// <param name="right">The second instance to compare.</param>
/// <returns>True if they're not equal, false otherwise.</returns>
public static bool operator !=(Azure.Storage.Files.Models.FileErrorCode left, Azure.Storage.Files.Models.FileErrorCode right) => !left.Equals(right);
}
}
#endregion enum strings FileErrorCode
#region class FileItem
namespace Azure.Storage.Files.Models
{
/// <summary>
/// A listed file item.
/// </summary>
internal partial class FileItem
{
/// <summary>
/// Name
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// File properties.
/// </summary>
public Azure.Storage.Files.Models.FileProperty Properties { get; internal set; }
/// <summary>
/// Creates a new FileItem instance
/// </summary>
public FileItem()
: this(false)
{
}
/// <summary>
/// Creates a new FileItem instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal FileItem(bool skipInitialization)
{
if (!skipInitialization)
{
Properties = new Azure.Storage.Files.Models.FileProperty();
}
}
/// <summary>
/// Deserializes XML into a new FileItem instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized FileItem instance.</returns>
internal static Azure.Storage.Files.Models.FileItem FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
Azure.Storage.Files.Models.FileItem _value = new Azure.Storage.Files.Models.FileItem(true);
_value.Name = element.Element(System.Xml.Linq.XName.Get("Name", "")).Value;
_value.Properties = Azure.Storage.Files.Models.FileProperty.FromXml(element.Element(System.Xml.Linq.XName.Get("Properties", "")));
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.FileItem value);
}
}
#endregion class FileItem
#region class FileProperty
namespace Azure.Storage.Files.Models
{
/// <summary>
/// File properties.
/// </summary>
internal partial class FileProperty
{
/// <summary>
/// Content length of the file. This value may not be up-to-date since an SMB client may have modified the file locally. The value of Content-Length may not reflect that fact until the handle is closed or the op-lock is broken. To retrieve current property values, call Get File Properties.
/// </summary>
public long ContentLength { get; internal set; }
/// <summary>
/// Prevent direct instantiation of FileProperty instances.
/// You can use FilesModelFactory.FileProperty instead.
/// </summary>
internal FileProperty() { }
/// <summary>
/// Deserializes XML into a new FileProperty instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized FileProperty instance.</returns>
internal static Azure.Storage.Files.Models.FileProperty FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
Azure.Storage.Files.Models.FileProperty _value = new Azure.Storage.Files.Models.FileProperty();
_value.ContentLength = long.Parse(element.Element(System.Xml.Linq.XName.Get("Content-Length", "")).Value, System.Globalization.CultureInfo.InvariantCulture);
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.FileProperty value);
}
}
#endregion class FileProperty
#region enum FileRangeWriteType
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Specify one of the following options: - Update: Writes the bytes specified by the request body into the specified range. The Range and Content-Length headers must match to perform the update. - Clear: Clears the specified range and releases the space used in storage for that range. To clear a range, set the Content-Length header to zero, and set the Range header to a value that indicates the range to clear, up to maximum file size.
/// </summary>
public enum FileRangeWriteType
{
/// <summary>
/// update
/// </summary>
Update,
/// <summary>
/// clear
/// </summary>
Clear
}
}
namespace Azure.Storage.Files
{
internal static partial class FileRestClient
{
public static partial class Serialization
{
public static string ToString(Azure.Storage.Files.Models.FileRangeWriteType value)
{
return value switch
{
Azure.Storage.Files.Models.FileRangeWriteType.Update => "update",
Azure.Storage.Files.Models.FileRangeWriteType.Clear => "clear",
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.FileRangeWriteType value.")
};
}
public static Azure.Storage.Files.Models.FileRangeWriteType ParseFileRangeWriteType(string value)
{
return value switch
{
"update" => Azure.Storage.Files.Models.FileRangeWriteType.Update,
"clear" => Azure.Storage.Files.Models.FileRangeWriteType.Clear,
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.FileRangeWriteType value.")
};
}
}
}
}
#endregion enum FileRangeWriteType
#region class FileServiceProperties
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Storage service properties.
/// </summary>
public partial class FileServiceProperties
{
/// <summary>
/// A summary of request statistics grouped by API in hourly aggregates for files.
/// </summary>
public Azure.Storage.Files.Models.Metrics HourMetrics { get; set; }
/// <summary>
/// A summary of request statistics grouped by API in minute aggregates for files.
/// </summary>
public Azure.Storage.Files.Models.Metrics MinuteMetrics { get; set; }
/// <summary>
/// The set of CORS rules.
/// </summary>
public System.Collections.Generic.IList<Azure.Storage.Files.Models.CorsRule> Cors { get; internal set; }
/// <summary>
/// Creates a new FileServiceProperties instance
/// </summary>
public FileServiceProperties()
: this(false)
{
}
/// <summary>
/// Creates a new FileServiceProperties instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal FileServiceProperties(bool skipInitialization)
{
if (!skipInitialization)
{
HourMetrics = new Azure.Storage.Files.Models.Metrics();
MinuteMetrics = new Azure.Storage.Files.Models.Metrics();
Cors = new System.Collections.Generic.List<Azure.Storage.Files.Models.CorsRule>();
}
}
/// <summary>
/// Serialize a FileServiceProperties instance as XML.
/// </summary>
/// <param name="value">The FileServiceProperties instance to serialize.</param>
/// <param name="name">An optional name to use for the root element instead of "StorageServiceProperties".</param>
/// <param name="ns">An optional namespace to use for the root element instead of "".</param>
/// <returns>The serialized XML element.</returns>
internal static System.Xml.Linq.XElement ToXml(Azure.Storage.Files.Models.FileServiceProperties value, string name = "StorageServiceProperties", string ns = "")
{
System.Diagnostics.Debug.Assert(value != null);
System.Xml.Linq.XElement _element = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get(name, ns));
if (value.HourMetrics != null)
{
_element.Add(Azure.Storage.Files.Models.Metrics.ToXml(value.HourMetrics, "HourMetrics", ""));
}
if (value.MinuteMetrics != null)
{
_element.Add(Azure.Storage.Files.Models.Metrics.ToXml(value.MinuteMetrics, "MinuteMetrics", ""));
}
if (value.Cors != null)
{
System.Xml.Linq.XElement _elements = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get("Cors", ""));
foreach (Azure.Storage.Files.Models.CorsRule _child in value.Cors)
{
_elements.Add(Azure.Storage.Files.Models.CorsRule.ToXml(_child));
}
_element.Add(_elements);
}
return _element;
}
/// <summary>
/// Deserializes XML into a new FileServiceProperties instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized FileServiceProperties instance.</returns>
internal static Azure.Storage.Files.Models.FileServiceProperties FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.FileServiceProperties _value = new Azure.Storage.Files.Models.FileServiceProperties(true);
_child = element.Element(System.Xml.Linq.XName.Get("HourMetrics", ""));
if (_child != null)
{
_value.HourMetrics = Azure.Storage.Files.Models.Metrics.FromXml(_child);
}
_child = element.Element(System.Xml.Linq.XName.Get("MinuteMetrics", ""));
if (_child != null)
{
_value.MinuteMetrics = Azure.Storage.Files.Models.Metrics.FromXml(_child);
}
_child = element.Element(System.Xml.Linq.XName.Get("Cors", ""));
if (_child != null)
{
_value.Cors = System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Select(
_child.Elements(System.Xml.Linq.XName.Get("CorsRule", "")),
e => Azure.Storage.Files.Models.CorsRule.FromXml(e)));
}
else
{
_value.Cors = new System.Collections.Generic.List<Azure.Storage.Files.Models.CorsRule>();
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.FileServiceProperties value);
}
}
#endregion class FileServiceProperties
#region class FilesAndDirectoriesSegment
namespace Azure.Storage.Files.Models
{
/// <summary>
/// An enumeration of directories and files.
/// </summary>
internal partial class FilesAndDirectoriesSegment
{
/// <summary>
/// ServiceEndpoint
/// </summary>
public string ServiceEndpoint { get; internal set; }
/// <summary>
/// ShareName
/// </summary>
public string ShareName { get; internal set; }
/// <summary>
/// ShareSnapshot
/// </summary>
public string ShareSnapshot { get; internal set; }
/// <summary>
/// DirectoryPath
/// </summary>
public string DirectoryPath { get; internal set; }
/// <summary>
/// Prefix
/// </summary>
public string Prefix { get; internal set; }
/// <summary>
/// Marker
/// </summary>
public string Marker { get; internal set; }
/// <summary>
/// MaxResults
/// </summary>
public int? MaxResults { get; internal set; }
/// <summary>
/// NextMarker
/// </summary>
public string NextMarker { get; internal set; }
/// <summary>
/// DirectoryItems
/// </summary>
public System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.DirectoryItem> DirectoryItems { get; internal set; }
/// <summary>
/// FileItems
/// </summary>
public System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.FileItem> FileItems { get; internal set; }
/// <summary>
/// Creates a new FilesAndDirectoriesSegment instance
/// </summary>
public FilesAndDirectoriesSegment()
: this(false)
{
}
/// <summary>
/// Creates a new FilesAndDirectoriesSegment instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal FilesAndDirectoriesSegment(bool skipInitialization)
{
if (!skipInitialization)
{
DirectoryItems = new System.Collections.Generic.List<Azure.Storage.Files.Models.DirectoryItem>();
FileItems = new System.Collections.Generic.List<Azure.Storage.Files.Models.FileItem>();
}
}
/// <summary>
/// Deserializes XML into a new FilesAndDirectoriesSegment instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized FilesAndDirectoriesSegment instance.</returns>
internal static Azure.Storage.Files.Models.FilesAndDirectoriesSegment FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
System.Xml.Linq.XAttribute _attribute;
Azure.Storage.Files.Models.FilesAndDirectoriesSegment _value = new Azure.Storage.Files.Models.FilesAndDirectoriesSegment(true);
_value.ServiceEndpoint = element.Attribute(System.Xml.Linq.XName.Get("ServiceEndpoint", "")).Value;
_value.ShareName = element.Attribute(System.Xml.Linq.XName.Get("ShareName", "")).Value;
_attribute = element.Attribute(System.Xml.Linq.XName.Get("ShareSnapshot", ""));
if (_attribute != null)
{
_value.ShareSnapshot = _attribute.Value;
}
_value.DirectoryPath = element.Attribute(System.Xml.Linq.XName.Get("DirectoryPath", "")).Value;
_child = element.Element(System.Xml.Linq.XName.Get("Prefix", ""));
if (_child != null)
{
_value.Prefix = _child.Value;
}
_child = element.Element(System.Xml.Linq.XName.Get("Marker", ""));
if (_child != null)
{
_value.Marker = _child.Value;
}
_child = element.Element(System.Xml.Linq.XName.Get("MaxResults", ""));
if (_child != null)
{
_value.MaxResults = int.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
_value.NextMarker = element.Element(System.Xml.Linq.XName.Get("NextMarker", "")).Value;
_child = element.Element(System.Xml.Linq.XName.Get("Entries", ""));
if (_child != null)
{
_value.DirectoryItems = System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Select(
_child.Elements(System.Xml.Linq.XName.Get("Directory", "")),
e => Azure.Storage.Files.Models.DirectoryItem.FromXml(e)));
}
else
{
_value.DirectoryItems = new System.Collections.Generic.List<Azure.Storage.Files.Models.DirectoryItem>();
}
_child = element.Element(System.Xml.Linq.XName.Get("Entries", ""));
if (_child != null)
{
_value.FileItems = System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Select(
_child.Elements(System.Xml.Linq.XName.Get("File", "")),
e => Azure.Storage.Files.Models.FileItem.FromXml(e)));
}
else
{
_value.FileItems = new System.Collections.Generic.List<Azure.Storage.Files.Models.FileItem>();
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.FilesAndDirectoriesSegment value);
}
}
#endregion class FilesAndDirectoriesSegment
#region class FlattenedStorageFileProperties
namespace Azure.Storage.Files.Models
{
/// <summary>
/// FlattenedStorageFileProperties
/// </summary>
internal partial class FlattenedStorageFileProperties
{
/// <summary>
/// Returns the date and time the file was last modified. Any operation that modifies the file or its properties updates the last modified time.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// A set of name-value pairs associated with this file as user-defined metadata.
/// </summary>
public System.Collections.Generic.IDictionary<string, string> Metadata { get; internal set; }
/// <summary>
/// The number of bytes present in the response body.
/// </summary>
public long ContentLength { get; internal set; }
/// <summary>
/// The content type specified for the file. The default content type is 'application/octet-stream'
/// </summary>
public string ContentType { get; internal set; }
/// <summary>
/// Indicates the range of bytes returned if the client requested a subset of the file by setting the Range request header.
/// </summary>
public string ContentRange { get; internal set; }
/// <summary>
/// The ETag contains a value that you can use to perform operations conditionally, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// If the file has an MD5 hash and the request is to read the full file, this response header is returned so that the client can check for message content integrity. If the request is to read a specified range and the 'x-ms-range-get-content-md5' is set to true, then the request returns an MD5 hash for the range, as long as the range size is less than or equal to 4 MB. If neither of these sets of conditions is true, then no value is returned for the 'Content-MD5' header.
/// </summary>
#pragma warning disable CA1819 // Properties should not return arrays
public byte[] ContentHash { get; internal set; }
#pragma warning restore CA1819 // Properties should not return arrays
/// <summary>
/// Returns the value that was specified for the Content-Encoding request header.
/// </summary>
public System.Collections.Generic.IEnumerable<string> ContentEncoding { get; internal set; }
/// <summary>
/// Returned if it was previously specified for the file.
/// </summary>
public string CacheControl { get; internal set; }
/// <summary>
/// Returns the value that was specified for the 'x-ms-content-disposition' header and specifies how to process the response.
/// </summary>
public string ContentDisposition { get; internal set; }
/// <summary>
/// Returns the value that was specified for the Content-Language request header.
/// </summary>
public System.Collections.Generic.IEnumerable<string> ContentLanguage { get; internal set; }
/// <summary>
/// Indicates that the service supports requests for partial file content.
/// </summary>
public string AcceptRanges { get; internal set; }
/// <summary>
/// Conclusion time of the last attempted Copy File operation where this file was the destination file. This value can specify the time of a completed, aborted, or failed copy attempt.
/// </summary>
public System.DateTimeOffset CopyCompletionTime { get; internal set; }
/// <summary>
/// Only appears when x-ms-copy-status is failed or pending. Describes cause of fatal or non-fatal copy operation failure.
/// </summary>
public string CopyStatusDescription { get; internal set; }
/// <summary>
/// String identifier for the last attempted Copy File operation where this file was the destination file.
/// </summary>
public string CopyId { get; internal set; }
/// <summary>
/// Contains the number of bytes copied and the total bytes in the source in the last attempted Copy File operation where this file was the destination file. Can show between 0 and Content-Length bytes copied.
/// </summary>
public string CopyProgress { get; internal set; }
/// <summary>
/// URL up to 2KB in length that specifies the source file used in the last attempted Copy File operation where this file was the destination file.
/// </summary>
public System.Uri CopySource { get; internal set; }
/// <summary>
/// State of the copy operation identified by 'x-ms-copy-id'.
/// </summary>
public Azure.Storage.Files.Models.CopyStatus CopyStatus { get; internal set; }
/// <summary>
/// If the file has a MD5 hash, and if request contains range header (Range or x-ms-range), this response header is returned with the value of the whole file's MD5 value. This value may or may not be equal to the value returned in Content-MD5 header, with the latter calculated from the requested range.
/// </summary>
#pragma warning disable CA1819 // Properties should not return arrays
public byte[] FileContentHash { get; internal set; }
#pragma warning restore CA1819 // Properties should not return arrays
/// <summary>
/// The value of this header is set to true if the file data and application metadata are completely encrypted using the specified algorithm. Otherwise, the value is set to false (when the file is unencrypted, or if only parts of the file/application metadata are encrypted).
/// </summary>
public bool IsServerEncrypted { get; internal set; }
/// <summary>
/// Attributes set for the file.
/// </summary>
public string FileAttributes { get; internal set; }
/// <summary>
/// Creation time for the file.
/// </summary>
public System.DateTimeOffset FileCreationTime { get; internal set; }
/// <summary>
/// Last write time for the file.
/// </summary>
public System.DateTimeOffset FileLastWriteTime { get; internal set; }
/// <summary>
/// Change time for the file.
/// </summary>
public System.DateTimeOffset FileChangeTime { get; internal set; }
/// <summary>
/// Key of the permission set for the file.
/// </summary>
public string FilePermissionKey { get; internal set; }
/// <summary>
/// The fileId of the file.
/// </summary>
public string FileId { get; internal set; }
/// <summary>
/// The parent fileId of the file.
/// </summary>
public string FileParentId { get; internal set; }
/// <summary>
/// Content
/// </summary>
public System.IO.Stream Content { get; internal set; }
/// <summary>
/// Creates a new FlattenedStorageFileProperties instance
/// </summary>
public FlattenedStorageFileProperties()
{
Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
ContentEncoding = new System.Collections.Generic.List<string>();
ContentLanguage = new System.Collections.Generic.List<string>();
}
}
}
#endregion class FlattenedStorageFileProperties
#region enum ListSharesIncludeType
namespace Azure.Storage.Files.Models
{
/// <summary>
/// ListSharesIncludeType values
/// </summary>
public enum ListSharesIncludeType
{
/// <summary>
/// snapshots
/// </summary>
Snapshots,
/// <summary>
/// metadata
/// </summary>
Metadata
}
}
namespace Azure.Storage.Files
{
internal static partial class FileRestClient
{
public static partial class Serialization
{
public static string ToString(Azure.Storage.Files.Models.ListSharesIncludeType value)
{
return value switch
{
Azure.Storage.Files.Models.ListSharesIncludeType.Snapshots => "snapshots",
Azure.Storage.Files.Models.ListSharesIncludeType.Metadata => "metadata",
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.ListSharesIncludeType value.")
};
}
public static Azure.Storage.Files.Models.ListSharesIncludeType ParseListSharesIncludeType(string value)
{
return value switch
{
"snapshots" => Azure.Storage.Files.Models.ListSharesIncludeType.Snapshots,
"metadata" => Azure.Storage.Files.Models.ListSharesIncludeType.Metadata,
_ => throw new System.ArgumentOutOfRangeException(nameof(value), value, "Unknown Azure.Storage.Files.Models.ListSharesIncludeType value.")
};
}
}
}
}
#endregion enum ListSharesIncludeType
#region class Metrics
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Storage Analytics metrics for file service.
/// </summary>
public partial class Metrics
{
/// <summary>
/// The version of Storage Analytics to configure.
/// </summary>
public string Version { get; set; }
/// <summary>
/// Indicates whether metrics are enabled for the File service.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Indicates whether metrics should generate summary statistics for called API operations.
/// </summary>
public bool? IncludeAPIs { get; set; }
/// <summary>
/// The retention policy.
/// </summary>
public Azure.Storage.Files.Models.RetentionPolicy RetentionPolicy { get; set; }
/// <summary>
/// Creates a new Metrics instance
/// </summary>
public Metrics()
: this(false)
{
}
/// <summary>
/// Creates a new Metrics instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal Metrics(bool skipInitialization)
{
if (!skipInitialization)
{
RetentionPolicy = new Azure.Storage.Files.Models.RetentionPolicy();
}
}
/// <summary>
/// Serialize a Metrics instance as XML.
/// </summary>
/// <param name="value">The Metrics instance to serialize.</param>
/// <param name="name">An optional name to use for the root element instead of "Metrics".</param>
/// <param name="ns">An optional namespace to use for the root element instead of "".</param>
/// <returns>The serialized XML element.</returns>
internal static System.Xml.Linq.XElement ToXml(Azure.Storage.Files.Models.Metrics value, string name = "Metrics", string ns = "")
{
System.Diagnostics.Debug.Assert(value != null);
System.Xml.Linq.XElement _element = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get(name, ns));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Version", ""),
value.Version));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Enabled", ""),
#pragma warning disable CA1308 // Normalize strings to uppercase
value.Enabled.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant()));
#pragma warning restore CA1308 // Normalize strings to uppercase
if (value.IncludeAPIs != null)
{
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("IncludeAPIs", ""),
#pragma warning disable CA1308 // Normalize strings to uppercase
value.IncludeAPIs.Value.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant()));
#pragma warning restore CA1308 // Normalize strings to uppercase
}
if (value.RetentionPolicy != null)
{
_element.Add(Azure.Storage.Files.Models.RetentionPolicy.ToXml(value.RetentionPolicy, "RetentionPolicy", ""));
}
return _element;
}
/// <summary>
/// Deserializes XML into a new Metrics instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized Metrics instance.</returns>
internal static Azure.Storage.Files.Models.Metrics FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.Metrics _value = new Azure.Storage.Files.Models.Metrics(true);
_value.Version = element.Element(System.Xml.Linq.XName.Get("Version", "")).Value;
_value.Enabled = bool.Parse(element.Element(System.Xml.Linq.XName.Get("Enabled", "")).Value);
_child = element.Element(System.Xml.Linq.XName.Get("IncludeAPIs", ""));
if (_child != null)
{
_value.IncludeAPIs = bool.Parse(_child.Value);
}
_child = element.Element(System.Xml.Linq.XName.Get("RetentionPolicy", ""));
if (_child != null)
{
_value.RetentionPolicy = Azure.Storage.Files.Models.RetentionPolicy.FromXml(_child);
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.Metrics value);
}
}
#endregion class Metrics
#region class PermissionInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// PermissionInfo
/// </summary>
public partial class PermissionInfo
{
/// <summary>
/// Key of the permission set for the directory/file.
/// </summary>
public string FilePermissionKey { get; internal set; }
/// <summary>
/// Prevent direct instantiation of PermissionInfo instances.
/// You can use FilesModelFactory.PermissionInfo instead.
/// </summary>
internal PermissionInfo() { }
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new PermissionInfo instance for mocking.
/// </summary>
public static PermissionInfo PermissionInfo(
string filePermissionKey)
{
return new PermissionInfo()
{
FilePermissionKey = filePermissionKey,
};
}
}
}
#endregion class PermissionInfo
#region class Range
namespace Azure.Storage.Files.Models
{
/// <summary>
/// An Azure Storage file range.
/// </summary>
public partial class Range
{
/// <summary>
/// Start of the range.
/// </summary>
public long Start { get; internal set; }
/// <summary>
/// End of the range.
/// </summary>
public long End { get; internal set; }
/// <summary>
/// Prevent direct instantiation of Range instances.
/// You can use FilesModelFactory.Range instead.
/// </summary>
internal Range() { }
/// <summary>
/// Deserializes XML into a new Range instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized Range instance.</returns>
internal static Azure.Storage.Files.Models.Range FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
Azure.Storage.Files.Models.Range _value = new Azure.Storage.Files.Models.Range();
_value.Start = long.Parse(element.Element(System.Xml.Linq.XName.Get("Start", "")).Value, System.Globalization.CultureInfo.InvariantCulture);
_value.End = long.Parse(element.Element(System.Xml.Linq.XName.Get("End", "")).Value, System.Globalization.CultureInfo.InvariantCulture);
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.Range value);
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new Range instance for mocking.
/// </summary>
public static Range Range(
long start,
long end)
{
return new Range()
{
Start = start,
End = end,
};
}
}
}
#endregion class Range
#region class RawStorageDirectoryInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// RawStorageDirectoryInfo
/// </summary>
internal partial class RawStorageDirectoryInfo
{
/// <summary>
/// The ETag contains a value which represents the version of the directory, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the share was last modified. Any operation that modifies the directory or its properties updates the last modified time. Operations on files do not affect the last modified time of the directory.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// Key of the permission set for the directory.
/// </summary>
public string FilePermissionKey { get; internal set; }
/// <summary>
/// Attributes set for the directory.
/// </summary>
public string FileAttributes { get; internal set; }
/// <summary>
/// Creation time for the directory.
/// </summary>
public System.DateTimeOffset FileCreationTime { get; internal set; }
/// <summary>
/// Last write time for the directory.
/// </summary>
public System.DateTimeOffset FileLastWriteTime { get; internal set; }
/// <summary>
/// Change time for the directory.
/// </summary>
public System.DateTimeOffset FileChangeTime { get; internal set; }
/// <summary>
/// The fileId of the directory.
/// </summary>
public string FileId { get; internal set; }
/// <summary>
/// The parent fileId of the directory.
/// </summary>
public string FileParentId { get; internal set; }
/// <summary>
/// Prevent direct instantiation of RawStorageDirectoryInfo instances.
/// You can use FilesModelFactory.RawStorageDirectoryInfo instead.
/// </summary>
internal RawStorageDirectoryInfo() { }
}
}
#endregion class RawStorageDirectoryInfo
#region class RawStorageDirectoryProperties
namespace Azure.Storage.Files.Models
{
/// <summary>
/// RawStorageDirectoryProperties
/// </summary>
internal partial class RawStorageDirectoryProperties
{
/// <summary>
/// A set of name-value pairs that contain metadata for the directory.
/// </summary>
public System.Collections.Generic.IDictionary<string, string> Metadata { get; internal set; }
/// <summary>
/// The ETag contains a value that you can use to perform operations conditionally, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the Directory was last modified. Operations on files within the directory do not affect the last modified time of the directory.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// The value of this header is set to true if the directory metadata is completely encrypted using the specified algorithm. Otherwise, the value is set to false.
/// </summary>
public bool IsServerEncrypted { get; internal set; }
/// <summary>
/// Attributes set for the directory.
/// </summary>
public string FileAttributes { get; internal set; }
/// <summary>
/// Creation time for the directory.
/// </summary>
public System.DateTimeOffset FileCreationTime { get; internal set; }
/// <summary>
/// Last write time for the directory.
/// </summary>
public System.DateTimeOffset FileLastWriteTime { get; internal set; }
/// <summary>
/// Change time for the directory.
/// </summary>
public System.DateTimeOffset FileChangeTime { get; internal set; }
/// <summary>
/// Key of the permission set for the directory.
/// </summary>
public string FilePermissionKey { get; internal set; }
/// <summary>
/// The fileId of the directory.
/// </summary>
public string FileId { get; internal set; }
/// <summary>
/// The parent fileId of the directory.
/// </summary>
public string FileParentId { get; internal set; }
/// <summary>
/// Creates a new RawStorageDirectoryProperties instance
/// </summary>
public RawStorageDirectoryProperties()
{
Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
}
}
}
#endregion class RawStorageDirectoryProperties
#region class RawStorageFileInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// RawStorageFileInfo
/// </summary>
internal partial class RawStorageFileInfo
{
/// <summary>
/// The ETag contains a value which represents the version of the file, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the share was last modified. Any operation that modifies the directory or its properties updates the last modified time. Operations on files do not affect the last modified time of the directory.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// The value of this header is set to true if the contents of the request are successfully encrypted using the specified algorithm, and false otherwise.
/// </summary>
public bool IsServerEncrypted { get; internal set; }
/// <summary>
/// Key of the permission set for the file.
/// </summary>
public string FilePermissionKey { get; internal set; }
/// <summary>
/// Attributes set for the file.
/// </summary>
public string FileAttributes { get; internal set; }
/// <summary>
/// Creation time for the file.
/// </summary>
public System.DateTimeOffset FileCreationTime { get; internal set; }
/// <summary>
/// Last write time for the file.
/// </summary>
public System.DateTimeOffset FileLastWriteTime { get; internal set; }
/// <summary>
/// Change time for the file.
/// </summary>
public System.DateTimeOffset FileChangeTime { get; internal set; }
/// <summary>
/// The fileId of the file.
/// </summary>
public string FileId { get; internal set; }
/// <summary>
/// The parent fileId of the file.
/// </summary>
public string FileParentId { get; internal set; }
/// <summary>
/// Prevent direct instantiation of RawStorageFileInfo instances.
/// You can use FilesModelFactory.RawStorageFileInfo instead.
/// </summary>
internal RawStorageFileInfo() { }
}
}
#endregion class RawStorageFileInfo
#region class RawStorageFileProperties
namespace Azure.Storage.Files.Models
{
/// <summary>
/// RawStorageFileProperties
/// </summary>
internal partial class RawStorageFileProperties
{
/// <summary>
/// Returns the date and time the file was last modified. The date format follows RFC 1123. Any operation that modifies the file or its properties updates the last modified time.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// A set of name-value pairs associated with this file as user-defined metadata.
/// </summary>
public System.Collections.Generic.IDictionary<string, string> Metadata { get; internal set; }
/// <summary>
/// Returns the type File. Reserved for future use.
/// </summary>
public Azure.Storage.Files.Models.Header FileType { get; internal set; }
/// <summary>
/// The size of the file in bytes. This header returns the value of the 'x-ms-content-length' header that is stored with the file.
/// </summary>
public long ContentLength { get; internal set; }
/// <summary>
/// The content type specified for the file. The default content type is 'application/octet-stream'
/// </summary>
public string ContentType { get; internal set; }
/// <summary>
/// The ETag contains a value that you can use to perform operations conditionally, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// If the Content-MD5 header has been set for the file, the Content-MD5 response header is returned so that the client can check for message content integrity.
/// </summary>
#pragma warning disable CA1819 // Properties should not return arrays
public byte[] ContentHash { get; internal set; }
#pragma warning restore CA1819 // Properties should not return arrays
/// <summary>
/// If the Content-Encoding request header has previously been set for the file, the Content-Encoding value is returned in this header.
/// </summary>
public System.Collections.Generic.IEnumerable<string> ContentEncoding { get; internal set; }
/// <summary>
/// If the Cache-Control request header has previously been set for the file, the Cache-Control value is returned in this header.
/// </summary>
public string CacheControl { get; internal set; }
/// <summary>
/// Returns the value that was specified for the 'x-ms-content-disposition' header and specifies how to process the response.
/// </summary>
public string ContentDisposition { get; internal set; }
/// <summary>
/// Returns the value that was specified for the Content-Language request header.
/// </summary>
public System.Collections.Generic.IEnumerable<string> ContentLanguage { get; internal set; }
/// <summary>
/// Conclusion time of the last attempted Copy File operation where this file was the destination file. This value can specify the time of a completed, aborted, or failed copy attempt.
/// </summary>
public System.DateTimeOffset CopyCompletionTime { get; internal set; }
/// <summary>
/// Only appears when x-ms-copy-status is failed or pending. Describes cause of fatal or non-fatal copy operation failure.
/// </summary>
public string CopyStatusDescription { get; internal set; }
/// <summary>
/// String identifier for the last attempted Copy File operation where this file was the destination file.
/// </summary>
public string CopyId { get; internal set; }
/// <summary>
/// Contains the number of bytes copied and the total bytes in the source in the last attempted Copy File operation where this file was the destination file. Can show between 0 and Content-Length bytes copied.
/// </summary>
public string CopyProgress { get; internal set; }
/// <summary>
/// URL up to 2KB in length that specifies the source file used in the last attempted Copy File operation where this file was the destination file.
/// </summary>
public string CopySource { get; internal set; }
/// <summary>
/// State of the copy operation identified by 'x-ms-copy-id'.
/// </summary>
public Azure.Storage.Files.Models.CopyStatus CopyStatus { get; internal set; }
/// <summary>
/// The value of this header is set to true if the file data and application metadata are completely encrypted using the specified algorithm. Otherwise, the value is set to false (when the file is unencrypted, or if only parts of the file/application metadata are encrypted).
/// </summary>
public bool IsServerEncrypted { get; internal set; }
/// <summary>
/// Attributes set for the file.
/// </summary>
public string FileAttributes { get; internal set; }
/// <summary>
/// Creation time for the file.
/// </summary>
public System.DateTimeOffset FileCreationTime { get; internal set; }
/// <summary>
/// Last write time for the file.
/// </summary>
public System.DateTimeOffset FileLastWriteTime { get; internal set; }
/// <summary>
/// Change time for the file.
/// </summary>
public System.DateTimeOffset FileChangeTime { get; internal set; }
/// <summary>
/// Key of the permission set for the file.
/// </summary>
public string FilePermissionKey { get; internal set; }
/// <summary>
/// The fileId of the file.
/// </summary>
public string FileId { get; internal set; }
/// <summary>
/// The parent fileId of the file.
/// </summary>
public string FileParentId { get; internal set; }
/// <summary>
/// Creates a new RawStorageFileProperties instance
/// </summary>
public RawStorageFileProperties()
{
Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
ContentEncoding = new System.Collections.Generic.List<string>();
ContentLanguage = new System.Collections.Generic.List<string>();
}
}
}
#endregion class RawStorageFileProperties
#region class RetentionPolicy
namespace Azure.Storage.Files.Models
{
/// <summary>
/// The retention policy.
/// </summary>
public partial class RetentionPolicy
{
/// <summary>
/// Indicates whether a retention policy is enabled for the File service. If false, metrics data is retained, and the user is responsible for deleting it.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Indicates the number of days that metrics data should be retained. All data older than this value will be deleted. Metrics data is deleted on a best-effort basis after the retention period expires.
/// </summary>
public int? Days { get; set; }
/// <summary>
/// Prevent direct instantiation of RetentionPolicy instances.
/// You can use FilesModelFactory.RetentionPolicy instead.
/// </summary>
internal RetentionPolicy() { }
/// <summary>
/// Serialize a RetentionPolicy instance as XML.
/// </summary>
/// <param name="value">The RetentionPolicy instance to serialize.</param>
/// <param name="name">An optional name to use for the root element instead of "RetentionPolicy".</param>
/// <param name="ns">An optional namespace to use for the root element instead of "".</param>
/// <returns>The serialized XML element.</returns>
internal static System.Xml.Linq.XElement ToXml(Azure.Storage.Files.Models.RetentionPolicy value, string name = "RetentionPolicy", string ns = "")
{
System.Diagnostics.Debug.Assert(value != null);
System.Xml.Linq.XElement _element = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get(name, ns));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Enabled", ""),
#pragma warning disable CA1308 // Normalize strings to uppercase
value.Enabled.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant()));
#pragma warning restore CA1308 // Normalize strings to uppercase
if (value.Days != null)
{
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Days", ""),
value.Days.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
return _element;
}
/// <summary>
/// Deserializes XML into a new RetentionPolicy instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized RetentionPolicy instance.</returns>
internal static Azure.Storage.Files.Models.RetentionPolicy FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.RetentionPolicy _value = new Azure.Storage.Files.Models.RetentionPolicy();
_value.Enabled = bool.Parse(element.Element(System.Xml.Linq.XName.Get("Enabled", "")).Value);
_child = element.Element(System.Xml.Linq.XName.Get("Days", ""));
if (_child != null)
{
_value.Days = int.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.RetentionPolicy value);
}
}
#endregion class RetentionPolicy
#region class ShareInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// ShareInfo
/// </summary>
public partial class ShareInfo
{
/// <summary>
/// The ETag contains a value which represents the version of the share, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the share was last modified. Any operation that modifies the share or its properties or metadata updates the last modified time. Operations on files do not affect the last modified time of the share.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// Prevent direct instantiation of ShareInfo instances.
/// You can use FilesModelFactory.ShareInfo instead.
/// </summary>
internal ShareInfo() { }
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new ShareInfo instance for mocking.
/// </summary>
public static ShareInfo ShareInfo(
Azure.Core.Http.ETag eTag,
System.DateTimeOffset lastModified)
{
return new ShareInfo()
{
ETag = eTag,
LastModified = lastModified,
};
}
}
}
#endregion class ShareInfo
#region class ShareItem
namespace Azure.Storage.Files.Models
{
/// <summary>
/// A listed Azure Storage share item.
/// </summary>
public partial class ShareItem
{
/// <summary>
/// Name
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// Snapshot
/// </summary>
public string Snapshot { get; internal set; }
/// <summary>
/// Properties of a share.
/// </summary>
public Azure.Storage.Files.Models.ShareItemProperties Properties { get; internal set; }
/// <summary>
/// Metadata
/// </summary>
public System.Collections.Generic.IDictionary<string, string> Metadata { get; internal set; }
/// <summary>
/// Creates a new ShareItem instance
/// </summary>
public ShareItem()
: this(false)
{
}
/// <summary>
/// Creates a new ShareItem instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal ShareItem(bool skipInitialization)
{
if (!skipInitialization)
{
Properties = new Azure.Storage.Files.Models.ShareItemProperties();
Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// Deserializes XML into a new ShareItem instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized ShareItem instance.</returns>
internal static Azure.Storage.Files.Models.ShareItem FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.ShareItem _value = new Azure.Storage.Files.Models.ShareItem(true);
_value.Name = element.Element(System.Xml.Linq.XName.Get("Name", "")).Value;
_child = element.Element(System.Xml.Linq.XName.Get("Snapshot", ""));
if (_child != null)
{
_value.Snapshot = _child.Value;
}
_value.Properties = Azure.Storage.Files.Models.ShareItemProperties.FromXml(element.Element(System.Xml.Linq.XName.Get("Properties", "")));
_value.Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
_child = element.Element(System.Xml.Linq.XName.Get("Metadata", ""));
if (_child != null)
{
foreach (System.Xml.Linq.XElement _pair in _child.Elements())
{
_value.Metadata[_pair.Name.LocalName] = _pair.Value;
}
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.ShareItem value);
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new ShareItem instance for mocking.
/// </summary>
public static ShareItem ShareItem(
string name,
Azure.Storage.Files.Models.ShareItemProperties properties,
string snapshot = default,
System.Collections.Generic.IDictionary<string, string> metadata = default)
{
return new ShareItem()
{
Name = name,
Properties = properties,
Snapshot = snapshot,
Metadata = metadata,
};
}
}
}
#endregion class ShareItem
#region class ShareItemProperties
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Properties of a share.
/// </summary>
public partial class ShareItemProperties
{
/// <summary>
/// Last-Modified
/// </summary>
public System.DateTimeOffset? LastModified { get; internal set; }
/// <summary>
/// Etag
/// </summary>
public Azure.Core.Http.ETag? Etag { get; internal set; }
/// <summary>
/// Quota
/// </summary>
public int? Quota { get; internal set; }
/// <summary>
/// Prevent direct instantiation of ShareItemProperties instances.
/// You can use FilesModelFactory.ShareItemProperties instead.
/// </summary>
internal ShareItemProperties() { }
/// <summary>
/// Deserializes XML into a new ShareItemProperties instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized ShareItemProperties instance.</returns>
internal static Azure.Storage.Files.Models.ShareItemProperties FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.ShareItemProperties _value = new Azure.Storage.Files.Models.ShareItemProperties();
_child = element.Element(System.Xml.Linq.XName.Get("Last-Modified", ""));
if (_child != null)
{
_value.LastModified = System.DateTimeOffset.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
_child = element.Element(System.Xml.Linq.XName.Get("Etag", ""));
if (_child != null)
{
_value.Etag = new Azure.Core.Http.ETag(_child.Value);
}
_child = element.Element(System.Xml.Linq.XName.Get("Quota", ""));
if (_child != null)
{
_value.Quota = int.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.ShareItemProperties value);
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new ShareItemProperties instance for mocking.
/// </summary>
public static ShareItemProperties ShareItemProperties(
System.DateTimeOffset? lastModified = default,
Azure.Core.Http.ETag? etag = default,
int? quota = default)
{
return new ShareItemProperties()
{
LastModified = lastModified,
Etag = etag,
Quota = quota,
};
}
}
}
#endregion class ShareItemProperties
#region class ShareProperties
namespace Azure.Storage.Files.Models
{
/// <summary>
/// ShareProperties
/// </summary>
public partial class ShareProperties
{
/// <summary>
/// A set of name-value pairs that contain the user-defined metadata of the share.
/// </summary>
public System.Collections.Generic.IDictionary<string, string> Metadata { get; internal set; }
/// <summary>
/// The ETag contains a value that you can use to perform operations conditionally, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the share was last modified. Any operation that modifies the share or its properties updates the last modified time. Operations on files do not affect the last modified time of the share.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// Returns the current share quota in GB.
/// </summary>
public int Quota { get; internal set; }
/// <summary>
/// Creates a new ShareProperties instance
/// </summary>
public ShareProperties()
{
Metadata = new System.Collections.Generic.Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new ShareProperties instance for mocking.
/// </summary>
public static ShareProperties ShareProperties(
System.Collections.Generic.IDictionary<string, string> metadata,
Azure.Core.Http.ETag eTag,
System.DateTimeOffset lastModified,
int quota)
{
return new ShareProperties()
{
Metadata = metadata,
ETag = eTag,
LastModified = lastModified,
Quota = quota,
};
}
}
}
#endregion class ShareProperties
#region class ShareSnapshotInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// ShareSnapshotInfo
/// </summary>
public partial class ShareSnapshotInfo
{
/// <summary>
/// This header is a DateTime value that uniquely identifies the share snapshot. The value of this header may be used in subsequent requests to access the share snapshot. This value is opaque.
/// </summary>
public string Snapshot { get; internal set; }
/// <summary>
/// The ETag contains a value which represents the version of the share snapshot, in quotes. A share snapshot cannot be modified, so the ETag of a given share snapshot never changes. However, if new metadata was supplied with the Snapshot Share request then the ETag of the share snapshot differs from that of the base share. If no metadata was specified with the request, the ETag of the share snapshot is identical to that of the base share at the time the share snapshot was taken.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the share was last modified. A share snapshot cannot be modified, so the last modified time of a given share snapshot never changes. However, if new metadata was supplied with the Snapshot Share request then the last modified time of the share snapshot differs from that of the base share. If no metadata was specified with the request, the last modified time of the share snapshot is identical to that of the base share at the time the share snapshot was taken.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// Prevent direct instantiation of ShareSnapshotInfo instances.
/// You can use FilesModelFactory.ShareSnapshotInfo instead.
/// </summary>
internal ShareSnapshotInfo() { }
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new ShareSnapshotInfo instance for mocking.
/// </summary>
public static ShareSnapshotInfo ShareSnapshotInfo(
string snapshot,
Azure.Core.Http.ETag eTag,
System.DateTimeOffset lastModified)
{
return new ShareSnapshotInfo()
{
Snapshot = snapshot,
ETag = eTag,
LastModified = lastModified,
};
}
}
}
#endregion class ShareSnapshotInfo
#region class ShareStatistics
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Stats for the share.
/// </summary>
public partial class ShareStatistics
{
/// <summary>
/// The approximate size of the data stored in bytes, rounded up to the nearest gigabyte. Note that this value may not include all recently created or recently resized files.
/// </summary>
public int ShareUsageBytes { get; internal set; }
/// <summary>
/// Prevent direct instantiation of ShareStatistics instances.
/// You can use FilesModelFactory.ShareStatistics instead.
/// </summary>
internal ShareStatistics() { }
/// <summary>
/// Deserializes XML into a new ShareStatistics instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized ShareStatistics instance.</returns>
internal static Azure.Storage.Files.Models.ShareStatistics FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
Azure.Storage.Files.Models.ShareStatistics _value = new Azure.Storage.Files.Models.ShareStatistics();
_value.ShareUsageBytes = int.Parse(element.Element(System.Xml.Linq.XName.Get("ShareUsageBytes", "")).Value, System.Globalization.CultureInfo.InvariantCulture);
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.ShareStatistics value);
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new ShareStatistics instance for mocking.
/// </summary>
public static ShareStatistics ShareStatistics(
int shareUsageBytes)
{
return new ShareStatistics()
{
ShareUsageBytes = shareUsageBytes,
};
}
}
}
#endregion class ShareStatistics
#region class SharesSegment
namespace Azure.Storage.Files.Models
{
/// <summary>
/// An enumeration of shares.
/// </summary>
internal partial class SharesSegment
{
/// <summary>
/// ServiceEndpoint
/// </summary>
public string ServiceEndpoint { get; internal set; }
/// <summary>
/// Prefix
/// </summary>
public string Prefix { get; internal set; }
/// <summary>
/// Marker
/// </summary>
public string Marker { get; internal set; }
/// <summary>
/// MaxResults
/// </summary>
public int? MaxResults { get; internal set; }
/// <summary>
/// ShareItems
/// </summary>
public System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.ShareItem> ShareItems { get; internal set; }
/// <summary>
/// NextMarker
/// </summary>
public string NextMarker { get; internal set; }
/// <summary>
/// Creates a new SharesSegment instance
/// </summary>
public SharesSegment()
: this(false)
{
}
/// <summary>
/// Creates a new SharesSegment instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal SharesSegment(bool skipInitialization)
{
if (!skipInitialization)
{
ShareItems = new System.Collections.Generic.List<Azure.Storage.Files.Models.ShareItem>();
}
}
/// <summary>
/// Deserializes XML into a new SharesSegment instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized SharesSegment instance.</returns>
internal static Azure.Storage.Files.Models.SharesSegment FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.SharesSegment _value = new Azure.Storage.Files.Models.SharesSegment(true);
_value.ServiceEndpoint = element.Attribute(System.Xml.Linq.XName.Get("ServiceEndpoint", "")).Value;
_child = element.Element(System.Xml.Linq.XName.Get("Prefix", ""));
if (_child != null)
{
_value.Prefix = _child.Value;
}
_child = element.Element(System.Xml.Linq.XName.Get("Marker", ""));
if (_child != null)
{
_value.Marker = _child.Value;
}
_child = element.Element(System.Xml.Linq.XName.Get("MaxResults", ""));
if (_child != null)
{
_value.MaxResults = int.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
_child = element.Element(System.Xml.Linq.XName.Get("Shares", ""));
if (_child != null)
{
_value.ShareItems = System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Select(
_child.Elements(System.Xml.Linq.XName.Get("Share", "")),
e => Azure.Storage.Files.Models.ShareItem.FromXml(e)));
}
else
{
_value.ShareItems = new System.Collections.Generic.List<Azure.Storage.Files.Models.ShareItem>();
}
_value.NextMarker = element.Element(System.Xml.Linq.XName.Get("NextMarker", "")).Value;
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.SharesSegment value);
}
}
#endregion class SharesSegment
#region class SignedIdentifier
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Signed identifier.
/// </summary>
public partial class SignedIdentifier
{
/// <summary>
/// A unique id.
/// </summary>
public string Id { get; set; }
/// <summary>
/// The access policy.
/// </summary>
public Azure.Storage.Files.Models.AccessPolicy AccessPolicy { get; set; }
/// <summary>
/// Creates a new SignedIdentifier instance
/// </summary>
public SignedIdentifier()
: this(false)
{
}
/// <summary>
/// Creates a new SignedIdentifier instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal SignedIdentifier(bool skipInitialization)
{
if (!skipInitialization)
{
AccessPolicy = new Azure.Storage.Files.Models.AccessPolicy();
}
}
/// <summary>
/// Serialize a SignedIdentifier instance as XML.
/// </summary>
/// <param name="value">The SignedIdentifier instance to serialize.</param>
/// <param name="name">An optional name to use for the root element instead of "SignedIdentifier".</param>
/// <param name="ns">An optional namespace to use for the root element instead of "".</param>
/// <returns>The serialized XML element.</returns>
internal static System.Xml.Linq.XElement ToXml(Azure.Storage.Files.Models.SignedIdentifier value, string name = "SignedIdentifier", string ns = "")
{
System.Diagnostics.Debug.Assert(value != null);
System.Xml.Linq.XElement _element = new System.Xml.Linq.XElement(System.Xml.Linq.XName.Get(name, ns));
_element.Add(new System.Xml.Linq.XElement(
System.Xml.Linq.XName.Get("Id", ""),
value.Id));
if (value.AccessPolicy != null)
{
_element.Add(Azure.Storage.Files.Models.AccessPolicy.ToXml(value.AccessPolicy, "AccessPolicy", ""));
}
return _element;
}
/// <summary>
/// Deserializes XML into a new SignedIdentifier instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized SignedIdentifier instance.</returns>
internal static Azure.Storage.Files.Models.SignedIdentifier FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.SignedIdentifier _value = new Azure.Storage.Files.Models.SignedIdentifier(true);
_value.Id = element.Element(System.Xml.Linq.XName.Get("Id", "")).Value;
_child = element.Element(System.Xml.Linq.XName.Get("AccessPolicy", ""));
if (_child != null)
{
_value.AccessPolicy = Azure.Storage.Files.Models.AccessPolicy.FromXml(_child);
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.SignedIdentifier value);
}
}
#endregion class SignedIdentifier
#region class StorageClosedHandlesSegment
namespace Azure.Storage.Files.Models
{
/// <summary>
/// StorageClosedHandlesSegment
/// </summary>
public partial class StorageClosedHandlesSegment
{
/// <summary>
/// A string describing next handle to be closed. It is returned when more handles need to be closed to complete the request.
/// </summary>
public string Marker { get; internal set; }
/// <summary>
/// Contains count of number of handles closed.
/// </summary>
public int NumberOfHandlesClosed { get; internal set; }
/// <summary>
/// Prevent direct instantiation of StorageClosedHandlesSegment instances.
/// You can use FilesModelFactory.StorageClosedHandlesSegment instead.
/// </summary>
internal StorageClosedHandlesSegment() { }
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new StorageClosedHandlesSegment instance for mocking.
/// </summary>
public static StorageClosedHandlesSegment StorageClosedHandlesSegment(
string marker,
int numberOfHandlesClosed)
{
return new StorageClosedHandlesSegment()
{
Marker = marker,
NumberOfHandlesClosed = numberOfHandlesClosed,
};
}
}
}
#endregion class StorageClosedHandlesSegment
#region class StorageError
namespace Azure.Storage.Files.Models
{
/// <summary>
/// StorageError
/// </summary>
internal partial class StorageError
{
/// <summary>
/// Message
/// </summary>
public string Message { get; internal set; }
/// <summary>
/// Code
/// </summary>
public string Code { get; internal set; }
/// <summary>
/// Prevent direct instantiation of StorageError instances.
/// You can use FilesModelFactory.StorageError instead.
/// </summary>
internal StorageError() { }
/// <summary>
/// Deserializes XML into a new StorageError instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized StorageError instance.</returns>
internal static Azure.Storage.Files.Models.StorageError FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.StorageError _value = new Azure.Storage.Files.Models.StorageError();
_child = element.Element(System.Xml.Linq.XName.Get("Message", ""));
if (_child != null)
{
_value.Message = _child.Value;
}
_child = element.Element(System.Xml.Linq.XName.Get("Code", ""));
if (_child != null)
{
_value.Code = _child.Value;
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.StorageError value);
}
}
#endregion class StorageError
#region class StorageFileCopyInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// StorageFileCopyInfo
/// </summary>
public partial class StorageFileCopyInfo
{
/// <summary>
/// If the copy is completed, contains the ETag of the destination file. If the copy is not complete, contains the ETag of the empty file created at the start of the copy.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date/time that the copy operation to the destination file completed.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// String identifier for this copy operation. Use with Get File or Get File Properties to check the status of this copy operation, or pass to Abort Copy File to abort a pending copy.
/// </summary>
public string CopyId { get; internal set; }
/// <summary>
/// State of the copy operation identified by x-ms-copy-id.
/// </summary>
public Azure.Storage.Files.Models.CopyStatus CopyStatus { get; internal set; }
/// <summary>
/// Prevent direct instantiation of StorageFileCopyInfo instances.
/// You can use FilesModelFactory.StorageFileCopyInfo instead.
/// </summary>
internal StorageFileCopyInfo() { }
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new StorageFileCopyInfo instance for mocking.
/// </summary>
public static StorageFileCopyInfo StorageFileCopyInfo(
Azure.Core.Http.ETag eTag,
System.DateTimeOffset lastModified,
string copyId,
Azure.Storage.Files.Models.CopyStatus copyStatus)
{
return new StorageFileCopyInfo()
{
ETag = eTag,
LastModified = lastModified,
CopyId = copyId,
CopyStatus = copyStatus,
};
}
}
}
#endregion class StorageFileCopyInfo
#region class StorageFileRangeInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// StorageFileRangeInfo
/// </summary>
public partial class StorageFileRangeInfo
{
/// <summary>
/// The date/time that the file was last modified. Any operation that modifies the file, including an update of the file's metadata or properties, changes the file's last modified time.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// The ETag contains a value which represents the version of the file, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// The size of the file in bytes.
/// </summary>
public long FileContentLength { get; internal set; }
/// <summary>
/// A list of non-overlapping valid ranges, sorted by increasing address range.
/// </summary>
public System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.Range> Ranges { get; internal set; }
/// <summary>
/// Creates a new StorageFileRangeInfo instance
/// </summary>
public StorageFileRangeInfo()
{
Ranges = new System.Collections.Generic.List<Azure.Storage.Files.Models.Range>();
}
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new StorageFileRangeInfo instance for mocking.
/// </summary>
public static StorageFileRangeInfo StorageFileRangeInfo(
System.DateTimeOffset lastModified,
Azure.Core.Http.ETag eTag,
long fileContentLength,
System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.Range> ranges)
{
return new StorageFileRangeInfo()
{
LastModified = lastModified,
ETag = eTag,
FileContentLength = fileContentLength,
Ranges = ranges,
};
}
}
}
#endregion class StorageFileRangeInfo
#region class StorageFileUploadInfo
namespace Azure.Storage.Files.Models
{
/// <summary>
/// StorageFileUploadInfo
/// </summary>
public partial class StorageFileUploadInfo
{
/// <summary>
/// The ETag contains a value which represents the version of the file, in quotes.
/// </summary>
public Azure.Core.Http.ETag ETag { get; internal set; }
/// <summary>
/// Returns the date and time the directory was last modified. Any operation that modifies the share or its properties or metadata updates the last modified time. Operations on files do not affect the last modified time of the share.
/// </summary>
public System.DateTimeOffset LastModified { get; internal set; }
/// <summary>
/// This header is returned so that the client can check for message content integrity. The value of this header is computed by the File service; it is not necessarily the same value as may have been specified in the request headers.
/// </summary>
#pragma warning disable CA1819 // Properties should not return arrays
public byte[] ContentHash { get; internal set; }
#pragma warning restore CA1819 // Properties should not return arrays
/// <summary>
/// The value of this header is set to true if the contents of the request are successfully encrypted using the specified algorithm, and false otherwise.
/// </summary>
public bool IsServerEncrypted { get; internal set; }
/// <summary>
/// Prevent direct instantiation of StorageFileUploadInfo instances.
/// You can use FilesModelFactory.StorageFileUploadInfo instead.
/// </summary>
internal StorageFileUploadInfo() { }
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new StorageFileUploadInfo instance for mocking.
/// </summary>
public static StorageFileUploadInfo StorageFileUploadInfo(
Azure.Core.Http.ETag eTag,
System.DateTimeOffset lastModified,
byte[] contentHash,
bool isServerEncrypted)
{
return new StorageFileUploadInfo()
{
ETag = eTag,
LastModified = lastModified,
ContentHash = contentHash,
IsServerEncrypted = isServerEncrypted,
};
}
}
}
#endregion class StorageFileUploadInfo
#region class StorageHandle
namespace Azure.Storage.Files.Models
{
/// <summary>
/// A listed Azure Storage handle item.
/// </summary>
public partial class StorageHandle
{
/// <summary>
/// XSMB service handle ID
/// </summary>
public string HandleId { get; internal set; }
/// <summary>
/// File or directory name including full path starting from share root
/// </summary>
public string Path { get; internal set; }
/// <summary>
/// FileId uniquely identifies the file or directory.
/// </summary>
public string FileId { get; internal set; }
/// <summary>
/// ParentId uniquely identifies the parent directory of the object.
/// </summary>
public string ParentId { get; internal set; }
/// <summary>
/// SMB session ID in context of which the file handle was opened
/// </summary>
public string SessionId { get; internal set; }
/// <summary>
/// Client IP that opened the handle
/// </summary>
public string ClientIp { get; internal set; }
/// <summary>
/// Time when the session that previously opened the handle has last been reconnected. (UTC)
/// </summary>
public System.DateTimeOffset OpenTime { get; internal set; }
/// <summary>
/// Time handle was last connected to (UTC)
/// </summary>
public System.DateTimeOffset? LastReconnectTime { get; internal set; }
/// <summary>
/// Prevent direct instantiation of StorageHandle instances.
/// You can use FilesModelFactory.StorageHandle instead.
/// </summary>
internal StorageHandle() { }
/// <summary>
/// Deserializes XML into a new StorageHandle instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized StorageHandle instance.</returns>
internal static Azure.Storage.Files.Models.StorageHandle FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.StorageHandle _value = new Azure.Storage.Files.Models.StorageHandle();
_value.HandleId = element.Element(System.Xml.Linq.XName.Get("HandleId", "")).Value;
_value.Path = element.Element(System.Xml.Linq.XName.Get("Path", "")).Value;
_value.FileId = element.Element(System.Xml.Linq.XName.Get("FileId", "")).Value;
_child = element.Element(System.Xml.Linq.XName.Get("ParentId", ""));
if (_child != null)
{
_value.ParentId = _child.Value;
}
_value.SessionId = element.Element(System.Xml.Linq.XName.Get("SessionId", "")).Value;
_value.ClientIp = element.Element(System.Xml.Linq.XName.Get("ClientIp", "")).Value;
_value.OpenTime = System.DateTimeOffset.Parse(element.Element(System.Xml.Linq.XName.Get("OpenTime", "")).Value, System.Globalization.CultureInfo.InvariantCulture);
_child = element.Element(System.Xml.Linq.XName.Get("LastReconnectTime", ""));
if (_child != null)
{
_value.LastReconnectTime = System.DateTimeOffset.Parse(_child.Value, System.Globalization.CultureInfo.InvariantCulture);
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.StorageHandle value);
}
/// <summary>
/// FilesModelFactory provides utilities for mocking.
/// </summary>
public static partial class FilesModelFactory
{
/// <summary>
/// Creates a new StorageHandle instance for mocking.
/// </summary>
public static StorageHandle StorageHandle(
string handleId,
string path,
string fileId,
string sessionId,
string clientIp,
System.DateTimeOffset openTime,
string parentId = default,
System.DateTimeOffset? lastReconnectTime = default)
{
return new StorageHandle()
{
HandleId = handleId,
Path = path,
FileId = fileId,
SessionId = sessionId,
ClientIp = clientIp,
OpenTime = openTime,
ParentId = parentId,
LastReconnectTime = lastReconnectTime,
};
}
}
}
#endregion class StorageHandle
#region class StorageHandlesSegment
namespace Azure.Storage.Files.Models
{
/// <summary>
/// An enumeration of handles.
/// </summary>
internal partial class StorageHandlesSegment
{
/// <summary>
/// NextMarker
/// </summary>
public string NextMarker { get; internal set; }
/// <summary>
/// Handles
/// </summary>
public System.Collections.Generic.IEnumerable<Azure.Storage.Files.Models.StorageHandle> Handles { get; internal set; }
/// <summary>
/// Creates a new StorageHandlesSegment instance
/// </summary>
public StorageHandlesSegment()
: this(false)
{
}
/// <summary>
/// Creates a new StorageHandlesSegment instance
/// </summary>
/// <param name="skipInitialization">Whether to skip initializing nested objects.</param>
internal StorageHandlesSegment(bool skipInitialization)
{
if (!skipInitialization)
{
Handles = new System.Collections.Generic.List<Azure.Storage.Files.Models.StorageHandle>();
}
}
/// <summary>
/// Deserializes XML into a new StorageHandlesSegment instance.
/// </summary>
/// <param name="element">The XML element to deserialize.</param>
/// <returns>A deserialized StorageHandlesSegment instance.</returns>
internal static Azure.Storage.Files.Models.StorageHandlesSegment FromXml(System.Xml.Linq.XElement element)
{
System.Diagnostics.Debug.Assert(element != null);
System.Xml.Linq.XElement _child;
Azure.Storage.Files.Models.StorageHandlesSegment _value = new Azure.Storage.Files.Models.StorageHandlesSegment(true);
_value.NextMarker = element.Element(System.Xml.Linq.XName.Get("NextMarker", "")).Value;
_child = element.Element(System.Xml.Linq.XName.Get("Entries", ""));
if (_child != null)
{
_value.Handles = System.Linq.Enumerable.ToList(
System.Linq.Enumerable.Select(
_child.Elements(System.Xml.Linq.XName.Get("Handle", "")),
e => Azure.Storage.Files.Models.StorageHandle.FromXml(e)));
}
else
{
_value.Handles = new System.Collections.Generic.List<Azure.Storage.Files.Models.StorageHandle>();
}
CustomizeFromXml(element, _value);
return _value;
}
static partial void CustomizeFromXml(System.Xml.Linq.XElement element, Azure.Storage.Files.Models.StorageHandlesSegment value);
}
}
#endregion class StorageHandlesSegment
#region enum Header
namespace Azure.Storage.Files.Models
{
/// <summary>
/// Returns the type File. Reserved for future use.
/// </summary>
public enum Header
{
/// <summary>
/// File
/// </summary>
File
}
}
#endregion enum Header
#endregion Models
| 53.114851 | 623 | 0.573733 | [
"MIT"
] | helgeu/azure-sdk-for-net | sdk/storage/Azure.Storage.Files/src/Generated/FileRestClient.cs | 486,166 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.