content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class OneSkyLocalizationService : ModuleRules
{
public OneSkyLocalizationService(TargetInfo Target)
{
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"CoreUObject",
"Engine",
"InputCore",
"Slate",
"SlateCore",
"EditorStyle",
"LocalizationService",
"Json",
"Internationalization",
"HTTP",
"Serialization",
"Localization",
"MainFrame",
}
);
PrivateIncludePathModuleNames.AddRange(
new string[] {
"LocalizationService",
"Json",
"Internationalization",
"HTTP",
}
);
}
}
| 21.473684 | 60 | 0.531863 | [
"MIT"
] | armroyce/Unreal | UnrealEngine-4.11.2-release/Engine/Plugins/Developer/OneSkyLocalizationService/Source/OneSkyLocalizationService/OneSkyLocalizationService.Build.cs | 816 | C# |
namespace Charming.Types.AppConfiguration
{
using System;
using Charming;
using Charming.Types.Internal;
public class ConfigurationStorePrivateEndpointConnection : Resource<ConfigurationStorePrivateEndpointConnectionProperties>
{
public ConfigurationStorePrivateEndpointConnection() => (Type, ApiVersion) = ("Microsoft.AppConfiguration/configurationStores/privateEndpointConnections", "2019-11-01-preview");
public ConfigurationStorePrivateEndpointConnection(string name) : this() => Name = name;
public ConfigurationStorePrivateEndpointConnection(string name, Location location) : this() => (Name, Location) = (name, location);
public ConfigurationStorePrivateEndpointConnection WithProperties(Action<ConfigurationStorePrivateEndpointConnectionProperties> setter)
{
PropertyBase.SetProperties(setter, Properties);
return this;
}
}
public class ConfigurationStorePrivateEndpointConnectionProperties : PropertyBase
{
private PrivateEndpointInfo _privateEndpoint;
public PrivateEndpointInfo PrivateEndpoint
{
get => _privateEndpoint = Get(_privateEndpoint);
set => _privateEndpoint = value;
}
private PrivateLinkServiceConnectionStateInfo _privateLinkServiceConnectionState;
public PrivateLinkServiceConnectionStateInfo PrivateLinkServiceConnectionState
{
get => _privateLinkServiceConnectionState = Get(_privateLinkServiceConnectionState);
set => _privateLinkServiceConnectionState = value;
}
}
public class PrivateEndpointInfo : PropertyBase
{
public string Id { get; set; }
}
public class PrivateLinkServiceConnectionStateInfo : PropertyBase
{
public string Status { get; set; }
public string Description { get; set; }
}
public class ConfigurationStore : Resource<ConfigurationStoreProperties>
{
public ConfigurationStore() => (Type, ApiVersion) = ("Microsoft.AppConfiguration/configurationStores", "2019-11-01-preview");
public ConfigurationStore(string name) : this() => Name = name;
public ConfigurationStore(string name, Location location) : this() => (Name, Location) = (name, location);
public IdentityInfo Identity { get; set; }
public ConfigurationStore WithProperties(Action<ConfigurationStoreProperties> setter)
{
PropertyBase.SetProperties(setter, Properties);
return this;
}
}
public class IdentityInfo : PropertyBase
{
public string Type { get; set; }
public object UserAssignedIdentities { get; set; }
}
public class ConfigurationStoreProperties : PropertyBase
{
private EncryptionInfo _encryption;
public EncryptionInfo Encryption
{
get => _encryption = Get(_encryption);
set => _encryption = value;
}
}
public class EncryptionInfo : PropertyBase
{
private KeyVaultPropertiesInfo _keyVaultProperties;
public KeyVaultPropertiesInfo KeyVaultProperties
{
get => _keyVaultProperties = Get(_keyVaultProperties);
set => _keyVaultProperties = value;
}
}
public class KeyVaultPropertiesInfo : PropertyBase
{
public string KeyIdentifier { get; set; }
public string IdentityClientId { get; set; }
}
}
| 33.161905 | 185 | 0.684951 | [
"MIT"
] | tzkhan/Charming | src/Charming.Types/AppConfiguration.g.cs | 3,482 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Recovery plan test failover input.</summary>
public partial class RecoveryPlanTestFailoverInput
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanTestFailoverInput.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanTestFailoverInput.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanTestFailoverInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new RecoveryPlanTestFailoverInput(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="RecoveryPlanTestFailoverInput" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param>
internal RecoveryPlanTestFailoverInput(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.RecoveryPlanTestFailoverInputProperties.FromJson(__jsonProperties) : Property;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="RecoveryPlanTestFailoverInput" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="RecoveryPlanTestFailoverInput" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 67.217822 | 298 | 0.68773 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180110/RecoveryPlanTestFailoverInput.json.cs | 6,689 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using System.IO;
namespace ToastBot
{
class rank
{
public async void tnsdnl(SocketMessage message)
{
Random random = new Random();
byte red = (byte)random.Next(0, 256);
byte green = (byte)random.Next(0, 256);
byte blue = (byte)random.Next(0, 256);
int arr = 2;
string[] money = File.ReadAllLines("Players.txt");
int biggest;
string playername = message.Author.Username;
string playerid = message.Author.Id.ToString();
int he = Array.IndexOf(money, playerid);
biggest = int.Parse(money[he + 1]);
int rank = 1;
int playermoney = biggest;
while (arr <= money.Length-1)
{
if (int.Parse(money[arr]) > biggest)
{
biggest = int.Parse(money[arr]);
rank++;
}
arr = arr + 3;
}
int ckdl = biggest - playermoney;
var builder = new EmbedBuilder()
.AddField(playername + "의 등수는...", rank + "등이다뮤~")
.AddField("그리고 1등과의 차이는...", "빵 " + ckdl + "개다뮤!")
.WithColor(new Color(red, green, blue));
var embed = builder.Build();
await message.Channel.SendMessageAsync("", embed: embed)
.ConfigureAwait(false);
}
}
}
| 31.92 | 68 | 0.510652 | [
"MIT"
] | csnewcs/DiscordMuBotCsharp | Codes/.Net Core/Toast (.Net Core)/0 rank.cs | 1,640 | C# |
using System.Collections.Generic;
namespace DeUrgenta.Emailing.Service.Models
{
public class EmailRequestModel
{
public string DestinationAddress { get; set; }
public Dictionary<string, string> PlaceholderContent { get; set; }
public EmailTemplate TemplateType { get; set; }
public EmailAttachment Attachment { get; set; }
public string Subject { get; set; }
}
}
| 29.785714 | 74 | 0.678657 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Alexei000/de-urgenta-backend | Src/DeUrgenta.Emailing.Service/Models/EmailRequestModel.cs | 419 | C# |
namespace BlazingTheWeb.UsingWasmInCSharp
{
public abstract class CollatzWithCallback
{
public abstract void collatz(int value);
}
} | 19.714286 | 42 | 0.797101 | [
"MIT"
] | JasonBock/BlazingTheWeb | BlazingTheWeb.UsingWasmInCSharp/CollatzWithCallback.cs | 140 | C# |
using System;
using System.Collections.Generic;
using static System.Console;
namespace FileProcessor2
{
class Program
{
static void Main(string[] args)
{
Processor processor = new Processor();
try
{
List<Person> people = processor.Process("Names.txt", "missing.txt");
foreach (var person in people)
{
WriteLine($"{person.Name},{person.Age}");
}
}
catch (Exception ex)
{
WriteLine(ex);
}
WriteLine();
WriteLine("Press enter to exit");
ReadLine();
}
}
}
| 21 | 84 | 0.457983 | [
"MIT"
] | SamIge7/SideWork | 06NullOperators/FileProcessor2/Program.cs | 716 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ExecOnLinux
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 27.784314 | 106 | 0.587156 | [
"Apache-2.0"
] | OpenTouryoProject/OpenTouryo | root/programs/CS/Frameworks/Tests/ExecOnLinux/ExecOnLinux/Startup.cs | 1,419 | C# |
using PuppeteerSharp;
using System;
using System.Net;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
namespace SF_DataExport.Interceptors
{
public class ProfilePhotoInterceptor : InterceptorBase
{
ResourceManager Resource { get; }
JsonConfig OrgSettings { get; }
AppStore Store { get; }
public ProfilePhotoInterceptor(ResourceManager resource, OrgSettingsConfig orgSettings, AppStore store)
{
Resource = resource;
OrgSettings = orgSettings;
Store = store;
}
public override async Task<bool> RequestAsync(Page appPage, Request request)
{
if (request.Url.Contains(".content.force.com/profilephoto/"))
{
await Observable.FromAsync(async () =>
{
var instanceUrl = (string)Store.GetState("currentInstanceUrl");
if (string.IsNullOrEmpty(instanceUrl))
await InterceptAsync(appPage, request, req => req.ContinueAsync()).GoOn();
else
{
var accessToken = (string)OrgSettings.Get(o => o[instanceUrl]?[OAuth.ACCESS_TOKEN]);
var bytes = await Resource.GetBytesViaAccessTokenAsync(instanceUrl, accessToken, request.Url);
if (bytes?.LongLength > 0)
await InterceptAsync(appPage, request, req => req.RespondAsync(new ResponseData
{
Status = HttpStatusCode.OK,
ContentType = "image/png",
BodyData = bytes
})).GoOn();
else
await InterceptAsync(appPage, request, req => req.ContinueAsync()).GoOn();
}
})
.Retry(1)
.Catch((Exception _) => Observable.Return(Unit.Default))
.LastOrDefaultAsync().ToTask().GoOn();
return true;
}
return false;
}
}
}
| 38.724138 | 118 | 0.529831 | [
"MIT"
] | ste80/SF-DataExport | SF-DataExport/Interceptors/ProfilePhotoInterceptor.cs | 2,248 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.AspNetCore.Http.Internal
{
public class BindingAddress
{
public string Host { get; private set; }
public string PathBase { get; private set; }
public int Port { get; internal set; }
public string Scheme { get; private set; }
public bool IsUnixPipe
{
get
{
return Host.StartsWith(Constants.UnixPipeHostPrefix, StringComparison.Ordinal);
}
}
public string UnixPipePath
{
get
{
if (!IsUnixPipe)
{
throw new InvalidOperationException("Binding address is not a unix pipe.");
}
return Host.Substring(Constants.UnixPipeHostPrefix.Length - 1);
}
}
public override string ToString()
{
if (IsUnixPipe)
{
return Scheme.ToLowerInvariant() + "://" + Host.ToLowerInvariant();
}
else
{
return Scheme.ToLowerInvariant() + "://" + Host.ToLowerInvariant() + ":" + Port.ToString(CultureInfo.InvariantCulture) + PathBase.ToString(CultureInfo.InvariantCulture);
}
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as BindingAddress;
if (other == null)
{
return false;
}
return string.Equals(Scheme, other.Scheme, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase)
&& Port == other.Port
&& PathBase == other.PathBase;
}
public static BindingAddress Parse(string address)
{
address = address ?? string.Empty;
int schemeDelimiterStart = address.IndexOf("://", StringComparison.Ordinal);
if (schemeDelimiterStart < 0)
{
throw new FormatException($"Invalid url: '{address}'");
}
int schemeDelimiterEnd = schemeDelimiterStart + "://".Length;
var isUnixPipe = address.IndexOf(Constants.UnixPipeHostPrefix, schemeDelimiterEnd, StringComparison.Ordinal) == schemeDelimiterEnd;
int pathDelimiterStart;
int pathDelimiterEnd;
if (!isUnixPipe)
{
pathDelimiterStart = address.IndexOf("/", schemeDelimiterEnd, StringComparison.Ordinal);
pathDelimiterEnd = pathDelimiterStart;
}
else
{
pathDelimiterStart = address.IndexOf(":", schemeDelimiterEnd + Constants.UnixPipeHostPrefix.Length, StringComparison.Ordinal);
pathDelimiterEnd = pathDelimiterStart + ":".Length;
}
if (pathDelimiterStart < 0)
{
pathDelimiterStart = pathDelimiterEnd = address.Length;
}
var serverAddress = new BindingAddress();
serverAddress.Scheme = address.Substring(0, schemeDelimiterStart);
var hasSpecifiedPort = false;
if (!isUnixPipe)
{
int portDelimiterStart = address.LastIndexOf(":", pathDelimiterStart - 1, pathDelimiterStart - schemeDelimiterEnd, StringComparison.Ordinal);
if (portDelimiterStart >= 0)
{
int portDelimiterEnd = portDelimiterStart + ":".Length;
string portString = address.Substring(portDelimiterEnd, pathDelimiterStart - portDelimiterEnd);
int portNumber;
if (int.TryParse(portString, NumberStyles.Integer, CultureInfo.InvariantCulture, out portNumber))
{
hasSpecifiedPort = true;
serverAddress.Host = address.Substring(schemeDelimiterEnd, portDelimiterStart - schemeDelimiterEnd);
serverAddress.Port = portNumber;
}
}
if (!hasSpecifiedPort)
{
if (string.Equals(serverAddress.Scheme, "http", StringComparison.OrdinalIgnoreCase))
{
serverAddress.Port = 80;
}
else if (string.Equals(serverAddress.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
serverAddress.Port = 443;
}
}
}
if (!hasSpecifiedPort)
{
serverAddress.Host = address.Substring(schemeDelimiterEnd, pathDelimiterStart - schemeDelimiterEnd);
}
if (string.IsNullOrEmpty(serverAddress.Host))
{
throw new FormatException($"Invalid url: '{address}'");
}
if (address[address.Length - 1] == '/')
{
serverAddress.PathBase = address.Substring(pathDelimiterEnd, address.Length - pathDelimiterEnd - 1);
}
else
{
serverAddress.PathBase = address.Substring(pathDelimiterEnd);
}
return serverAddress;
}
}
} | 36.2 | 185 | 0.542862 | [
"Apache-2.0"
] | 0xced/AspNetCore | src/Http/Http/src/Internal/BindingAddress.cs | 5,613 | C# |
namespace SetApplicationStatus.Console
{
using System.Linq;
using NLog;
public class ApplicationStatusPatch
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly string _ukprn;
private readonly string _sqlConnectionString;
private readonly string _mongoConnectionString;
private readonly bool _update;
public ApplicationStatusPatch(string ukprn, string sqlConnectionString, string mongoConnectionString, bool update)
{
_ukprn = ukprn;
_sqlConnectionString = sqlConnectionString;
_mongoConnectionString = mongoConnectionString;
_update = update;
}
public void Run()
{
var sqlApplicationRepository = new Repositories.Sql.ApplicationRepository(_sqlConnectionString);
var sourceApplications = sqlApplicationRepository
.GetApplicationIdsByUkprn(_ukprn)
.Where(application => application.Status == Entities.Sql.ApplicationStatus.Unsuccessful);
var mongoApplicationRepository = new Repositories.Mongo.ApplicationRepository(_mongoConnectionString);
foreach (var sourceApplication in sourceApplications)
{
Logger.Info($"SOURCE: Application ID: {sourceApplication.ApplicationId}, Status: {sourceApplication.Status}");
var ids = new[]
{
sourceApplication.ApplicationId
};
var targetApplications = mongoApplicationRepository.GetApplicationByLegacyIds(ids);
foreach (var targetApplication in targetApplications)
{
Logger.Info($"TARGET: Id: {targetApplication.Id} Legacy Application ID: {targetApplication.LegacyApplicationId}, Status: {targetApplication.Status}");
if (targetApplication.Status == Entities.Mongo.ApplicationStatus.InProgress)
{
continue;
}
Logger.Warn($"Expected: {Entities.Mongo.ApplicationStatus.InProgress}, Actual: {targetApplication.Status}");
if (targetApplication.Status != Entities.Mongo.ApplicationStatus.Submitted)
{
continue;
}
}
}
}
}
}
| 37.84375 | 170 | 0.614781 | [
"MIT"
] | BugsUK/FindApprenticeship | tools/SetApplicationStatus/SetApplicationStatus.Console/ApplicationStatusPatch.cs | 2,422 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class MusicManager : MonoBehaviour
{
public static MusicManager instance;
private string currentscenename;
private string previousscenename;
[SerializeField]
private AudioSource goost;
[SerializeField]
private AudioClip[] ost;
private delegate void onSceneChanged();
private onSceneChanged SceneChanged;
private void Awake()
{
currentscenename = "Menu";
SceneChanged += ChangeMusic;
goost = gameObject.GetComponent<AudioSource>();
if (instance != null)
{
GameObject.Destroy(gameObject);
return;
}
else
{
DontDestroyOnLoad(transform.gameObject);
}
}
private void Start()
{
instance = this;
}
private void Update()
{
string activescene = SceneManager.GetActiveScene().name;
if (!currentscenename.Equals(activescene))
{
previousscenename = currentscenename;
currentscenename = activescene;
if (SceneChanged != null)
SceneChanged.Invoke();
}
}
private void ChangeMusic()
{
switch (currentscenename)
{
case "Menu":
if (!previousscenename.Equals("Settings") && !previousscenename.Equals("Credits"))
{
goost.Stop();
goost.PlayOneShot(ost[0]);
goost.loop = true;
}
break;
case "Salles":
goost.Stop();
goost.PlayOneShot(ost[1]);
goost.loop = true;
break;
default: break;
}
}
}
| 24.253165 | 99 | 0.521399 | [
"Apache-2.0"
] | ChristianSourisseau/Projet-Escape-Game | Escape_Game/Assets/Scripts/MusicManager.cs | 1,918 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ev3Controller.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ev3Controller.ViewModel;
namespace Ev3Controller.Model.Tests
{
[TestClass()]
public class BrickDataUpdater_Tests : Ev3Brick_TestBase
{
#region Unit test of BrickDataUpdater constructor.
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_Constructor")]
public void BrickDataUpdater_Test()
{
}
#endregion
#region Unit test of BrickDataUpdater constructor.
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateViewModel")]
public void BrickDataUpdater_UpdateViewModel_Test()
{
}
#endregion
#region Unit test of UpdateMotorViewModel
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_001()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice.ConnectedPort = Ev3Device.OUTPORT.OUTPORT_A;
MotorDevice.DeviceType = Ev3MotorDevice.DEVICE_TYPE.MOTOR_DEVICE_LARGE_MOTOR;
MotorDevice.Power = 10;
Brick.MotorDeviceArray[0] = MotorDevice;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsTrue(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.AreEqual("PORT_A", ViewModel.MotorViewModelArray[0].PortName);
Assert.AreEqual("LARGE MOTOR", ViewModel.MotorViewModelArray[0].DeviceName);
Assert.AreEqual(10, ViewModel.MotorViewModelArray[0].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[0].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_002()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice.ConnectedPort = Ev3Device.OUTPORT.OUTPORT_B;
MotorDevice.DeviceType = Ev3MotorDevice.DEVICE_TYPE.MOTOR_DEVICE_LARGE_MOTOR;
MotorDevice.Power = 11;
Brick.MotorDeviceArray[1] = MotorDevice;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsFalse(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.AreEqual("PORT_B", ViewModel.MotorViewModelArray[1].PortName);
Assert.AreEqual("LARGE MOTOR", ViewModel.MotorViewModelArray[1].DeviceName);
Assert.AreEqual(11, ViewModel.MotorViewModelArray[1].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[1].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_003()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice.ConnectedPort = Ev3Device.OUTPORT.OUTPORT_C;
MotorDevice.DeviceType = Ev3MotorDevice.DEVICE_TYPE.MOTOR_DEVICE_LARGE_MOTOR;
MotorDevice.Power = 12;
Brick.MotorDeviceArray[2] = MotorDevice;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsFalse(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.AreEqual("PORT_C", ViewModel.MotorViewModelArray[2].PortName);
Assert.AreEqual("LARGE MOTOR", ViewModel.MotorViewModelArray[2].DeviceName);
Assert.AreEqual(12, ViewModel.MotorViewModelArray[2].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[2].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_004()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice.ConnectedPort = Ev3Device.OUTPORT.OUTPORT_D;
MotorDevice.DeviceType = Ev3MotorDevice.DEVICE_TYPE.MOTOR_DEVICE_LARGE_MOTOR;
MotorDevice.Power = 13;
Brick.MotorDeviceArray[3] = MotorDevice;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsFalse(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[3].IsConnected);
Assert.AreEqual("PORT_D", ViewModel.MotorViewModelArray[3].PortName);
Assert.AreEqual("LARGE MOTOR", ViewModel.MotorViewModelArray[3].DeviceName);
Assert.AreEqual(13, ViewModel.MotorViewModelArray[3].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[3].CurrentOutputUnit);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_005()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice1 = new Ev3MotorDevice();
var MotorDevice2 = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice1.Power = 13;
MotorDevice2.Power = 23;
Brick.MotorDeviceArray[0] = MotorDevice1;
Brick.MotorDeviceArray[1] = MotorDevice2;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsTrue(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.AreEqual(13, ViewModel.MotorViewModelArray[0].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[0].CurrentOutputUnit);
Assert.IsTrue(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.AreEqual(23, ViewModel.MotorViewModelArray[1].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[1].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_006()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice1 = new Ev3MotorDevice();
var MotorDevice2 = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice1.Power = 13;
MotorDevice2.Power = 23;
Brick.MotorDeviceArray[0] = MotorDevice1;
Brick.MotorDeviceArray[2] = MotorDevice2;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsTrue(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.AreEqual(13, ViewModel.MotorViewModelArray[0].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[0].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.AreEqual(23, ViewModel.MotorViewModelArray[2].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[2].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_007()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice1 = new Ev3MotorDevice();
var MotorDevice2 = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice1.Power = 13;
MotorDevice2.Power = 23;
Brick.MotorDeviceArray[0] = MotorDevice1;
Brick.MotorDeviceArray[3] = MotorDevice2;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsTrue(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.AreEqual(13, ViewModel.MotorViewModelArray[0].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[0].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[3].IsConnected);
Assert.AreEqual(23, ViewModel.MotorViewModelArray[3].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[3].CurrentOutputUnit);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_008()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice1 = new Ev3MotorDevice();
var MotorDevice2 = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice1.Power = 13;
MotorDevice2.Power = 23;
Brick.MotorDeviceArray[1] = MotorDevice1;
Brick.MotorDeviceArray[2] = MotorDevice2;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsFalse(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.AreEqual(13, ViewModel.MotorViewModelArray[1].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[1].CurrentOutputUnit);
Assert.IsTrue(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.AreEqual(23, ViewModel.MotorViewModelArray[2].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[2].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_009()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice1 = new Ev3MotorDevice();
var MotorDevice2 = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice1.Power = 13;
MotorDevice2.Power = 23;
Brick.MotorDeviceArray[1] = MotorDevice1;
Brick.MotorDeviceArray[3] = MotorDevice2;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsFalse(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.AreEqual(13, ViewModel.MotorViewModelArray[1].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[1].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[3].IsConnected);
Assert.AreEqual(23, ViewModel.MotorViewModelArray[3].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[3].CurrentOutputUnit);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateMotorViewModel_Test_010()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice1 = new Ev3MotorDevice();
var MotorDevice2 = new Ev3MotorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
}
MotorDevice1.Power = 13;
MotorDevice2.Power = 23;
Brick.MotorDeviceArray[2] = MotorDevice1;
Brick.MotorDeviceArray[3] = MotorDevice2;
Updater.UpdateMotorViewModel(ViewModel);
Assert.IsFalse(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.IsTrue(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.AreEqual(13, ViewModel.MotorViewModelArray[2].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[2].CurrentOutputUnit);
Assert.IsTrue(ViewModel.MotorViewModelArray[3].IsConnected);
Assert.AreEqual(23, ViewModel.MotorViewModelArray[3].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[3].CurrentOutputUnit);
}
#endregion
#region Unit test of UpdateMotorViewModel
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateSensorViewModel_Test_001()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var SensorDevice = new Ev3SensorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.SensorViewModelArray[index] = new Ev3SensorDeviceViewModel();
}
SensorDevice.ConnectedPort = Ev3Device.INPORT.INPORT_1;
SensorDevice.DeviceType = Ev3SensorDevice.DEVICE_TYPE.SENSOR_DEVICE_COLOR;
SensorDevice.Value1 = 10;
SensorDevice.Value2 = 11;
SensorDevice.Value3 = 12;
Brick.SensorDeviceArray[0] = SensorDevice;
Updater.UpdateSensorViewModel(ViewModel);
Assert.IsTrue(ViewModel.SensorViewModelArray[0].IsConnected);
Assert.AreEqual("PORT_1", ViewModel.SensorViewModelArray[0].PortName);
Assert.AreEqual("COLOR", ViewModel.SensorViewModelArray[0].DeviceName);
Assert.AreEqual(10, ViewModel.SensorViewModelArray[0].SensorValue1);
Assert.AreEqual(11, ViewModel.SensorViewModelArray[0].SensorValue2);
Assert.AreEqual(12, ViewModel.SensorViewModelArray[0].SensorValue3);
Assert.AreEqual("", ViewModel.SensorViewModelArray[0].SensorValue1Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[0].SensorValue2Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[0].SensorValue3Unit);
Assert.IsFalse(ViewModel.SensorViewModelArray[1].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[2].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateSensorViewModel_Test_002()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var SensorDevice = new Ev3SensorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.SensorViewModelArray[index] = new Ev3SensorDeviceViewModel();
}
SensorDevice.ConnectedPort = Ev3Device.INPORT.INPORT_2;
SensorDevice.DeviceType = Ev3SensorDevice.DEVICE_TYPE.SENSOR_DEVICE_GYRO;
SensorDevice.Value1 = 10;
SensorDevice.Value2 = 11;
SensorDevice.Value3 = 12;
Brick.SensorDeviceArray[1] = SensorDevice;
Updater.UpdateSensorViewModel(ViewModel);
Assert.IsFalse(ViewModel.SensorViewModelArray[0].IsConnected);
Assert.IsTrue(ViewModel.SensorViewModelArray[1].IsConnected);
Assert.AreEqual("PORT_2", ViewModel.SensorViewModelArray[1].PortName);
Assert.AreEqual("GYRO", ViewModel.SensorViewModelArray[1].DeviceName);
Assert.AreEqual(10, ViewModel.SensorViewModelArray[1].SensorValue1);
Assert.AreEqual(11, ViewModel.SensorViewModelArray[1].SensorValue2);
Assert.AreEqual(12, ViewModel.SensorViewModelArray[1].SensorValue3);
Assert.AreEqual("", ViewModel.SensorViewModelArray[1].SensorValue1Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[1].SensorValue2Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[1].SensorValue3Unit);
Assert.IsFalse(ViewModel.SensorViewModelArray[2].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateSensorViewModel_Test_003()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var SensorDevice = new Ev3SensorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.SensorViewModelArray[index] = new Ev3SensorDeviceViewModel();
}
SensorDevice.ConnectedPort = Ev3Device.INPORT.INPORT_3;
SensorDevice.DeviceType = Ev3SensorDevice.DEVICE_TYPE.SENSOR_DEVICE_TOUCH;
SensorDevice.Value1 = 10;
SensorDevice.Value2 = 11;
SensorDevice.Value3 = 12;
Brick.SensorDeviceArray[2] = SensorDevice;
Updater.UpdateSensorViewModel(ViewModel);
Assert.IsFalse(ViewModel.SensorViewModelArray[0].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[1].IsConnected);
Assert.IsTrue(ViewModel.SensorViewModelArray[2].IsConnected);
Assert.AreEqual("PORT_3", ViewModel.SensorViewModelArray[2].PortName);
Assert.AreEqual("TOUCH", ViewModel.SensorViewModelArray[2].DeviceName);
Assert.AreEqual(10, ViewModel.SensorViewModelArray[2].SensorValue1);
Assert.AreEqual(11, ViewModel.SensorViewModelArray[2].SensorValue2);
Assert.AreEqual(12, ViewModel.SensorViewModelArray[2].SensorValue3);
Assert.AreEqual("", ViewModel.SensorViewModelArray[2].SensorValue1Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[2].SensorValue2Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[2].SensorValue3Unit);
Assert.IsFalse(ViewModel.SensorViewModelArray[3].IsConnected);
}
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateMotorViewModel_Test")]
public void BrickDataUpdater_UpdateSensorViewModel_Test_004()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var SensorDevice = new Ev3SensorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.SensorViewModelArray[index] = new Ev3SensorDeviceViewModel();
}
SensorDevice.ConnectedPort = Ev3Device.INPORT.INPORT_4;
SensorDevice.DeviceType = Ev3SensorDevice.DEVICE_TYPE.SENSOR_DEVICE_ULTRASONIC;
SensorDevice.Value1 = 10;
SensorDevice.Value2 = 11;
SensorDevice.Value3 = 12;
Brick.SensorDeviceArray[3] = SensorDevice;
Updater.UpdateSensorViewModel(ViewModel);
Assert.IsFalse(ViewModel.SensorViewModelArray[0].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[1].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[2].IsConnected);
Assert.IsTrue(ViewModel.SensorViewModelArray[3].IsConnected);
Assert.AreEqual("PORT_4", ViewModel.SensorViewModelArray[3].PortName);
Assert.AreEqual("ULTRASONIC", ViewModel.SensorViewModelArray[3].DeviceName);
Assert.AreEqual(10, ViewModel.SensorViewModelArray[3].SensorValue1);
Assert.AreEqual(11, ViewModel.SensorViewModelArray[3].SensorValue2);
Assert.AreEqual(12, ViewModel.SensorViewModelArray[3].SensorValue3);
Assert.AreEqual("", ViewModel.SensorViewModelArray[3].SensorValue1Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[3].SensorValue2Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[3].SensorValue3Unit);
}
#endregion
[TestMethod()]
[TestCategory("BrickDataUpdater")]
[TestCategory("BrickDataUpdater_UpdateViewModel_Test")]
public void BrickDataUpdater_UpdateViewModel_Test_001()
{
var Updater = new BrickDataUpdater();
var ViewModel = new Ev3ControllerMainViewModel();
var MotorDevice = new Ev3MotorDevice();
var SensorDevice = new Ev3SensorDevice();
var Brick = Ev3Brick.GetInstance();
for (int index = 0; index < 4; index++)
{
ViewModel.MotorViewModelArray[index] = new Ev3MotorDeviceViewModel();
ViewModel.SensorViewModelArray[index] = new Ev3SensorDeviceViewModel();
}
MotorDevice.ConnectedPort = Ev3Device.OUTPORT.OUTPORT_A;
MotorDevice.DeviceType = Ev3MotorDevice.DEVICE_TYPE.MOTOR_DEVICE_LARGE_MOTOR;
MotorDevice.Power = 10;
Brick.MotorDeviceArray[0] = MotorDevice;
SensorDevice.ConnectedPort = Ev3Device.INPORT.INPORT_1;
SensorDevice.DeviceType = Ev3SensorDevice.DEVICE_TYPE.SENSOR_DEVICE_COLOR;
SensorDevice.Value1 = 10;
SensorDevice.Value2 = 11;
SensorDevice.Value3 = 12;
Brick.SensorDeviceArray[0] = SensorDevice;
Updater.UpdateViewModel(ViewModel);
Assert.IsTrue(ViewModel.MotorViewModelArray[0].IsConnected);
Assert.AreEqual("PORT_A", ViewModel.MotorViewModelArray[0].PortName);
Assert.AreEqual("LARGE MOTOR", ViewModel.MotorViewModelArray[0].DeviceName);
Assert.AreEqual(10, ViewModel.MotorViewModelArray[0].CurrentOutput);
Assert.AreEqual("%", ViewModel.MotorViewModelArray[0].CurrentOutputUnit);
Assert.IsFalse(ViewModel.MotorViewModelArray[1].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[2].IsConnected);
Assert.IsFalse(ViewModel.MotorViewModelArray[3].IsConnected);
Assert.IsTrue(ViewModel.SensorViewModelArray[0].IsConnected);
Assert.AreEqual("PORT_1", ViewModel.SensorViewModelArray[0].PortName);
Assert.AreEqual("COLOR", ViewModel.SensorViewModelArray[0].DeviceName);
Assert.AreEqual(10, ViewModel.SensorViewModelArray[0].SensorValue1);
Assert.AreEqual(11, ViewModel.SensorViewModelArray[0].SensorValue2);
Assert.AreEqual(12, ViewModel.SensorViewModelArray[0].SensorValue3);
Assert.AreEqual("", ViewModel.SensorViewModelArray[0].SensorValue1Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[0].SensorValue2Unit);
Assert.AreEqual("", ViewModel.SensorViewModelArray[0].SensorValue3Unit);
Assert.IsFalse(ViewModel.SensorViewModelArray[1].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[2].IsConnected);
Assert.IsFalse(ViewModel.SensorViewModelArray[3].IsConnected);
}
}
} | 52.594286 | 92 | 0.645372 | [
"MIT"
] | CountrySideEngineer/Ev3Controller | dev/src/Ev3ControllerTests/Model/BrickDataUpdater_Tests.cs | 27,614 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
namespace ZeroReact
{
public interface IReactScopedContext
{
ReactComponent CreateComponent<T>(string componentName) where T: ReactComponent;
void GetInitJavaScript(TextWriter writer);
}
public class ReactScopedContext : IDisposable, IReactScopedContext
{
protected readonly IList<ReactComponent> _components = new List<ReactComponent>();
private readonly IServiceProvider _serviceProvider;
public ReactScopedContext(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public virtual ReactComponent CreateComponent<T>(string componentName) where T: ReactComponent
{
var component = ActivatorUtilities.CreateInstance<T>(_serviceProvider);
component.ComponentName = componentName;
_components.Add(component);
return component;
}
public virtual void GetInitJavaScript(TextWriter writer)
{
foreach (var component in _components)
{
if (!component.ServerOnly)
{
component.RenderJavaScript(writer);
writer.WriteLine(';');
}
}
}
public void Dispose()
{
foreach (var component in _components)
{
component.Dispose();
}
}
}
}
| 26.724138 | 102 | 0.609032 | [
"MIT"
] | redzumi/ZeroReact.NET | src/ZeroReact/ReactScopedContext.cs | 1,552 | C# |
namespace XMPP_API.Classes.Network.XML.Messages.XEP_0384.Session
{
public enum OmemoSessionBuildError
{
UNKNOWN,
TARGET_DOES_NOT_SUPPORT_OMEMO,
REQUEST_DEVICE_LIST_TIMEOUT,
REQUEST_BUNDLE_INFORMATION_TIMEOUT,
REQUEST_DEVICE_LIST_IQ_ERROR,
REQUEST_BUNDLE_INFORMATION_IQ_ERROR,
KEY_ERROR
}
}
| 25.642857 | 65 | 0.718663 | [
"MPL-2.0"
] | LibreHacker/UWPX-Client | XMPP_API/Classes/Network/XML/Messages/XEP-0384/Session/OmemoSessionBuildError.cs | 361 | C# |
using System;
using System.ComponentModel.Design;
//int配列を使う場合ためのサンプル
internal class IntsEditor : CollectionEditor {
public IntsEditor(Type t) : base(t) { }
//初期値を決める
protected override object CreateInstance(Type itemType) {
return 10;
}
//右上の表示がint[]プロパティになってしまうのでintに修正する
protected override Type CreateCollectionItemType() {
return typeof(int);
}
//そのままだとobject配列になってしまうので変換する
protected override object SetItems(object editValue, object[] value) {
int[] ia;
ia = new int[value.Length];
value.CopyTo(ia, 0);
return ia;
}
}
| 22.888889 | 74 | 0.661812 | [
"Unlicense"
] | EleBrain/-CS-ZWJsonEditor | ZWData/IntsEditor.cs | 754 | 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.
*
* Live-Video
* 直播管理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;
namespace JDCloudSDK.Live.Apis
{
/// <summary>
/// 添加域名翻译配置
/// /// - 添加域名级别的翻译模板配置
/// /// - 一个域名最多可绑定一个翻译模板
/// /// - 重新推流后生效
/// ///
/// </summary>
public class AddLiveStreamDomainTranslateRequest : JdcloudRequest
{
///<summary>
/// 直播的推流域名
///Required:true
///</summary>
[Required]
public string PublishDomain{ get; set; }
///<summary>
/// 翻译模版
/// - 取值范围: 系统标准翻译模板, 用户自定义翻译模板
/// - 系统标准翻译模板
/// system-zh-en (中译英)
/// system-en-zh (英译中)
///
///Required:true
///</summary>
[Required]
public string Template{ get; set; }
}
} | 26.111111 | 76 | 0.6 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Live/Apis/AddLiveStreamDomainTranslateRequest.cs | 1,831 | C# |
using System.Collections.Generic;
using HexCore;
namespace HexCoreTests.Fixtures
{
public static class MovementTypesFixture
{
public static readonly MovementType Walking = new MovementType(1, " Walking");
public static readonly MovementType Swimming = new MovementType(2, "Swimming");
public static readonly MovementType Flying = new MovementType(3, "Flying");
public static readonly TerrainType Ground = new TerrainType(1, "Ground");
public static readonly TerrainType Water = new TerrainType(2, "Water");
public static readonly TerrainType Air = new TerrainType(3, "Air");
public static MovementTypes GetMovementTypes()
{
TerrainType[] terrainTypes = {Ground, Water, Air};
var movementTypes = new MovementTypes(terrainTypes,
new Dictionary<MovementType, Dictionary<TerrainType, int>>
{
[Walking] = new Dictionary<TerrainType, int>
{
[Ground] = 1,
[Water] = 2,
[Air] = 999
},
[Swimming] = new Dictionary<TerrainType, int>
{
[Ground] = 2,
[Water] = 1,
[Air] = 999
},
[Flying] = new Dictionary<TerrainType, int>
{
[Ground] = 1,
[Water] = 1,
[Air] = 1
}
});
return movementTypes;
}
}
} | 37.522727 | 87 | 0.488189 | [
"MIT"
] | antouhou/HexCore | HexCore.Tests/Fixtures/MovementTypes.Mock.cs | 1,653 | 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("01.ExtractEmails")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01.ExtractEmails")]
[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("1fe61aeb-aa74-40db-b89e-c0e20906ab54")]
// 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.837838 | 84 | 0.747857 | [
"MIT"
] | YonchevSimeon/Programming-Fundamentals-CSharp | InExRegularExpressions/01.ExtractEmails/Properties/AssemblyInfo.cs | 1,403 | C# |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Globalization;
using MsVsShell = Microsoft.VisualStudio.Shell;
namespace Microsoft.Samples.VisualStudio.SourceControlIntegration.SccProvider
{
/// <summary>
/// This attribute registers the visibility of a Tools/Options property page.
/// While Microsoft.VisualStudio.Shell allow registering a tools options page
/// using the ProvideOptionPageAttribute attribute, currently there is no better way
/// of declaring the options page visibility, so a custom attribute needs to be used.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class ProvideToolsOptionsPageVisibility : MsVsShell.RegistrationAttribute
{
private string _categoryName = null;
private string _pageName = null;
private Guid _commandUIGuid;
/// <summary>
/// </summary>
public ProvideToolsOptionsPageVisibility(string categoryName, string pageName, string commandUIGuid)
{
_categoryName = categoryName;
_pageName = pageName;
_commandUIGuid = new Guid(commandUIGuid);
}
/// <summary>
/// The programmatic name for this category (non localized).
/// </summary>
public string CategoryName
{
get { return _categoryName; }
}
/// <summary>
/// The programmatic name for this page (non localized).
/// </summary>
public string PageName
{
get { return _pageName; }
}
/// <summary>
/// Get the command UI guid controlling the visibility of the page.
/// </summary>
public Guid CommandUIGuid
{
get { return _commandUIGuid; }
}
private string RegistryPath
{
get { return string.Format(CultureInfo.InvariantCulture, "ToolsOptionsPages\\{0}\\{1}\\VisibilityCmdUIContexts", CategoryName, PageName); }
}
/// <summary>
/// Called to register this attribute with the given context. The context
/// contains the location where the registration inforomation should be placed.
/// It also contains other information such as the type being registered and path information.
/// </summary>
public override void Register(RegistrationContext context)
{
// Write to the context's log what we are about to do
context.Log.WriteLine(String.Format(CultureInfo.CurrentCulture, "Opt.Page Visibility:\t{0}\\{1}, {2}\n", CategoryName, PageName, CommandUIGuid.ToString("B")));
// Create the visibility key.
using (Key childKey = context.CreateKey(RegistryPath))
{
// Set the value for the command UI guid.
childKey.SetValue(CommandUIGuid.ToString("B"), 1);
}
}
/// <summary>
/// Unregister this visibility entry.
/// </summary>
public override void Unregister(RegistrationContext context)
{
context.RemoveValue(RegistryPath, CommandUIGuid.ToString("B"));
}
}
}
| 37.263158 | 171 | 0.618644 | [
"MIT"
] | 48355746/VSSDK-Extensibility-Samples | ArchivedSamples/Source_Control_Provider_Status_Bar_Integration/C#/ProvideToolsOptionsPageVisibility.cs | 3,540 | C# |
namespace WaifuShork.Common.NativeLoader;
using System;
using System.Runtime.InteropServices;
internal static class Libdl
{
private const string _libName = "libdl";
public const int RtldNow = 0x002;
[DllImport(_libName, EntryPoint = "dlopen", CharSet = CharSet.Unicode)]
public static extern IntPtr DlOpen(string fileName, int flags);
[DllImport(_libName, EntryPoint = "dlclose", CharSet = CharSet.Unicode)]
public static extern int DlClose(IntPtr handle);
[DllImport(_libName, EntryPoint = "dlsym", CharSet = CharSet.Unicode)]
public static extern IntPtr DlSym(IntPtr handle, string name);
[DllImport(_libName, EntryPoint = "dlerror", CharSet = CharSet.Unicode)]
public static extern string DlError();
} | 32.818182 | 73 | 0.765928 | [
"MIT"
] | WaifuShork/Common | src/WaifuShork.Common/NativeLoader/Libdl.cs | 724 | C# |
#nullable enable
using Microsoft.Maui.Controls;
using Microsoft.Maui.Essentials;
namespace Microsoft.Maui.TestUtils.DeviceTests.Runners.VisualRunner.Pages
{
partial class CreditsPage : ContentPage
{
public CreditsPage()
{
InitializeComponent();
}
void OnNavigating(object? sender, WebNavigatingEventArgs e)
{
Browser.OpenAsync(e.Url);
e.Cancel = true;
}
}
} | 18.333333 | 73 | 0.742857 | [
"MIT"
] | 41396/maui | src/TestUtils/src/DeviceTests.Runners/VisualRunner/Pages/CreditsPage.xaml.cs | 387 | C# |
using System;
namespace MAVN.Service.OperationsHistory.Domain.Models
{
public interface ITransactionHistory
{
string CustomerId { get; set; }
string TransactionId { get; set; }
string AssetSymbol { get; set; }
DateTime Timestamp { get; set; }
string Type { get; set; }
}
}
| 18.333333 | 54 | 0.615152 | [
"MIT"
] | HannaAndreevna/MAVN.Service.OperationsHistory | src/MAVN.Service.OperationsHistory.Domain/Models/ITransactionHistory.cs | 330 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.Audio
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class EqualizerBand
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public double Gain
{
get
{
throw new global::System.NotImplementedException("The member double EqualizerBand.Gain is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Audio.EqualizerBand", "double EqualizerBand.Gain");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public double FrequencyCenter
{
get
{
throw new global::System.NotImplementedException("The member double EqualizerBand.FrequencyCenter is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Audio.EqualizerBand", "double EqualizerBand.FrequencyCenter");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public double Bandwidth
{
get
{
throw new global::System.NotImplementedException("The member double EqualizerBand.Bandwidth is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Audio.EqualizerBand", "double EqualizerBand.Bandwidth");
}
}
#endif
// Forced skipping of method Windows.Media.Audio.EqualizerBand.Bandwidth.get
// Forced skipping of method Windows.Media.Audio.EqualizerBand.Bandwidth.set
// Forced skipping of method Windows.Media.Audio.EqualizerBand.FrequencyCenter.get
// Forced skipping of method Windows.Media.Audio.EqualizerBand.FrequencyCenter.set
// Forced skipping of method Windows.Media.Audio.EqualizerBand.Gain.get
// Forced skipping of method Windows.Media.Audio.EqualizerBand.Gain.set
}
}
| 35.083333 | 155 | 0.744418 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Audio/EqualizerBand.cs | 2,105 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using toDoList;
namespace toDoList.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20201218112832_NewMigration6")]
partial class NewMigration6
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0");
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")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
b.HasData(
new
{
Id = "1fa0c9b8-45f9-4835-9a3e-a6eb2b64d005",
ConcurrencyStamp = "2134c8a2-6538-453d-8726-4f6b9e21d3f5",
Name = "Super Admin",
NormalizedName = "SUPER ADMIN"
},
new
{
Id = "8db3a46b-918b-4b0f-90e9-81fa103f262e",
ConcurrencyStamp = "fe4e795f-7624-4a96-b684-50c069396a24",
Name = "Administrator",
NormalizedName = "ADMINISTRATOR"
},
new
{
Id = "bb413bf2-537e-497e-bf5c-68dc0002e47c",
ConcurrencyStamp = "8a4b1f65-36e3-4a42-b3b2-d7f6d688ae14",
Name = "Power User",
NormalizedName = "POWER USER"
},
new
{
Id = "fc2ab893-2d06-4f50-8608-a94bd4d3ab3a",
ConcurrencyStamp = "eb5ecd96-0446-4342-af10-8f47aef49fa4",
Name = "User",
NormalizedName = "USER"
});
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
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.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
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(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
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");
b.HasData(
new
{
UserId = "82b1a0e1-61f5-40ab-9773-bb74814413f8",
RoleId = "1fa0c9b8-45f9-4835-9a3e-a6eb2b64d005"
});
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("toDoList.Models.AppUserAddress", b =>
{
b.Property<int>("UserAddressId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("City")
.HasColumnType("nvarchar(max)");
b.Property<string>("Country")
.HasColumnType("nvarchar(max)");
b.Property<string>("District")
.HasColumnType("nvarchar(max)");
b.Property<string>("Gender")
.HasColumnType("nvarchar(max)");
b.Property<string>("IdUser")
.HasColumnType("nvarchar(max)");
b.Property<string>("Municipality")
.HasColumnType("nvarchar(max)");
b.HasKey("UserAddressId");
b.ToTable("UserAddress");
});
modelBuilder.Entity("toDoList.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<int?>("AppUserAddressUserAddressId")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(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")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("AppUserAddressUserAddressId");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
b.HasData(
new
{
Id = "82b1a0e1-61f5-40ab-9773-bb74814413f8",
AccessFailedCount = 0,
ConcurrencyStamp = "6a985bc3-e1c5-4b3e-80a4-7ac93ce7030a",
Email = "superadmin@gmail.com",
EmailConfirmed = true,
LockoutEnabled = false,
NormalizedEmail = "SUPERADMIN@GMAIL.COM",
NormalizedUserName = "SUPERADMIN@GMAIL.COM",
PasswordHash = "AQAAAAEAACcQAAAAEEgjKSeD2Ds8RIJ40d4OYKamq5wQopldzWzPJicN6IHgC/ZrMFjZyvyUX+Tuqdu1LQ==",
PhoneNumberConfirmed = false,
SecurityStamp = "V4PJL2RQEZ6FIRGR3LQPLMKQVYEQIMIL",
TwoFactorEnabled = false,
UserName = "superadmin@gmail.com"
});
});
modelBuilder.Entity("toDoList.Models.CLab", b =>
{
b.Property<int>("IdCLab")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<short>("Ano")
.HasColumnType("smallint");
b.Property<DateTime>("DataLancamento")
.HasColumnType("datetime2");
b.Property<int>("EmpresaSageId")
.HasColumnType("int");
b.Property<string>("InputFilePAth")
.HasColumnType("nvarchar(max)");
b.Property<string>("OutputFilePAth")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserID")
.HasColumnType("nvarchar(max)");
b.HasKey("IdCLab");
b.ToTable("cLabs");
});
modelBuilder.Entity("toDoList.Models.mapView_UtilzadoresEmpresa", b =>
{
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<int>("AppUserAddressUserAddressId")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<int>("EmpresaId")
.HasColumnType("int");
b.Property<string>("Id")
.HasColumnType("nvarchar(max)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(max)");
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(max)");
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(max)");
b.ToView("db_vw_UtilizadoresEmpresa");
});
modelBuilder.Entity("toDoList.ViewModels.ConConfigViewModel", b =>
{
b.Property<int>("ConexaoID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<bool>("ActiveConnection")
.HasColumnType("bit");
b.Property<int>("EmpresaId")
.HasColumnType("int");
b.Property<string>("InstanciaSQL")
.HasColumnType("nvarchar(max)");
b.Property<string>("NomeServidor")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Utilizador")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("ConexaoID");
b.ToTable("ConConfigViewModel");
});
modelBuilder.Entity("toDoList.ViewModels.EditRoleViewModel", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("EditRoleViewModel");
});
modelBuilder.Entity("toDoList.ViewModels.EmpresaUtilizadoresViewModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("EmpresaId")
.HasColumnType("int");
b.Property<bool>("IsSelected")
.HasColumnType("bit");
b.Property<string>("UserID")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("EmpresaUtilizadores");
});
modelBuilder.Entity("toDoList.ViewModels.EmpresasViewModel", b =>
{
b.Property<int>("EmpresaID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<bool>("Ativo")
.HasColumnType("bit");
b.Property<DateTime>("DataCriacao")
.HasColumnType("datetime2");
b.Property<DateTime>("DataExpiracao")
.HasColumnType("datetime2");
b.Property<int>("IdCabContabilidade")
.HasColumnType("int");
b.Property<string>("Licenca")
.HasColumnType("nvarchar(max)");
b.Property<string>("NIF")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nome")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("NrEmpresas")
.HasColumnType("int");
b.Property<string>("NrPostos")
.HasColumnType("nvarchar(max)");
b.Property<bool>("isCabContabilidade")
.HasColumnType("bit");
b.HasKey("EmpresaID");
b.ToTable("EmpresasViewModel");
});
modelBuilder.Entity("toDoList.ViewModels.ForgotPasswordViewModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("ResetLinkConfirmationDate")
.HasColumnType("datetime2");
b.Property<DateTime>("ResetLinkCreatedTime")
.HasColumnType("datetime2");
b.Property<DateTime>("ResetLinkValidity")
.HasColumnType("datetime2");
b.Property<string>("Token")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("ForgotPasswordViewModel");
});
modelBuilder.Entity("toDoList.ViewModels.ResetPasswordViewModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("ConfirmPassword")
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Token")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("ResetPasswordViewModel");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("toDoList.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("toDoList.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("toDoList.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("toDoList.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("toDoList.Models.ApplicationUser", b =>
{
b.HasOne("toDoList.Models.AppUserAddress", "AppUserAddress")
.WithMany()
.HasForeignKey("AppUserAddressUserAddressId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("AppUserAddress");
});
#pragma warning restore 612, 618
}
}
}
| 37.027027 | 130 | 0.43538 | [
"Apache-2.0"
] | ggraur/toDoList | Migrations/20201218112832_NewMigration6.Designer.cs | 23,292 | C# |
/*******************************************************************************
* Copyright (C) Git Corporation. All rights reserved.
*
* Author: 情缘
* Create Date: 2013-11-30 12:35:03
*
* Description: Git.Framework
* http://www.cnblogs.com/qingyuan/
* Revision History:
* Date Author Description
* 2013-11-30 12:35:03 情缘
*********************************************************************************/
using Git.Storage.Entity.Move;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using Git.Framework.DataTypes.ExtensionMethods;
using Git.Framework.DataTypes;
using Git.Storage.Common;
using Git.Framework.ORM;
using Git.Storage.Entity.Base;
using Git.Storage.Entity.Store;
using Git.Storage.Provider.Store;
using System.Data;
using Git.Storage.Provider.Base;
namespace Git.Storage.Provider.Move
{
public partial class MoveOrder : Bill<MoveOrderEntity, MoveOrderDetailEntity>
{
public MoveOrder() { }
/// <summary>
/// 创建单据
/// </summary>
/// <param name="entity"></param>
/// <param name="list"></param>
/// <returns></returns>
public override string Create(MoveOrderEntity entity, List<MoveOrderDetailEntity> list)
{
using (TransactionScope ts = new TransactionScope())
{
int line = 0;
entity.OrderNum = entity.OrderNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(MoveOrderEntity)) : entity.OrderNum;
entity.IncludeAll();
if (!list.IsNullOrEmpty())
{
list.ForEach(a =>
{
a.IncludeAll();
a.OrderNum = entity.OrderNum;
});
line = this.MoveOrder.Add(entity);
line += this.MoveOrderDetail.Add(list);
}
ts.Complete();
return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
}
}
/// <summary>
/// 取消单据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override string Cancel(MoveOrderEntity entity)
{
//只有待审核状态的单据才能取消,已经成功的订单不能取消
MoveOrderEntity checkOrder = new MoveOrderEntity();
entity.Where(a => a.Status == (int)EAudite.Wait).And(a => a.OrderNum == entity.OrderNum);
if (this.MoveOrder.GetCount(checkOrder) > 0)
{
return EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Pass); //已经审核或者取消的订单不能审核
}
entity.Status = (int)EAudite.NotPass;
entity.IncludeStatus(true);
entity.Where(a => a.OrderNum == entity.OrderNum);
int line = this.MoveOrder.Update(entity);
return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
}
/// <summary>
/// 删除单据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override string Delete(MoveOrderEntity entity)
{
entity.IsDelete = (int)EIsDelete.Deleted;
entity.IncludeIsDelete(true);
entity.Where(a => a.OrderNum == entity.OrderNum);
int line = this.MoveOrder.Update(entity);
return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
}
/// <summary>
/// 审核单据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override string Audite(MoveOrderEntity entity)
{
if (entity.Status == (int)EAudite.NotPass)
{
entity.IncludeStatus(true).IncludeReason(true).Where(a => a.OrderNum == entity.OrderNum);
int line = this.MoveOrder.Update(entity);
return line > 0 ? "1000" : string.Empty;
}
else if (entity.Status == (int)EAudite.Pass)
{
Proc_AuditeMoveEntity auditeEntity = new Proc_AuditeMoveEntity();
auditeEntity.OrderNum = entity.OrderNum;
auditeEntity.Status = entity.Status;
auditeEntity.AuditUser = entity.AuditUser;
auditeEntity.Reason = entity.Reason;
auditeEntity.OperateType = entity.OperateType;
auditeEntity.EquipmentNum = entity.EquipmentNum;
auditeEntity.EquipmentCode = entity.EquipmentCode;
auditeEntity.Remark = entity.Remark;
int line = this.Proc_AuditeMove.ExecuteNonQuery(auditeEntity);
return auditeEntity.ReturnValue;
}
return string.Empty;
}
/// <summary>
/// 打印单据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override string Print(MoveOrderEntity entity)
{
entity.IncludePrintUser(true).IncludePrintTime(true)
.Where(a => a.OrderNum == entity.OrderNum);
int line = this.MoveOrder.Update(entity);
return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
}
/// <summary>
/// 查询单据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override MoveOrderEntity GetOrder(MoveOrderEntity entity)
{
entity.IncludeAll();
AdminEntity admin = new AdminEntity();
admin.Include(a => new { CreateUserName = a.UserName });
entity.Left<AdminEntity>(admin, new Params<string, string>() { Item1 = "CreateUser", Item2 = "UserCode" });
entity.Where(a => a.OrderNum == entity.OrderNum);
entity = this.MoveOrder.GetSingle(entity);
return entity;
}
/// <summary>
/// 获得单据详细信息
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override List<MoveOrderDetailEntity> GetOrderDetail(MoveOrderDetailEntity entity)
{
MoveOrderDetailEntity detail = new MoveOrderDetailEntity();
detail.IncludeAll();
detail.Where(a => a.OrderNum == entity.OrderNum);
List<MoveOrderDetailEntity> list = this.MoveOrderDetail.GetList(detail);
if (!list.IsNullOrEmpty())
{
List<LocationEntity> listLocation = new LocationProvider().GetList();
listLocation = listLocation == null ? new List<LocationEntity>() : listLocation;
foreach (MoveOrderDetailEntity item in list)
{
LocationEntity location = listLocation.FirstOrDefault(a => a.LocalNum == item.FromLocalNum);
item.FromLocalName = location == null ? "" : location.LocalName;
location = listLocation.FirstOrDefault(a => a.LocalNum == item.ToLocalNum);
item.ToLocalName = location == null ? "" : location.LocalName;
}
}
return list;
}
/// <summary>
/// 查询单据分页
/// </summary>
/// <param name="entity"></param>
/// <param name="pageInfo"></param>
/// <returns></returns>
public override List<MoveOrderEntity> GetList(MoveOrderEntity entity, ref Framework.DataTypes.PageInfo pageInfo)
{
entity.IncludeAll();
entity.Where(a => a.IsDelete == (int)EIsDelete.NotDelete);
entity.OrderBy(a => a.ID, EOrderBy.DESC);
AdminEntity admin = new AdminEntity();
admin.Include(a => new { CreateUserName = a.UserName });
entity.Left<AdminEntity>(admin, new Params<string, string>() { Item1 = "CreateUser", Item2 = "UserCode" });
int rowCount = 0;
List<MoveOrderEntity> listResult = this.MoveOrder.GetList(entity, pageInfo.PageSize, pageInfo.PageIndex, out rowCount);
pageInfo.RowCount = rowCount;
return listResult;
}
/// <summary>
/// 查询单据详细数据分页
/// </summary>
/// <param name="entity"></param>
/// <param name="pageInfo"></param>
/// <returns></returns>
public override List<MoveOrderDetailEntity> GetDetailList(MoveOrderDetailEntity entity, ref Framework.DataTypes.PageInfo pageInfo)
{
MoveOrderDetailEntity detail = new MoveOrderDetailEntity();
detail.Where(a => a.OrderNum == entity.OrderNum);
detail.IncludeAll();
detail.OrderBy(a => a.ID, EOrderBy.DESC);
int rowCount = 0;
List<MoveOrderDetailEntity> listResult = this.MoveOrderDetail.GetList(detail, pageInfo.PageSize, pageInfo.PageIndex, out rowCount);
pageInfo.RowCount = rowCount;
if (!listResult.IsNullOrEmpty())
{
List<LocationEntity> listLocation = new LocationProvider().GetList();
listLocation = listLocation == null ? new List<LocationEntity>() : listLocation;
foreach (MoveOrderDetailEntity item in listResult)
{
LocationEntity location = listLocation.FirstOrDefault(a => a.LocalNum == item.FromLocalNum);
item.FromLocalName = location == null ? "" : location.LocalName;
location = listLocation.FirstOrDefault(a => a.LocalNum == item.ToLocalNum);
item.ToLocalName = location == null ? "" : location.LocalName;
}
}
return listResult;
}
/// <summary>
/// 编辑单据信息
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override string EditOrder(MoveOrderEntity entity)
{
entity.Include(a => new { a.MoveType, a.ProductType, a.ContractOrder, a.Remark, a.Amout, a.Num });
entity.Where(a => a.OrderNum == entity.OrderNum);
int line = this.MoveOrder.Update(entity);
return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
}
/// <summary>
/// 编辑单据详细信息
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override string EditDetail(MoveOrderDetailEntity entity)
{
entity.Where(a => a.SnNum == entity.SnNum);
int line = this.MoveOrderDetail.Update(entity);
return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
}
/// <summary>
/// 获得订单数量
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override int GetCount(MoveOrderEntity entity)
{
return this.MoveOrder.GetCount(entity);
}
/// <summary>
/// 编辑移库单
/// </summary>
/// <param name="entity"></param>
/// <param name="list"></param>
/// <returns></returns>
public override string EditOrder(MoveOrderEntity entity, List<MoveOrderDetailEntity> list)
{
using (TransactionScope ts = new TransactionScope())
{
int line = 0;
entity.Include(a => new { a.MoveType, a.ProductType, a.ContractOrder, a.Remark, a.Amout, a.Num });
entity.Where(a => a.OrderNum == entity.OrderNum);
MoveOrderDetailEntity detail = new MoveOrderDetailEntity();
detail.Where(a => a.OrderNum == entity.OrderNum);
this.MoveOrderDetail.Delete(detail);
foreach (MoveOrderDetailEntity item in list)
{
item.OrderNum = entity.OrderNum;
item.IncludeAll();
}
entity.Num = list.Sum(a => a.Num);
entity.Amout = list.Sum(a => a.Amout);
line = this.MoveOrder.Update(entity);
this.MoveOrderDetail.Add(list);
ts.Complete();
return line > 0 ? EnumHelper.GetEnumDesc<EReturnStatus>(EReturnStatus.Success) : string.Empty;
}
}
/// <summary>
/// 获得打印单据的数据源
/// </summary>
/// <param name="argOrderNum"></param>
/// <returns></returns>
public override DataSet GetPrint(string argOrderNum)
{
DataSet ds = new DataSet();
MoveOrderEntity entity = new MoveOrderEntity();
entity.OrderNum = argOrderNum;
entity = GetOrder(entity);
if (entity != null)
{
List<MoveOrderEntity> list = new List<MoveOrderEntity>();
list.Add(entity);
DataTable tableOrder = list.ToDataTable();
ds.Tables.Add(tableOrder);
MoveOrderDetailEntity detail = new MoveOrderDetailEntity();
detail.OrderNum = argOrderNum;
List<MoveOrderDetailEntity> listDetail = GetOrderDetail(detail);
if (!listDetail.IsNullOrEmpty())
{
DataTable tableDetail = listDetail.ToDataTable();
ds.Tables.Add(tableDetail);
}
}
return ds;
}
}
}
| 40.519403 | 143 | 0.549212 | [
"MIT"
] | KittenCN/WMS | Git.Storage.Provider/Move/MoveOrder.cs | 13,832 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x1018_ddba-154565e0")]
public void /* sys */ Method_1018_ddba()
{
ii(0x1018_ddba, 1); push(ebp); /* push ebp */
ii(0x1018_ddbb, 2); mov(ebp, esp); /* mov ebp, esp */
ii(0x1018_ddbd, 1); push(esi); /* push esi */
ii(0x1018_ddbe, 1); push(edi); /* push edi */
ii(0x1018_ddbf, 1); push(ebx); /* push ebx */
ii(0x1018_ddc0, 3); mov(ecx, memd[ss, ebp + 16]); /* mov ecx, [ebp+0x10] */
ii(0x1018_ddc3, 2); shr(ecx, 1); /* shr ecx, 1 */
ii(0x1018_ddc5, 2); if(jz(0x1018_de1b, 0x54)) goto l_0x1018_de1b;/* jz 0x1018de1b */
ii(0x1018_ddc7, 3); mov(esi, memd[ss, ebp + 12]); /* mov esi, [ebp+0xc] */
ii(0x1018_ddca, 3); mov(edi, memd[ss, ebp + 8]); /* mov edi, [ebp+0x8] */
ii(0x1018_ddcd, 3); mov(ax, memw[ds, esi]); /* mov ax, [esi] */
ii(0x1018_ddd0, 3); add(esi, 2); /* add esi, 0x2 */
ii(0x1018_ddd3, 2); xor(ebx, ebx); /* xor ebx, ebx */
ii(0x1018_ddd5, 3); mov(memw[ds, edi], ax); /* mov [edi], ax */
ii(0x1018_ddd8, 3); add(edi, 2); /* add edi, 0x2 */
ii(0x1018_dddb, 1); dec(ecx); /* dec ecx */
ii(0x1018_dddc, 2); if(jz(0x1018_de1b, 0x3d)) goto l_0x1018_de1b;/* jz 0x1018de1b */
ii(0x1018_ddde, 3); mov(dx, memw[ds, esi]); /* mov dx, [esi] */
ii(0x1018_dde1, 3); add(esi, 2); /* add esi, 0x2 */
ii(0x1018_dde4, 2); xor(ebx, ebx); /* xor ebx, ebx */
ii(0x1018_dde6, 3); mov(memw[ds, edi], dx); /* mov [edi], dx */
ii(0x1018_dde9, 3); add(edi, 2); /* add edi, 0x2 */
ii(0x1018_ddec, 1); dec(ecx); /* dec ecx */
ii(0x1018_dded, 2); if(jz(0x1018_de1b, 0x2c)) goto l_0x1018_de1b;/* jz 0x1018de1b */
l_0x1018_ddef:
ii(0x1018_ddef, 2); mov(bl, memb[ds, esi]); /* mov bl, [esi] */
ii(0x1018_ddf1, 3); add(esi, 1); /* add esi, 0x1 */
ii(0x1018_ddf4, 8); add(ax, memw[ds, ebx * 2 + 0x101b_e218]);/* add ax, [ebx*2+0x101be218] */
ii(0x1018_ddfc, 3); mov(memw[ds, edi], ax); /* mov [edi], ax */
ii(0x1018_ddff, 3); add(edi, 2); /* add edi, 0x2 */
ii(0x1018_de02, 1); dec(ecx); /* dec ecx */
ii(0x1018_de03, 2); if(jz(0x1018_de1b, 0x16)) goto l_0x1018_de1b;/* jz 0x1018de1b */
ii(0x1018_de05, 2); mov(bl, memb[ds, esi]); /* mov bl, [esi] */
ii(0x1018_de07, 3); add(esi, 1); /* add esi, 0x1 */
ii(0x1018_de0a, 8); add(dx, memw[ds, ebx * 2 + 0x101b_e218]);/* add dx, [ebx*2+0x101be218] */
ii(0x1018_de12, 3); mov(memw[ds, edi], dx); /* mov [edi], dx */
ii(0x1018_de15, 3); add(edi, 2); /* add edi, 0x2 */
ii(0x1018_de18, 1); dec(ecx); /* dec ecx */
ii(0x1018_de19, 2); if(jnz(0x1018_ddef, -0x2c)) goto l_0x1018_ddef;/* jnz 0x1018ddef */
l_0x1018_de1b:
ii(0x1018_de1b, 1); pop(ebx); /* pop ebx */
ii(0x1018_de1c, 1); pop(edi); /* pop edi */
ii(0x1018_de1d, 1); pop(esi); /* pop esi */
ii(0x1018_de1e, 1); leave(); /* leave */
ii(0x1018_de1f, 1); ret(); /* ret */
}
}
}
| 72.491525 | 107 | 0.408931 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-1018-ddba-sys.cs | 4,277 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DefaultDataContextFactoryTest.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Implements the default data context provider test class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Data.Tests
{
using System.Collections.Generic;
using System.Security.Principal;
using Kephas.Composition;
using Kephas.Composition.ExportFactories;
using Kephas.Data;
using Kephas.Data.Composition;
using Kephas.Data.Store;
using Kephas.Services;
using NSubstitute;
using NUnit.Framework;
[TestFixture]
public class DefaultDataContextFactoryTest
{
[Test]
public void CreateDataContext_success()
{
var dataStoreProvider = Substitute.For<IDataStoreProvider>();
dataStoreProvider.GetDataStore("test-store").Returns(new DataStore("test-store", "kind1"));
var dataContext1 = Substitute.For<IDataContext>();
var provider = new DefaultDataContextFactory(
new List<IExportFactory<IDataContext, DataContextMetadata>>
{
new ExportFactory<IDataContext, DataContextMetadata>(() => dataContext1, new DataContextMetadata(new[] { "kind1" }))
},
dataStoreProvider);
var dataContext = provider.CreateDataContext("test-store");
Assert.AreSame(dataContext1, dataContext);
}
[Test]
public void CreateDataContext_proper_initialized()
{
var dataStoreProvider = Substitute.For<IDataStoreProvider>();
var dcConfig = Substitute.For<IDataContextSettings>();
var dataStore = new DataStore("test-store", "kind1", dataContextSettings: dcConfig);
dataStoreProvider.GetDataStore("test-store").Returns(dataStore);
IDataInitializationContext initContext = null;
var dataContext1 = Substitute.For<IDataContext>();
dataContext1.When(ctx => ctx.Initialize(Arg.Any<IContext>())).Do(ci => initContext = ci.Arg<IContext>() as IDataInitializationContext);
var provider = new DefaultDataContextFactory(
new List<IExportFactory<IDataContext, DataContextMetadata>>
{
new ExportFactory<IDataContext, DataContextMetadata>(() => dataContext1, new DataContextMetadata(new[] { "kind1" }))
},
dataStoreProvider);
var initData = Substitute.For<IContext>();
var dataContext = provider.CreateDataContext("test-store", initData);
Assert.AreSame(dataStore, initContext.DataStore);
Assert.AreSame(initData, initContext.InitializationContext);
}
[Test]
public void CreateDataContext_ambiguous_match_for_two_same_kinds()
{
var dataStoreProvider = Substitute.For<IDataStoreProvider>();
dataStoreProvider.GetDataStore("test-store").Returns(new DataStore("test-store", "kind1"));
var dataContext1 = Substitute.For<IDataContext>();
var dataContext2 = Substitute.For<IDataContext>();
var provider = new DefaultDataContextFactory(
new List<IExportFactory<IDataContext, DataContextMetadata>>
{
new ExportFactory<IDataContext, DataContextMetadata>(() => dataContext1, new DataContextMetadata(new[] { "kind1" })),
new ExportFactory<IDataContext, DataContextMetadata>(() => dataContext2, new DataContextMetadata(new[] { "kind1" }))
},
dataStoreProvider);
Assert.Throws<AmbiguousMatchDataException>(() => provider.CreateDataContext("test-store"));
}
}
} | 45.736264 | 147 | 0.602114 | [
"MIT"
] | snakefoot/kephas | src/Tests/Kephas.Data.Tests/DefaultDataContextFactoryTest.cs | 4,164 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallLaserBehavior : MonoBehaviour {
public float MoveSpeed = 10;
public bool IsVertical = true;
public bool IsCharging = false;
public float shotFrequency = 10;
public float chargeTime = 10;
public Sprite IdleSprite;
public ParticleSystem chargingParticles;
Rigidbody2D rb2d;
public SpriteRenderer sprite;
public float timeLeft;
public GameObject projectilePrefab;
public Vector2 facing;
public Vector2 maxSpawn;
public Vector2 minSpawn;
public Transform firingPosition;
public SoundEffectHandler chargeSound;
public SoundEffectHandler fireSound;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
timeLeft = shotFrequency;
if (Random.value > 0.5f) MoveSpeed = -MoveSpeed;
}
// Update is called once per frame
void Update () {
Vector2 moveDirection;
if (IsVertical)
{
moveDirection = new Vector2(0, MoveSpeed);
} else
{
moveDirection = new Vector2(MoveSpeed, 0);
}
rb2d.velocity = moveDirection;
timeLeft -= Time.deltaTime;
if (timeLeft <= 0)
{
if (IsCharging)
{
ToggleCharging();
FireWeapon();
timeLeft = shotFrequency;
} else
{
ToggleCharging();
timeLeft = chargeTime;
}
}
}
private void OnTriggerEnter2D(Collider2D collider)
{
MoveSpeed = -MoveSpeed;
}
private void ToggleCharging()
{
if (IsCharging)
{
IsCharging = false;
sprite.sprite = IdleSprite;
if (fireSound != null)
{
fireSound.PlayEffect();
}
}
else
{
IsCharging = true;
chargingParticles.Play();
if (chargeSound != null)
{
chargeSound.PlayEffect();
}
}
}
private void FireWeapon()
{
Transform DynamicsParent = Globals.Instance.GetComponent<GameManager>().dynamicsParent;
GameObject laser = Instantiate(projectilePrefab, DynamicsParent);
//laser.transform.position = firingPosition.position;
laser.transform.position = new Vector2(firingPosition.position.x, firingPosition.position.y) + rb2d.velocity * Time.fixedDeltaTime * 3;
laser.transform.rotation = transform.rotation;
ProjectileController pc = laser.GetComponent<ProjectileController>();
pc.fireDirection = facing;
pc.maxWallBounceCount = Globals.Instance.GameManager.gameOptions.wallLaserBounceCount;
pc.moveSpeed = Globals.Instance.GameManager.gameOptions.wallLaserSpeed;
}
}
| 28.811881 | 143 | 0.601718 | [
"MIT"
] | ironpencil/suddendeath | suddendeath/Assets/WallLaserBehavior.cs | 2,912 | C# |
//
// Encog(tm) Core v3.1 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2012 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.ML.Data;
using Encog.Neural.Networks.Training.Propagation.Resilient;
namespace Encog.Neural.Networks.Training.Propagation.Manhattan
{
/// <summary>
/// One problem that the backpropagation technique has is that the magnitude of
/// the partial derivative may be calculated too large or too small. The
/// Manhattan update algorithm attempts to solve this by using the partial
/// derivative to only indicate the sign of the update to the weight matrix. The
/// actual amount added or subtracted from the weight matrix is obtained from a
/// simple constant. This constant must be adjusted based on the type of neural
/// network being trained. In general, start with a higher constant and decrease
/// it as needed.
/// The Manhattan update algorithm can be thought of as a simplified version of
/// the resilient algorithm. The resilient algorithm uses more complex techniques
/// to determine the update value.
/// </summary>
///
public class ManhattanPropagation : Propagation, ILearningRate
{
/// <summary>
/// The default tolerance to determine of a number is close to zero.
/// </summary>
///
internal const double DefaultZeroTolerance = 0.001d;
/// <summary>
/// The zero tolerance to use.
/// </summary>
///
private readonly double _zeroTolerance;
/// <summary>
/// The learning rate.
/// </summary>
///
private double _learningRate;
/// <summary>
/// Construct a Manhattan propagation training object.
/// </summary>
///
/// <param name="network">The network to train.</param>
/// <param name="training">The training data to use.</param>
/// <param name="learnRate">The learning rate.</param>
public ManhattanPropagation(BasicNetwork network,
IMLDataSet training, double learnRate) : base(network, training)
{
_learningRate = learnRate;
_zeroTolerance = RPROPConst.DefaultZeroTolerance;
}
/// <inheritdoc />
public override sealed bool CanContinue
{
get { return false; }
}
#region ILearningRate Members
/// <summary>
/// Set the learning rate.
/// </summary>
public virtual double LearningRate
{
get { return _learningRate; }
set { _learningRate = value; }
}
#endregion
/// <summary>
/// This training type does not support training continue.
/// </summary>
///
/// <returns>Always returns null.</returns>
public override sealed TrainingContinuation Pause()
{
return null;
}
/// <summary>
/// This training type does not support training continue.
/// </summary>
///
/// <param name="state">Not used.</param>
public override sealed void Resume(TrainingContinuation state)
{
}
/// <summary>
/// Calculate the amount to change the weight by.
/// </summary>
///
/// <param name="gradients">The gradients.</param>
/// <param name="lastGradient">The last gradients.</param>
/// <param name="index">The index to update.</param>
/// <returns>The amount to change the weight by.</returns>
public override sealed double UpdateWeight(double[] gradients,
double[] lastGradient, int index)
{
if (Math.Abs(gradients[index]) < _zeroTolerance)
{
return 0;
}
else if (gradients[index] > 0)
{
return _learningRate;
}
else
{
return -_learningRate;
}
}
/// <summary>
/// Not needed for this training type.
/// </summary>
public override void InitOthers()
{
}
}
}
| 32.953642 | 100 | 0.588223 | [
"BSD-3-Clause"
] | mpcoombes/MaterialPredictor | encog-core-cs/Neural/Networks/Training/Propagation/Manhattan/ManhattanPropagation.cs | 4,976 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.IO;
namespace NuGet.Protocol.Core.v3.Data
{
public class MemoryFileCache : FileCacheBase
{
private readonly ConcurrentDictionary<Uri, MemoryStream> _entries;
public MemoryFileCache()
: base()
{
_entries = new ConcurrentDictionary<Uri, MemoryStream>();
}
public override void Remove(Uri uri)
{
MemoryStream entry = null;
if (_entries.TryRemove(uri, out entry)
&& entry != null)
{
entry.Dispose();
}
}
public override bool TryGet(Uri uri, out Stream stream)
{
stream = null;
MemoryStream cacheStream = null;
if (_entries.TryGetValue(uri, out cacheStream))
{
stream = new MemoryStream();
cacheStream.Seek(0, SeekOrigin.Begin);
cacheStream.CopyTo(stream);
return true;
}
return false;
}
public override void Add(Uri uri, TimeSpan lifeSpan, Stream stream)
{
var cacheStream = new MemoryStream();
stream.CopyTo(cacheStream);
stream.Seek(0, SeekOrigin.Begin);
_entries.AddOrUpdate(uri, cacheStream, (k, v) => cacheStream);
}
}
}
| 27.508772 | 111 | 0.561862 | [
"Apache-2.0"
] | david-driscoll/NuGet3 | src/NuGet.Protocol.Core.v3/DataClient/FileCache/MemoryFileCache.cs | 1,570 | C# |
// This source code is dual-licensed under the Apache License, version
// 2.0, and the Mozilla Public License, version 1.1.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (C) 2007-2009 LShift Ltd., Cohesive Financial
// Technologies LLC., and Rabbit Technologies 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.
//---------------------------------------------------------------------------
//
// The MPL v1.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.rabbitmq.com/mpl.html
//
// 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 Original Code is The RabbitMQ .NET Client.
//
// The Initial Developers of the Original Code are LShift Ltd,
// Cohesive Financial Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created before 22-Nov-2008 00:00:00 GMT by LShift Ltd,
// Cohesive Financial Technologies LLC, or Rabbit Technologies Ltd
// are Copyright (C) 2007-2008 LShift Ltd, Cohesive Financial
// Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created by LShift Ltd are Copyright (C) 2007-2009 LShift
// Ltd. Portions created by Cohesive Financial Technologies LLC are
// Copyright (C) 2007-2009 Cohesive Financial Technologies
// LLC. Portions created by Rabbit Technologies Ltd are Copyright
// (C) 2007-2009 Rabbit Technologies Ltd.
//
// All Rights Reserved.
//
// Contributor(s): ______________________________________.
//
//---------------------------------------------------------------------------
using System.Collections;
using System.Threading;
namespace RabbitMQ.Util {
///<summary>Used internally by class Either.</summary>
public enum EitherAlternative {
Left,
Right
}
///<summary>Models the disjoint union of two alternatives, a
///"left" alternative and a "right" alternative.</summary>
///<remarks>Borrowed from ML, Haskell etc.</remarks>
public class Either {
///<summary>Records which alternative this instance represents.</summary>
private EitherAlternative m_alternative;
///<summary>Holds the value this instance carries.</summary>
private object m_value;
///<summary>Private constructor. Use the static methods Left, Right instead.</summary>
private Either(EitherAlternative alternative, object value) {
m_alternative = alternative;
m_value = value;
}
///<summary>Constructs an Either instance representing a Left alternative.</summary>
public static Either Left(object value) {
return new Either(EitherAlternative.Left, value);
}
///<summary>Constructs an Either instance representing a Right alternative.</summary>
public static Either Right(object value) {
return new Either(EitherAlternative.Right, value);
}
///<summary>Retrieve the alternative represented by this instance.</summary>
public EitherAlternative Alternative {
get {
return m_alternative;
}
}
///<summary>Retrieve the value carried by this instance.</summary>
public object Value {
get {
return m_value;
}
}
}
}
| 39.925234 | 94 | 0.633193 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/RabbitMQ.Client/src/util/Either.cs | 4,272 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace FabricDCA
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Fabric.Common.Tracing;
using System.Fabric.Dca;
using System.Fabric.Health;
using System.IO;
using System.Linq;
// This class implements the logic for managing DCA settings
internal class DCASettings
{
// Constants
private const string TraceType = "Settings";
// Parameter names in DCA-specific sections in settings.xml
private const string AssemblyParamName = "Assembly";
private const string TypeParamName = "Type";
private const string HealthSubProperty = "Configuration";
// Configuration reader
private readonly IDcaSettingsConfigReader configReader;
private readonly ReadOnlyDictionary<string, ProducerInstanceInfo> producerInstances;
private readonly ReadOnlyDictionary<string, ConsumerInstanceInfo> consumerInstances;
private readonly string applicationInstanceId;
private readonly List<string> errors = new List<string>();
internal DCASettings(string applicationInstanceId)
: this(applicationInstanceId, new DcaSettingsConfigReader(applicationInstanceId))
{
}
internal DCASettings(string applicationInstanceId, IDcaSettingsConfigReader dcaSettingsConfigReader)
{
this.applicationInstanceId = applicationInstanceId;
this.configReader = dcaSettingsConfigReader;
Action<string> onError = error =>
{
// Trace immediately and aggregate for health.
Utility.TraceSource.WriteError(TraceType, error);
this.errors.Add(error);
};
this.producerInstances = new ReadOnlyDictionary<string, ProducerInstanceInfo>(this.GetProducers(onError));
this.consumerInstances = new ReadOnlyDictionary<string, ConsumerInstanceInfo>(this.GetConsumers(onError));
var pluginsEnabledBitFlags = this.producerInstances
.Where(pair => StandardPluginTypes.PluginTypeMap.ContainsKey(pair.Value.TypeName))
.Aggregate(StandardPluginTypes.PluginType.None, (agg, pair) => agg | StandardPluginTypes.PluginTypeMap[pair.Value.TypeName]);
pluginsEnabledBitFlags = this.consumerInstances
.Where(pair => StandardPluginTypes.PluginTypeMap.ContainsKey(pair.Value.TypeName))
.Aggregate(pluginsEnabledBitFlags, (agg, pair) => agg | StandardPluginTypes.PluginTypeMap[pair.Value.TypeName]);
if (Utility.IsSystemApplicationInstanceId(this.applicationInstanceId))
{
FabricEvents.Events.PluginConfigurationTelemetry((long)pluginsEnabledBitFlags);
if (this.errors.Any())
{
HealthClient.SendNodeHealthReport(string.Join("\n", this.errors), HealthState.Error, HealthSubProperty);
}
else
{
HealthClient.ClearNodeHealthReport(HealthSubProperty);
}
}
else
{
// ApplicationInstanceId will contain user app names, so we should hash value.
var derivedApplicationInstanceId = string.Format("App{0}", this.applicationInstanceId.GetHashCode());
FabricEvents.Events.AppPluginConfigurationTelemetry(derivedApplicationInstanceId, (long)pluginsEnabledBitFlags);
}
}
internal interface IDcaSettingsConfigReader
{
string GetProducerType(string sectionName);
string GetProducerInstances();
string GetAssemblyName(string consumerType);
string GetTypeName(string consumerType);
string GetConsumerType(string sectionName);
string GetConsumerInstances();
string GetProducerInstance(string sectionName);
}
internal IEnumerable<string> Errors
{
get
{
return this.errors.AsReadOnly();
}
}
// Dictionary of producer instances. The key is the name of the section
// containing information about the producer instance.
internal IReadOnlyDictionary<string, ProducerInstanceInfo> ProducerInstances
{
get
{
return this.producerInstances;
}
}
// Dictionary of consumer instances. The key is the name of the section
// containing information about the consumer instance.
internal IReadOnlyDictionary<string, ConsumerInstanceInfo> ConsumerInstances
{
get
{
return this.consumerInstances;
}
}
private ProducerInstanceInfo GetProducerInstanceInfo(string sectionName)
{
// Get the producer type
string producerType = this.configReader.GetProducerType(sectionName);
if (string.IsNullOrEmpty(producerType))
{
throw new InvalidOperationException(string.Format("Producer type has not been specified in section '{0}'.", sectionName));
}
producerType = producerType.Trim();
// Ensure that the producer type is supported
if (false == StandardPlugins.Producers.Contains(producerType))
{
throw new InvalidOperationException(
string.Format(
"Producer type '{0}' in section '{1}' is not supported.",
producerType,
sectionName));
}
// Return information to caller
var instanceInfo = new ProducerInstanceInfo
{
TypeName = producerType,
SectionName = sectionName
};
Utility.TraceSource.WriteInfo(
TraceType,
"Producer instance: {0}, producer type: {1}.",
sectionName,
producerType);
return instanceInfo;
}
private Dictionary<string, ProducerInstanceInfo> GetProducers(Action<string> onError)
{
// Initialize the producer info list
var instances = new Dictionary<string, ProducerInstanceInfo>();
// Get the producer information as a string from settings.xml
string producerList = this.configReader.GetProducerInstances();
if (string.IsNullOrEmpty(producerList))
{
Utility.TraceSource.WriteInfo(
TraceType,
"No producer instances specified in section '{0}'.",
ConfigReader.DiagnosticsSectionName);
return instances;
}
// Get the producer instance sections
string[] producers = producerList.Split(',');
// Go through each producer instance section to get more information
foreach (string producerAsIs in producers)
{
string producer = producerAsIs.Trim();
if (instances.ContainsKey(producer))
{
var message = string.Format(
"Producer instance '{0}' has been specified more than once in section '{1}'. Only the first appearance is used, subsequent appearances are ignored.",
producer,
ConfigReader.DiagnosticsSectionName);
onError(message);
continue;
}
try
{
instances[producer] = this.GetProducerInstanceInfo(producer);
}
catch (InvalidOperationException ex)
{
onError(ex.Message);
}
}
return instances;
}
private PluginInfo GetConsumerPluginInfo(string consumerType)
{
string assemblyName;
string typeName;
if (StandardPlugins.Consumers.ContainsKey(consumerType))
{
// This is a standard consumer plugin
assemblyName = StandardPlugins.Consumers[consumerType].AssemblyName;
typeName = StandardPlugins.Consumers[consumerType].TypeName;
}
else
{
// This is a custom consumer plugin
// Get the assembly name
assemblyName = this.configReader.GetAssemblyName(consumerType);
if (string.IsNullOrEmpty(assemblyName))
{
throw new InvalidOperationException(
string.Format(
"Assembly has not been specified in section '{0}'.",
consumerType));
}
assemblyName = assemblyName.Trim();
// Make sure that only the name of plug-in assembly is specified,
// without any path information
if (false == assemblyName.Equals(Path.GetFileName(assemblyName)))
{
throw new InvalidOperationException(
string.Format(
"Assembly name '{0}' in section '{1}' is not in the correct format. The assembly name should not include the path.",
assemblyName,
consumerType));
}
// Get the type name
typeName = this.configReader.GetTypeName(consumerType);
if (string.IsNullOrEmpty(typeName))
{
throw new InvalidOperationException(
string.Format(
"Type has not been specified in section '{0}'.",
consumerType));
}
typeName = typeName.Trim();
}
// Return information to caller
return new PluginInfo
{
AssemblyName = assemblyName,
TypeName = typeName
};
}
private ConsumerInstanceInfo GetConsumerInstanceInfo(string sectionName)
{
// Get the consumer type name
string consumerType = this.configReader.GetConsumerType(sectionName);
if (string.IsNullOrEmpty(consumerType))
{
throw new InvalidOperationException(
string.Format(
"Consumer type has not been specified in section '{0}'.",
sectionName));
}
consumerType = consumerType.Trim();
// Get information about the plug in that implements the consumer type
var pluginInfo = this.GetConsumerPluginInfo(consumerType);
// Get the producer instance that the consumer is associated with
string producerInstance = this.configReader.GetProducerInstance(sectionName);
if (string.IsNullOrEmpty(producerInstance))
{
throw new InvalidOperationException(
string.Format(
"Producer instance has not been specified in section '{0}'.",
sectionName));
}
producerInstance = producerInstance.Trim();
if (false == this.producerInstances.ContainsKey(producerInstance))
{
throw new InvalidOperationException(
string.Format(
"Producer instance '{0}' referenced in section '{1}' could not be found. This could be because the producer instance was not specified or was incorrectly specified.",
producerInstance,
sectionName));
}
// Return information to caller
var instanceInfo = new ConsumerInstanceInfo
{
TypeName = consumerType,
TypeInfo = pluginInfo,
ProducerInstance = producerInstance,
SectionName = sectionName
};
Utility.TraceSource.WriteInfo(
TraceType,
"Consumer instance: {0}, consumer type: {1}, consumer assembly: {2}, consumer type name: {3}, producer instance: {4}.",
sectionName,
consumerType,
pluginInfo.AssemblyName,
pluginInfo.TypeName,
producerInstance);
return instanceInfo;
}
private Dictionary<string, ConsumerInstanceInfo> GetConsumers(Action<string> onError)
{
// Initialize the consumer info list
var instances = new Dictionary<string, ConsumerInstanceInfo>();
// Get the consumer information as a string from settings.xml
string consumerList = this.configReader.GetConsumerInstances();
if (string.IsNullOrEmpty(consumerList))
{
Utility.TraceSource.WriteInfo(
TraceType,
"No consumer instances specified in section '{0}'.",
ConfigReader.DiagnosticsSectionName);
return instances;
}
// Get the consumer instance sections
string[] consumers = consumerList.Split(',');
// Go through each consumer instance section to get more information
foreach (string consumerAsIs in consumers)
{
string consumer = consumerAsIs.Trim();
if (instances.ContainsKey(consumer))
{
var message = string.Format(
"Consumer instance '{0}' has been specified more than once in section '{1}'. Only the first appearance is used, subsequent appearances are ignored.",
consumer,
ConfigReader.DiagnosticsSectionName);
onError(message);
continue;
}
try
{
instances[consumer] = this.GetConsumerInstanceInfo(consumer);
}
catch (InvalidOperationException ioe)
{
onError(ioe.Message);
}
}
return instances;
}
// Information about a producer instance
internal class ProducerInstanceInfo
{
internal string TypeName { get; set; }
internal string SectionName { get; set; }
}
// Information about plugins
internal class PluginInfo
{
internal string AssemblyName { get; set; }
internal string TypeName { get; set; }
}
// Information about a consumer instance
internal class ConsumerInstanceInfo
{
internal string TypeName { get; set; }
internal PluginInfo TypeInfo { get; set; }
internal string ProducerInstance { get; set; }
internal string SectionName { get; set; }
}
private class DcaSettingsConfigReader : IDcaSettingsConfigReader
{
private readonly ConfigReader configReader;
public DcaSettingsConfigReader(string applicationInstanceId)
{
this.configReader = new ConfigReader(applicationInstanceId);
}
public string GetProducerType(string sectionName)
{
return this.configReader.GetUnencryptedConfigValue(
sectionName,
ConfigReader.ProducerTypeParamName,
string.Empty);
}
public string GetProducerInstances()
{
return this.configReader.GetUnencryptedConfigValue(
ConfigReader.DiagnosticsSectionName,
ConfigReader.ProducerInstancesParamName,
string.Empty);
}
public string GetAssemblyName(string consumerType)
{
return this.configReader.GetUnencryptedConfigValue(
consumerType,
AssemblyParamName,
string.Empty);
}
public string GetTypeName(string consumerType)
{
return this.configReader.GetUnencryptedConfigValue(
consumerType,
TypeParamName,
string.Empty);
}
public string GetConsumerType(string sectionName)
{
return this.configReader.GetUnencryptedConfigValue(
sectionName,
ConfigReader.ConsumerTypeParamName,
string.Empty);
}
public string GetConsumerInstances()
{
return this.configReader.GetUnencryptedConfigValue(
ConfigReader.DiagnosticsSectionName,
ConfigReader.ConsumerInstancesParamName,
string.Empty);
}
public string GetProducerInstance(string sectionName)
{
return this.configReader.GetUnencryptedConfigValue(
sectionName,
ConfigReader.ProducerInstanceParamName,
string.Empty);
}
}
}
} | 39.087607 | 186 | 0.541792 | [
"MIT"
] | AlkisFortuneFish/service-fabric | src/prod/src/managed/DCA/product/host/DCASettings.cs | 18,293 | C# |
using System.Runtime.InteropServices;
namespace Libgpgme.Interop
{
[StructLayout(LayoutKind.Sequential)]
internal class _gpgme_op_keylist_result // *gpgme_keylist_result_t
{
public uint flags;
public bool truncated {
get => ((flags & 1) > 0);
set {
if (value) {
flags |= 1;
} else {
flags &= (~(uint) 1);
}
}
}
}
} | 23.809524 | 71 | 0.444 | [
"MIT"
] | Daniel15/gpgme-sharp | gpgme-sharp/Interop/_gpgme_op_keylist_result.cs | 500 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace Poker.Test
{
[TestClass]
public class IsFlushTests
{
[TestMethod]
public void IsFlushShouldReturnFalseIfDiffSuit()
{
var checker = new PokerHandsChecker();
var hand = new Hand(new List<ICard>
{
new Card(CardFace.Queen,CardSuit.Hearts),
new Card(CardFace.Jack,CardSuit.Hearts),
new Card(CardFace.King,CardSuit.Clubs),
new Card(CardFace.Ace,CardSuit.Spades),
new Card(CardFace.Ten,CardSuit.Diamonds)
});
Assert.IsFalse(checker.IsFlush(hand));
}
[TestMethod]
public void IsFlushShouldReturnTrueIfValidFlush()
{
var checker = new PokerHandsChecker();
var hand = new Hand(new List<ICard>
{
new Card(CardFace.Two,CardSuit.Hearts),
new Card(CardFace.Jack,CardSuit.Hearts),
new Card(CardFace.Eight,CardSuit.Hearts),
new Card(CardFace.Ace,CardSuit.Hearts),
new Card(CardFace.Ten,CardSuit.Hearts)
});
Assert.IsTrue(checker.IsFlush(hand));
}
}
}
| 31.068182 | 61 | 0.545721 | [
"MIT"
] | zvet80/TelerikAcademy | 08.High Quality Code/12.TestDrivenDevelopment/Poker.Test/IsFlushTests.cs | 1,369 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WFA_OOP_Class
{
//Nesnenin özelliklerini(Property) ve davranışlarını(Metot) tanımlayan şablonlardır.
class Hayvan
{
//Propety=> nesne için tanımlanan özellikler olarak adlandırılır. değer ataması yada okuması yapılır. bazı durumlarda sadece okuma ya da sadece yazma özellikleri verilebilir.
#region Diğer Dillerde GEt ve Set işlemi
//get: get metodu olarak adlandırılır.nedeni ise c# dan önceki gelişmiş oop tabandı dillerde (c++ ve Java) nesne içerisinde property diye bir kavram yoktur.
/*
class Hayvan
{
string _cinsi //field
public string getterCinsi()//fieldaki değeri okuması için tanımlanır.
{
return _cinsi;
}
public void setterCinsi(string value) //field'a değer ataması yapmak için
{
_cinsi=value;
}
}
*/
#endregion
public string Cinsi { get; set; }//auto implemented property
public string Renk { get; set; }
public string Ad { get; set; }
public byte Agirlik { get; set; }
public byte Yas { get; set; }
//Metotlar classların(Nesnelerin) davranışlarını belirlediğimiz yapılardır.
public void SesCikar()
{
}
}
}
| 31.458333 | 183 | 0.592715 | [
"MIT"
] | BercKoskun/CSharpBilge | OOP/22.01/WFA_OOP_Class/WFA_OOP_Class/Hayvan.cs | 1,559 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61968.Customers;
using TTC2017.SmartGrids.CIM.IEC61968.Metering;
using TTC2017.SmartGrids.CIM.IEC61968.PaymentMetering;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon;
namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfPaymentMetering
{
/// <summary>
/// The default implementation of the TransactionSummary class
/// </summary>
[XmlNamespaceAttribute("http://iec.ch/TC57/2009/CIM-schema-cim14#InfPaymentMetering")]
[XmlNamespacePrefixAttribute("cimInfPaymentMetering")]
[ModelRepresentationClassAttribute("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/Informative/InfPaymentMeterin" +
"g/TransactionSummary")]
[DebuggerDisplayAttribute("TransactionSummary {UUID}")]
public partial class TransactionSummary : Element, ITransactionSummary, IModelElement
{
/// <summary>
/// The backing field for the TransactionKind property
/// </summary>
private Nullable<TransactionKind> _transactionKind;
private static Lazy<ITypedElement> _transactionKindAttribute = new Lazy<ITypedElement>(RetrieveTransactionKindAttribute);
private static Lazy<ITypedElement> _lineReference = new Lazy<ITypedElement>(RetrieveLineReference);
/// <summary>
/// The backing field for the Line property
/// </summary>
private ILineDetail _line;
private static Lazy<ITypedElement> _shiftReference = new Lazy<ITypedElement>(RetrieveShiftReference);
/// <summary>
/// The backing field for the Shift property
/// </summary>
private IShift _shift;
private static IClass _classInstance;
/// <summary>
/// The transactionKind property
/// </summary>
[XmlElementNameAttribute("transactionKind")]
[XmlAttributeAttribute(true)]
public virtual Nullable<TransactionKind> TransactionKind
{
get
{
return this._transactionKind;
}
set
{
if ((this._transactionKind != value))
{
Nullable<TransactionKind> old = this._transactionKind;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnTransactionKindChanging(e);
this.OnPropertyChanging("TransactionKind", e, _transactionKindAttribute);
this._transactionKind = value;
this.OnTransactionKindChanged(e);
this.OnPropertyChanged("TransactionKind", e, _transactionKindAttribute);
}
}
}
/// <summary>
/// The line property
/// </summary>
[XmlElementNameAttribute("line")]
[XmlAttributeAttribute(true)]
public virtual ILineDetail Line
{
get
{
return this._line;
}
set
{
if ((this._line != value))
{
ILineDetail old = this._line;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnLineChanging(e);
this.OnPropertyChanging("Line", e, _lineReference);
this._line = value;
if ((old != null))
{
old.Deleted -= this.OnResetLine;
}
if ((value != null))
{
value.Deleted += this.OnResetLine;
}
this.OnLineChanged(e);
this.OnPropertyChanged("Line", e, _lineReference);
}
}
}
/// <summary>
/// The Shift property
/// </summary>
[XmlAttributeAttribute(true)]
[XmlOppositeAttribute("TransactionSummaries")]
public virtual IShift Shift
{
get
{
return this._shift;
}
set
{
if ((this._shift != value))
{
IShift old = this._shift;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnShiftChanging(e);
this.OnPropertyChanging("Shift", e, _shiftReference);
this._shift = value;
if ((old != null))
{
old.TransactionSummaries.Remove(this);
old.Deleted -= this.OnResetShift;
}
if ((value != null))
{
value.TransactionSummaries.Add(this);
value.Deleted += this.OnResetShift;
}
this.OnShiftChanged(e);
this.OnPropertyChanged("Shift", e, _shiftReference);
}
}
}
/// <summary>
/// Gets the referenced model elements of this model element
/// </summary>
public override IEnumerableExpression<IModelElement> ReferencedElements
{
get
{
return base.ReferencedElements.Concat(new TransactionSummaryReferencedElementsCollection(this));
}
}
/// <summary>
/// Gets the Class model for this type
/// </summary>
public new static IClass ClassInstance
{
get
{
if ((_classInstance == null))
{
_classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/Informative/InfPaymentMeterin" +
"g/TransactionSummary")));
}
return _classInstance;
}
}
/// <summary>
/// Gets fired before the TransactionKind property changes its value
/// </summary>
public event System.EventHandler<ValueChangedEventArgs> TransactionKindChanging;
/// <summary>
/// Gets fired when the TransactionKind property changed its value
/// </summary>
public event System.EventHandler<ValueChangedEventArgs> TransactionKindChanged;
/// <summary>
/// Gets fired before the Line property changes its value
/// </summary>
public event System.EventHandler<ValueChangedEventArgs> LineChanging;
/// <summary>
/// Gets fired when the Line property changed its value
/// </summary>
public event System.EventHandler<ValueChangedEventArgs> LineChanged;
/// <summary>
/// Gets fired before the Shift property changes its value
/// </summary>
public event System.EventHandler<ValueChangedEventArgs> ShiftChanging;
/// <summary>
/// Gets fired when the Shift property changed its value
/// </summary>
public event System.EventHandler<ValueChangedEventArgs> ShiftChanged;
private static ITypedElement RetrieveTransactionKindAttribute()
{
return ((ITypedElement)(((ModelElement)(TransactionSummary.ClassInstance)).Resolve("transactionKind")));
}
/// <summary>
/// Raises the TransactionKindChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnTransactionKindChanging(ValueChangedEventArgs eventArgs)
{
System.EventHandler<ValueChangedEventArgs> handler = this.TransactionKindChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the TransactionKindChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnTransactionKindChanged(ValueChangedEventArgs eventArgs)
{
System.EventHandler<ValueChangedEventArgs> handler = this.TransactionKindChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
private static ITypedElement RetrieveLineReference()
{
return ((ITypedElement)(((ModelElement)(TransactionSummary.ClassInstance)).Resolve("line")));
}
/// <summary>
/// Raises the LineChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnLineChanging(ValueChangedEventArgs eventArgs)
{
System.EventHandler<ValueChangedEventArgs> handler = this.LineChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the LineChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnLineChanged(ValueChangedEventArgs eventArgs)
{
System.EventHandler<ValueChangedEventArgs> handler = this.LineChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Handles the event that the Line property must reset
/// </summary>
/// <param name="sender">The object that sent this reset request</param>
/// <param name="eventArgs">The event data for the reset event</param>
private void OnResetLine(object sender, System.EventArgs eventArgs)
{
this.Line = null;
}
private static ITypedElement RetrieveShiftReference()
{
return ((ITypedElement)(((ModelElement)(TransactionSummary.ClassInstance)).Resolve("Shift")));
}
/// <summary>
/// Raises the ShiftChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnShiftChanging(ValueChangedEventArgs eventArgs)
{
System.EventHandler<ValueChangedEventArgs> handler = this.ShiftChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the ShiftChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnShiftChanged(ValueChangedEventArgs eventArgs)
{
System.EventHandler<ValueChangedEventArgs> handler = this.ShiftChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Handles the event that the Shift property must reset
/// </summary>
/// <param name="sender">The object that sent this reset request</param>
/// <param name="eventArgs">The event data for the reset event</param>
private void OnResetShift(object sender, System.EventArgs eventArgs)
{
this.Shift = null;
}
/// <summary>
/// Resolves the given attribute name
/// </summary>
/// <returns>The attribute value or null if it could not be found</returns>
/// <param name="attribute">The requested attribute name</param>
/// <param name="index">The index of this attribute</param>
protected override object GetAttributeValue(string attribute, int index)
{
if ((attribute == "TRANSACTIONKIND"))
{
return this.TransactionKind;
}
return base.GetAttributeValue(attribute, index);
}
/// <summary>
/// Sets a value to the given feature
/// </summary>
/// <param name="feature">The requested feature</param>
/// <param name="value">The value that should be set to that feature</param>
protected override void SetFeature(string feature, object value)
{
if ((feature == "LINE"))
{
this.Line = ((ILineDetail)(value));
return;
}
if ((feature == "SHIFT"))
{
this.Shift = ((IShift)(value));
return;
}
if ((feature == "TRANSACTIONKIND"))
{
this.TransactionKind = ((TransactionKind)(value));
return;
}
base.SetFeature(feature, value);
}
/// <summary>
/// Gets the property expression for the given attribute
/// </summary>
/// <returns>An incremental property expression</returns>
/// <param name="attribute">The requested attribute in upper case</param>
protected override NMF.Expressions.INotifyExpression<object> GetExpressionForAttribute(string attribute)
{
if ((attribute == "Line"))
{
return new LineProxy(this);
}
if ((attribute == "Shift"))
{
return new ShiftProxy(this);
}
return base.GetExpressionForAttribute(attribute);
}
/// <summary>
/// Gets the property expression for the given reference
/// </summary>
/// <returns>An incremental property expression</returns>
/// <param name="reference">The requested reference in upper case</param>
protected override NMF.Expressions.INotifyExpression<NMF.Models.IModelElement> GetExpressionForReference(string reference)
{
if ((reference == "Line"))
{
return new LineProxy(this);
}
if ((reference == "Shift"))
{
return new ShiftProxy(this);
}
return base.GetExpressionForReference(reference);
}
/// <summary>
/// Gets the Class for this model element
/// </summary>
public override IClass GetClass()
{
if ((_classInstance == null))
{
_classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/Informative/InfPaymentMeterin" +
"g/TransactionSummary")));
}
return _classInstance;
}
/// <summary>
/// The collection class to to represent the children of the TransactionSummary class
/// </summary>
public class TransactionSummaryReferencedElementsCollection : ReferenceCollection, ICollectionExpression<IModelElement>, ICollection<IModelElement>
{
private TransactionSummary _parent;
/// <summary>
/// Creates a new instance
/// </summary>
public TransactionSummaryReferencedElementsCollection(TransactionSummary parent)
{
this._parent = parent;
}
/// <summary>
/// Gets the amount of elements contained in this collection
/// </summary>
public override int Count
{
get
{
int count = 0;
if ((this._parent.Line != null))
{
count = (count + 1);
}
if ((this._parent.Shift != null))
{
count = (count + 1);
}
return count;
}
}
protected override void AttachCore()
{
this._parent.LineChanged += this.PropagateValueChanges;
this._parent.ShiftChanged += this.PropagateValueChanges;
}
protected override void DetachCore()
{
this._parent.LineChanged -= this.PropagateValueChanges;
this._parent.ShiftChanged -= this.PropagateValueChanges;
}
/// <summary>
/// Adds the given element to the collection
/// </summary>
/// <param name="item">The item to add</param>
public override void Add(IModelElement item)
{
if ((this._parent.Line == null))
{
ILineDetail lineCasted = item.As<ILineDetail>();
if ((lineCasted != null))
{
this._parent.Line = lineCasted;
return;
}
}
if ((this._parent.Shift == null))
{
IShift shiftCasted = item.As<IShift>();
if ((shiftCasted != null))
{
this._parent.Shift = shiftCasted;
return;
}
}
}
/// <summary>
/// Clears the collection and resets all references that implement it.
/// </summary>
public override void Clear()
{
this._parent.Line = null;
this._parent.Shift = null;
}
/// <summary>
/// Gets a value indicating whether the given element is contained in the collection
/// </summary>
/// <returns>True, if it is contained, otherwise False</returns>
/// <param name="item">The item that should be looked out for</param>
public override bool Contains(IModelElement item)
{
if ((item == this._parent.Line))
{
return true;
}
if ((item == this._parent.Shift))
{
return true;
}
return false;
}
/// <summary>
/// Copies the contents of the collection to the given array starting from the given array index
/// </summary>
/// <param name="array">The array in which the elements should be copied</param>
/// <param name="arrayIndex">The starting index</param>
public override void CopyTo(IModelElement[] array, int arrayIndex)
{
if ((this._parent.Line != null))
{
array[arrayIndex] = this._parent.Line;
arrayIndex = (arrayIndex + 1);
}
if ((this._parent.Shift != null))
{
array[arrayIndex] = this._parent.Shift;
arrayIndex = (arrayIndex + 1);
}
}
/// <summary>
/// Removes the given item from the collection
/// </summary>
/// <returns>True, if the item was removed, otherwise False</returns>
/// <param name="item">The item that should be removed</param>
public override bool Remove(IModelElement item)
{
if ((this._parent.Line == item))
{
this._parent.Line = null;
return true;
}
if ((this._parent.Shift == item))
{
this._parent.Shift = null;
return true;
}
return false;
}
/// <summary>
/// Gets an enumerator that enumerates the collection
/// </summary>
/// <returns>A generic enumerator</returns>
public override IEnumerator<IModelElement> GetEnumerator()
{
return Enumerable.Empty<IModelElement>().Concat(this._parent.Line).Concat(this._parent.Shift).GetEnumerator();
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the transactionKind property
/// </summary>
private sealed class TransactionKindProxy : ModelPropertyChange<ITransactionSummary, Nullable<TransactionKind>>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public TransactionKindProxy(ITransactionSummary modelElement) :
base(modelElement, "transactionKind")
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override Nullable<TransactionKind> Value
{
get
{
return this.ModelElement.TransactionKind;
}
set
{
this.ModelElement.TransactionKind = value;
}
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the line property
/// </summary>
private sealed class LineProxy : ModelPropertyChange<ITransactionSummary, ILineDetail>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public LineProxy(ITransactionSummary modelElement) :
base(modelElement, "line")
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override ILineDetail Value
{
get
{
return this.ModelElement.Line;
}
set
{
this.ModelElement.Line = value;
}
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the Shift property
/// </summary>
private sealed class ShiftProxy : ModelPropertyChange<ITransactionSummary, IShift>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public ShiftProxy(ITransactionSummary modelElement) :
base(modelElement, "Shift")
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override IShift Value
{
get
{
return this.ModelElement.Shift;
}
set
{
this.ModelElement.Shift = value;
}
}
}
}
}
| 36.638519 | 164 | 0.514739 | [
"MIT"
] | georghinkel/ttc2017smartGrids | generator/Schema/IEC61970/Informative/InfPaymentMetering/TransactionSummary.cs | 24,733 | C# |
using System.Linq;
namespace SparkPost
{
public static class LeftRight
{
public static void SetValuesToMatch(object left, object right)
{
var leftProperties = left.GetType().GetProperties();
var rightProperties = left.GetType().GetProperties();
foreach (var rightProperty in rightProperties)
{
try
{
var leftProperty = leftProperties.FirstOrDefault(x => x.Name == rightProperty.Name);
leftProperty?.SetValue(left, rightProperty.GetValue(right));
}
catch
{
// ignore
}
}
}
}
} | 29.16 | 104 | 0.500686 | [
"Apache-2.0"
] | Combeenation/csharp-sparkpost | src/SparkPost/LeftRight.cs | 731 | C# |
using RuriLib.Parallelization.Exceptions;
using RuriLib.Parallelization.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace RuriLib.Parallelization
{
/// <summary>
/// Provides a managed way to execute parallelized work.
/// </summary>
/// <typeparam name="TInput">The type of the workload items</typeparam>
/// <typeparam name="TOutput">The type of the results</typeparam>
public abstract class Parallelizer<TInput, TOutput>
{
#region Public Fields
public int MaxDegreeOfParallelism { get; set; } = 200;
public ParallelizerStatus Status
{
get => status;
protected set
{
status = value;
OnStatusChanged(status);
}
}
/// <summary>
/// Retrieves the current progress in the interval [0, 1].
/// The progress is -1 if the manager hasn't been started yet.
/// </summary>
public float Progress { get; protected set; } = 0;
/// <summary>
/// Retrieves the completed work per minute.
/// </summary>
public int CPM { get; protected set; } = 0;
/// <summary>
/// Sets a maximum threshold for CPM. 0 to disable.
/// </summary>
public int CPMLimit { get; set; } = 0;
public DateTime StartTime { get; private set; }
public DateTime? EndTime { get; private set; }
public DateTime ETA => CPM > 0
? StartTime + TimeSpan.FromMinutes((totalAmount * (1 - Progress)) / CPM)
: DateTime.MaxValue;
public TimeSpan Elapsed => (EndTime ?? DateTime.Now) - StartTime;
public TimeSpan Remaining => EndTime.HasValue ? TimeSpan.Zero : ETA - DateTime.Now;
#endregion
#region Protected Fields
protected ParallelizerStatus status = ParallelizerStatus.Idle;
protected int degreeOfParallelism;
protected readonly IEnumerable<TInput> workItems;
protected readonly Func<TInput, CancellationToken, Task<TOutput>> workFunction;
protected readonly Func<TInput, Task> taskFunction;
protected readonly int totalAmount;
protected readonly int skip;
protected int current;
protected List<DateTime> checkedTimestamps = new();
protected readonly object cpmLock = new();
protected CancellationTokenSource softCTS; // Cancel this for soft AND hard abort
protected CancellationTokenSource hardCTS; // Cancel this for hard abort
#endregion
#region Events
/// <summary>Called when an operation throws an exception.</summary>
public event EventHandler<ErrorDetails<TInput>> TaskError;
protected virtual void OnTaskError(ErrorDetails<TInput> input) => TaskError?.Invoke(this, input);
/// <summary>Called when the <see cref="IParallelizer{TInput, TOutput}"/> itself throws an exception.</summary>
public event EventHandler<Exception> Error;
protected virtual void OnError(Exception ex) => Error?.Invoke(this, ex);
/// <summary>Called when an operation is completed successfully.</summary>
public event EventHandler<ResultDetails<TInput, TOutput>> NewResult;
protected virtual void OnNewResult(ResultDetails<TInput, TOutput> result) => NewResult?.Invoke(this, result);
/// <summary>Called when the progress changes.</summary>
public event EventHandler<float> ProgressChanged;
protected virtual void OnProgressChanged(float progress) => ProgressChanged?.Invoke(this, progress);
/// <summary>Called when all operations were completed successfully.</summary>
public event EventHandler Completed;
protected virtual void OnCompleted() => Completed?.Invoke(this, EventArgs.Empty);
/// <summary>Called when <see cref="Status"/> changes.</summary>
public event EventHandler<ParallelizerStatus> StatusChanged;
protected virtual void OnStatusChanged(ParallelizerStatus newStatus) => StatusChanged?.Invoke(this, newStatus);
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of <see cref="Parallelizer{TInput, TOutput}"/>.
/// </summary>
/// <param name="workItems">The collection of data to process in parallel</param>
/// <param name="workFunction">The work function that must be executed on the data</param>
/// <param name="degreeOfParallelism">The amount of concurrent tasks that can be started</param>
/// <param name="totalAmount">The total amount of data that is expected from <paramref name="workItems"/></param>
/// <param name="skip">The amount of <paramref name="workItems"/> to skip at the beginning</param>
public Parallelizer(IEnumerable<TInput> workItems, Func<TInput, CancellationToken, Task<TOutput>> workFunction,
int degreeOfParallelism, int totalAmount, int skip = 0)
{
if (degreeOfParallelism < 1)
throw new ArgumentException("The degree of parallelism must be greater than 1");
if (skip >= totalAmount)
throw new ArgumentException("The skip must be less than the total amount");
this.workItems = workItems ?? throw new ArgumentNullException(nameof(workItems));
this.workFunction = workFunction ?? throw new ArgumentNullException(nameof(workFunction));
this.totalAmount = totalAmount;
this.degreeOfParallelism = degreeOfParallelism;
this.skip = skip;
MaxDegreeOfParallelism = Math.Max(200, degreeOfParallelism);
// Assign the task function
taskFunction = new Func<TInput, Task>(async item =>
{
if (softCTS.IsCancellationRequested)
return;
// Try to execute the work and report the result
try
{
var workResult = await workFunction.Invoke(item, hardCTS.Token).ConfigureAwait(false);
OnNewResult(new ResultDetails<TInput, TOutput>(item, workResult));
hardCTS.Token.ThrowIfCancellationRequested();
}
// Catch and report any exceptions
catch (Exception ex)
{
OnTaskError(new ErrorDetails<TInput>(item, ex));
}
// Report the progress, update the CPM and release the semaphore slot
finally
{
Progress = (float)(++current + skip) / totalAmount;
OnProgressChanged(Progress);
checkedTimestamps.Add(DateTime.Now);
UpdateCPM();
}
});
}
#endregion
#region Public Methods
/// <summary>
/// Starts the execution (without waiting for completion).
/// </summary>
public virtual Task Start()
{
if (Status != ParallelizerStatus.Idle)
throw new RequiredStatusException(ParallelizerStatus.Idle, Status);
StartTime = DateTime.Now;
EndTime = null;
checkedTimestamps.Clear();
softCTS = new CancellationTokenSource();
hardCTS = new CancellationTokenSource();
return Task.CompletedTask;
}
/// <summary>Pauses the execution (waits until the ongoing operations are completed).</summary>
public virtual Task Pause()
{
if (Status != ParallelizerStatus.Running)
throw new RequiredStatusException(ParallelizerStatus.Running, Status);
return Task.CompletedTask;
}
/// <summary>Resumes a paused execution.</summary>
public virtual Task Resume()
{
if (Status != ParallelizerStatus.Paused)
throw new RequiredStatusException(ParallelizerStatus.Paused, Status);
return Task.CompletedTask;
}
/// <summary>
/// Stops the execution (waits for the current items to finish).
/// </summary>
public virtual Task Stop()
{
if (Status != ParallelizerStatus.Running && Status != ParallelizerStatus.Paused)
throw new RequiredStatusException(new ParallelizerStatus[] { ParallelizerStatus.Running, ParallelizerStatus.Paused }, Status);
EndTime = DateTime.Now;
return Task.CompletedTask;
}
/// <summary>
/// Aborts the execution without waiting for the current work to finish.
/// </summary>
public virtual Task Abort()
{
if (Status != ParallelizerStatus.Running && Status != ParallelizerStatus.Paused && Status != ParallelizerStatus.Stopping)
throw new RequiredStatusException(new ParallelizerStatus[]
{ ParallelizerStatus.Running, ParallelizerStatus.Paused, ParallelizerStatus.Stopping}, Status);
EndTime = DateTime.Now;
return Task.CompletedTask;
}
/// <summary>
/// Dynamically changes the degree of parallelism.
/// </summary>
public virtual Task ChangeDegreeOfParallelism(int newValue)
{
// This can be 0 because we can use 0 dop as a pausing system
if (newValue < 0 || newValue > MaxDegreeOfParallelism)
throw new ArgumentException($"Must be within 0 and {MaxDegreeOfParallelism}", nameof(newValue));
return Task.CompletedTask;
}
/// <summary>
/// An awaitable handler that completes when the <see cref="Status"/> is <see cref="ParallelizerStatus.Idle"/>.
/// </summary>
public async Task WaitCompletion(CancellationToken cancellationToken = default)
{
while (Status != ParallelizerStatus.Idle)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(100, cancellationToken);
}
}
#endregion
#region Protected Methods
protected bool IsCPMLimited() => CPMLimit > 0 && CPM > CPMLimit;
protected void UpdateCPM()
{
// Update CPM (only 1 task can enter)
if (Monitor.TryEnter(cpmLock))
{
try
{
var now = DateTime.Now;
checkedTimestamps = checkedTimestamps.Where(t => (now - t).TotalSeconds < 60).ToList();
CPM = checkedTimestamps.Count;
}
finally
{
Monitor.Exit(cpmLock);
}
}
}
#endregion
}
}
| 40.745318 | 142 | 0.605478 | [
"MIT"
] | EvoDotBlack/OpenBullet2 | RuriLib.Parallelization/Parallelizer.cs | 10,881 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
namespace Zenject
{
public abstract class ProviderBindingFinalizer : IBindingFinalizer
{
public ProviderBindingFinalizer(BindInfo bindInfo)
{
BindInfo = bindInfo;
}
public bool CopyIntoAllSubContainers
{
get { return BindInfo.CopyIntoAllSubContainers; }
}
public BindInfo BindInfo
{
get;
private set;
}
protected ScopeTypes GetScope()
{
if (BindInfo.Scope == ScopeTypes.Unset)
{
// If condition is set then it's probably fine to allow the default of transient
Assert.That(!BindInfo.RequireExplicitScope || BindInfo.Condition != null,
"Scope must be set for the previous binding! Please either specify AsTransient, AsCached, or AsSingle. Last binding: Contract: {0}, Identifier: {1} {2}",
BindInfo.ContractTypes.Select(x => x.ToString()).Join(", "), BindInfo.Identifier,
BindInfo.ContextInfo != null ? "Context: '{0}'".Fmt(BindInfo.ContextInfo) : "");
return ScopeTypes.Transient;
}
return BindInfo.Scope;
}
public void FinalizeBinding(DiContainer container)
{
if (BindInfo.ContractTypes.IsEmpty())
{
// We could assert her instead but it is nice when used with things like
// BindInterfaces() (and there aren't any interfaces) to allow
// interfaces to be added later
return;
}
OnFinalizeBinding(container);
if (BindInfo.NonLazy)
{
// Note that we can't simply use container.BindRootResolve here because
// binding finalizers must only use RegisterProvider to allow cloning / bind
// inheritance to work properly
var bindingId = new BindingId(
typeof(object), DiContainer.DependencyRootIdentifier);
foreach (var contractType in BindInfo.ContractTypes)
{
container.RegisterProvider(
bindingId, null, new ResolveProvider(
contractType, container, BindInfo.Identifier, false,
// We always want to only use local here so that we can use
// NonLazy() inside subcontainers
InjectSources.Local));
}
}
}
protected abstract void OnFinalizeBinding(DiContainer container);
protected void RegisterProvider<TContract>(
DiContainer container, IProvider provider)
{
RegisterProvider(container, typeof(TContract), provider);
}
protected void RegisterProvider(
DiContainer container, Type contractType, IProvider provider)
{
container.RegisterProvider(
new BindingId(contractType, BindInfo.Identifier),
BindInfo.Condition,
provider);
if (contractType.IsValueType())
{
var nullableType = typeof(Nullable<>).MakeGenericType(contractType);
// Also bind to nullable primitives
// this is useful so that we can have optional primitive dependencies
container.RegisterProvider(
new BindingId(nullableType, BindInfo.Identifier),
BindInfo.Condition,
provider);
}
}
protected void RegisterProviderPerContract(
DiContainer container, Func<DiContainer, Type, IProvider> providerFunc)
{
foreach (var contractType in BindInfo.ContractTypes)
{
RegisterProvider(container, contractType, providerFunc(container, contractType));
}
}
protected void RegisterProviderForAllContracts(
DiContainer container, IProvider provider)
{
foreach (var contractType in BindInfo.ContractTypes)
{
RegisterProvider(container, contractType, provider);
}
}
protected void RegisterProvidersPerContractAndConcreteType(
DiContainer container,
List<Type> concreteTypes,
Func<Type, Type, IProvider> providerFunc)
{
Assert.That(!BindInfo.ContractTypes.IsEmpty());
Assert.That(!concreteTypes.IsEmpty());
foreach (var contractType in BindInfo.ContractTypes)
{
foreach (var concreteType in concreteTypes)
{
if (ValidateBindTypes(concreteType, contractType))
{
RegisterProvider(
container, contractType, providerFunc(contractType, concreteType));
}
}
}
}
// Returns true if the bind should continue, false to skip
bool ValidateBindTypes(Type concreteType, Type contractType)
{
if (concreteType.IsOpenGenericType() != contractType.IsOpenGenericType())
{
return false;
}
#if !(UNITY_WSA && ENABLE_DOTNET)
// TODO: Is it possible to do this on WSA?
if (contractType.IsOpenGenericType())
{
Assert.That(concreteType.IsOpenGenericType());
if (TypeExtensions.IsAssignableToGenericType(concreteType, contractType))
{
return true;
}
}
else if (concreteType.DerivesFromOrEqual(contractType))
{
return true;
}
#else
if (concreteType.DerivesFromOrEqual(contractType))
{
return true;
}
#endif
if (BindInfo.InvalidBindResponse == InvalidBindResponses.Assert)
{
throw Assert.CreateException(
"Expected type '{0}' to derive from or be equal to '{1}'", concreteType, contractType);
}
Assert.IsEqual(BindInfo.InvalidBindResponse, InvalidBindResponses.Skip);
return false;
}
// Note that if multiple contract types are provided per concrete type,
// it will re-use the same provider for each contract type
// (each concrete type will have its own provider though)
protected void RegisterProvidersForAllContractsPerConcreteType(
DiContainer container,
List<Type> concreteTypes,
Func<DiContainer, Type, IProvider> providerFunc)
{
Assert.That(!BindInfo.ContractTypes.IsEmpty());
Assert.That(!concreteTypes.IsEmpty());
var providerMap = concreteTypes.ToDictionary(x => x, x => providerFunc(container, x));
foreach (var contractType in BindInfo.ContractTypes)
{
foreach (var concreteType in concreteTypes)
{
if (ValidateBindTypes(concreteType, contractType))
{
RegisterProvider(container, contractType, providerMap[concreteType]);
}
}
}
}
}
}
| 35.947368 | 174 | 0.555171 | [
"MIT"
] | mgrman/TycoonTerain | Assets/Plugins/Zenject/Source/Binding/Finalizers/ProviderBindingFinalizer.cs | 7,513 | C# |
// This file has been generated using the Simplic.Flow.NodeGenerator
using System;
using Simplic.Flow;
namespace Simplic.Flow.Node
{
[ActionNodeDefinition(Name = nameof(SystemConvertToByte_Int32), DisplayName = "ToByte(Int32)", Category = "System/Convert")]
public class SystemConvertToByte_Int32 : ActionNode
{
public override bool Execute(IFlowRuntimeService runtime, DataPinScope scope)
{
try
{
var returnValue = System.Convert.ToByte(
scope.GetValue<System.Int32>(InPinValue));
scope.SetValue(OutPinReturn, returnValue);
if (OutNodeSuccess != null)
{
runtime.EnqueueNode(OutNodeSuccess, scope);
}
}
catch (Exception ex)
{
Simplic.Log.LogManagerInstance.Instance.Error("Error in SystemConvertToByte_Int32: ", ex);
if (OutNodeFailed != null)
runtime.EnqueueNode(OutNodeFailed, scope);
}
return true;
}
public override string Name => nameof(SystemConvertToByte_Int32);
public override string FriendlyName => nameof(SystemConvertToByte_Int32);
[FlowPinDefinition(
PinDirection = PinDirection.Out,
DisplayName = "Success",
Name = nameof(OutNodeSuccess),
AllowMultiple = false)]
public ActionNode OutNodeSuccess { get; set; }
[FlowPinDefinition(
PinDirection = PinDirection.Out,
DisplayName = "Failed",
Name = nameof(OutNodeFailed),
AllowMultiple = false)]
public ActionNode OutNodeFailed { get; set; }
[DataPinDefinition(
Id = "ba09d7a9-bfaa-4558-9156-f9a1db8d4be6",
ContainerType = DataPinContainerType.Single,
DataType = typeof(System.Int32),
Direction = PinDirection.In,
Name = nameof(InPinValue),
DisplayName = "Value",
IsGeneric = false,
AllowedTypes = null)]
public DataPin InPinValue { get; set; }
[DataPinDefinition(
Id = "06e50b93-8f18-4fc6-afdc-4a912f995647",
ContainerType = DataPinContainerType.Single,
DataType = typeof(System.Byte),
Direction = PinDirection.Out,
Name = nameof(OutPinReturn),
DisplayName = "Return",
IsGeneric = false,
AllowedTypes = null)]
public DataPin OutPinReturn { get; set; }
}
} | 34.916667 | 128 | 0.59825 | [
"MIT"
] | simplic/flow | src/Simplic.Flow.Node/ActionNode/Generic/System.Convert/SystemConvertToByte_Int32Node.cs | 2,514 | C# |
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using CMS.Base.Web.UI;
using CMS.FormEngine;
using CMS.FormEngine.Web.UI;
using CMS.Helpers;
using Newtonsoft.Json;
public partial class CMSFormControls_Basic_DropDownListControl : ListFormControl
{
private bool? mEditText;
private string mOnChangeScript;
protected override ListControl ListControl => dropDownList;
protected override ListSelectionMode SelectionMode => ListSelectionMode.Single;
protected override string FormControlName => FormFieldControlName.DROPDOWNLIST;
protected override string DefaultCssClass => null;
/// <summary>
/// Returns display name of the value.
/// </summary>
public override string ValueDisplayName => (EditText || (dropDownList.SelectedItem == null) ? txtCombo.Text : dropDownList.SelectedItem.Text);
/// <summary>
/// Gets or sets selected string value.
/// </summary>
public string SelectedValue
{
get
{
return (EditText) ? txtCombo.Text : dropDownList.SelectedValue;
}
set
{
if (EditText)
{
txtCombo.Text = value;
}
else
{
dropDownList.SelectedValue = value;
}
}
}
/// <summary>
/// Gets or sets selected index. Returns -1 if no element is selected.
/// </summary>
public int SelectedIndex
{
get
{
if (EditText)
{
if (dropDownList.Items.FindByValue(txtCombo.Text) != null)
{
return dropDownList.SelectedIndex;
}
return -1;
}
return dropDownList.SelectedIndex;
}
set
{
dropDownList.SelectedIndex = value;
if (EditText)
{
txtCombo.Text = dropDownList.SelectedValue;
}
}
}
/// <summary>
/// Enables to edit text from textbox and select values from dropdown list.
/// </summary>
public bool EditText
{
get
{
return mEditText ?? ValidationHelper.GetBoolean(GetValue("edittext"), false);
}
set
{
mEditText = value;
}
}
/// <summary>
/// Gets dropdown list control.
/// </summary>
public CMSDropDownList DropDownList => dropDownList;
/// <summary>
/// Gets textbox control.
/// </summary>
public CMSTextBox TextBoxControl => txtCombo;
/// <summary>
/// Gets or sets Javascript code that is executed when selected item is changed.
/// </summary>
public string OnChangeClientScript
{
get
{
return mOnChangeScript ?? ValidationHelper.GetString(GetValue("OnChangeClientScript"), String.Empty);
}
set
{
mOnChangeScript = value;
}
}
/// <summary>
/// Indicates whether actual value (that is not present among options) will be displayed as DDL item.
/// </summary>
public bool DisplayActualValueAsItem
{
get
{
return GetValue("DisplayActualValueAsItem", false);
}
set
{
SetValue("DisplayActualValueAsItem", value);
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (EditText)
{
ApplyCssClassAndStyles(txtCombo);
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// It's always necessary to determine visible control
txtCombo.Visible = EditText;
dropDownList.Visible = !EditText;
if (StopProcessing || !Enabled)
{
// Do nothing
return;
}
if (EditText)
{
btnAutocomplete.Visible = true;
string dependingScriptPart = HasDependingFields ? string.Format(
@",
change: function (event, ui) {{
__doPostBack('#{0}', '');
}},
close: function(event, ui) {{
if (event.originalEvent && event.originalEvent.type === 'menuselect') {{
__doPostBack('#{0}', '');
}}
}}", txtCombo.ClientID) : "";
ScriptHelper.RegisterJQueryUI(Page);
ScriptHelper.RegisterStartupScript(Page, typeof (string), "Autocomplete_" + ClientID, ScriptHelper.GetScript(string.Format(
@"var txtCombo{0} = $cmsj('#{0}');
// Perform autocomplete
txtCombo{0}.autocomplete({{
source: {1},
minLength: 0,
appendTo: '#{2}'{4}
}});
// Open dropdown list
txtCombo{0}.add($cmsj('#{3}')).on('click', function () {{
txtCombo{0}.autocomplete('search', '');
txtCombo{0}.focus();
}});
// Close dropdown list if scrolled outside the list
$cmsj(document).bind('mousewheel DOMMouseScroll', function (e) {{
if (!txtCombo{0}.autocomplete('widget').is(':hover')) {{
txtCombo{0}.autocomplete('close');
}}
}});", txtCombo.ClientID, GetDataAsJsArray(), autoComplete.ClientID, btnAutocomplete.ClientID, dependingScriptPart)));
}
else
{
if (!String.IsNullOrEmpty(OnChangeClientScript))
{
dropDownList.Attributes.Add("onchange", OnChangeClientScript);
}
}
}
/// <summary>
/// Returns string with selected value of the <see cref="DropDownList"/> or text of the <see cref="TextBoxControl"/>.
/// </summary>
protected override object GetControlValue()
{
return (EditText) ? txtCombo.Text : dropDownList.SelectedValue;
}
/// <summary>
/// Sets selected item of the <see cref="DropDownList"/> or text of the <see cref="TextBoxControl"/> based on the given <paramref name="value"/>.
/// </summary>
/// <param name="value">Value to be set</param>
protected override void SetControlValue(object value)
{
LoadAndSelectList();
value = ConvertInputValue(value);
string selectedValue = ValidationHelper.GetString(value, String.Empty);
if (value != null)
{
EnsureActualValueAsItem(selectedValue);
}
if (EditText)
{
txtCombo.Text = selectedValue;
}
else
{
dropDownList.ClearSelection();
SelectSingleValue(selectedValue);
}
}
/// <summary>
/// Returns data as JavaScript array (e.g.: ['value1', 'value2']).
/// </summary>
private string GetDataAsJsArray()
{
var array = new List<string>();
foreach (var item in dropDownList.Items)
{
array.Add(((ListItem)item).Text);
}
return JsonConvert.SerializeObject(array, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml });
}
/// <summary>
/// Ensures that a value which is not among DDL items but is present in the database is added to DDL items collection.
/// </summary>
private void EnsureActualValueAsItem(string value)
{
if (DisplayActualValueAsItem)
{
var item = dropDownList.Items.FindByValue(value);
if (item == null)
{
dropDownList.Items.Add(new ListItem(value));
if (SortItems)
{
dropDownList.SortItems();
}
}
}
}
} | 25.833887 | 150 | 0.548354 | [
"MIT"
] | Kentico/xperience-module-intercom | src/CMS/CMSFormControls/Basic/DropDownListControl.ascx.cs | 7,778 | 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.ServiceFabric.V20200301.Inputs
{
/// <summary>
/// Describes the policy for a monitored application upgrade.
/// </summary>
public sealed class ApplicationUpgradePolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Defines a health policy used to evaluate the health of an application or one of its children entities.
/// </summary>
[Input("applicationHealthPolicy")]
public Input<Inputs.ArmApplicationHealthPolicyArgs>? ApplicationHealthPolicy { get; set; }
/// <summary>
/// If true, then processes are forcefully restarted during upgrade even when the code version has not changed (the upgrade only changes configuration or data).
/// </summary>
[Input("forceRestart")]
public Input<bool>? ForceRestart { get; set; }
/// <summary>
/// The policy used for monitoring the application upgrade
/// </summary>
[Input("rollingUpgradeMonitoringPolicy")]
public Input<Inputs.ArmRollingUpgradeMonitoringPolicyArgs>? RollingUpgradeMonitoringPolicy { get; set; }
/// <summary>
/// The mode used to monitor health during a rolling upgrade. The values are UnmonitoredAuto, UnmonitoredManual, and Monitored.
/// </summary>
[Input("upgradeMode")]
public Input<string>? UpgradeMode { get; set; }
/// <summary>
/// The maximum amount of time to block processing of an upgrade domain and prevent loss of availability when there are unexpected issues. When this timeout expires, processing of the upgrade domain will proceed regardless of availability loss issues. The timeout is reset at the start of each upgrade domain. Valid values are between 0 and 42949672925 inclusive. (unsigned 32-bit integer).
/// </summary>
[Input("upgradeReplicaSetCheckTimeout")]
public Input<string>? UpgradeReplicaSetCheckTimeout { get; set; }
public ApplicationUpgradePolicyArgs()
{
}
}
}
| 44.132075 | 398 | 0.686618 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ServiceFabric/V20200301/Inputs/ApplicationUpgradePolicyArgs.cs | 2,339 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Vikekh.FilmtipsetExport.Cli.Models
{
public class MovieRatingsPageItem
{
public int Rating { get; set; }
public string Slug { get; set; }
public string SwedishTitle { get; set; }
public DateTime Date { get; set; }
}
}
| 19.555556 | 48 | 0.633523 | [
"MIT"
] | vikekh/filmtipset-export | src/Vikekh.FilmtipsetExport.Cli/Models/MovieRatingsPageItem.cs | 354 | C# |
using System;
using Calabonga.AspNetCore.MicroModule.Core.Exceptions;
using Microsoft.Extensions.Caching.Memory;
namespace Calabonga.AspNetCore.MicroModule.Web.Infrastructure.Services
{
/// <summary>
/// Cache service
/// </summary>
public class CacheService : ICacheService
{
private readonly IMemoryCache _cache;
private readonly TimeSpan _defaultSlidingExpiration = TimeSpan.FromSeconds(60);
/// <inheritdoc />
public CacheService(IMemoryCache cache)
{
_cache = cache;
}
/// <inheritdoc />
public TEntry Get<TEntry>(object key)
{
if (key == null)
{
throw new MicroserviceArgumentNullException(nameof(key));
}
return _cache.Get<TEntry>(key);
}
/// <inheritdoc />
public void SetForMinute<TEntry>(object key, TEntry cacheEntry)
{
SetWithSlidingExpiration(key, cacheEntry, _defaultSlidingExpiration);
}
/// <inheritdoc />
public void SetForThirtyMinutes<TEntry>(object key, TEntry cacheEntry)
{
SetWithSlidingExpiration(key, cacheEntry, TimeSpan.FromMinutes(30));
}
/// <summary>
/// Default set mechanism
/// </summary>
/// <typeparam name="TEntry"></typeparam>
/// <param name="key"></param>
/// <param name="cacheEntry"></param>
/// <param name="slidingExpiration"></param>
public void SetWithSlidingExpiration<TEntry>(object key, TEntry cacheEntry, TimeSpan slidingExpiration)
{
if (cacheEntry == null)
{
throw new MicroserviceArgumentNullException(nameof(cacheEntry));
}
if (key == null)
{
throw new MicroserviceArgumentNullException(nameof(key));
}
if (slidingExpiration.Ticks == 0)
{
slidingExpiration = _defaultSlidingExpiration;
}
var options = new MemoryCacheEntryOptions().SetSlidingExpiration(slidingExpiration);
_cache.Set(key, cacheEntry, options);
}
/// <inheritdoc />
public TEntry GetOrCreate<TKey, TEntry>(TKey key, Func<ICacheEntry, TEntry> findIfNotFoundFunc)
{
return _cache.GetOrCreate(key, findIfNotFoundFunc);
}
}
}
| 30.325 | 111 | 0.582852 | [
"MIT"
] | Calabonga/Microservice-Template | AspNetCore v2.2/Calabonga.AspNetCore.MicroModule/Calabonga.AspNetCore.MicroModule/Calabonga.AspNetCore.MicroModule.Web/Infrastructure/Services/CacheService.cs | 2,428 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teknik.Areas.Shortener.Models;
using Teknik.Utilities;
using Teknik.Models;
using Teknik.Data;
namespace Teknik.Areas.Shortener
{
public static class ShortenerHelper
{
public static ShortenedUrl ShortenUrl(TeknikEntities db, string url, int length)
{
// Generate the shortened url
string shortUrl = StringHelper.RandomString(length);
while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null)
{
shortUrl = StringHelper.RandomString(length);
}
ShortenedUrl newUrl = new ShortenedUrl();
newUrl.OriginalUrl = url;
newUrl.ShortUrl = shortUrl;
newUrl.DateAdded = DateTime.Now;
return newUrl;
}
}
}
| 27.787879 | 96 | 0.63904 | [
"BSD-3-Clause"
] | Teknikode/Teknik | Teknik/Areas/Shortener/ShortenerHelper.cs | 919 | C# |
using System;
using StarodubOleg.GPPG.Runtime;
using DevLab.JmesPath.Tokens;
namespace DevLab.JmesPath
{
partial class JmesPathParser
{
readonly IJmesPathGenerator generator_;
public JmesPathParser(AbstractScanner<ValueType, LexLocation> scanner,
IJmesPathGenerator generator)
: base(scanner)
{
generator_ = generator;
}
#region Implementation
void OnExpression() => generator_.OnExpression();
void ResolveParsingState()
{
// the grammar does not specify this but the canonical
// implementation accepts constructs that consist of
// projections immediately followed by a multi_select_list.
// these constructs should be separated with a T_DOT
// because these really are sub_expressions in disguise.
// when this method is called, upon each successful
// parse of an expression, we need to identify
// whether we are in such a case and insert a T_DOT
// in the token stream if necessary
// only interested in cases where previous construct is a projection
if (!generator_.IsProjection())
return;
var scanner = this.Scanner as JmesPathScanner;
System.Diagnostics.Debug.Assert(scanner != null);
var next = scanner.EnqueueAndReturnInitialToken(NextToken);
NextToken = 0;
if (next == (int)TokenType.T_LBRACKET && IsParsingMultiSelectList())
ResolveSubExpressionToMultiSelectList();
scanner.AddPushbackBufferToQueue();
}
bool IsParsingMultiSelectList()
{
var scanner = this.Scanner as JmesPathScanner;
System.Diagnostics.Debug.Assert(scanner != null);
// this method is called upon each successfull parse of an expression
//
// (T_LBRACKET) T_STAR T_RBRACKET => list_wildcard => bracket_specifier
// (T_LBRACKET) T_STAR ... <any> => hash_wildcard => in the context of a multi_select_list
// (T_LBRACKET) T_COLON => slice_expression => bracket_specifier
// (T_LBRACKET) T_NUMBER => number => bracket_specifier
// (T_LBRACKET) <any> => multi_select_list
var next = scanner.GetAndEnqueue();
switch (next)
{
case (int)TokenType.T_STAR:
{
var lookahead = scanner.GetAndEnqueue();
if (lookahead != (int)TokenType.T_RBRACKET)
return true;
}
break;
case (int)TokenType.T_COLON:
case (int)TokenType.T_NUMBER:
{
// next construct is a bracket specifier
// do nothing
}
break;
// otherwise, resolve to a multi_select_list
default:
return true;
}
return false;
}
void ResolveSubExpressionToMultiSelectList()
{
// next construct is a multi_select_list
// check that the previous construct is a projection
// and prepend a "." to parse as a sub_expression
NextToken = (int)TokenType.T_DOT;
}
#endregion
#region Expressions
void OnSubExpression() => generator_.OnSubExpression();
#region index_expression
void OnIndex(Token token)
{
var number = token as NumberToken;
System.Diagnostics.Debug.Assert(token.Type == TokenType.T_NUMBER);
System.Diagnostics.Debug.Assert(number != null);
var index = (int)number.Value;
generator_.OnIndex(index);
}
void OnFilterProjection() => generator_.OnFilterProjection();
void OnFlattenProjection() => generator_.OnFlattenProjection();
void OnListWildcardProjection() => generator_.OnListWildcardProjection();
void OnIndexExpression() => generator_.OnIndexExpression();
void OnSliceExpression(Token start, Token stop, Token step)
{
System.Diagnostics.Debug.Assert(start == null || start is NumberToken);
System.Diagnostics.Debug.Assert(stop == null || stop is NumberToken);
System.Diagnostics.Debug.Assert(step == null || step is NumberToken);
var startIndex = (int?)start?.Value;
var stopIndex = (int?)stop?.Value;
var stepIndex = (int?)step?.Value;
generator_.OnSliceExpression(startIndex, stopIndex, stepIndex);
}
#endregion
#region comparator_expression
void OnComparisonExpression(Token token)
{
switch (token.Type)
{
case TokenType.T_EQ: generator_.OnComparisonEqual(); break;
case TokenType.T_GE: generator_.OnComparisonGreaterOrEqual(); break;
case TokenType.T_GT: generator_.OnComparisonGreater(); break;
case TokenType.T_LE: generator_.OnComparisonLesserOrEqual(); break;
case TokenType.T_LT: generator_.OnComparisonLesser(); break;
case TokenType.T_NE: generator_.OnComparisonNotEqual(); break;
default:
System.Diagnostics.Debug.Assert(false);
throw new NotSupportedException();
}
}
#endregion
void OnOrExpression() => generator_.OnOrExpression();
void OnAndExpression() => generator_.OnAndExpression();
void OnNotExpression() => generator_.OnNotExpression();
void OnIdentifier(Token token) =>
generator_.OnIdentifier((string)token.Value);
void OnHashWildcardProjection() =>
generator_.OnHashWildcardProjection();
#region multi_select_hash
void PushMultiSelectHash() => generator_.PushMultiSelectHash();
void AddMultiSelectHashExpression() => generator_.AddMultiSelectHashExpression();
void PopMultiSelectHash() => generator_.PopMultiSelectHash();
#endregion
#region multi_select_list
void PushMultiSelectList() => generator_.PushMultiSelectList();
void AddMultiSelectListExpression() => generator_.AddMultiSelectListExpression();
void PopMultiSelectList() => generator_.PopMultiSelectList();
#endregion
void OnLiteralString(Token token) =>
generator_.OnLiteralString((string)((LiteralStringToken)token).Value);
void OnPipeExpression() => generator_.OnPipeExpression();
#region function_expression
void PushFunction() => generator_.PushFunction();
void PopFunction(Token token)
{
System.Diagnostics.Debug.Assert(token.Type == TokenType.T_USTRING);
var name = (string)token.Value;
generator_.PopFunction(name);
}
void AddFunctionArg() => generator_.AddFunctionArg();
void OnExpressionType() => generator_.OnExpressionType();
#endregion
void OnRawString(Token token)
{
var @string = (string)token.Value;
generator_.OnRawString(@string);
}
void OnCurrentNode() => generator_.OnCurrentNode();
#endregion // Expressions
}
} | 34.259912 | 104 | 0.574129 | [
"Apache-2.0"
] | atifaziz/JmesPath.Net | src/Parser/JmesPathParser.cs | 7,779 | C# |
namespace Microsoft.Protocols.TestSuites.MS_ASCMD
{
using System;
using System.Collections.Generic;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
using Response = Microsoft.Protocols.TestSuites.Common.Response;
/// <summary>
/// This scenario is designed to test the GetItemEstimate command.
/// </summary>
[TestClass]
public class S07_GetItemEstimate : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Cases
/// <summary>
/// This test case is used to verify the requirements related to a successful GetItemEstimate command.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC01_GetItemEstimate_Success()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Send a MIME-formatted email from User1 to User2.
string emailSubject = Common.GenerateResourceName(Site, "subject");
this.SendPlainTextEmail(null, emailSubject, this.User1Information.UserName, this.User2Information.UserName, null);
#endregion
this.SwitchUser(this.User2Information);
TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject);
this.CheckEmail(this.User2Information.InboxCollectionId, emailSubject, null);
#region Call method GetItemEstimate to get an estimate of the number of items in the Inbox folder.
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User2Information.InboxCollectionId), false);
Request.Options option = new Request.Options
{
Items = new object[] { "Email" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User2Information.InboxCollectionId, new Request.Options[] { option });
GetItemEstimateResponse getItemEstimateResponse = this.CMDAdapter.GetItemEstimate(getItemEstimateRequest);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The Response element in the GetItemEstimate command response should not be null.");
#endregion
#region Call Sync command to get all items in the Inbox folder.
SyncRequest syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User2Information.InboxCollectionId);
this.Sync(syncRequest, false);
syncRequest.RequestData.Collections[0].SyncKey = this.LastSyncKey;
SyncResponse syncResponse = this.Sync(syncRequest, false);
Response.SyncCollectionsCollectionCommands commands = TestSuiteBase.GetCollectionItem(syncResponse, Response.ItemsChoiceType10.Commands) as Response.SyncCollectionsCollectionCommands;
Site.Assert.IsNotNull(commands, "The Commands element in the Sync command response should not be null.");
Site.Assert.IsNotNull(commands.Add, "The Add element of the Commands element in the Sync command response should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4134");
// Verify MS-ASCMD requirement: MS-ASCMD_R4134
Site.CaptureRequirementIfAreEqual<string>(
"1",
getItemEstimateResponse.ResponseData.Response[0].Status,
4134,
@"[In Status(GetItemEstimate)] [When the scope is Global], [the cause of the status value 1 is] Server successfully completed command.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R171");
// Verify MS-ASCMD requirement: MS-ASCMD_R171
Site.CaptureRequirementIfAreEqual<int>(
commands.Add.Length,
Convert.ToInt32(getItemEstimateResponse.ResponseData.Response[0].Collection.Estimate),
171,
@"[In GetItemEstimate] The GetItemEstimate command gets an estimate of the number of items in a collection or folder on the server that have to be synchronized.");
// If R171 has been verified, then the GetItemEstimate command gets an estimate of the number of items in a collection or folder.
// So R5056 will be verified.
this.Site.CaptureRequirement(
5056,
@"[In Synchronizing Inbox, Calendar, Contacts, and Tasks Folders] [Command sequence for folder synchronization, order [3]:] The server responds to indicate how many items will be added, changed, or deleted, for each collection.");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if Options element is not included in a request, server will enumerate all of the items within the collection, without any filter.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC02_GetItemEstimate_WithoutOptions()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call method GetItemEstiamte with filters within the airsync:Options container to Email class to get an estimate of the number of the items in the Inbox folder.
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.InboxCollectionId));
Request.Options option = new Request.Options
{
Items = new object[] { "Email" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User1Information.InboxCollectionId, new Request.Options[] { option });
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
#endregion
#region Call method GetItemEstimate without Options element to get an estimate of the number of items in the Inbox folder on server.
getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User1Information.InboxCollectionId, null);
GetItemEstimateResponse getItemEstimateResponseNoOption = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3543");
// Verify MS-ASCMD requirement: MS-ASCMD_R3543
Site.CaptureRequirementIfAreEqual<string>(
getItemEstimateResponse.ResponseData.Response[0].Collection.Estimate,
getItemEstimateResponseNoOption.ResponseData.Response[0].Collection.Estimate,
3543,
@"[In Options(GetItemEstimate)] If the airsync:Options element is not included in a request, then the GetItemEstimate command (section 2.2.2.7) will enumerate all of the items within the collection, without any filter (up to a maximum of 512 items).");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command for a contact collection, if FilterType element is included, no error is returned.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC03_GetItemEstimate_Contacts_FilterType()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.ContactsCollectionId));
#region Call GetItemEstimate with setting FilterType to get an estimate number of items in Contacts folder.
GetItemEstimateResponse getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.ContactsCollectionId, 0);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2967");
// Verify MS-ASCMD requirement: MS-ASCMD_R2967
// If the returned value of the Estimate in previous step is not null, then R2967 should be covered.
Site.CaptureRequirementIfIsNotNull(
getItemEstimateResponse.ResponseData.Response[0].Collection.Estimate,
2967,
@"[In FilterType(GetItemEstimate)] If a filter type is specified, then the server sends an estimate of the items within the filter specifications.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2973");
// Verify MS-ASCMD requirement: MS-ASCMD_R2973
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
2973,
@"[In FilterType(GetItemEstimate)] However, if the airsync:FilterType element is included in a GetItemEstimate request for a contact collection, no error is returned.");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command for e-mail, the status should be correspond to the value of FilterType.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC04_GetItemEstimate_Email_FilterType()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Send an email from user1 to user2
string emailSubject = Common.GenerateResourceName(Site, "subject");
this.SendPlainTextEmail(null, emailSubject, this.User1Information.UserName, this.User2Information.UserName, null);
this.SwitchUser(this.User2Information);
this.CheckEmail(this.User2Information.InboxCollectionId, emailSubject, null);
TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject);
#endregion
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User2Information.InboxCollectionId));
#region Call GetItemEstimate with FilterType setting to 0 to get estimate number of all items in Inbox folder.
GetItemEstimateResponse getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 0);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
int original = Convert.ToInt32(getItemEstimateResponse.ResponseData.Response[0].Collection.Estimate);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2999");
// Verify MS-ASCMD requirement: MS-ASCMD_R2999
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
2999,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to email, if FilterType is 0, Status element value is 1.]");
#endregion
#region Call GetItemEstimate without FilterType
getItemEstimateResponse = this.CMDAdapter.GetItemEstimate(TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User2Information.InboxCollectionId, null));
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
int current = Convert.ToInt32(getItemEstimateResponse.ResponseData.Response[0].Collection.Estimate);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2970");
// Verify MS-ASCMD requirement: MS-ASCMD_R2970
Site.CaptureRequirementIfAreEqual<int>(
original,
current,
2970,
@"[In FilterType(GetItemEstimate)] If the airsync:FilterType element is omitted, then all objects are sent from the server.");
#endregion
#region Call GetItemEstimate with FilterType setting to 1 to get estimate number of the items within 1 day in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 1);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
original = Convert.ToInt32(getItemEstimateResponse.ResponseData.Response[0].Collection.Estimate);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3000");
// Verify MS-ASCMD requirement: MS-ASCMD_R3000
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3000,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to email, if FilterType is 1, Status element value is 1.]");
#endregion
#region Send an email from user1 to user2
this.SwitchUser(this.User1Information);
string anotherEmailSubject = Common.GenerateResourceName(Site, "subject");
this.SendPlainTextEmail(null, anotherEmailSubject, this.User1Information.UserName, this.User2Information.UserName, null);
this.SwitchUser(this.User2Information);
this.CheckEmail(this.User2Information.InboxCollectionId, anotherEmailSubject, null);
TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, anotherEmailSubject);
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User2Information.InboxCollectionId));
#endregion
#region Call GetItemEstimate with FilterType setting to 1 to get estimate number of the items within 1 day in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 1);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
current = Convert.ToInt32(getItemEstimateResponse.ResponseData.Response[0].Collection.Estimate);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2969");
// Verify MS-ASCMD requirement: MS-ASCMD_R2969
Site.CaptureRequirementIfAreEqual<int>(
original + 1,
current,
2969,
@"[In FilterType(GetItemEstimate)] New objects are added to the client when they are within the time window.");
#endregion
#region Call GetItemEstimate with FilterType setting to 2 to get estimate number of the items within 3 days in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 2);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3001");
// Verify MS-ASCMD requirement: MS-ASCMD_R3001
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3001,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to email, if FilterType is 2, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 3 to get estimate number of the items within 1 week in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 3);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3002");
// Verify MS-ASCMD requirement: MS-ASCMD_R3002
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3002,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to email, if FilterType is 3, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 4 to get estimate number of the items within 2 weeks in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 4);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3003");
// Verify MS-ASCMD requirement: MS-ASCMD_R3003
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3003,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to email, if FilterType is 4, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 5 to get estimate number of the items within 1 month in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 5);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3004");
// Verify MS-ASCMD requirement: MS-ASCMD_R3004
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3004,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to email, if FilterType is 5, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 6 to get estimate number of items within 3 months in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 6);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3005");
// Verify MS-ASCMD requirement: MS-ASCMD_R3005
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3005,
@"[In FilterType(GetItemEstimate)] No,[Applies to email, if FilterType is 6,] Status element value 110");
#endregion
#region Call GetItemEstimate with FilterType setting to 7 to get estimate number of items within 6 months in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 7);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3006");
// Verify MS-ASCMD requirement: MS-ASCMD_R3006
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3006,
@"[In FilterType(GetItemEstimate)] No,[Applies to email, if FilterType is 7,] Status element value 110");
#endregion
#region Call GetItemEstimate with FilterType setting to 8 to get estimate number of incomplete tasks in Inbox folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User2Information.InboxCollectionId, 8);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3007");
// Verify MS-ASCMD requirement: MS-ASCMD_R3007
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3007,
@"[In FilterType(GetItemEstimate)] No, [Applies to email, if FilterType is 8,] Status element value is 110.");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command for calendar, the value of status should be correspond to the value of FilterType.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC05_GetItemEstimate_Calendar_FilterType()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Recurrences cannot be added in protocol version 16.0");
#region Add a new calendar
string calendarSubject = Common.GenerateResourceName(Site, "calendarSubject");
DateTime startTime = DateTime.Now.AddDays(1.0);
DateTime endTime = startTime.AddMinutes(10.0);
Request.SyncCollectionAdd calendarData = new Request.SyncCollectionAdd
{
ClientId = TestSuiteBase.ClientId,
ApplicationData = new Request.SyncCollectionAddApplicationData
{
ItemsElementName =
new Request.ItemsChoiceType8[]
{
Request.ItemsChoiceType8.Subject,
Request.ItemsChoiceType8.StartTime,
Request.ItemsChoiceType8.EndTime
},
Items =
new object[]
{
calendarSubject,
startTime.ToString("yyyyMMddTHHmmssZ"),
endTime.ToString("yyyyMMddTHHmmssZ")
}
},
Class = "Calendar"
};
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.CalendarCollectionId));
SyncRequest syncRequest = TestSuiteBase.CreateSyncAddRequest(this.LastSyncKey, this.User1Information.CalendarCollectionId, calendarData);
SyncResponse syncResponse = this.Sync(syncRequest);
Response.SyncCollectionsCollectionResponses responses = TestSuiteBase.GetCollectionItem(syncResponse, Response.ItemsChoiceType10.Responses) as Response.SyncCollectionsCollectionResponses;
Site.Assert.AreEqual<int>(1, int.Parse(responses.Add[0].Status), "The calendar should be added successfully.");
TestSuiteBase.RecordCaseRelativeItems(this.User1Information, this.User1Information.CalendarCollectionId, calendarSubject);
#endregion
#region Call GetItemEstimate with FilterType setting to 0 to get estimate number of all items in Calendar folder.
GetItemEstimateResponse getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)0);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3008");
// Verify MS-ASCMD requirement: MS-ASCMD_R3008
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3008,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to calendar, if FilterType is 0, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 1 to get estimate number of items within 1 day in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)1);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3009");
// Verify MS-ASCMD requirement: MS-ASCMD_R3009
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3009,
@"[In FilterType(GetItemEstimate)] No, [Applies to calendar, if FilterType is 1,] Status element (section 2.2.3.162.6) value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 2 to get estimate number of items within 3 days in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)2);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3010");
// Verify MS-ASCMD requirement: MS-ASCMD_R3010
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3010,
@"[In FilterType(GetItemEstimate)] No, [Applies to calendar, if FilterType is 2,] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 3 to get estimate number of items within 1 week in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)3);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3011");
// Verify MS-ASCMD requirement: MS-ASCMD_R3011
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3011,
@"[In FilterType(GetItemEstimate)] No, [Applies to calendar, if FilterType is 3,] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 4 to get estimate number of items within 2 weeks in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)4);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3012");
// Verify MS-ASCMD requirement: MS-ASCMD_R3012
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3012,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to calendar, if FilterType is 4, Status element value 1]");
#endregion
#region Create a future calendar
this.GetInitialSyncResponse(this.User1Information.CalendarCollectionId);
calendarSubject = Common.GenerateResourceName(this.Site, "canlendarSubject");
startTime = DateTime.Now.AddDays(15.0);
endTime = startTime.AddMinutes(10.0);
calendarData = new Request.SyncCollectionAdd
{
ClientId = TestSuiteBase.ClientId,
ApplicationData = new Request.SyncCollectionAddApplicationData
{
ItemsElementName = new Request.ItemsChoiceType8[]
{
Request.ItemsChoiceType8.Subject,
Request.ItemsChoiceType8.StartTime,
Request.ItemsChoiceType8.EndTime,
},
Items = new object[]
{
calendarSubject,
startTime.ToString("yyyyMMddTHHmmssZ"),
endTime.ToString("yyyyMMddTHHmmssZ"),
}
},
Class = "Calendar"
};
syncRequest = TestSuiteBase.CreateSyncAddRequest(this.LastSyncKey, this.User1Information.CalendarCollectionId, calendarData);
syncResponse = this.Sync(syncRequest);
Site.Assert.IsNotNull(syncResponse.ResponseData.Item, "The items returned in the Sync command response should not be null.");
responses = TestSuiteBase.GetCollectionItem(syncResponse, Response.ItemsChoiceType10.Responses) as Response.SyncCollectionsCollectionResponses;
Site.Assert.AreEqual<int>(1, int.Parse(responses.Add[0].Status), "The calendar should be added successfully.");
TestSuiteBase.RecordCaseRelativeItems(this.User1Information, this.User1Information.CalendarCollectionId, calendarSubject);
syncResponse = this.SyncChanges(this.User1Information.CalendarCollectionId);
Site.Assert.IsNotNull(syncResponse.ResponseData.Item, "The items returned in the Sync command response should not be null.");
bool isVerifyR2971 = !string.IsNullOrEmpty(TestSuiteBase.FindServerId(syncResponse, "Subject", calendarSubject));
syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.CalendarCollectionId, 4);
this.Sync(syncRequest);
syncRequest.RequestData.Collections[0].SyncKey = this.LastSyncKey;
syncResponse = this.Sync(syncRequest);
Site.Assert.IsNotNull(syncResponse.ResponseData.Item, "The items returned in the Sync command response should not be null.");
isVerifyR2971 = isVerifyR2971 && !string.IsNullOrEmpty(TestSuiteBase.FindServerId(syncResponse, "Subject", calendarSubject));
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2971");
// Verify MS-ASCMD requirement: MS-ASCMD_R2971
Site.CaptureRequirementIfIsTrue(
isVerifyR2971,
2971,
@"[In FilterType(GetItemEstimate)] Calendar items that are in the future [or that have recurrence, but no end date], are sent to the client regardless of the airsync:FilterType element value.");
#endregion
#region Create a recurrence calendar without EndTime
string recurrenceCalendarSubject = Common.GenerateResourceName(Site, "recurrenceCanlendarSubject");
Request.SyncCollectionAdd recurrenceCalendarData = new Request.SyncCollectionAdd
{
ClientId = TestSuiteBase.ClientId,
ApplicationData = new Request.SyncCollectionAddApplicationData
{
ItemsElementName = new Request.ItemsChoiceType8[] { Request.ItemsChoiceType8.Subject, Request.ItemsChoiceType8.Recurrence },
Items = new object[]
{
recurrenceCalendarSubject,
new Request.Recurrence
{
Type = 1,
OccurrencesSpecified = false,
DayOfWeek = 2,
DayOfWeekSpecified = true,
IsLeapMonthSpecified = false
},
}
},
Class = "Calendar"
};
syncRequest = TestSuiteBase.CreateSyncAddRequest(this.LastSyncKey, this.User1Information.CalendarCollectionId, recurrenceCalendarData);
syncResponse = this.Sync(syncRequest);
responses = TestSuiteBase.GetCollectionItem(syncResponse, Response.ItemsChoiceType10.Responses) as Response.SyncCollectionsCollectionResponses;
Site.Assert.AreEqual<int>(1, int.Parse(responses.Add[0].Status), "The calendar should be added successfully.");
TestSuiteBase.RecordCaseRelativeItems(this.User1Information, this.User1Information.CalendarCollectionId, recurrenceCalendarSubject);
syncResponse = this.SyncChanges(this.User1Information.CalendarCollectionId);
Site.Assert.IsNotNull(syncResponse.ResponseData.Item, "The items returned in the Sync command response should not be null.");
bool isVerifyR5877 = !string.IsNullOrEmpty(TestSuiteBase.FindServerId(syncResponse, "Subject", recurrenceCalendarSubject));
syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.CalendarCollectionId, 4);
this.Sync(syncRequest);
syncRequest.RequestData.Collections[0].SyncKey = this.LastSyncKey;
syncResponse = this.Sync(syncRequest);
Site.Assert.IsNotNull(syncResponse.ResponseData.Item, "The items returned in the Sync command response should not be null.");
isVerifyR5877 = isVerifyR5877 && !string.IsNullOrEmpty(TestSuiteBase.FindServerId(syncResponse, "Subject", recurrenceCalendarSubject));
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5877");
// Verify MS-ASCMD requirement: MS-ASCMD_R5877
Site.CaptureRequirementIfIsTrue(
isVerifyR5877,
5877,
@"[In FilterType(GetItemEstimate)] Calendar items [that are in the future or] that have recurrence, but no end date, are sent to the client regardless of the airsync:FilterType element value.");
#endregion
#region Call GetItemEstimate with FilterType setting to 5 to get estimate number of items within 1 month in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)5);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3013");
// Verify MS-ASCMD requirement: MS-ASCMD_R3013
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3013,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to calendar, if FilterType is 5, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 6 to get estimate number of items within 3 months in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)6);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3014");
// Verify MS-ASCMD requirement: MS-ASCMD_R3014
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3014,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to calendar, if FilterType is 6, Status element value 1]");
#endregion
#region Call GetItemEstimate with FilterType setting to 7 to get estimate number of items within 6 months in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)7);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3015");
// Verify MS-ASCMD requirement: MS-ASCMD_R3015
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3015,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to calendar, if FilterType is 7, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 8 to get estimate number of incomplete tasks in Calendar folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, (byte)8);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3016");
// Verify MS-ASCMD requirement: MS-ASCMD_R3016
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3016,
@"[In FilterType(GetItemEstimate)] No, [Applies to calendar, if FilterType is 8,] Status element value is 110.");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command for tasks, the value of status should be correspond to the value of FilterType.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC06_GetItemEstimate_Tasks_FilterType()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.TasksCollectionId));
#region Call GetItemEstimate with FilterType setting to 0 to get estimate number of all items in Tasks folder.
GetItemEstimateResponse getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)0);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3017");
// Verify MS-ASCMD requirement: MS-ASCMD_R3017
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3017,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to tasks, if FilterType is 0, Status element value is 1.]");
#endregion
#region Call GetItemEstimate with FilterType setting to 1 to get estimate number of items within 1 day in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)1);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3018");
// Verify MS-ASCMD requirement: MS-ASCMD_R3018
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3018,
@"[In FilterType(GetItemEstimate)] No, [Applies to tasks, if FilterType is 1, ] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 2 to get estimate number of items within 3 days in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)2);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3019");
// Verify MS-ASCMD requirement: MS-ASCMD_R3019
Site.CaptureRequirementIfAreEqual<int>(
(byte)110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3019,
@"[In FilterType(GetItemEstimate)] No, [In FilterType] No, [Applies to tasks, if FilterType is 2, ] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 3 to get estimate number of items within 1 week in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)3);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3020");
// Verify MS-ASCMD requirement: MS-ASCMD_R3020
Site.CaptureRequirementIfAreEqual<int>(
(byte)110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3020,
@"[In FilterType(GetItemEstimate)] No, [In FilterType] No, [Applies to tasks, if FilterType is 3, ] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 4 to get estimate number of items within 2 weeks in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)4);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3021");
// Verify MS-ASCMD requirement: MS-ASCMD_R3021
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3021,
@"[In FilterType(GetItemEstimate)] No, [Applies to tasks, if FilterType is 4, ] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 5 to get estimate number of items within 1 month in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)5);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3022");
// Verify MS-ASCMD requirement: MS-ASCMD_R3022
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3022,
@"[In FilterType(GetItemEstimate)] No, [Applies to tasks, if FilterType is 5, ]Status element value 110");
#endregion
#region Call GetItemEstimate with FilterType setting to 6 to get estimate number of items within 3 months in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)6);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3023");
// Verify MS-ASCMD requirement: MS-ASCMD_R3023
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3023,
@"[In FilterType(GetItemEstimate)] No, [Applies to tasks, if FilterType is 6, ] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 7 to get estimate number of items within 6 months in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)7);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3024");
// Verify MS-ASCMD requirement: MS-ASCMD_R3024
Site.CaptureRequirementIfAreEqual<int>(
110,
int.Parse(getItemEstimateResponse.ResponseData.Status),
3024,
@"[In FilterType(GetItemEstimate)] No, [Applies to tasks, if FilterType is 7, ] Status element value is 110.");
#endregion
#region Call GetItemEstimate with FilterType setting to 8 to get estimate number of incomplete tasks in Tasks folder.
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, (byte)8);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3025");
// Verify MS-ASCMD requirement: MS-ASCMD_R3025
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3025,
@"[In FilterType(GetItemEstimate)] Yes. [Applies to tasks, if FilterType is 8, Status element value is 1.]");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if FilterType element is invalid, the status should be equal to 103.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC07_GetItemEstimate_InvalidFilterType()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.ContactsCollectionId));
#region Call method GetItemEstimate with invalid FilterType value to get an estimate of the number of items in Contacts folder on server.
GetItemEstimateResponse getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.ContactsCollectionId, 9);
int statusOfContacts = int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status);
Assert.AreEqual<int>(103, statusOfContacts, "Specifying a airsync:FilterType of 9 or above for when the CollectionId element identifies contact collection should result in a Status element value of 103.");
#endregion
#region Call method GetItemEstimate with invalid FilterType value to get an estimate of the number of items in Inbox folder on server.
this.GetInitialSyncResponse(this.User1Information.InboxCollectionId);
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.InboxCollectionId, 9);
int statusOfInbox = int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status);
Assert.AreEqual<int>(103, statusOfInbox, "Specifying a airsync:FilterType of 9 or above for when the CollectionId element identifies e-mail collection should result in a Status element value of 103.");
#endregion
#region Call method GetItemEstimate with invalid FilterType value to get an estimate of the number of items in Calendar folder on server.
this.GetInitialSyncResponse(this.User1Information.CalendarCollectionId);
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.CalendarCollectionId, 9);
int statusOfCalendar = int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status);
Assert.AreEqual<int>(103, statusOfCalendar, "Specifying a airsync:FilterType of 9 or above for when the CollectionId element identifies calendar collection should result in a Status element value of 103.");
#endregion
#region Call method GetItemEstimate with invalid FilterType value to get an estimate of the number of items in Tasks folder on server.
this.GetInitialSyncResponse(this.User1Information.TasksCollectionId);
getItemEstimateResponse = this.GetItemEstimateWithFilterType(this.User1Information.TasksCollectionId, 9);
int statusOfTasks = int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status);
Assert.AreEqual<int>(103, statusOfTasks, "Specifying a airsync:FilterType of 9 or above for when the CollectionId element identifies tasks collection should result in a Status element value of 103.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2984");
// Verify MS-ASCMD requirement: MS-ASCMD_R2984
// When all above four steps are passed, it means that a airsync:FilterType of 9 or above
// can cause a Status element of 103 when the CollectionId element (section 2.2.3.30.1)
// identifies any email, contact, calendar or task collection.
Site.CaptureRequirement(
2984,
@"[In FilterType(GetItemEstimate)] Specifying a airsync:FilterType of 9 or above for when the CollectionId element (section 2.2.3.30.1) identifies any email, contact, calendar or task collection results in a Status element value of 103.");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if the request includes more than one MaxItem element, the server doesn't return error.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC08_GetItemEstimate_MoreThanOneMaxItems()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call Sync command with 2 MaxItems elements on RI.
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.RecipientInformationCacheCollectionId));
Request.Options option = new Request.Options
{
Items = new object[] { "2", "3" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.MaxItems, Request.ItemsChoiceType1.MaxItems }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User1Information.RecipientInformationCacheCollectionId, new Request.Options[] { option });
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
if (Common.IsRequirementEnabled(3272, this.Site))
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3272");
// Verify MS-ASCMD requirement: MS-ASCMD_R3272
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
3272,
@"[In Appendix A: Product Behavior] The implementation does not return a protocol status error in response to such a command request [more than one airsync:MaxItems element as the child of the airsync:Options element is undefined]. (Exchange 2007 and above follow this behavior.)");
}
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if the specified collection id is invalid, server should return a status code 2.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC09_GetItemEstimate_Status2()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.ContactsCollectionId));
#region Call method GetItemEstimate with two collection ids, one is invalid CollectionId, to get an estimate of the number of items in Contacts folder on server.
GetItemEstimateRequest getItemEstimateRequest = new GetItemEstimateRequest
{
RequestData = new Request.GetItemEstimate
{
Collections = new Request.GetItemEstimateCollection[]
{
new Request.GetItemEstimateCollection
{
CollectionId = this.User1Information.ContactsCollectionId,
SyncKey = this.LastSyncKey,
Options = new Request.Options[]
{
new Request.Options
{
Items = new object[]
{
"Contacts"
},
ItemsElementName = new Request.ItemsChoiceType1[]
{
Request.ItemsChoiceType1.Class
}
}
}
},
new Request.GetItemEstimateCollection
{
CollectionId = Common.GenerateResourceName(Site, "InvalidCollectionId"),
SyncKey = this.LastSyncKey,
Options = new Request.Options[]
{
new Request.Options
{
Items = new object[]
{
"Email"
},
ItemsElementName = new Request.ItemsChoiceType1[]
{
Request.ItemsChoiceType1.Class
}
}
}
}
}
}
};
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4135");
// Verify MS-ASCMD requirement: MS-ASCMD_R4135
// When the Status value is 2, it means one of the specified CollectionIds is invalid.
Site.CaptureRequirementIfAreEqual<int>(
2,
int.Parse(getItemEstimateResponse.ResponseData.Response[1].Status),
4135,
@"[In Status(GetItemEstimate)] [When the scope is] Item, [the meaning of the status value] 2 [is] A collection was invalid or one of the specified collection IDs was invalid.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4136");
// Verify MS-ASCMD requirement: MS-ASCMD_R4136
// When the Status value is 2, it means one or more of the specified folders does not exist or an incorrect folder is requested..
Site.CaptureRequirementIfAreEqual<int>(
2,
int.Parse(getItemEstimateResponse.ResponseData.Response[1].Status),
4136,
@"[In Status(GetItemEstimate)] [When the scope is Item], [the cause of the status value 2 is] One or more of the specified folders does not exist or an incorrect folder was requested.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4130");
// Verify MS-ASCMD requirement: MS-ASCMD_R4130
bool isVerifyR4130 = int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status) == 1 && int.Parse(getItemEstimateResponse.ResponseData.Response[1].Status) != 1;
Site.CaptureRequirementIfIsTrue(
isVerifyR4130,
4130,
@"[In Status(GetItemEstimate)] However, if the failure occurs at the Collection (section 2.2.3.29.1) level, a Status value is returned per Collection as a child of the Response element.");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if the synchronization state has not been primed, server should return a status code 3.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC10_GetItemEstimate_Status3()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call method GetItemEstimate without priming the synchronization state.
Request.Options option = new Request.Options
{
Items = new object[] { "Email" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest("0", this.User1Information.InboxCollectionId, new Request.Options[] { option });
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4139");
// Verify MS-ASCMD requirement: MS-ASCMD_R4139
// When the Status value is 3, it means the synchronization state has not been primed.
Site.CaptureRequirementIfAreEqual<int>(
3,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
4139,
@"[In Status(GetItemEstimate)] [When the scope is] Item, [the meaning of the status value] 3 [is] The synchronization state has not been primed.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4140");
// Verify MS-ASCMD requirement: MS-ASCMD_R4140
// When the Status value is 3, it means the issued GetItemEstimate command without first issuing a Sync command request with a SyncKey value of 0.
Site.CaptureRequirementIfAreEqual<int>(
3,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
4140,
@"[In Status(GetItemEstimate)] [When the scope is Item], [the cause of the status value 3 is] The client has issued a GetItemEstimate command without first issuing a Sync command request (section 2.2.2.19) with an airsync:SyncKey element (section 2.2.3.156.4) value of zero (0).");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if the synchronization key is invalid, server should return a status code 4.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC11_GetItemEstimate_Status4_InvalidSyncKey()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.InboxCollectionId));
#region Call method GetItemEstimate with an invalid SyncKey.
string invalidSyncKey = Common.GenerateResourceName(Site, "InvalidSyncKey");
Request.Options option = new Request.Options
{
Items = new object[] { "Email" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(invalidSyncKey, this.User1Information.InboxCollectionId, new Request.Options[] { option });
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4142");
// Verify MS-ASCMD requirement: MS-ASCMD_R4142
Site.CaptureRequirementIfAreEqual<int>(
4,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
4142,
@"[In Status(GetItemEstimate)] [When the scope is] Global, [the meaning of the status value] 4 [is] The specified synchronization key was invalid.");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if the SyncKey value provided in the GetItemEstimate request does not match those expected within the next Sync command request, server should return a status value of 4.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC12_GetItemEstimate_Status4_MismatchedSyncKey()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.ContactsCollectionId));
string unmatchedSyncKey = this.LastSyncKey;
#region Call Sync command on the Inbox folder.
SyncRequest syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.InboxCollectionId);
this.Sync(syncRequest);
#endregion
#region Call method GetItemEstimate with a SyncKey that does not match the expected value.
Request.Options option = new Request.Options
{
Items = new object[] { "Email" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(unmatchedSyncKey, this.User1Information.InboxCollectionId, new Request.Options[] { option });
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4594");
// Verify MS-ASCMD requirement: MS-ASCMD_R4594
Site.CaptureRequirementIfAreEqual<int>(
4,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
4594,
@"[In SyncKey(GetItemEstimate)] The server MUST provide a Status element (section 2.2.3.162.6) value of 4 if the airsync:SyncKey value provided in the GetItemEstimate request does not match those expected within the next Sync command request (section 2.2.2.19).");
#endregion
}
/// <summary>
/// This test case is used to verify GetItemEstimate command, if the ConversationMode element for collections that do not store e-mail results in an invalid XML error, server should return a status value of 103.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC13_GetItemEstimate_ConversationMode_Status103()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call GetItemEstimate with the ConversationMode element for collections that do not store e-mail.
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User1Information.ContactsCollectionId, null);
getItemEstimateRequest.RequestData.Collections[0].ConversationMode = true;
getItemEstimateRequest.RequestData.Collections[0].ConversationModeSpecified = true;
GetItemEstimateResponse getItemEstimateResponse = this.CMDAdapter.GetItemEstimate(getItemEstimateRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2100");
// Verify MS-ASCMD requirement: MS-ASCMD_R2100
Site.CaptureRequirementIfAreEqual<int>(
103,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
2100,
@"[In ConversationMode (GetItemEstimate)] Specifying the airsync:ConversationMode element for collections that do not store email results in an invalid XML error, Status element (section 2.2.3.162.6) value 103.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4129");
// Verify MS-ASCMD requirement: MS-ASCMD_R4129
Site.CaptureRequirementIfAreEqual<int>(
103,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
4129,
@"[In Status(GetItemEstimate)] If the entire request command fails, the Status element is present as a child of the GetItemEstimate element and contains a value that indicates the type of global failure.");
#endregion
}
/// <summary>
/// This test case is used to verify only SMS messages and email messages can be synchronized at the same time.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC14_GetItemEstimate_WithCombinationClasses()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.InboxCollectionId));
#region Call GetItemEstimate to get the number of both Email and SMS messages.
Request.Options option1 = new Request.Options
{
Items = new object[] { "Email" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
Request.Options option2 = new Request.Options
{
Items = new object[] { "SMS" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User1Information.InboxCollectionId, new Request.Options[] { option1, option2 });
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData.Response, "The response of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R907");
// Verify MS-ASCMD requirement: MS-ASCMD_R907
Site.CaptureRequirementIfAreEqual<int>(
1,
int.Parse(getItemEstimateResponse.ResponseData.Response[0].Status),
907,
@"[In Class(GetItemEstimate)] Only SMS messages and email messages can be synchronized at the same time.");
#endregion
}
/// <summary>
/// This test case is used to verify the limit value of Collection element of GetItemEstimate command.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC15_GetItemEstimate_Collection_LimitValue()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Send an email from user1 to user2.
string emailSubject = Common.GenerateResourceName(Site, "subject");
this.SendPlainTextEmail(null, emailSubject, this.User1Information.UserName, this.User2Information.UserName, null);
this.SwitchUser(this.User2Information);
this.CheckEmail(this.User2Information.InboxCollectionId, emailSubject, null);
TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject);
#endregion
#region Create 1001 objects of GetItemEstimateCollection type for GetItemEstimate command.
Request.Options option = new Request.Options
{
Items = new object[] { "Email" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
List<Request.GetItemEstimateCollection> collections = new List<Request.GetItemEstimateCollection>();
for (int i = 0; i <= 1000; i++)
{
Request.GetItemEstimateCollection collection = new Request.GetItemEstimateCollection
{
CollectionId = this.User2Information.InboxCollectionId,
SyncKey = this.LastSyncKey,
Options = new Request.Options[] { option }
};
collections.Add(collection);
}
GetItemEstimateRequest getItemEstimateRequest = Common.CreateGetItemEstimateRequest(collections.ToArray());
GetItemEstimateResponse getItemEstimateResponse = this.CMDAdapter.GetItemEstimate(getItemEstimateRequest);
Site.Assert.IsNotNull(getItemEstimateResponse.ResponseData, "The response data of GetItemEstimate command should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5647");
// Verify MS-ASCMD requirement: MS-ASCMD_R5647
Site.CaptureRequirementIfAreEqual<int>(
103,
int.Parse(getItemEstimateResponse.ResponseData.Status),
5647,
@"[In Limiting Size of Command Requests] In GetItemEstimate (section 2.2.2.7) command request, when the limit value of Collection element is bigger than 1000 (minimum 30, maximum 5000), the error returned by server is Status element (section 2.2.3.162.6) value of 103.");
#endregion
}
/// <summary>
/// This test case is used to verify the combination of classes other than SMS messages or email messages synchronization at the same time cause status value 4 returned.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S07_TC16_GetItemEstimate_WithStatusValue4Returned()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Options element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.Sync(TestSuiteBase.CreateEmptySyncRequest(this.User1Information.InboxCollectionId));
#region Call GetItemEstimate to get the number of both Email and SMS messages.
Request.Options option1 = new Request.Options
{
Items = new object[] { "Tasks" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
Request.Options option2 = new Request.Options
{
Items = new object[] { "Contacts" },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.Class }
};
GetItemEstimateRequest getItemEstimateRequest = TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, this.User1Information.InboxCollectionId, new Request.Options[] { option1, option2 });
GetItemEstimateResponse getItemEstimateResponse = CMDAdapter.GetItemEstimate(getItemEstimateRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R908");
Site.CaptureRequirementIfAreEqual<int>(
4,
int.Parse(getItemEstimateResponse.ResponseData.Status),
908,
@"[In Class(GetItemEstimate)] A request for any other combination of classes will fail with a status value of 4.");
#endregion
}
#endregion
#region Private Methods
/// <summary>
/// Get estimate number of items in specified time window depends on FilterType in a collection.
/// </summary>
/// <param name="collectionId">Specifies collection id of the folder.</param>
/// <param name="filterType">Specifies time window for the objects sent from the server to the client.</param>
/// <returns>GetItemEstimate command response.</returns>
private GetItemEstimateResponse GetItemEstimateWithFilterType(string collectionId, byte filterType)
{
Request.Options option = new Request.Options
{
Items = new object[] { filterType },
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.FilterType }
};
return this.CMDAdapter.GetItemEstimate(TestSuiteBase.CreateGetItemEstimateRequest(this.LastSyncKey, collectionId, new Request.Options[] { option }));
}
#endregion
}
} | 61.324261 | 337 | 0.652359 | [
"MIT"
] | FangfangFan/Interop-TestSuites | ExchangeActiveSync/Source/MS-ASCMD/TestSuite/S07_GetItemEstimate.cs | 78,863 | C# |
using System;
using System.Drawing;
using System.Net;
namespace DotNetNuke.Services.GeneratedImage
{
public class ImageInfo {
public Image Image { get; private set; }
public byte[] ImageByteBuffer { get; private set; }
public HttpStatusCode? HttpStatusCode { get; private set; }
public ImageInfo(HttpStatusCode statusCode) {
HttpStatusCode = statusCode;
}
public ImageInfo(Image image) {
if (image == null) {
throw new ArgumentNullException("image");
}
Image = image;
}
public ImageInfo(byte[] imageBuffer) {
if (imageBuffer == null) {
throw new ArgumentNullException("imageBuffer");
}
ImageByteBuffer = imageBuffer;
}
}
}
| 24.323529 | 67 | 0.573156 | [
"MIT"
] | DNN-Connect/Dnn.Platform | DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs | 829 | C# |
// <copyright file="AutomaticTracerTests.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
using System;
using Datadog.Trace.ClrProfiler;
using Datadog.Trace.TestHelpers;
using FluentAssertions;
using Moq;
using Xunit;
namespace Datadog.Trace.Tests.DistributedTracer
{
[Collection(nameof(TracerInstanceTestCollection))]
[TracerRestorer]
public class AutomaticTracerTests
{
[Fact]
public void GetSpanContext_NoChild()
{
var automaticTracer = new AutomaticTracer();
automaticTracer.GetDistributedTrace().Should().BeNull();
automaticTracer.SetDistributedTrace(new SpanContext(1, 2));
((IDistributedTracer)automaticTracer).GetSpanContext().Should().BeNull("automatic tracer shouldn't read the distributed trace unless there is a child tracer");
}
[Fact]
public void GetSpanContext()
{
var automaticTracer = new AutomaticTracer();
automaticTracer.Register(Mock.Of<ICommonTracer>());
automaticTracer.GetDistributedTrace().Should().BeNull();
var expectedSpanContext = new SpanContext(1, 2, SamplingPriority.UserKeep, "Service", "Origin");
automaticTracer.SetDistributedTrace(expectedSpanContext);
var actualSpanContext = ((IDistributedTracer)automaticTracer).GetSpanContext();
actualSpanContext.Should().BeEquivalentTo(expectedSpanContext);
}
[Fact]
public void SetSpanContext()
{
var automaticTracer = new AutomaticTracer();
automaticTracer.Register(Mock.Of<ICommonTracer>());
var distributedTracer = (IDistributedTracer)automaticTracer;
var expectedSpanContext = new SpanContext(1, 2);
distributedTracer.SetSpanContext(expectedSpanContext);
distributedTracer.GetSpanContext().Should().BeEquivalentTo(expectedSpanContext);
}
[Fact]
public void SetSamplingPriority_NoChild()
{
var automaticTracer = new AutomaticTracer();
((IDistributedTracer)automaticTracer).SetSamplingPriority(SamplingPriority.UserKeep);
}
[Fact]
public void SetSamplingPriority()
{
var manualTracer = new Mock<ICommonTracer>();
var automaticTracer = new AutomaticTracer();
automaticTracer.Register(manualTracer.Object);
((IDistributedTracer)automaticTracer).SetSamplingPriority(SamplingPriority.UserKeep);
manualTracer.Verify(t => t.SetSamplingPriority((int?)SamplingPriority.UserKeep), Times.Once);
}
[Fact]
public void GetDistributedTrace()
{
var automaticTracer = new AutomaticTracer();
automaticTracer.GetDistributedTrace().Should().BeNull();
using (var scope = Tracer.Instance.StartActive("Test"))
{
var spanContext = SpanContextPropagator.Instance.Extract(automaticTracer.GetDistributedTrace());
spanContext.Should().NotBeNull();
spanContext.TraceId.Should().Be(scope.Span.TraceId);
spanContext.SpanId.Should().Be(scope.Span.SpanId);
}
automaticTracer.GetDistributedTrace().Should().BeNull();
}
[Fact]
public void RuntimeId()
{
var automaticTracer = new AutomaticTracer();
var runtimeId = automaticTracer.GetAutomaticRuntimeId();
Guid.TryParse(runtimeId, out _).Should().BeTrue();
automaticTracer.GetAutomaticRuntimeId().Should().Be(runtimeId, "runtime id should remain the same");
((IDistributedTracer)automaticTracer).GetRuntimeId().Should().Be(runtimeId, "distributed tracer API should return the same runtime id");
}
[Fact]
public void IsChildTracer()
{
var automaticTracer = new AutomaticTracer();
((IDistributedTracer)automaticTracer).IsChildTracer.Should().BeFalse();
}
}
}
| 34.772358 | 171 | 0.65256 | [
"Apache-2.0"
] | DataDog/dd-trace-dotnet | tracer/test/Datadog.Trace.Tests/DistributedTracer/AutomaticTracerTests.cs | 4,277 | C# |
namespace SMK_Restaurant
{
partial class FrmPayment
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmPayment));
this.lblTotal = new System.Windows.Forms.Label();
this.cbPayment = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.txtCard = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.dg1 = new System.Windows.Forms.DataGridView();
this.label3 = new System.Windows.Forms.Label();
this.panel3 = new System.Windows.Forms.Panel();
this.cbOrderID = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.cbBank = new System.Windows.Forms.ComboBox();
this.btnSave = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dg1)).BeginInit();
this.panel3.SuspendLayout();
this.SuspendLayout();
//
// lblTotal
//
this.lblTotal.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTotal.Location = new System.Drawing.Point(388, 355);
this.lblTotal.Name = "lblTotal";
this.lblTotal.Size = new System.Drawing.Size(540, 20);
this.lblTotal.TabIndex = 103;
this.lblTotal.Text = "Total : 0";
this.lblTotal.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// cbPayment
//
this.cbPayment.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cbPayment.FormattingEnabled = true;
this.cbPayment.Items.AddRange(new object[] {
"Cash",
"Credit Card"});
this.cbPayment.Location = new System.Drawing.Point(543, 393);
this.cbPayment.Name = "cbPayment";
this.cbPayment.Size = new System.Drawing.Size(185, 23);
this.cbPayment.TabIndex = 100;
this.cbPayment.SelectedValueChanged += new System.EventHandler(this.cbPayment_SelectedValueChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(18, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(107, 19);
this.label2.TabIndex = 0;
this.label2.Text = "Form Payment";
//
// txtCard
//
this.txtCard.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtCard.Location = new System.Drawing.Point(543, 428);
this.txtCard.Name = "txtCard";
this.txtCard.Size = new System.Drawing.Size(185, 23);
this.txtCard.TabIndex = 94;
this.txtCard.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtCard_KeyPress);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(407, 466);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(41, 20);
this.label5.TabIndex = 92;
this.label5.Text = "Bank";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(407, 431);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(98, 20);
this.label4.TabIndex = 91;
this.label4.Text = "Card Number";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(407, 391);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 20);
this.label1.TabIndex = 90;
this.label1.Text = "Payment Type";
//
// dg1
//
this.dg1.AllowUserToAddRows = false;
this.dg1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dg1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dg1.Location = new System.Drawing.Point(208, 102);
this.dg1.Name = "dg1";
this.dg1.Size = new System.Drawing.Size(720, 250);
this.dg1.TabIndex = 89;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(1017, 9);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(113, 19);
this.label3.TabIndex = 3;
this.label3.Text = "Home / Payment";
//
// panel3
//
this.panel3.BackColor = System.Drawing.Color.White;
this.panel3.Controls.Add(this.label3);
this.panel3.Controls.Add(this.label2);
this.panel3.Dock = System.Windows.Forms.DockStyle.Top;
this.panel3.Location = new System.Drawing.Point(0, 0);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(1240, 37);
this.panel3.TabIndex = 88;
//
// cbOrderID
//
this.cbOrderID.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cbOrderID.FormattingEnabled = true;
this.cbOrderID.Location = new System.Drawing.Point(543, 60);
this.cbOrderID.Name = "cbOrderID";
this.cbOrderID.Size = new System.Drawing.Size(185, 23);
this.cbOrderID.TabIndex = 105;
this.cbOrderID.SelectedValueChanged += new System.EventHandler(this.cbOrderID_SelectedValueChanged);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(407, 59);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(66, 20);
this.label7.TabIndex = 104;
this.label7.Text = "Order ID";
//
// cbBank
//
this.cbBank.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cbBank.FormattingEnabled = true;
this.cbBank.Items.AddRange(new object[] {
"BRI",
"BNI",
"Mandiri",
"BTN",
"BCA"});
this.cbBank.Location = new System.Drawing.Point(543, 463);
this.cbBank.Name = "cbBank";
this.cbBank.Size = new System.Drawing.Size(185, 23);
this.cbBank.TabIndex = 106;
//
// btnSave
//
this.btnSave.BackColor = System.Drawing.Color.RoyalBlue;
this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnSave.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSave.ForeColor = System.Drawing.Color.White;
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnSave.Location = new System.Drawing.Point(543, 507);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(87, 40);
this.btnSave.TabIndex = 107;
this.btnSave.Text = " Save";
this.btnSave.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnSave.UseVisualStyleBackColor = false;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// FrmPayment
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btnSave);
this.Controls.Add(this.cbBank);
this.Controls.Add(this.cbOrderID);
this.Controls.Add(this.label7);
this.Controls.Add(this.lblTotal);
this.Controls.Add(this.cbPayment);
this.Controls.Add(this.txtCard);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label1);
this.Controls.Add(this.dg1);
this.Controls.Add(this.panel3);
this.Name = "FrmPayment";
this.Size = new System.Drawing.Size(1240, 844);
this.Load += new System.EventHandler(this.FrmPayment_Load);
((System.ComponentModel.ISupportInitialize)(this.dg1)).EndInit();
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblTotal;
private System.Windows.Forms.ComboBox cbPayment;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtCard;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.DataGridView dg1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.ComboBox cbOrderID;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ComboBox cbBank;
private System.Windows.Forms.Button btnSave;
}
}
| 49.297189 | 159 | 0.589246 | [
"MIT"
] | altrawan/smk-restaurant | SMK Restaurant/FrmPayment.Designer.cs | 12,277 | C# |
/* Copyright 2010-2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
namespace MongoDB.Driver.Linq
{
/// <summary>
/// A class that formats an Expression as a string.
/// </summary>
public class ExpressionFormatter : ExpressionVisitor
{
// private fields
private StringBuilder _sb;
// constructors
/// <summary>
/// Initializes a new instance of the ExpressionFormatter class.
/// </summary>
public ExpressionFormatter()
{
_sb = new StringBuilder();
}
// public methods
/// <summary>
/// Returns a string that represents the Expression.
/// </summary>
/// <param name="node">The Expression to format.</param>
/// <returns>A string that represents the Expression.</returns>
public static string ToString(Expression node)
{
var formatter = new ExpressionFormatter();
formatter.Visit(node);
return formatter.ToString();
}
/// <summary>
/// Returns a string that represents the Expression.
/// </summary>
/// <returns>A string that represents the Expression.</returns>
public override string ToString()
{
return _sb.ToString();
}
// protected methods
/// <summary>
/// Visits a BinaryExpression.
/// </summary>
/// <param name="node">The BinaryExpression.</param>
/// <returns>The BinaryExpression.</returns>
protected override Expression VisitBinary(BinaryExpression node)
{
if (node.NodeType == ExpressionType.ArrayIndex)
{
Visit(node.Left);
_sb.Append("[");
Visit(node.Right);
_sb.Append("]");
return node;
}
_sb.Append("(");
Visit(node.Left);
switch (node.NodeType)
{
case ExpressionType.Add: _sb.Append(" + "); break;
case ExpressionType.And: _sb.Append(" & "); break;
case ExpressionType.AndAlso: _sb.Append(" && "); break;
case ExpressionType.Coalesce: _sb.Append(" ?? "); break;
case ExpressionType.Divide: _sb.Append(" / "); break;
case ExpressionType.Equal: _sb.Append(" == "); break;
case ExpressionType.ExclusiveOr: _sb.Append(" ^ "); break;
case ExpressionType.GreaterThan: _sb.Append(" > "); break;
case ExpressionType.GreaterThanOrEqual: _sb.Append(" >= "); break;
case ExpressionType.LeftShift: _sb.Append(" << "); break;
case ExpressionType.LessThan: _sb.Append(" < "); break;
case ExpressionType.LessThanOrEqual: _sb.Append(" <= "); break;
case ExpressionType.Modulo: _sb.Append(" % "); break;
case ExpressionType.Multiply: _sb.Append(" * "); break;
case ExpressionType.NotEqual: _sb.Append(" != "); break;
case ExpressionType.Or: _sb.Append(" | "); break;
case ExpressionType.OrElse: _sb.Append(" || "); break;
case ExpressionType.RightShift: _sb.Append(" >> "); break;
case ExpressionType.Subtract: _sb.Append(" - "); break;
case ExpressionType.TypeAs: _sb.Append(" as "); break;
case ExpressionType.TypeIs: _sb.Append(" is "); break;
default: _sb.AppendFormat(" <{0}> ", node.NodeType); break;
}
Visit(node.Right);
_sb.Append(")");
return node;
}
/// <summary>
/// Visits a ConditionalExpression.
/// </summary>
/// <param name="node">The ConditionalExpression.</param>
/// <returns>The ConditionalExpression.</returns>
protected override Expression VisitConditional(ConditionalExpression node)
{
_sb.Append("<ConditionalExpression>");
return node;
}
/// <summary>
/// Visits a ConstantExpression.
/// </summary>
/// <param name="node">The ConstantExpression.</param>
/// <returns>The ConstantExpression.</returns>
protected override Expression VisitConstant(ConstantExpression node)
{
// need to check node.Type instead of value.GetType() because boxed Nullable<T> values are boxed as <T>
if (node.Type.IsGenericType && node.Type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
_sb.AppendFormat("({0})", FriendlyTypeName(node.Type));
}
VisitValue(node.Value);
return node;
}
/// <summary>
/// Visits an ElementInit node.
/// </summary>
/// <param name="node">The ElementInit node.</param>
/// <returns>The ElementInit node.</returns>
protected override ElementInit VisitElementInit(ElementInit node)
{
_sb.Append("<ElementInit>");
return node;
}
/// <summary>
/// Visits an ElementInit list.
/// </summary>
/// <param name="nodes">The ElementInit list.</param>
/// <returns>The ElementInit list.</returns>
protected override IEnumerable<ElementInit> VisitElementInitList(ReadOnlyCollection<ElementInit> nodes)
{
_sb.Append("<ReadOnlyCollection<ElementInit>");
return nodes;
}
/// <summary>
/// Visits an InvocationExpression.
/// </summary>
/// <param name="node">The InvocationExpression.</param>
/// <returns>The InvocationExpression.</returns>
protected override Expression VisitInvocation(InvocationExpression node)
{
_sb.Append("<InvocationExpression>");
return node;
}
/// <summary>
/// Visits a LambdaExpression.
/// </summary>
/// <param name="node">The LambdaExpression.</param>
/// <returns>The LambdaExpression.</returns>
protected override Expression VisitLambda(LambdaExpression node)
{
_sb.Append("(");
_sb.Append(string.Join(", ", node.Parameters.Select(p => FriendlyTypeName(p.Type) + " " + p.Name).ToArray()));
_sb.Append(") => ");
Visit(node.Body);
return node;
}
/// <summary>
/// Visits a ListInitExpression.
/// </summary>
/// <param name="node">The ListInitExpression.</param>
/// <returns>The ListInitExpression.</returns>
protected override Expression VisitListInit(ListInitExpression node)
{
_sb.Append("<ListInitExpression>");
return node;
}
/// <summary>
/// Visits a MemberExpression.
/// </summary>
/// <param name="node">The MemberExpression.</param>
/// <returns>The MemberExpression.</returns>
protected override Expression VisitMember(MemberExpression node)
{
Visit(node.Expression);
_sb.Append(".");
_sb.Append(node.Member.Name);
return node;
}
/// <summary>
/// Visits a MemberAssignment.
/// </summary>
/// <param name="node">The MemberAssignment.</param>
/// <returns>The MemberAssignment.</returns>
protected override MemberAssignment VisitMemberAssignment(MemberAssignment node)
{
_sb.Append("<MemberAssignment>");
return node;
}
/// <summary>
/// Visits a MemberBinding.
/// </summary>
/// <param name="node">The MemberBinding.</param>
/// <returns>The MemberBinding (possibly modified).</returns>
protected override MemberBinding VisitMemberBinding(MemberBinding node)
{
_sb.Append("<MemberBinding>");
return node;
}
/// <summary>
/// Visits a MemberBinding list.
/// </summary>
/// <param name="nodes">The MemberBinding list.</param>
/// <returns>The MemberBinding list.</returns>
protected override IEnumerable<MemberBinding> VisitMemberBindingList(ReadOnlyCollection<MemberBinding> nodes)
{
_sb.Append("<ReadOnlyCollection<MemberBinding>>");
return nodes;
}
/// <summary>
/// Visits a MemberInitExpression.
/// </summary>
/// <param name="node">The MemberInitExpression.</param>
/// <returns>The MemberInitExpression.</returns>
protected override Expression VisitMemberInit(MemberInitExpression node)
{
_sb.Append("<MemberInitExpression>");
return node;
}
/// <summary>
/// Visits a MemberListBinding.
/// </summary>
/// <param name="node">The MemberListBinding.</param>
/// <returns>The MemberListBinding.</returns>
protected override MemberListBinding VisitMemberListBinding(MemberListBinding node)
{
_sb.Append("<MemberListBinding>");
return node;
}
/// <summary>
/// Visits a MemberMemberBinding.
/// </summary>
/// <param name="node">The MemberMemberBinding.</param>
/// <returns>The MemberMemberBinding.</returns>
protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node)
{
_sb.Append("<MemberMemberBinding>");
return node;
}
/// <summary>
/// Visits a MethodCallExpression.
/// </summary>
/// <param name="node">The MethodCallExpression.</param>
/// <returns>The MethodCallExpression.</returns>
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.IsStatic)
{
_sb.Append(FriendlyTypeName(node.Method.DeclaringType));
}
else
{
Visit(node.Object);
}
_sb.Append(".");
_sb.Append(node.Method.Name);
if (node.Method.IsGenericMethod)
{
_sb.AppendFormat("<{0}>", string.Join(", ", node.Method.GetGenericArguments().Select(t => FriendlyTypeName(t)).ToArray()));
}
_sb.Append("(");
var separator = "";
foreach (var arg in node.Arguments)
{
_sb.Append(separator);
Visit(arg);
separator = ", ";
}
_sb.Append(")");
return node;
}
/// <summary>
/// Visits a NewExpression.
/// </summary>
/// <param name="node">The NewExpression.</param>
/// <returns>The NewExpression.</returns>
protected override NewExpression VisitNew(NewExpression node)
{
_sb.Append("new ");
_sb.Append(FriendlyTypeName(node.Type));
_sb.Append("(");
var separator = "";
foreach (var arg in node.Arguments)
{
_sb.Append(separator);
Visit(arg);
separator = ", ";
}
_sb.Append(")");
return node;
}
/// <summary>
/// Visits a NewArrayExpression.
/// </summary>
/// <param name="node">The NewArrayExpression.</param>
/// <returns>The NewArrayExpression.</returns>
protected override Expression VisitNewArray(NewArrayExpression node)
{
var elementType = node.Type.GetElementType();
_sb.AppendFormat("new {0}[] {{ ", FriendlyTypeName(elementType));
var separator = "";
foreach (var item in node.Expressions)
{
_sb.Append(separator);
Visit(item);
separator = ", ";
}
_sb.Append(" }");
return node;
}
/// <summary>
/// Visits a ParameterExpression.
/// </summary>
/// <param name="node">The ParameterExpression.</param>
/// <returns>The ParameterExpression.</returns>
protected override Expression VisitParameter(ParameterExpression node)
{
_sb.Append(node.Name);
return node;
}
/// <summary>
/// Visits a TypeBinaryExpression.
/// </summary>
/// <param name="node">The TypeBinaryExpression.</param>
/// <returns>The TypeBinaryExpression.</returns>
protected override Expression VisitTypeBinary(TypeBinaryExpression node)
{
_sb.Append("(");
Visit(node.Expression);
_sb.Append(" is ");
_sb.Append(FriendlyTypeName(node.TypeOperand));
_sb.Append(")");
return node;
}
/// <summary>
/// Visits a UnaryExpression.
/// </summary>
/// <param name="node">The UnaryExpression.</param>
/// <returns>The UnaryExpression.</returns>
protected override Expression VisitUnary(UnaryExpression node)
{
switch (node.NodeType)
{
case ExpressionType.ArrayLength: break;
case ExpressionType.Convert: _sb.AppendFormat("({0})", FriendlyTypeName(node.Type)); break;
case ExpressionType.Negate: _sb.Append("-"); break;
case ExpressionType.Not: _sb.Append("!"); break;
case ExpressionType.Quote: break;
case ExpressionType.UnaryPlus: _sb.Append("+"); break;
default: _sb.AppendFormat("<{0}>", node.NodeType); break;
}
Visit(node.Operand);
switch (node.NodeType)
{
case ExpressionType.ArrayLength: _sb.Append(".Length"); break;
}
return node;
}
// private methods
private string FriendlyTypeName(Type type)
{
var typeName = IsAnonymousType(type) ? "__AnonymousType" : type.Name;
if (type.IsGenericType)
{
var sb = new StringBuilder();
sb.AppendFormat("{0}<", Regex.Replace(typeName, @"\`\d+$", ""));
foreach (var typeParameter in type.GetGenericArguments())
{
sb.AppendFormat("{0}, ", FriendlyTypeName(typeParameter));
}
sb.Remove(sb.Length - 2, 2);
sb.Append(">");
return sb.ToString();
}
else
{
return typeName;
}
}
private bool IsAnonymousType(Type type)
{
// don't test for too many things in case implementation details change in the future
return
Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false) &&
type.IsGenericType &&
type.Name.Contains("Anon"); // don't check for more than "Anon" so it works in mono also
}
private void VisitValue(object value)
{
if (value == null)
{
_sb.Append("null");
return;
}
var a = value as Array;
if (a != null && a.Rank == 1)
{
var elementType = a.GetType().GetElementType();
_sb.AppendFormat("{0}[]:{{", FriendlyTypeName(elementType));
var separator = " ";
foreach (var item in a)
{
_sb.Append(separator);
VisitValue(item);
separator = ", ";
}
_sb.Append(" }");
return;
}
if (value.GetType() == typeof(bool))
{
_sb.Append(((bool)value) ? "true" : "false");
return;
}
if (value.GetType() == typeof(char))
{
var c = (char)value;
_sb.AppendFormat("'{0}'", c.ToString());
return;
}
if (value.GetType() == typeof(DateTime))
{
var dt = (DateTime)value;
var formatted = dt.ToString("o");
formatted = Regex.Replace(formatted, @"\.0000000", "");
formatted = Regex.Replace(formatted, @"0000[Z+-]", "");
if (dt.Kind == DateTimeKind.Utc)
{
_sb.AppendFormat("DateTime:({0})", formatted);
}
else
{
_sb.AppendFormat("DateTime:({0}, {1})", formatted, dt.Kind);
}
return;
}
var e = value as Enum;
if (e != null)
{
_sb.Append(FriendlyTypeName(e.GetType()) + "." + e.ToString());
return;
}
var regex = value as Regex;
if (regex != null)
{
var pattern = regex.ToString();
var options = regex.Options;
_sb.Append("Regex:(@\"");
_sb.Append(pattern);
_sb.Append("\"");
if (options != RegexOptions.None)
{
_sb.AppendFormat(", {0}", options.ToString());
}
_sb.Append(")");
return;
}
var s = value as string;
if (s != null)
{
s = Regex.Replace(s, @"([""\\])", @"\\$1");
_sb.Append("\"");
_sb.Append(s);
_sb.Append("\"");
return;
}
if (value.GetType() == typeof(TimeSpan))
{
var ts = (TimeSpan)value;
_sb.AppendFormat("TimeSpan:({0})", ts.ToString());
return;
}
var type = value as Type;
if (type != null)
{
_sb.AppendFormat("typeof({0})", FriendlyTypeName(type));
return;
}
_sb.Append(value.ToString());
}
}
}
| 35.187845 | 139 | 0.517402 | [
"Apache-2.0"
] | InternationNova/MEANJS | src/MongoDB.Driver.Legacy/Linq/Expressions/ExpressionFormatter.cs | 19,107 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace A0002_HelloWorldMvc
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| 22.24 | 64 | 0.579137 | [
"MIT"
] | wangzhiqing999/my-dotnetcore-sample | A0002_HelloWorldMvc/Program.cs | 558 | 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("HackathonAPITests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("EPAM Systems")]
[assembly: AssemblyProduct("HackathonAPITests")]
[assembly: AssemblyCopyright("Copyright © EPAM Systems 2016")]
[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("31f3fb43-9726-40f7-81e4-3486bfc1a885")]
// 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")]
| 38.675676 | 84 | 0.749825 | [
"MIT"
] | ChristianKis/HackathonEpam2016 | SlbHackWeek2016/HackathonAPITests/Properties/AssemblyInfo.cs | 1,434 | C# |
using Newtonsoft.Json;
namespace ThreeRingsSharp.XansData.IO.GLTF.JSON {
/// <summary>
/// Represents an animation sampler.
/// </summary>
public class GLTFAnimationChannel : GLTFObject {
[JsonProperty("sampler")] public int Sampler;
[JsonProperty("target")] public GLTFAnimationChannelTarget Target;
}
}
| 20.9375 | 69 | 0.701493 | [
"MIT"
] | aytimothy/ThreeRingsSharp | ThreeRingsSharp/XansData/IO/GLTF/JSON/GLTFAnimationChannel.cs | 337 | C# |
using Neo.Core.Shared;
namespace Neo.Core.Communication.Packages
{
/// <summary>
/// Contains the data for the <see cref="PackageType.EditProfileResponse"/> package.
/// </summary>
public class EditProfileResponsePackageContent
{
/// <summary>
/// The account of the edited profile.
/// </summary>
public Account Account { get; set; }
/// <summary>
/// The identity of the edited profile.
/// </summary>
public Identity Identity { get; set; }
/// <summary>
/// The original edit request.
/// </summary>
public EditProfilePackageContent Request { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="EditProfileResponsePackageContent"/> class.
/// </summary>
/// <param name="account">The account of the edited profile.</param>
/// <param name="identity">The identity of the edited profile.</param>
/// <param name="request">The original edit request.</param>
public EditProfileResponsePackageContent(Account account, Identity identity, EditProfilePackageContent request = null) {
this.Account = account;
this.Identity = identity;
this.Request = request;
}
}
}
| 34.051282 | 128 | 0.593373 | [
"MIT"
] | festivaledu/neo-core | Communication/Packages/EditProfileResponsePackageContent.cs | 1,330 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bot.Messenger.Models
{
public class AttachmentMessage : Message
{
[JsonProperty("attachment")]
public virtual Attachment Attachment { get; set; }
}
}
| 20.5625 | 58 | 0.720365 | [
"MIT"
] | Be5NzZ/Bot_DotNet | Bot.Messenger/Models/Messaging/Messages/AttachmentMessage.cs | 331 | C# |
using UnityEngine;
using Photon.Pun;
public class PaddleController : MonoBehaviour
{
public string upKey, downKey;
public float speed;
private PhotonView myPv;
private void Start()
{
myPv = GetComponent<PhotonView>();
}
private void Update()
{
if (myPv.IsMine)
PaddleMovement();
}
void PaddleMovement()
{
if(Input.GetKey(upKey) && transform.position.y < 40)
{
transform.Translate(Vector3.up * Time.deltaTime * speed, Space.World);
}
if (Input.GetKey(downKey) && transform.position.y > -40)
{
transform.Translate(Vector3.down * Time.deltaTime * speed, Space.World);
}
}
} | 21.909091 | 84 | 0.586445 | [
"MIT"
] | xavimarin35/MultiplayerGame | Game/Assets/Scripts/Pong/PaddleController.cs | 723 | C# |
using System;
using System.Collections.Generic;
namespace PixelSquare.Utility.EventListener
{
using Parameters;
internal class PSObjectListener
{
private List<Action> m_emptyEvents = null;
private List<Action<PSParameters>> m_paramEvents = null;
public PSObjectListener()
{
m_emptyEvents = new List<Action>();
m_paramEvents = new List<Action<PSParameters>>();
}
public void addObserver(Action p_callback)
{
m_emptyEvents.Add(p_callback);
}
public void addObserver(Action<PSParameters> p_callback)
{
m_paramEvents.Add(p_callback);
}
public void removeObserver(Action p_callback)
{
m_emptyEvents.Remove(p_callback);
}
public void removeObserver(Action<PSParameters> p_callback)
{
m_paramEvents.Remove(p_callback);
}
public void dispose()
{
m_emptyEvents.Clear();
m_paramEvents.Clear();
}
public void notifyObservers()
{
for(int i = 0; i < m_emptyEvents.Count; i++)
{
Action callback = m_emptyEvents[i];
if(null != callback)
{
callback();
}
}
}
public void notifyObservers(PSParameters p_params)
{
for(int i = 0; i < m_paramEvents.Count; i++)
{
Action<PSParameters> callback = m_paramEvents[i];
if(null != callback)
{
callback(p_params);
}
}
}
public int getEmptyEventCount()
{
return m_emptyEvents.Count;
}
public int getParamEventCount()
{
return m_paramEvents.Count;
}
public int getTotalEventCount()
{
return m_emptyEvents.Count + m_paramEvents.Count;
}
}
}
| 17.758621 | 61 | 0.678317 | [
"MIT"
] | pixelsquare/pixel-square-utility | PixelSquare/Utility/EventListener/PSObjectListener.cs | 1,547 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using East.Tool.UseCaseTranslator.WebAPI.Areas.HelpPage.ModelDescriptions;
using East.Tool.UseCaseTranslator.WebAPI.Areas.HelpPage.Models;
namespace East.Tool.UseCaseTranslator.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| 51.598291 | 196 | 0.623654 | [
"MIT"
] | east-pmo/UseCaseTranslator | UseCaseTranslator.WebAPI/Areas/HelpPage/HelpPageConfigurationExtensions.cs | 24,148 | 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.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
/// <summary>
/// Tests that apply to the filesystem/cache portions of the X509 infrastructure on Unix implementations.
/// </summary>
[Collection("X509Filesystem")]
public static class X509FilesystemTests
{
// #9293: Our Fedora and Ubuntu1610 CI machines use NTFS for "tmphome", which causes our filesystem permissions checks to fail.
private static bool IsReliableInCI { get; } = ChainTests.IsReliableInCI;
[ActiveIssue(12833, TestPlatforms.AnyUnix)]
[Fact]
[OuterLoop]
public static void VerifyCrlCache()
{
string crlDirectory = PersistedFiles.GetUserFeatureDirectory("cryptography", "crls");
string crlFile = Path.Combine(crlDirectory,MicrosoftDotComRootCrlFilename);
Directory.CreateDirectory(crlDirectory);
File.Delete(crlFile);
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// The very start of the CRL period.
chain.ChainPolicy.VerificationTime = new DateTime(2015, 6, 17, 0, 0, 0, DateTimeKind.Utc);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly;
chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
bool valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Precondition: Chain builds with no revocation checks");
int initialErrorCount = chain.ChainStatus.Length;
Assert.InRange(initialErrorCount, 0, 1);
if (initialErrorCount > 0)
{
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainStatus[0].Status);
}
chainHolder.DisposeChainElements();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
valid = chain.Build(microsoftDotComIssuer);
Assert.False(valid, "Chain should not build validly");
Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);
File.WriteAllText(crlFile, MicrosoftDotComRootCrlPem, Encoding.ASCII);
chainHolder.DisposeChainElements();
valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Chain should build validly now");
Assert.Equal(initialErrorCount, chain.ChainStatus.Length);
}
}
[Fact]
public static void X509Store_OpenExisting_Fails()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
// Since the directory was explicitly deleted already, this should fail.
Assert.Throws<CryptographicException>(
() => store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly));
});
}
[Fact]
private static void X509Store_AddReadOnly()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[Fact]
private static void X509Store_AddClosed()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOne()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
using (var coll = new ImportedCollection(store.Certificates))
{
X509Certificate2Collection storeCerts = coll.Collection;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOneAfterUpgrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
// Calling Open on an open store changes the access rights:
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
using (var coll = new ImportedCollection(store.Certificates))
{
X509Certificate2Collection storeCerts = coll.Collection;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DowngradePermissions()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
// Ensure that ReadWrite took effect.
store.Add(certA);
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddAfterDispose()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
// Dispose returns the store to the pre-opened state.
store.Dispose();
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddAndClear()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Remove(cert);
// The directory should still exist.
Assert.True(Directory.Exists(storeDirectory), "Store Directory Still Exists");
Assert.Equal(0, Directory.GetFiles(storeDirectory).Length);
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddDuplicate()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
using (var certClone = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Add(certClone);
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certA, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string[] storeFiles = Directory.GetFiles(storeDirectory);
Assert.Equal(2, storeFiles.Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
storeCert.Dispose();
}
store.Add(certAPrivate);
// It replaces the existing file, the names should be unaffected.
Assert.Equal(storeFiles, Directory.GetFiles(storeDirectory));
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
// The public instance and private instance are .Equal
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey_NoDowngrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
// Add the private (checked in X509Store_AddTwo_UpgradePrivateKey)
store.Add(certAPrivate);
// Then add the public again, which shouldn't do anything.
store.Add(certAPublic);
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DistinctCollections()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCertsA = store.Certificates;
X509Certificate2Collection storeCertsB = store.Certificates;
Assert.NotSame(storeCertsA, storeCertsB);
Assert.Equal(storeCertsA.Count, storeCertsB.Count);
foreach (X509Certificate2 collACert in storeCertsA)
{
int bIndex = storeCertsB.IndexOf(collACert);
Assert.InRange(bIndex, 0, storeCertsB.Count);
X509Certificate2 collBCert = storeCertsB[bIndex];
// Equal is implied by IndexOf working.
Assert.NotSame(collACert, collBCert);
storeCertsB.RemoveAt(bIndex);
collACert.Dispose();
collBCert.Dispose();
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_Add4_Remove1()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certBClone = new X509Certificate2(certB.RawData))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
store.Add(certC);
store.Add(certD);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(4, Directory.GetFiles(storeDirectory).Length);
X509Certificate2[] expectedCerts = { certA, certB, certC, certD };
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(4, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
store.Remove(certBClone);
Assert.Equal(3, Directory.GetFiles(storeDirectory).Length);
expectedCerts = new[] { certA, certC, certD };
storeCerts = store.Certificates;
Assert.Equal(3, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[ConditionalTheory(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
[InlineData(false)]
[InlineData(true)]
private static void X509Store_MultipleObjects(bool matchCase)
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string newName = store.Name;
if (!matchCase)
{
newName = newName.ToUpperInvariant();
Assert.NotEqual(store.Name, newName);
}
using (X509Store storeClone = new X509Store(newName, store.Location))
{
storeClone.Open(OpenFlags.ReadWrite);
AssertEqualContents(store, storeClone);
store.Add(certC);
// The object was added to store, but should show up in both objects
// after re-reading the Certificates property
AssertEqualContents(store, storeClone);
// Now add one to storeClone to prove bidirectionality.
storeClone.Add(certD);
AssertEqualContents(store, storeClone);
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop( /* Alters user/machine state */)]
private static void X509Store_FiltersDuplicateOnLoad()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
// Emulate a race condition of parallel adds with the following flow
// AdderA: Notice [thumbprint].pfx is available, create it (0 bytes)
// AdderB: Notice [thumbprint].pfx already exists, but can't be read, move to [thumbprint].1.pfx
// AdderA: finish write
// AdderB: finish write
string[] files = Directory.GetFiles(storeDirectory, "*.pfx");
Assert.Equal(1, files.Length);
string srcFile = files[0];
string baseName = Path.GetFileNameWithoutExtension(srcFile);
string destFile = Path.Combine(storeDirectory, srcFile + ".1.pfx");
File.Copy(srcFile, destFile);
using (var coll = new ImportedCollection(store.Certificates))
{
Assert.Equal(1, coll.Collection.Count);
Assert.Equal(certA, coll.Collection[0]);
}
// Also check that remove removes both files.
store.Remove(certA);
string[] filesAfter = Directory.GetFiles(storeDirectory, "*.pfx");
Assert.Equal(0, filesAfter.Length);
}
});
}
private static void AssertEqualContents(X509Store storeA, X509Store storeB)
{
Assert.NotSame(storeA, storeB);
using (var storeATracker = new ImportedCollection(storeA.Certificates))
using (var storeBTracker = new ImportedCollection(storeB.Certificates))
{
X509Certificate2Collection storeACerts = storeATracker.Collection;
X509Certificate2Collection storeBCerts = storeBTracker.Collection;
Assert.Equal(storeACerts.OfType<X509Certificate2>(), storeBCerts.OfType<X509Certificate2>());
}
}
private static void RunX509StoreTest(Action<X509Store, string> testAction)
{
string certStoresFeaturePath = PersistedFiles.GetUserFeatureDirectory("cryptography", "x509stores");
string storeName = "TestStore" + Guid.NewGuid().ToString("N");
string storeDirectory = Path.Combine(certStoresFeaturePath, storeName.ToLowerInvariant());
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
try
{
using (X509Store store = new X509Store(storeName, StoreLocation.CurrentUser))
{
testAction(store, storeDirectory);
}
}
finally
{
try
{
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
}
catch
{
// Don't allow any (additional?) I/O errors to propagate.
}
}
}
// `openssl crl -in [MicrosoftDotComRootCrlPem] -noout -hash`.crl
private const string MicrosoftDotComRootCrlFilename = "b204d74a.crl";
// This CRL was downloaded 2015-08-31 20:31 PDT
// It is valid from Jun 17 00:00:00 2015 GMT to Sep 30 23:59:59 2015 GMT
private const string MicrosoftDotComRootCrlPem =
@"-----BEGIN X509 CRL-----
MIICETCB+jANBgkqhkiG9w0BAQUFADCByjELMAkGA1UEBhMCVVMxFzAVBgNVBAoT
DlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3Jr
MTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp
emVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQ
cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUXDTE1MDYxNzAwMDAw
MFoXDTE1MDkzMDIzNTk1OVowDQYJKoZIhvcNAQEFBQADggEBAFxqobObEqKNSAe+
A9cHCYI7sw+Vc8HuE7E+VZc6ni3a2UHiprYuXDsvD18+cyv/nFSLpLqLmExZrsf/
dzH8GH2HgBTt5aO/nX08EBrDgcjHo9b0VI6ZuOOaEeS0NsRh28Jupfn1Xwcsbdw9
nVh1OaExpHwxgg7pJr4pXzaAjbl3b4QfCPyTd5aaOQOEmqvJtRrMwCna4qQ3p4r6
QYe19/pXqK9my7lSmH1vZ0CmNvQeNPmnx+YmFXYTBgap+Xi2cs6GX/qI04CDzjWi
sm6L0+S1Zx2wMhiYOi0JvrRizf+rIyKkDbPMoYEyXZqcCwSnv6mJQY81vmKRKU5N
WKo2mLw=
-----END X509 CRL-----";
}
}
| 43.262626 | 135 | 0.516127 | [
"MIT"
] | ERROR-FAILS-NewData-News/corefx | src/System.Security.Cryptography.X509Certificates/tests/X509FilesystemTests.Unix.cs | 29,981 | C# |
using System;
using System.Text;
using UnityEngine;
namespace ThirdParty
{
public static class RandomName
{
public static string GetName(bool male)
{
string[] array = new string[]
{
"腼腆的",
"机灵的",
"英勇的",
"可爱的",
"阳光的",
"开朗的",
"活泼的",
"无敌的",
"伟大的",
"高贵的",
"温柔的",
"善良的",
"乐观的",
"机智的",
"美丽的",
"傲娇的",
"中二的",
"单纯的",
"俊俏的",
"大方的",
"纯洁的",
"优雅的",
"淳朴的",
"清秀的",
"稚气的",
"俏皮的",
"干脆的",
"爽直的",
"憨直的",
"耿直的",
"公道的",
"公允的",
"正派的",
"简捷的",
"开阔的",
"明朗的",
"率直的",
"率真的",
"理智的",
"老实的",
"坚强的",
"萌萌的",
"温和的",
"负责的",
"正直的",
"无私的",
"友好的",
"直爽的",
"热情的",
"好动的",
"幽默的",
"风趣的",
"高冷的",
"逗比的",
"体贴的",
"积极的",
"自信的",
"深沉的",
"知足的",
"浪漫的",
"快乐的",
"灵巧的",
"捣蛋的",
"大胆的",
"能干的",
"踏实的",
"稳健的",
"成熟的",
"谦卑的",
"谦虚的",
"勇敢的",
"老练的",
"可靠的",
"果敢的",
"精悍的",
"调皮的",
"古怪的",
"勤劳的",
"恭顺的",
"诚实的",
"公正的",
"聪慧的",
"笃实的",
"温厚的",
"赤诚的",
"竭诚的",
"恳挚的",
"赤忱的",
"衷心的",
"坦率的",
"规矩的",
"热诚的",
"虔诚的",
"尽职的",
"和善的",
"过谦的",
"客气的",
"和婉的",
"好客的",
"安静的",
"沉默的",
"静谧的",
"勤奋的"
};
string[] array2 = new string[]
{
"亚伦",
"亚伦",
"艾伦",
"埃布尔",
"亚尔维斯",
"亚托克斯",
"巴伦",
"班森",
"布鲁斯",
"伯特",
"布兰茨",
"科林",
"克里斯",
"采尼",
"卡尔",
"科加斯",
"丹尼尔",
"德里克",
"唐纳德",
"大卫",
"蒙多",
"爱德华",
"艾德文",
"埃里克",
"埃尔斯特",
"伊泽瑞尔",
"佛朗西斯",
"佛兰德",
"弗兰克",
"富兰克林",
"费德提克",
"加比",
"加百利",
"基诺",
"格林",
"普朗克",
"哈里森",
"汉克",
"雨果",
"霍德华",
"黑默丁格",
"伊恩",
"英格玛",
"艾萨克",
"伊西多",
"贾斯汀",
"约瑟夫",
"吉米",
"杰罗姆",
"嘉文",
"肯",
"凯文",
"肯尼",
"肯尼",
"卡尔萨斯",
"雷欧",
"里奥波特",
"劳瑞",
"卢克",
"卢锡安",
"马克",
"马修斯",
"麦克",
"迈克尔",
"玛尔扎哈",
"尼尔",
"尼古拉斯",
"诺尔",
"诺曼",
"诺提勒斯",
"欧格登",
"奥利佛",
"奥玛",
"奥斯卡",
"奥拉夫",
"佩吉",
"派克",
"保罗",
"皮特",
"潘森",
"昆特",
"昆西",
"昆",
"昆顿",
"奎因",
"雷尔夫",
"雷切尔",
"里根",
"罗宾",
"兰博",
"山姆",
"肖恩",
"所罗门",
"史丹佛",
"斯卡纳",
"泰勒",
"提姆",
"汤尼",
"杜鲁门",
"塔里克",
"尤多",
"尤利西斯",
"阿普顿",
"尤莱亚",
"乌迪尔",
"范拉丁",
"维克",
"维多特",
"文森",
"维迦",
"韦德",
"瓦尔特",
"韦恩",
"温德尔",
"沃里克",
"塞维尔",
"莱昂纳多",
"塞西尔",
"莱斯特",
"泽拉斯",
"耶鲁",
"耶尔希",
"约克",
"伊夫",
"约里克",
"扎克",
"扎卡莱",
"纪伯伦",
"苏洛",
"吉格斯"
};
string[] array3 = new string[]
{
"艾莉丝",
"艾莉丝",
"阿曼达",
"艾米",
"安琪拉",
"阿卡丽",
"芭芭拉",
"贝拉",
"柏莎",
"贝丝",
"卡萝",
"凯丝",
"塞西莉亚",
"坎蒂丝",
"凯特琳",
"达莲娜",
"黛比",
"黛娜",
"狄德丽",
"黛安娜",
"爱琳",
"伊甸",
"伊迪丝",
"艾西",
"伊芙琳",
"梵妮",
"法兰西斯",
"佛莉达",
"费怡",
"菲奥娜",
"姬玛",
"珍妮芙",
"姬儿",
"格莱蒂斯",
"赫达",
"海伦",
"希尔达",
"何蒙莎",
"艾娜",
"艾尔玛",
"艾薇",
"伊莎贝尔",
"婕咪",
"乔安娜",
"珍妮",
"杰西卡",
"迦娜",
"卡玛",
"凯伊",
"凯蒂",
"克莉丝汀",
"卡特琳娜",
"莉拉",
"丽娜",
"莉莉丝",
"莉莲",
"乐芙兰",
"美乐蒂",
"玛琪",
"玛乔丽",
"美莲丝",
"莫甘娜",
"妮可",
"妮狄娅",
"妮娜",
"诺维雅",
"奈德丽",
"奥利维亚",
"奥利芙",
"奥利薇兰",
"奥克薇儿",
"奥莉安娜",
"蓓姬",
"潘妮",
"潘朵拉",
"普力玛",
"波比",
"昆娜",
"昆蒂娜",
"克拉",
"克尔莱",
"奎因",
"丽贝卡",
"蕾佳娜",
"丽达",
"莉娃",
"瑞雯",
"雪莉",
"莎拉",
"赛拉",
"雪伦",
"希瓦娜",
"泰丽莎",
"托比",
"翠西",
"尤娜",
"崔丝塔娜",
"优娜",
"优拉",
"尤瑞娅",
"乌兰妮",
"维纳斯",
"维多利亚",
"维琪",
"维尔拉",
"薇恩",
"温蒂",
"温妮",
"旺妲",
"华莉丝",
"桑席",
"赛薇亚拉",
"芝妮雅",
"席娜",
"耶达",
"依耶塔",
"依耶芙特",
"伊芳",
"若伊",
"若娜",
"若拉",
"丽诺比丽",
"婕拉"
};
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(array[UnityEngine.Random.Range(0, array.Length - 1)]);
if (male)
{
stringBuilder.Append(array2[UnityEngine.Random.Range(0, array2.Length - 1)]);
}
else
{
stringBuilder.Append(array3[UnityEngine.Random.Range(0, array3.Length - 1)]);
}
return stringBuilder.ToString();
}
public static string GetName()
{
return RandomName.GetName(UnityEngine.Random.value == 1f);
}
}
}
| 11.635443 | 81 | 0.32376 | [
"MIT"
] | moto2002/jiandangjianghu | src/ThirdParty/RandomName.cs | 6,542 | C# |
// sysORUpTime class.
// Copyright (C) 2009-2010 Lex Li
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Lextm.SharpSnmpLib.Pipeline;
namespace Lextm.SharpSnmpLib.Objects
{
internal sealed class SysORUpTime : ScalarObject
{
private readonly TimeTicks _data;
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public SysORUpTime (int index, TimeTicks time)
: base ("1.3.6.1.2.1.1.9.1.4.{0}", index)
{
_data = time;
}
public override ISnmpData Data
{
get { return _data; }
set { throw new AccessFailureException (); }
}
}
}
| 39.333333 | 112 | 0.746973 | [
"MIT"
] | oznetmaster/SSharpSharpSnmpLibLibrary | Objects/SysORUpTime.cs | 1,652 | C# |
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using Kit;
using Kit.Forms.Extensions;
using Kit.Model;
using Kit.Sql.Attributes;
using Kit.Sql.Interfaces;
using RSAVault.Resources;
using Xamarin.Essentials;
namespace RSAVault.Models
{
public class Note : ModelBase, IGuid
{
[PrimaryKey]
public Guid Guid { get; set; }
private string _Text;
public string Text
{
get => _Text;
set
{
if (value != _Text)
{
_Text = value;
Raise(() => IsEmpty);
Raise(() => Text);
}
}
}
private string _Title;
public string Title
{
get => _Title;
set
{
_Title = value;
Raise(() => Title);
Raise(() => IsEmpty);
}
}
public string DisplayLastModificationTime => LastModificationTime.ToString(CultureInfo.CurrentCulture);
private DateTime _LastModificationTime;
public DateTime LastModificationTime
{
get => _LastModificationTime;
set
{
_LastModificationTime = value;
Raise(() => LastModificationTime);
Raise(() => DisplayLastModificationTime);
}
}
public bool IsEmpty => string.IsNullOrEmpty(Title?.Trim()) && string.IsNullOrEmpty(Text?.Trim()) && Guid == Guid.Empty;
public Note()
{
LastModificationTime = DateTime.Now;
}
internal async void Share()
{
if (!await Permisos.RequestStorage())
{
Acr.UserDialogs.UserDialogs.Instance.Alert(AppResources.HasDeniedStorage);
return;
}
FileInfo file = new FileInfo(Path.Combine(Tools.Instance.TemporalPath, $"{Guid.NewGuid():N}.txt"));
if (file.Exists)
{
file.Delete();
}
using (FileStream mStream = new FileStream(file.FullName, FileMode.OpenOrCreate))
{
using (TextWriter writer = new StreamWriter(mStream, Encoding.UTF8))
{
try
{
await writer.WriteAsync(this.Text);
await writer.FlushAsync();
await mStream.FlushAsync();
}
catch (XmlException ex)
{
Log.Logger.Error(ex, "KeyChain.Share");
}
}
}
ShareFileRequest request = new ShareFileRequest(new ShareFile(file.FullName));
await Xamarin.Essentials.Share.RequestAsync(request);
}
}
} | 27.308411 | 127 | 0.490075 | [
"MIT"
] | Jon2G/RSA-Vault | RSAVault/RSAVault/Models/Note.cs | 2,924 | C# |
using System;
using System.Collections.Generic;
using System.Xml.Schema;
using System.Xml.Serialization;
using NPOI.OpenXmlFormats.Vml.Wordprocessing;
using NPOI.OpenXmlFormats.Vml.Office;
using NPOI.OpenXmlFormats.Vml.Spreadsheet;
using NPOI.OpenXmlFormats.Vml.Presentation;
using System.IO;
using System.Xml;
using System.Text;
namespace NPOI.OpenXmlFormats.Vml
{
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot("shape",Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Shape {
private string typeField;
private string adjField;
private string styleField;
private CT_Path pathField;
private string equationxmlField;
private string idField;
private string fillcolorField;
private ST_InsetMode insetmodeField;
private ST_TrueFalse strokedField;
private string wrapcoordsField;
[XmlAttribute]
public string wrapcoords
{
get { return wrapcoordsField; }
set { wrapcoordsField = value; }
}
[XmlAttribute]
public ST_TrueFalse stroked
{
get { return strokedField; }
set { strokedField = value; }
}
static XmlSerializer serializer = new XmlSerializer(typeof(CT_Shape), "urn:schemas-microsoft-com:vml");
public static CT_Shape Parse(string xmltext)
{
TextReader tr = new StringReader(xmltext);
CT_Shape obj = (CT_Shape)serializer.Deserialize(tr);
return obj;
}
private string spidField;
[XmlAttribute(Namespace = "urn:schemas-microsoft-com:office:office")]
public string spid
{
get { return this.spidField; }
set { this.spidField = value; }
}
[XmlAttribute]
public string id
{
get { return idField; }
set { idField = value; }
}
[XmlAttribute]
public string fillcolor
{
get { return fillcolorField; }
set { fillcolorField = value; }
}
[XmlAttribute(Namespace = "urn:schemas-microsoft-com:office:office")]
public ST_InsetMode insetmode
{
get { return insetmodeField; }
set { insetmodeField = value; }
}
public CT_Textbox AddNewTextbox()
{
textboxField = new CT_Textbox();
return this.textboxField;
}
private CT_Wrap wrapField;
private CT_Fill fillField;
private CT_Formulas formulasField;
private CT_Handles handlesField;
private CT_ImageData imagedataField;
private CT_Stroke strokeField;
private CT_Shadow shadowField;
private CT_Textbox textboxField;
private CT_TextPath textpathField;
private CT_Empty iscommentField;
/*[XmlElement("textdata", typeof(CT_Rel), Namespace = "urn:schemas-microsoft-com:office:powerpoint")]
[XmlElement("anchorlock", typeof(CT_AnchorLock), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("borderbottom", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("borderleft", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("borderright", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("bordertop", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]*/
[XmlElement(Namespace = "urn:schemas-microsoft-com:office:powerpoint")]
public CT_Empty iscomment
{
get { return this.iscommentField; }
set { this.iscommentField = value; }
}
[XmlElement(Namespace="urn:schemas-microsoft-com:office:word")]
public CT_Wrap wrap
{
get { return this.wrapField; }
set { this.wrapField = value; }
}
[XmlElement]
public CT_Textbox textbox
{
get { return this.textboxField; }
set { this.textboxField = value; }
}
[XmlElement]
public CT_Fill fill
{
get { return this.fillField; }
set { this.fillField = value; }
}
[XmlElement]
public CT_Formulas formulas
{
get { return this.formulasField; }
set { this.formulasField = value; }
}
[XmlElement]
public CT_Handles handles
{
get { return this.handlesField; }
set { this.handlesField = value; }
}
[XmlElement]
public CT_ImageData imagedata
{
get { return this.imagedataField; }
set { this.imagedataField = value; }
}
[XmlElement]
public CT_Stroke stroke
{
get { return this.strokeField; }
set { this.strokeField = value; }
}
[XmlElement]
public CT_Shadow shadow
{
get { return this.shadowField; }
set { this.shadowField = value; }
}
public CT_Fill AddNewFill()
{
this.fillField=new CT_Fill();
return this.fillField;
}
public CT_Shadow AddNewShadow()
{
this.shadowField = new CT_Shadow();
return this.shadowField;
}
public CT_Path AddNewPath()
{
this.pathField = new CT_Path();
return this.pathField;
}
List<CT_ClientData> clientDataField = null;
[XmlElement("ClientData",Namespace = "urn:schemas-microsoft-com:office:excel")]
public CT_ClientData[] ClientData
{
get
{
if (clientDataField == null)
return null;
return clientDataField.ToArray();
}
set
{
if (value == null)
this.clientDataField = new List<CT_ClientData>();
else
this.clientDataField = new List<CT_ClientData>(value);
}
}
public CT_ClientData GetClientDataArray(int index)
{
return clientDataField != null ? this.clientDataField[index] : null;
}
public int sizeOfClientDataArray()
{
if (clientDataField == null)
return 0;
return clientDataField.Count;
}
public CT_ClientData AddNewClientData()
{
CT_ClientData cd=new CT_ClientData();
if (clientDataField == null)
this.clientDataField = new List<CT_ClientData>();
this.clientDataField.Add(cd);
return cd;
}
[XmlAttribute]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[XmlAttribute]
public string adj {
get {
return this.adjField;
}
set {
this.adjField = value;
}
}
[XmlElement]
public CT_Path path {
get {
return this.pathField;
}
set {
this.pathField = value;
}
}
[XmlAttribute]
public string equationxml {
get {
return this.equationxmlField;
}
set {
this.equationxmlField = value;
}
}
[XmlAttribute]
public string style
{
get
{
return this.styleField;
}
set
{
this.styleField = value;
}
}
internal static XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName("o", "urn:schemas-microsoft-com:office:office"),
new XmlQualifiedName("x", "urn:schemas-microsoft-com:office:excel"),
new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml")
});
public override string ToString()
{
using (StringWriter stringWriter = new StringWriter())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlWriter.Create(stringWriter, settings))
{
serializer.Serialize(writer, this, namespaces);
}
return stringWriter.ToString();
}
}
[XmlElement]
public CT_TextPath textpath
{
get
{
return this.textpathField;
}
set
{
this.textpathField = value;
}
}
public CT_TextPath AddNewTextpath()
{
this.textpathField = new CT_TextPath();
return this.textpathField;
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "urn:schemas-microsoft-com:vml")]
public partial class CT_Formulas
{
private List<CT_F> fField = null; // 0..*
[XmlElement("f", Form = XmlSchemaForm.Qualified, Namespace = "urn:schemas-microsoft-com:vml")]
public List<CT_F> f
{
get { return this.fField; }
set { this.fField = value; }
}
[XmlIgnore]
public bool fSpecified
{
get { return (null != fField); }
}
public CT_F AddNewF()
{
if (this.fField == null)
this.fField = new List<CT_F>();
this.fField.Add(new CT_F());
return this.fField[this.fField.Count - 1];
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "urn:schemas-microsoft-com:vml")]
public partial class CT_F
{
private string eqnField = null;
[XmlAttribute]
public string eqn
{
get { return this.eqnField; }
set { this.eqnField = value; }
}
[XmlIgnore]
public bool eqnSpecified
{
get { return (null != eqnField); }
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace = "urn:schemas-microsoft-com:vml")]
public partial class CT_Handles
{
private List<CT_H> hField = null;
[XmlElement("h")]
public List<CT_H> h
{
get { return this.hField; }
set { this.hField = value; }
}
[XmlIgnore]
public bool hSpecified
{
get { return (null != hField); }
}
public CT_H AddNewH()
{
if (hField == null)
hField = new List<CT_H>();
CT_H h = new CT_H();
hField.Add(h);
return h;
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
public partial class CT_H {
private string positionField;
private string polarField;
private string mapField;
private ST_TrueFalse invxField;
private bool invxFieldSpecified;
private ST_TrueFalse invyField;
private bool invyFieldSpecified; // TODO remove
private ST_TrueFalseBlank switchField;
private bool switchFieldSpecified;
private string xrangeField;
private string yrangeField;
private string radiusrangeField;
[XmlAttribute]
public string position {
get {
return this.positionField;
}
set {
this.positionField = value;
}
}
[XmlAttribute]
public string polar {
get {
return this.polarField;
}
set {
this.polarField = value;
}
}
[XmlAttribute]
public string map {
get {
return this.mapField;
}
set {
this.mapField = value;
}
}
[XmlAttribute]
public ST_TrueFalse invx {
get {
return this.invxField;
}
set {
this.invxField = value;
}
}
[XmlIgnore]
public bool invxSpecified {
get {
return this.invxFieldSpecified;
}
set {
this.invxFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse invy {
get {
return this.invyField;
}
set {
this.invyField = value;
}
}
[XmlIgnore]
public bool invySpecified {
get {
return this.invyFieldSpecified;
}
set {
this.invyFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalseBlank @switch {
get {
return this.switchField;
}
set {
this.switchField = value;
}
}
[XmlIgnore]
public bool switchSpecified {
get {
return this.switchFieldSpecified;
}
set {
this.switchFieldSpecified = value;
}
}
[XmlAttribute]
public string xrange {
get {
return this.xrangeField;
}
set {
this.xrangeField = value;
}
}
[XmlAttribute]
public string yrange {
get {
return this.yrangeField;
}
set {
this.yrangeField = value;
}
}
[XmlAttribute]
public string radiusrange {
get {
return this.radiusrangeField;
}
set {
this.radiusrangeField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_ImageData {
private string idField;
private string srcField;
private string cropleftField;
private string croptopField;
private string croprightField;
private string cropbottomField;
private string gainField;
private string blacklevelField;
private string gammaField;
private ST_TrueFalse grayscaleField;
private bool grayscaleFieldSpecified;
private ST_TrueFalse bilevelField;
private bool bilevelFieldSpecified;
private string chromakeyField;
private string embosscolorField;
private string recolortargetField;
private string id1Field;
private string pictField;
private string hrefField;
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set {
this.idField = value;
}
}
[XmlAttribute]
public string src {
get {
return this.srcField;
}
set {
this.srcField = value;
}
}
[XmlAttribute]
public string cropleft {
get {
return this.cropleftField;
}
set {
this.cropleftField = value;
}
}
[XmlAttribute]
public string croptop {
get {
return this.croptopField;
}
set {
this.croptopField = value;
}
}
[XmlAttribute]
public string cropright {
get {
return this.croprightField;
}
set {
this.croprightField = value;
}
}
[XmlAttribute]
public string cropbottom {
get {
return this.cropbottomField;
}
set {
this.cropbottomField = value;
}
}
[XmlAttribute]
public string gain {
get {
return this.gainField;
}
set {
this.gainField = value;
}
}
[XmlAttribute]
public string blacklevel {
get {
return this.blacklevelField;
}
set {
this.blacklevelField = value;
}
}
[XmlAttribute]
public string gamma {
get {
return this.gammaField;
}
set {
this.gammaField = value;
}
}
[XmlAttribute]
public ST_TrueFalse grayscale {
get {
return this.grayscaleField;
}
set {
this.grayscaleField = value;
}
}
[XmlIgnore]
public bool grayscaleSpecified {
get {
return this.grayscaleFieldSpecified;
}
set {
this.grayscaleFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse bilevel {
get {
return this.bilevelField;
}
set {
this.bilevelField = value;
}
}
[XmlIgnore]
public bool bilevelSpecified {
get {
return this.bilevelFieldSpecified;
}
set {
this.bilevelFieldSpecified = value;
}
}
[XmlAttribute]
public string chromakey {
get {
return this.chromakeyField;
}
set {
this.chromakeyField = value;
}
}
[XmlAttribute]
public string embosscolor {
get {
return this.embosscolorField;
}
set {
this.embosscolorField = value;
}
}
[XmlAttribute]
public string recolortarget {
get {
return this.recolortargetField;
}
set {
this.recolortargetField = value;
}
}
[XmlAttribute]//(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://schemas.openxmlformats.org/officeDocument/2006/relationships")]
public string pict {
get {
return this.pictField;
}
set {
this.pictField = value;
}
}
[XmlAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://schemas.openxmlformats.org/officeDocument/2006/relationships")]
public string href {
get {
return this.hrefField;
}
set {
this.hrefField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Path {
private string idField;
private string vField;
private string limoField;
private string textboxrectField;
private ST_TrueFalse fillokField;
private bool fillokFieldSpecified;
private ST_TrueFalse strokeokField;
private bool strokeokFieldSpecified;
private ST_TrueFalse shadowokField;
private bool shadowokFieldSpecified;
private ST_TrueFalse arrowokField;
private bool arrowokFieldSpecified;
private ST_TrueFalse gradientshapeokField;
private bool gradientshapeokFieldSpecified;
private ST_TrueFalse textpathokField;
private bool textpathokFieldSpecified;
private ST_TrueFalse insetpenokField;
private bool insetpenokFieldSpecified;
private ST_ConnectType connecttypeField;
private string connectlocsField;
private bool connectlocsFieldSpecified;
private string connectanglesField;
private bool connectanglesFieldSpecified;
private ST_TrueFalse extrusionokField;
private bool extrusionokFieldSpecified;
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set {
this.idField = value;
}
}
[XmlAttribute(Namespace = "urn:schemas-microsoft-com:office:office")]
public ST_ConnectType connecttype
{
get
{
return this.connecttypeField;
}
set
{
this.connecttypeField = value;
}
}
[XmlAttribute]
public string v {
get {
return this.vField;
}
set {
this.vField = value;
}
}
[XmlAttribute]
public string limo {
get {
return this.limoField;
}
set {
this.limoField = value;
}
}
[XmlAttribute]
public string textboxrect {
get {
return this.textboxrectField;
}
set {
this.textboxrectField = value;
}
}
[XmlAttribute]
public ST_TrueFalse fillok {
get {
return this.fillokField;
}
set {
this.fillokField = value;
}
}
[XmlIgnore]
public bool fillokSpecified {
get {
return this.fillokFieldSpecified;
}
set {
this.fillokFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse strokeok {
get {
return this.strokeokField;
}
set {
this.strokeokField = value;
}
}
[XmlIgnore]
public bool strokeokSpecified {
get {
return this.strokeokFieldSpecified;
}
set {
this.strokeokFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse shadowok {
get {
return this.shadowokField;
}
set {
this.shadowokField = value;
}
}
[XmlIgnore]
public bool shadowokSpecified {
get {
return this.shadowokFieldSpecified;
}
set {
this.shadowokFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse arrowok {
get {
return this.arrowokField;
}
set {
this.arrowokField = value;
}
}
[XmlIgnore]
public bool arrowokSpecified {
get {
return this.arrowokFieldSpecified;
}
set {
this.arrowokFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse gradientshapeok {
get {
return this.gradientshapeokField;
}
set {
this.gradientshapeokField = value;
}
}
[XmlIgnore]
public bool gradientshapeokSpecified {
get {
return this.gradientshapeokFieldSpecified;
}
set {
this.gradientshapeokFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse textpathok {
get {
return this.textpathokField;
}
set {
this.textpathokField = value;
}
}
[XmlIgnore]
public bool textpathokSpecified {
get {
return this.textpathokFieldSpecified;
}
set {
this.textpathokFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse insetpenok {
get {
return this.insetpenokField;
}
set {
this.insetpenokField = value;
}
}
[XmlIgnore]
public bool insetpenokSpecified {
get {
return this.insetpenokFieldSpecified;
}
set {
this.insetpenokFieldSpecified = value;
}
}
[XmlAttribute]
public string connectlocs
{
get
{
return this.connectlocsField;
}
set
{
this.connectlocsField = value;
}
}
[XmlIgnore]
public bool connectlocsSpecified
{
get
{
return this.connectlocsFieldSpecified;
}
set
{
this.connectlocsFieldSpecified = value;
}
}
[XmlAttribute]
public string connectangles
{
get
{
return this.connectanglesField;
}
set
{
this.connectanglesField = value;
}
}
[XmlIgnore]
public bool connectanglesSpecified
{
get
{
return this.connectanglesFieldSpecified;
}
set
{
this.connectanglesFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse extrusionok
{
get
{
return this.extrusionokField;
}
set
{
this.extrusionokField = value;
}
}
[XmlIgnore]
public bool extrusionokSpecified
{
get
{
return this.extrusionokFieldSpecified;
}
set
{
this.extrusionokFieldSpecified = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Shadow {
private string idField;
private ST_TrueFalse onField;
private bool onFieldSpecified;
private ST_ShadowType typeField;
private bool typeFieldSpecified;
private ST_TrueFalse obscuredField;
private bool obscuredFieldSpecified;
private string colorField;
private string opacityField;
private string offsetField;
private string color2Field;
private string offset2Field;
private string originField;
private string matrixField;
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set {
this.idField = value;
}
}
[XmlAttribute]
public ST_TrueFalse on {
get {
return this.onField;
}
set {
this.onField = value;
}
}
[XmlIgnore]
public bool onSpecified {
get {
return this.onFieldSpecified;
}
set {
this.onFieldSpecified = value;
}
}
[XmlAttribute]
public ST_ShadowType type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[XmlIgnore]
public bool typeSpecified {
get {
return this.typeFieldSpecified;
}
set {
this.typeFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse obscured {
get {
return this.obscuredField;
}
set {
this.obscuredField = value;
}
}
[XmlIgnore]
public bool obscuredSpecified {
get {
return this.obscuredFieldSpecified;
}
set {
this.obscuredFieldSpecified = value;
}
}
[XmlAttribute]
public string color {
get {
return this.colorField;
}
set {
this.colorField = value;
}
}
[XmlAttribute]
public string opacity {
get {
return this.opacityField;
}
set {
this.opacityField = value;
}
}
[XmlAttribute]
public string offset {
get {
return this.offsetField;
}
set {
this.offsetField = value;
}
}
[XmlAttribute]
public string color2 {
get {
return this.color2Field;
}
set {
this.color2Field = value;
}
}
[XmlAttribute]
public string offset2 {
get {
return this.offset2Field;
}
set {
this.offset2Field = value;
}
}
[XmlAttribute]
public string origin {
get {
return this.originField;
}
set {
this.originField = value;
}
}
[XmlAttribute]
public string matrix {
get {
return this.matrixField;
}
set {
this.matrixField = value;
}
}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_ShadowType {
single,
@double,
emboss,
perspective,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Stroke {
private string idField;
private ST_TrueFalse onField;
private bool onFieldSpecified;
private string weightField;
private string colorField;
private string opacityField;
private ST_StrokeLineStyle linestyleField;
private bool linestyleFieldSpecified;
private decimal miterlimitField;
private bool miterlimitFieldSpecified;
private ST_StrokeJoinStyle joinstyleField;
private bool joinstyleFieldSpecified;
private ST_StrokeEndCap endcapField;
private bool endcapFieldSpecified;
private string dashstyleField;
private ST_FillType filltypeField;
private bool filltypeFieldSpecified;
private string srcField;
private ST_ImageAspect imageaspectField;
private bool imageaspectFieldSpecified;
private string imagesizeField;
private ST_TrueFalse imagealignshapeField;
private bool imagealignshapeFieldSpecified;
private string color2Field;
private ST_StrokeArrowType startarrowField;
private bool startarrowFieldSpecified;
private ST_StrokeArrowWidth startarrowwidthField;
private bool startarrowwidthFieldSpecified;
private ST_StrokeArrowLength startarrowlengthField;
private bool startarrowlengthFieldSpecified;
private ST_StrokeArrowType endarrowField;
private bool endarrowFieldSpecified;
private ST_StrokeArrowWidth endarrowwidthField;
private bool endarrowwidthFieldSpecified;
private ST_StrokeArrowLength endarrowlengthField;
private bool endarrowlengthFieldSpecified;
private string id1Field;
private ST_TrueFalse insetpenField;
private bool insetpenFieldSpecified;
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set {
this.idField = value;
}
}
[XmlAttribute]
public ST_TrueFalse on {
get {
return this.onField;
}
set {
this.onField = value;
}
}
[XmlIgnore]
public bool onSpecified {
get {
return this.onFieldSpecified;
}
set {
this.onFieldSpecified = value;
}
}
[XmlAttribute]
public string weight {
get {
return this.weightField;
}
set {
this.weightField = value;
}
}
[XmlAttribute]
public string color {
get {
return this.colorField;
}
set {
this.colorField = value;
}
}
[XmlAttribute]
public string opacity {
get {
return this.opacityField;
}
set {
this.opacityField = value;
}
}
[XmlAttribute]
public ST_StrokeLineStyle linestyle {
get {
return this.linestyleField;
}
set {
this.linestyleField = value;
}
}
[XmlIgnore]
public bool linestyleSpecified {
get {
return this.linestyleFieldSpecified;
}
set {
this.linestyleFieldSpecified = value;
}
}
[XmlAttribute]
public decimal miterlimit {
get {
return this.miterlimitField;
}
set {
this.miterlimitField = value;
}
}
[XmlIgnore]
public bool miterlimitSpecified {
get {
return this.miterlimitFieldSpecified;
}
set {
this.miterlimitFieldSpecified = value;
}
}
[XmlAttribute]
public ST_StrokeJoinStyle joinstyle {
get {
return this.joinstyleField;
}
set {
this.joinstyleField = value;
}
}
[XmlIgnore]
public bool joinstyleSpecified {
get {
return this.joinstyleFieldSpecified;
}
set {
this.joinstyleFieldSpecified = value;
}
}
[XmlAttribute]
public ST_StrokeEndCap endcap {
get {
return this.endcapField;
}
set {
this.endcapField = value;
}
}
[XmlIgnore]
public bool endcapSpecified {
get {
return this.endcapFieldSpecified;
}
set {
this.endcapFieldSpecified = value;
}
}
[XmlAttribute]
public string dashstyle {
get {
return this.dashstyleField;
}
set {
this.dashstyleField = value;
}
}
[XmlAttribute]
public ST_FillType filltype {
get {
return this.filltypeField;
}
set {
this.filltypeField = value;
}
}
[XmlIgnore]
public bool filltypeSpecified {
get {
return this.filltypeFieldSpecified;
}
set {
this.filltypeFieldSpecified = value;
}
}
[XmlAttribute]
public string src {
get {
return this.srcField;
}
set {
this.srcField = value;
}
}
[XmlAttribute]
public ST_ImageAspect imageaspect {
get {
return this.imageaspectField;
}
set {
this.imageaspectField = value;
}
}
[XmlIgnore]
public bool imageaspectSpecified {
get {
return this.imageaspectFieldSpecified;
}
set {
this.imageaspectFieldSpecified = value;
}
}
[XmlAttribute]
public string imagesize {
get {
return this.imagesizeField;
}
set {
this.imagesizeField = value;
}
}
[XmlAttribute]
public ST_TrueFalse imagealignshape {
get {
return this.imagealignshapeField;
}
set {
this.imagealignshapeField = value;
}
}
[XmlIgnore]
public bool imagealignshapeSpecified {
get {
return this.imagealignshapeFieldSpecified;
}
set {
this.imagealignshapeFieldSpecified = value;
}
}
[XmlAttribute]
public string color2 {
get {
return this.color2Field;
}
set {
this.color2Field = value;
}
}
[XmlAttribute]
public ST_StrokeArrowType startarrow {
get {
return this.startarrowField;
}
set {
this.startarrowField = value;
}
}
[XmlIgnore]
public bool startarrowSpecified {
get {
return this.startarrowFieldSpecified;
}
set {
this.startarrowFieldSpecified = value;
}
}
[XmlAttribute]
public ST_StrokeArrowWidth startarrowwidth {
get {
return this.startarrowwidthField;
}
set {
this.startarrowwidthField = value;
}
}
[XmlIgnore]
public bool startarrowwidthSpecified {
get {
return this.startarrowwidthFieldSpecified;
}
set {
this.startarrowwidthFieldSpecified = value;
}
}
[XmlAttribute]
public ST_StrokeArrowLength startarrowlength {
get {
return this.startarrowlengthField;
}
set {
this.startarrowlengthField = value;
}
}
[XmlIgnore]
public bool startarrowlengthSpecified {
get {
return this.startarrowlengthFieldSpecified;
}
set {
this.startarrowlengthFieldSpecified = value;
}
}
[XmlAttribute]
public ST_StrokeArrowType endarrow {
get {
return this.endarrowField;
}
set {
this.endarrowField = value;
}
}
[XmlIgnore]
public bool endarrowSpecified {
get {
return this.endarrowFieldSpecified;
}
set {
this.endarrowFieldSpecified = value;
}
}
[XmlAttribute]
public ST_StrokeArrowWidth endarrowwidth {
get {
return this.endarrowwidthField;
}
set {
this.endarrowwidthField = value;
}
}
[XmlIgnore]
public bool endarrowwidthSpecified {
get {
return this.endarrowwidthFieldSpecified;
}
set {
this.endarrowwidthFieldSpecified = value;
}
}
[XmlAttribute]
public ST_StrokeArrowLength endarrowlength {
get {
return this.endarrowlengthField;
}
set {
this.endarrowlengthField = value;
}
}
[XmlIgnore]
public bool endarrowlengthSpecified {
get {
return this.endarrowlengthFieldSpecified;
}
set {
this.endarrowlengthFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse insetpen {
get {
return this.insetpenField;
}
set {
this.insetpenField = value;
}
}
[XmlIgnore]
public bool insetpenSpecified {
get {
return this.insetpenFieldSpecified;
}
set {
this.insetpenFieldSpecified = value;
}
}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_StrokeLineStyle {
single,
thinThin,
thinThick,
thickThin,
thickBetweenThin,
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_StrokeJoinStyle {
round,
bevel,
miter,
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_StrokeEndCap {
flat,
square,
round,
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_StrokeArrowType {
none,
block,
classic,
oval,
diamond,
open,
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_StrokeArrowWidth {
narrow,
medium,
wide,
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_StrokeArrowLength {
@short,
medium,
@long,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Textbox {
private System.Xml.XmlElement itemField;
private string idField;
private string styleField;
private string insetField;
[XmlAnyElement()]
public System.Xml.XmlElement Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set {
this.idField = value;
}
}
[XmlAttribute]
public string style {
get {
return this.styleField;
}
set {
this.styleField = value;
}
}
[XmlAttribute]
public string inset {
get {
return this.insetField;
}
set {
this.insetField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_TextPath {
private string idField;
private string styleField;
private ST_TrueFalse onField;
private bool onFieldSpecified;
private ST_TrueFalse fitshapeField;
private bool fitshapeFieldSpecified;
private ST_TrueFalse fitpathField;
private bool fitpathFieldSpecified;
private ST_TrueFalse trimField;
private bool trimFieldSpecified;
private ST_TrueFalse xscaleField;
private bool xscaleFieldSpecified;
private string stringField;
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set {
this.idField = value;
}
}
[XmlAttribute]
public string style {
get {
return this.styleField;
}
set {
this.styleField = value;
}
}
[XmlAttribute]
public ST_TrueFalse on {
get {
return this.onField;
}
set {
this.onField = value;
}
}
[XmlIgnore]
public bool onSpecified {
get {
return this.onFieldSpecified;
}
set {
this.onFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse fitshape {
get {
return this.fitshapeField;
}
set {
this.fitshapeField = value;
}
}
[XmlIgnore]
public bool fitshapeSpecified {
get {
return this.fitshapeFieldSpecified;
}
set {
this.fitshapeFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse fitpath {
get {
return this.fitpathField;
}
set {
this.fitpathField = value;
}
}
[XmlIgnore]
public bool fitpathSpecified {
get {
return this.fitpathFieldSpecified;
}
set {
this.fitpathFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse trim {
get {
return this.trimField;
}
set {
this.trimField = value;
}
}
[XmlIgnore]
public bool trimSpecified {
get {
return this.trimFieldSpecified;
}
set {
this.trimFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse xscale {
get {
return this.xscaleField;
}
set {
this.xscaleField = value;
}
}
[XmlIgnore]
public bool xscaleSpecified {
get {
return this.xscaleFieldSpecified;
}
set {
this.xscaleFieldSpecified = value;
}
}
[XmlAttribute]
public string @string {
get {
return this.stringField;
}
set {
this.stringField = value;
}
}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml", IncludeInSchema=false)]
public enum ItemsChoiceType1 {
[XmlEnum("urn:schemas-microsoft-com:office:excel:ClientData")]
ClientData,
[XmlEnum("urn:schemas-microsoft-com:office:powerpoint:iscomment")]
iscomment,
[XmlEnum("urn:schemas-microsoft-com:office:powerpoint:textdata")]
textdata,
[XmlEnum("urn:schemas-microsoft-com:office:word:anchorlock")]
anchorlock,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderbottom")]
borderbottom,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderleft")]
borderleft,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderright")]
borderright,
[XmlEnum("urn:schemas-microsoft-com:office:word:bordertop")]
bordertop,
[XmlEnum("urn:schemas-microsoft-com:office:word:wrap")]
wrap,
fill,
formulas,
handles,
imagedata,
path,
shadow,
stroke,
textbox,
textpath,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot("shapetype",Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Shapetype {
private CT_Path pathField;
private List<CT_Formulas> formulasField = new List<CT_Formulas>();
private List<CT_Handles> handlesField = new List<CT_Handles>();
private List<CT_Fill> fillField = new List<CT_Fill>();
private CT_Stroke strokeField;
private List<CT_Shadow> shadowField;
private List<CT_Textbox> textboxField;
private List<CT_TextPath> textpathField = new List<CT_TextPath>();
private List<CT_ImageData> imagedataField;
private List<CT_Wrap> wrapField;
private List<CT_AnchorLock> anchorlockField;
private List<CT_Lock> lockField = new List<CT_Lock>();
private List<CT_Border> bordertopField;
private List<CT_Border> borderbottomField;
private List<CT_Border> borderleftField;
private List<CT_Border> borderrightField;
private List<CT_ClientData> clientDataField;
private List<CT_Rel> textdataField;
private string adjField;
private string idField;
private string styleField;
private float sptField;
private string coordsizeField;
static XmlSerializer serializer = new XmlSerializer(typeof(CT_Shapetype), "urn:schemas-microsoft-com:vml");
public static CT_Shapetype Parse(string xmltext)
{
TextReader tr = new StringReader(xmltext);
CT_Shapetype obj = (CT_Shapetype)serializer.Deserialize(tr);
return obj;
}
[XmlAttribute(Namespace = "urn:schemas-microsoft-com:office:office")]
public string coordsize
{
get
{
return this.coordsizeField;
}
set
{
this.coordsizeField = value;
}
}
[XmlAttribute(Namespace = "urn:schemas-microsoft-com:office:office")]
public float spt
{
get
{
return this.sptField;
}
set
{
this.sptField = value;
}
}
private string path1Field;
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set
{
this.idField = value;
}
}
[XmlElement("path")]
public CT_Path path {
get {
return this.pathField;
}
set {
this.pathField = value;
}
}
[XmlElement("formulas")]
public CT_Formulas[] formulas
{
get
{
return this.formulasField.ToArray();
}
set
{
if (value == null)
this.formulasField = new List<CT_Formulas>();
else
this.formulasField = new List<CT_Formulas>(value);
}
}
[XmlElement("handles")]
public CT_Handles[] handles
{
get
{
return this.handlesField.ToArray();
}
set
{
if (value == null)
this.handlesField = new List<CT_Handles>();
else
this.handlesField = new List<CT_Handles>(value);
}
}
[XmlElement("fill")]
public CT_Fill[] fill
{
get
{
return this.fillField.ToArray();
}
set
{
if (value == null)
this.fillField = new List<CT_Fill>();
else
this.fillField = new List<CT_Fill>(value);
}
}
[XmlElement("stroke")]
public CT_Stroke stroke {
get {
return this.strokeField;
}
set {
this.strokeField = value;
}
}
//[XmlElement("shadow")]
//public List<CT_Shadow> shadow {
// get {
// return this.shadowField;
// }
// set {
// this.shadowField = value;
// }
//}
//[XmlElement("textbox")]
//public List<CT_Textbox> textbox {
// get {
// return this.textboxField;
// }
// set {
// this.textboxField = value;
// }
//}
[XmlElement("textpath")]
public CT_TextPath[] textpath
{
get
{
return this.textpathField.ToArray();
}
set
{
if (value == null)
this.textpathField = new List<CT_TextPath>();
else
this.textpathField = new List<CT_TextPath>(value);
}
}
//[XmlElement("imagedata")]
//public List<CT_ImageData> imagedata {
// get {
// return this.imagedataField;
// }
// set {
// this.imagedataField = value;
// }
//}
//[XmlElement("wrap", Namespace="urn:schemas-microsoft-com:office:word")]
//public List<CT_Wrap> wrap {
// get {
// return this.wrapField;
// }
// set {
// this.wrapField = value;
// }
//}
//[XmlElement("anchorlock", Namespace="urn:schemas-microsoft-com:office:word")]
//public List<CT_AnchorLock> anchorlock {
// get {
// return this.anchorlockField;
// }
// set {
// this.anchorlockField = value;
// }
//}
[XmlElement("lock", Namespace = "urn:schemas-microsoft-com:office:word")]
public CT_Lock[] @lock
{
get
{
return this.lockField.ToArray();
}
set
{
if (value == null)
this.lockField = new List<CT_Lock>();
else
this.lockField = new List<CT_Lock>(value);
}
}
//[XmlElement("bordertop", Namespace="urn:schemas-microsoft-com:office:word")]
//public List<CT_Border> bordertop {
// get {
// return this.bordertopField;
// }
// set {
// this.bordertopField = value;
// }
//}
//[XmlElement("borderbottom", Namespace="urn:schemas-microsoft-com:office:word")]
//public List<CT_Border> borderbottom {
// get {
// return this.borderbottomField;
// }
// set {
// this.borderbottomField = value;
// }
//}
//[XmlElement("borderleft", Namespace="urn:schemas-microsoft-com:office:word")]
//public List<CT_Border> borderleft {
// get {
// return this.borderleftField;
// }
// set {
// this.borderleftField = value;
// }
//}
//[XmlElement("borderright", Namespace="urn:schemas-microsoft-com:office:word")]
//public List<CT_Border> borderright {
// get {
// return this.borderrightField;
// }
// set {
// this.borderrightField = value;
// }
//}
//[XmlElement("ClientData", Namespace="urn:schemas-microsoft-com:office:excel")]
//public List<CT_ClientData> ClientData {
// get {
// return this.clientDataField;
// }
// set {
// this.clientDataField = value;
// }
//}
//[XmlElement("textdata", Namespace="urn:schemas-microsoft-com:office:powerpoint")]
//public List<CT_Rel> textdata {
// get {
// return this.textdataField;
// }
// set {
// this.textdataField = value;
// }
//}
[XmlAttribute]
public string adj {
get {
return this.adjField;
}
set {
this.adjField = value;
}
}
[XmlAttribute("path")]
public string path2 {
get {
return this.path1Field;
}
set {
this.path1Field = value;
}
}
public CT_Stroke AddNewStroke()
{
this.strokeField = new CT_Stroke();
return strokeField;
}
public CT_Path AddNewPath()
{
this.pathField = new CT_Path();
return this.pathField;
}
internal static XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName("o", "urn:schemas-microsoft-com:office:office"),
new XmlQualifiedName("x", "urn:schemas-microsoft-com:office:excel"),
new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml")
});
public override string ToString()
{
using (StringWriter stringWriter = new StringWriter())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlWriter.Create(stringWriter, settings))
{
serializer.Serialize(writer, this, namespaces);
}
return stringWriter.ToString();
}
}
public CT_Formulas AddNewFormulas()
{
if (this.formulasField == null)
this.formulasField = new List<CT_Formulas>();
CT_Formulas obj = new CT_Formulas();
this.formulasField.Add(obj);
return obj;
}
public CT_TextPath AddNewTextpath()
{
if (this.textpathField == null)
this.textpathField = new List<CT_TextPath>();
CT_TextPath obj = new CT_TextPath();
this.textpathField.Add(obj);
return obj;
}
public CT_Handles AddNewHandles()
{
if (this.handlesField == null)
this.handlesField = new List<CT_Handles>();
CT_Handles obj = new CT_Handles();
this.handlesField.Add(obj);
return obj;
}
public CT_Lock AddNewLock()
{
if (this.lockField == null)
this.lockField = new List<CT_Lock>();
CT_Lock obj = new CT_Lock();
this.lockField.Add(obj);
return obj;
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Group {
private List<object> itemsField = new List<object>();
private List<ItemsChoiceType6> itemsElementNameField = new List<ItemsChoiceType6>();
private ST_TrueFalse filledField;
private bool filledFieldSpecified;
private string fillcolorField;
private ST_EditAs editasField;
private bool editasFieldSpecified;
[XmlElement("ClientData", typeof(CT_ClientData), Namespace="urn:schemas-microsoft-com:office:excel")]
[XmlElement("textdata", typeof(CT_Rel), Namespace="urn:schemas-microsoft-com:office:powerpoint")]
[XmlElement("anchorlock", typeof(CT_AnchorLock), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("borderbottom", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("borderleft", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("borderright", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("bordertop", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("wrap", typeof(CT_Wrap), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("arc", typeof(CT_Arc))]
[XmlElement("curve", typeof(CT_Curve))]
[XmlElement("fill", typeof(CT_Fill))]
[XmlElement("formulas", typeof(CT_Formulas))]
[XmlElement("group", typeof(CT_Group))]
[XmlElement("handles", typeof(CT_Handles))]
[XmlElement("image", typeof(CT_Image))]
[XmlElement("imagedata", typeof(CT_ImageData))]
[XmlElement("line", typeof(CT_Line))]
[XmlElement("oval", typeof(CT_Oval))]
[XmlElement("path", typeof(CT_Path))]
[XmlElement("polyline", typeof(CT_PolyLine))]
[XmlElement("rect", typeof(CT_Rect))]
[XmlElement("roundrect", typeof(CT_RoundRect))]
[XmlElement("shadow", typeof(CT_Shadow))]
[XmlElement("shape", typeof(CT_Shape))]
[XmlElement("shapetype", typeof(CT_Shapetype))]
[XmlElement("stroke", typeof(CT_Stroke))]
[XmlElement("textbox", typeof(CT_Textbox))]
[XmlElement("textpath", typeof(CT_TextPath))]
[XmlChoiceIdentifier("ItemsElementName")]
public object[] Items {
get {
if (this.itemsField == null)
return null;
return this.itemsField.ToArray();
}
set {
if (value == null)
this.itemsField = new List<object>();
else
this.itemsField = new List<object>(value);
}
}
[XmlElement("ItemsElementName")]
[XmlIgnore]
public ItemsChoiceType6[] ItemsElementName {
get {
return this.itemsElementNameField.ToArray();
}
set {
if (value == null)
this.itemsElementNameField = new List<ItemsChoiceType6>();
else
this.itemsElementNameField = new List<ItemsChoiceType6>(value);
}
}
[XmlAttribute]
public ST_TrueFalse filled {
get {
return this.filledField;
}
set {
this.filledField = value;
}
}
[XmlIgnore]
public bool filledSpecified {
get {
return this.filledFieldSpecified;
}
set {
this.filledFieldSpecified = value;
}
}
[XmlAttribute]
public string fillcolor {
get {
return this.fillcolorField;
}
set {
this.fillcolorField = value;
}
}
[XmlAttribute]
public ST_EditAs editas {
get {
return this.editasField;
}
set {
this.editasField = value;
}
}
[XmlIgnore]
public bool editasSpecified {
get {
return this.editasFieldSpecified;
}
set {
this.editasFieldSpecified = value;
}
}
public CT_Shapetype AddNewShapetype()
{
return AddNewObject<CT_Shapetype>(ItemsChoiceType6.shapetype);
}
#region Generic methods for object operation
private List<T> GetObjectList<T>(ItemsChoiceType6 type) where T : class
{
lock (this)
{
List<T> list = new List<T>();
for (int i = 0; i < itemsElementNameField.Count; i++)
{
if (itemsElementNameField[i] == type)
list.Add(itemsField[i] as T);
}
return list;
}
}
private int SizeOfObjectArray(ItemsChoiceType6 type)
{
lock (this)
{
int size = 0;
for (int i = 0; i < itemsElementNameField.Count; i++)
{
if (itemsElementNameField[i] == type)
size++;
}
return size;
}
}
private T GetObjectArray<T>(int p, ItemsChoiceType6 type) where T : class
{
lock (this)
{
int pos = GetObjectIndex(type, p);
if (pos < 0 || pos >= this.itemsField.Count)
return null;
return itemsField[pos] as T;
}
}
private T InsertNewObject<T>(ItemsChoiceType6 type, int p) where T : class, new()
{
T t = new T();
lock (this)
{
int pos = GetObjectIndex(type, p);
this.itemsElementNameField.Insert(pos, type);
this.itemsField.Insert(pos, t);
}
return t;
}
private T AddNewObject<T>(ItemsChoiceType6 type) where T : class, new()
{
T t = new T();
lock (this)
{
this.itemsElementNameField.Add(type);
this.itemsField.Add(t);
}
return t;
}
private void SetObjectArray<T>(ItemsChoiceType6 type, int p, T obj) where T : class
{
lock (this)
{
int pos = GetObjectIndex(type, p);
if (pos < 0 || pos >= this.itemsField.Count)
return;
if (this.itemsField[pos] is T)
this.itemsField[pos] = obj;
else
throw new Exception(string.Format(@"object types are difference, itemsField[{0}] is {1}, and parameter obj is {2}",
pos, this.itemsField[pos].GetType().Name, typeof(T).Name));
}
}
private int GetObjectIndex(ItemsChoiceType6 type, int p)
{
int index = -1;
int pos = 0;
for (int i = 0; i < itemsElementNameField.Count; i++)
{
if (itemsElementNameField[i] == type)
{
if (pos == p)
{
//return itemsField[p] as T;
index = i;
break;
}
else
pos++;
}
}
return index;
}
private void RemoveObject(ItemsChoiceType6 type, int p)
{
lock (this)
{
int pos = GetObjectIndex(type, p);
if (pos < 0 || pos >= this.itemsField.Count)
return;
itemsElementNameField.RemoveAt(pos);
itemsField.RemoveAt(pos);
}
}
#endregion
public CT_Shape AddNewShape()
{
return AddNewObject<CT_Shape>(ItemsChoiceType6.shape);
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Arc {
private List<CT_Path> pathField;
private List<CT_Formulas> formulasField;
private List<CT_Handles> handlesField;
private List<CT_Fill> fillField;
private List<CT_Stroke> strokeField;
private List<CT_Shadow> shadowField;
private List<CT_Textbox> textboxField;
private List<CT_TextPath> textpathField;
private List<CT_ImageData> imagedataField;
private List<CT_Wrap> wrapField;
private List<CT_AnchorLock> anchorlockField;
private List<CT_Border> bordertopField;
private List<CT_Border> borderbottomField;
private List<CT_Border> borderleftField;
private List<CT_Border> borderrightField;
private List<CT_ClientData> clientDataField;
private List<CT_Rel> textdataField;
private decimal startAngleField;
private bool startAngleFieldSpecified;
private decimal endAngleField;
private bool endAngleFieldSpecified;
[XmlElement("path")]
public List<CT_Path> path {
get {
return this.pathField;
}
set {
this.pathField = value;
}
}
[XmlElement("formulas")]
public List<CT_Formulas> formulas {
get {
return this.formulasField;
}
set {
this.formulasField = value;
}
}
[XmlElement("handles")]
public List<CT_Handles> handles {
get {
return this.handlesField;
}
set {
this.handlesField = value;
}
}
[XmlElement("fill")]
public List<CT_Fill> fill {
get {
return this.fillField;
}
set {
this.fillField = value;
}
}
[XmlElement("stroke")]
public List<CT_Stroke> stroke {
get {
return this.strokeField;
}
set {
this.strokeField = value;
}
}
[XmlElement("shadow")]
public List<CT_Shadow> shadow {
get {
return this.shadowField;
}
set {
this.shadowField = value;
}
}
[XmlElement("textbox")]
public List<CT_Textbox> textbox {
get {
return this.textboxField;
}
set {
this.textboxField = value;
}
}
[XmlElement("textpath")]
public List<CT_TextPath> textpath {
get {
return this.textpathField;
}
set {
this.textpathField = value;
}
}
[XmlElement("imagedata")]
public List<CT_ImageData> imagedata {
get {
return this.imagedataField;
}
set {
this.imagedataField = value;
}
}
[XmlElement("wrap", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Wrap> wrap {
get {
return this.wrapField;
}
set {
this.wrapField = value;
}
}
[XmlElement("anchorlock", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_AnchorLock> anchorlock {
get {
return this.anchorlockField;
}
set {
this.anchorlockField = value;
}
}
[XmlElement("bordertop", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> bordertop {
get {
return this.bordertopField;
}
set {
this.bordertopField = value;
}
}
[XmlElement("borderbottom", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderbottom {
get {
return this.borderbottomField;
}
set {
this.borderbottomField = value;
}
}
[XmlElement("borderleft", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderleft {
get {
return this.borderleftField;
}
set {
this.borderleftField = value;
}
}
[XmlElement("borderright", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderright {
get {
return this.borderrightField;
}
set {
this.borderrightField = value;
}
}
[XmlElement("ClientData", Namespace="urn:schemas-microsoft-com:office:excel")]
public List<CT_ClientData> ClientData {
get {
return this.clientDataField;
}
set {
this.clientDataField = value;
}
}
[XmlElement("textdata", Namespace="urn:schemas-microsoft-com:office:powerpoint")]
public List<CT_Rel> textdata {
get {
return this.textdataField;
}
set {
this.textdataField = value;
}
}
[XmlAttribute]
public decimal startAngle {
get {
return this.startAngleField;
}
set {
this.startAngleField = value;
}
}
[XmlIgnore]
public bool startAngleSpecified {
get {
return this.startAngleFieldSpecified;
}
set {
this.startAngleFieldSpecified = value;
}
}
[XmlAttribute]
public decimal endAngle {
get {
return this.endAngleField;
}
set {
this.endAngleField = value;
}
}
[XmlIgnore]
public bool endAngleSpecified {
get {
return this.endAngleFieldSpecified;
}
set {
this.endAngleFieldSpecified = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Curve {
private List<CT_Path> pathField;
private List<CT_Formulas> formulasField;
private List<CT_Handles> handlesField;
private List<CT_Fill> fillField;
private List<CT_Stroke> strokeField;
private List<CT_Shadow> shadowField;
private List<CT_Textbox> textboxField;
private List<CT_TextPath> textpathField;
private List<CT_ImageData> imagedataField;
private List<CT_Wrap> wrapField;
private List<CT_AnchorLock> anchorlockField;
private List<CT_Border> bordertopField;
private List<CT_Border> borderbottomField;
private List<CT_Border> borderleftField;
private List<CT_Border> borderrightField;
private List<CT_ClientData> clientDataField;
private List<CT_Rel> textdataField;
private string fromField;
private string control1Field;
private string control2Field;
private string toField;
[XmlElement("path")]
public List<CT_Path> path {
get {
return this.pathField;
}
set {
this.pathField = value;
}
}
[XmlElement("formulas")]
public List<CT_Formulas> formulas {
get {
return this.formulasField;
}
set {
this.formulasField = value;
}
}
[XmlElement("handles")]
public List<CT_Handles> handles {
get {
return this.handlesField;
}
set {
this.handlesField = value;
}
}
[XmlElement("fill")]
public List<CT_Fill> fill {
get {
return this.fillField;
}
set {
this.fillField = value;
}
}
[XmlElement("stroke")]
public List<CT_Stroke> stroke {
get {
return this.strokeField;
}
set {
this.strokeField = value;
}
}
[XmlElement("shadow")]
public List<CT_Shadow> shadow {
get {
return this.shadowField;
}
set {
this.shadowField = value;
}
}
[XmlElement("textbox")]
public List<CT_Textbox> textbox {
get {
return this.textboxField;
}
set {
this.textboxField = value;
}
}
[XmlElement("textpath")]
public List<CT_TextPath> textpath {
get {
return this.textpathField;
}
set {
this.textpathField = value;
}
}
[XmlElement("imagedata")]
public List<CT_ImageData> imagedata {
get {
return this.imagedataField;
}
set {
this.imagedataField = value;
}
}
[XmlElement("wrap", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Wrap> wrap {
get {
return this.wrapField;
}
set {
this.wrapField = value;
}
}
[XmlElement("anchorlock", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_AnchorLock> anchorlock {
get {
return this.anchorlockField;
}
set {
this.anchorlockField = value;
}
}
[XmlElement("bordertop", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> bordertop {
get {
return this.bordertopField;
}
set {
this.bordertopField = value;
}
}
[XmlElement("borderbottom", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderbottom {
get {
return this.borderbottomField;
}
set {
this.borderbottomField = value;
}
}
[XmlElement("borderleft", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderleft {
get {
return this.borderleftField;
}
set {
this.borderleftField = value;
}
}
[XmlElement("borderright", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderright {
get {
return this.borderrightField;
}
set {
this.borderrightField = value;
}
}
[XmlElement("ClientData", Namespace="urn:schemas-microsoft-com:office:excel")]
public List<CT_ClientData> ClientData {
get {
return this.clientDataField;
}
set {
this.clientDataField = value;
}
}
[XmlElement("textdata", Namespace="urn:schemas-microsoft-com:office:powerpoint")]
public List<CT_Rel> textdata {
get {
return this.textdataField;
}
set {
this.textdataField = value;
}
}
[XmlAttribute]
public string from {
get {
return this.fromField;
}
set {
this.fromField = value;
}
}
[XmlAttribute]
public string control1 {
get {
return this.control1Field;
}
set {
this.control1Field = value;
}
}
[XmlAttribute]
public string control2 {
get {
return this.control2Field;
}
set {
this.control2Field = value;
}
}
[XmlAttribute]
public string to {
get {
return this.toField;
}
set {
this.toField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Image {
private List<CT_Path> pathField;
private List<CT_Formulas> formulasField;
private List<CT_Handles> handlesField;
private List<CT_Fill> fillField;
private List<CT_Stroke> strokeField;
private List<CT_Shadow> shadowField;
private List<CT_Textbox> textboxField;
private List<CT_TextPath> textpathField;
private List<CT_ImageData> imagedataField;
private List<CT_Wrap> wrapField;
private List<CT_AnchorLock> anchorlockField;
private List<CT_Border> bordertopField;
private List<CT_Border> borderbottomField;
private List<CT_Border> borderleftField;
private List<CT_Border> borderrightField;
private List<CT_ClientData> clientDataField;
private List<CT_Rel> textdataField;
private string srcField;
private string cropleftField;
private string croptopField;
private string croprightField;
private string cropbottomField;
private string gainField;
private string blacklevelField;
private string gammaField;
private ST_TrueFalse grayscaleField;
private bool grayscaleFieldSpecified;
private ST_TrueFalse bilevelField;
private bool bilevelFieldSpecified;
[XmlElement("path")]
public List<CT_Path> path {
get {
return this.pathField;
}
set {
this.pathField = value;
}
}
[XmlElement("formulas")]
public List<CT_Formulas> formulas {
get {
return this.formulasField;
}
set {
this.formulasField = value;
}
}
[XmlElement("handles")]
public List<CT_Handles> handles {
get {
return this.handlesField;
}
set {
this.handlesField = value;
}
}
[XmlElement("fill")]
public List<CT_Fill> fill {
get {
return this.fillField;
}
set {
this.fillField = value;
}
}
[XmlElement("stroke")]
public List<CT_Stroke> stroke {
get {
return this.strokeField;
}
set {
this.strokeField = value;
}
}
[XmlElement("shadow")]
public List<CT_Shadow> shadow {
get {
return this.shadowField;
}
set {
this.shadowField = value;
}
}
[XmlElement("textbox")]
public List<CT_Textbox> textbox {
get {
return this.textboxField;
}
set {
this.textboxField = value;
}
}
[XmlElement("textpath")]
public List<CT_TextPath> textpath {
get {
return this.textpathField;
}
set {
this.textpathField = value;
}
}
[XmlElement("imagedata")]
public List<CT_ImageData> imagedata {
get {
return this.imagedataField;
}
set {
this.imagedataField = value;
}
}
[XmlElement("wrap", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Wrap> wrap {
get {
return this.wrapField;
}
set {
this.wrapField = value;
}
}
[XmlElement("anchorlock", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_AnchorLock> anchorlock {
get {
return this.anchorlockField;
}
set {
this.anchorlockField = value;
}
}
[XmlElement("bordertop", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> bordertop {
get {
return this.bordertopField;
}
set {
this.bordertopField = value;
}
}
[XmlElement("borderbottom", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderbottom {
get {
return this.borderbottomField;
}
set {
this.borderbottomField = value;
}
}
[XmlElement("borderleft", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderleft {
get {
return this.borderleftField;
}
set {
this.borderleftField = value;
}
}
[XmlElement("borderright", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderright {
get {
return this.borderrightField;
}
set {
this.borderrightField = value;
}
}
[XmlElement("ClientData", Namespace="urn:schemas-microsoft-com:office:excel")]
public List<CT_ClientData> ClientData {
get {
return this.clientDataField;
}
set {
this.clientDataField = value;
}
}
[XmlElement("textdata", Namespace="urn:schemas-microsoft-com:office:powerpoint")]
public List<CT_Rel> textdata {
get {
return this.textdataField;
}
set {
this.textdataField = value;
}
}
[XmlAttribute]
public string src {
get {
return this.srcField;
}
set {
this.srcField = value;
}
}
[XmlAttribute]
public string cropleft {
get {
return this.cropleftField;
}
set {
this.cropleftField = value;
}
}
[XmlAttribute]
public string croptop {
get {
return this.croptopField;
}
set {
this.croptopField = value;
}
}
[XmlAttribute]
public string cropright {
get {
return this.croprightField;
}
set {
this.croprightField = value;
}
}
[XmlAttribute]
public string cropbottom {
get {
return this.cropbottomField;
}
set {
this.cropbottomField = value;
}
}
[XmlAttribute]
public string gain {
get {
return this.gainField;
}
set {
this.gainField = value;
}
}
[XmlAttribute]
public string blacklevel {
get {
return this.blacklevelField;
}
set {
this.blacklevelField = value;
}
}
[XmlAttribute]
public string gamma {
get {
return this.gammaField;
}
set {
this.gammaField = value;
}
}
[XmlAttribute]
public ST_TrueFalse grayscale {
get {
return this.grayscaleField;
}
set {
this.grayscaleField = value;
}
}
[XmlIgnore]
public bool grayscaleSpecified {
get {
return this.grayscaleFieldSpecified;
}
set {
this.grayscaleFieldSpecified = value;
}
}
[XmlAttribute]
public ST_TrueFalse bilevel {
get {
return this.bilevelField;
}
set {
this.bilevelField = value;
}
}
[XmlIgnore]
public bool bilevelSpecified {
get {
return this.bilevelFieldSpecified;
}
set {
this.bilevelFieldSpecified = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Line {
private List<CT_Path> pathField;
private List<CT_Formulas> formulasField;
private List<CT_Handles> handlesField;
private List<CT_Fill> fillField;
private List<CT_Stroke> strokeField;
private List<CT_Shadow> shadowField;
private List<CT_Textbox> textboxField;
private List<CT_TextPath> textpathField;
private List<CT_ImageData> imagedataField;
private List<CT_Wrap> wrapField;
private List<CT_AnchorLock> anchorlockField;
private List<CT_Border> bordertopField;
private List<CT_Border> borderbottomField;
private List<CT_Border> borderleftField;
private List<CT_Border> borderrightField;
private List<CT_ClientData> clientDataField;
private List<CT_Rel> textdataField;
private string fromField;
private string toField;
[XmlElement("path")]
public List<CT_Path> path {
get {
return this.pathField;
}
set {
this.pathField = value;
}
}
[XmlElement("formulas")]
public List<CT_Formulas> formulas {
get {
return this.formulasField;
}
set {
this.formulasField = value;
}
}
[XmlElement("handles")]
public List<CT_Handles> handles {
get {
return this.handlesField;
}
set {
this.handlesField = value;
}
}
[XmlElement("fill")]
public List<CT_Fill> fill {
get {
return this.fillField;
}
set {
this.fillField = value;
}
}
[XmlElement("stroke")]
public List<CT_Stroke> stroke {
get {
return this.strokeField;
}
set {
this.strokeField = value;
}
}
[XmlElement("shadow")]
public List<CT_Shadow> shadow {
get {
return this.shadowField;
}
set {
this.shadowField = value;
}
}
[XmlElement("textbox")]
public List<CT_Textbox> textbox {
get {
return this.textboxField;
}
set {
this.textboxField = value;
}
}
[XmlElement("textpath")]
public List<CT_TextPath> textpath {
get {
return this.textpathField;
}
set {
this.textpathField = value;
}
}
[XmlElement("imagedata")]
public List<CT_ImageData> imagedata {
get {
return this.imagedataField;
}
set {
this.imagedataField = value;
}
}
[XmlElement("wrap", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Wrap> wrap {
get {
return this.wrapField;
}
set {
this.wrapField = value;
}
}
[XmlElement("anchorlock", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_AnchorLock> anchorlock {
get {
return this.anchorlockField;
}
set {
this.anchorlockField = value;
}
}
[XmlElement("bordertop", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> bordertop {
get {
return this.bordertopField;
}
set {
this.bordertopField = value;
}
}
[XmlElement("borderbottom", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderbottom {
get {
return this.borderbottomField;
}
set {
this.borderbottomField = value;
}
}
[XmlElement("borderleft", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderleft {
get {
return this.borderleftField;
}
set {
this.borderleftField = value;
}
}
[XmlElement("borderright", Namespace="urn:schemas-microsoft-com:office:word")]
public List<CT_Border> borderright {
get {
return this.borderrightField;
}
set {
this.borderrightField = value;
}
}
[XmlElement("ClientData", Namespace="urn:schemas-microsoft-com:office:excel")]
public List<CT_ClientData> ClientData {
get {
return this.clientDataField;
}
set {
this.clientDataField = value;
}
}
[XmlElement("textdata", Namespace="urn:schemas-microsoft-com:office:powerpoint")]
public List<CT_Rel> textdata {
get {
return this.textdataField;
}
set {
this.textdataField = value;
}
}
[XmlAttribute]
public string from {
get {
return this.fromField;
}
set {
this.fromField = value;
}
}
[XmlAttribute]
public string to {
get {
return this.toField;
}
set {
this.toField = value;
}
}
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Oval {
private List<object> itemsField = new List<object>();
private List<ItemsChoiceType2> itemsElementNameField = new List<ItemsChoiceType2>();
[XmlElement("ClientData", typeof(CT_ClientData), Namespace = "urn:schemas-microsoft-com:office:excel")]
[XmlElement("textdata", typeof(CT_Rel), Namespace = "urn:schemas-microsoft-com:office:powerpoint")]
[XmlElement("anchorlock", typeof(CT_AnchorLock), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("borderbottom", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("borderleft", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("borderright", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("bordertop", typeof(CT_Border), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("wrap", typeof(CT_Wrap), Namespace = "urn:schemas-microsoft-com:office:word")]
[XmlElement("fill", typeof(CT_Fill))]
[XmlElement("formulas", typeof(CT_Formulas))]
[XmlElement("handles", typeof(CT_Handles))]
[XmlElement("imagedata", typeof(CT_ImageData))]
[XmlElement("path", typeof(CT_Path))]
[XmlElement("shadow", typeof(CT_Shadow))]
[XmlElement("stroke", typeof(CT_Stroke))]
[XmlElement("textbox", typeof(CT_Textbox))]
[XmlElement("textpath", typeof(CT_TextPath))]
[XmlChoiceIdentifier("ItemsElementName")]
public object[] Items
{
get
{
return this.itemsField.ToArray();
}
set
{
if (value == null)
this.itemsField = new List<object>();
else
this.itemsField = new List<object>(value);
}
}
[XmlElement("ItemsElementName")]
[XmlIgnore]
public ItemsChoiceType2[] ItemsElementName {
get {
return this.itemsElementNameField.ToArray();
}
set {
if (value == null)
this.itemsElementNameField = new List<ItemsChoiceType2>();
else
this.itemsElementNameField = new List<ItemsChoiceType2>(value);
}
}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml", IncludeInSchema=false)]
public enum ItemsChoiceType2 {
[XmlEnum("urn:schemas-microsoft-com:office:excel:ClientData")]
ClientData,
[XmlEnum("urn:schemas-microsoft-com:office:powerpoint:textdata")]
textdata,
[XmlEnum("urn:schemas-microsoft-com:office:word:anchorlock")]
anchorlock,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderbottom")]
borderbottom,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderleft")]
borderleft,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderright")]
borderright,
[XmlEnum("urn:schemas-microsoft-com:office:word:bordertop")]
bordertop,
[XmlEnum("urn:schemas-microsoft-com:office:word:wrap")]
wrap,
fill,
formulas,
handles,
imagedata,
path,
shadow,
stroke,
textbox,
textpath,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_PolyLine {
private List<object> itemsField = new List<object>();
private List<ItemsChoiceType3> itemsElementNameField = new List<ItemsChoiceType3>();
private string pointsField;
[XmlElement("ClientData", typeof(CT_ClientData), Namespace="urn:schemas-microsoft-com:office:excel")]
[XmlElement("textdata", typeof(CT_Rel), Namespace="urn:schemas-microsoft-com:office:powerpoint")]
[XmlElement("anchorlock", typeof(CT_AnchorLock), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("borderbottom", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("borderleft", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("borderright", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("bordertop", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("wrap", typeof(CT_Wrap), Namespace="urn:schemas-microsoft-com:office:word")]
[XmlElement("fill", typeof(CT_Fill))]
[XmlElement("formulas", typeof(CT_Formulas))]
[XmlElement("handles", typeof(CT_Handles))]
[XmlElement("imagedata", typeof(CT_ImageData))]
[XmlElement("path", typeof(CT_Path))]
[XmlElement("shadow", typeof(CT_Shadow))]
[XmlElement("stroke", typeof(CT_Stroke))]
[XmlElement("textbox", typeof(CT_Textbox))]
[XmlElement("textpath", typeof(CT_TextPath))]
[XmlChoiceIdentifier("ItemsElementName")]
public object[] Items {
get {
return this.itemsField.ToArray();
}
set {
if (value == null)
this.itemsField = new List<object>();
else
this.itemsField = new List<object>(value);
}
}
[XmlElement("ItemsElementName")]
[XmlIgnore]
public ItemsChoiceType3[] ItemsElementName {
get {
return this.itemsElementNameField.ToArray();
}
set {
if (value == null)
this.itemsElementNameField = new List<ItemsChoiceType3>();
else
this.itemsElementNameField = new List<ItemsChoiceType3>(value);
}
}
[XmlAttribute]
public string points {
get {
return this.pointsField;
}
set {
this.pointsField = value;
}
}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml", IncludeInSchema=false)]
public enum ItemsChoiceType3 {
[XmlEnum("urn:schemas-microsoft-com:office:excel:ClientData")]
ClientData,
[XmlEnum("urn:schemas-microsoft-com:office:powerpoint:textdata")]
textdata,
[XmlEnum("urn:schemas-microsoft-com:office:word:anchorlock")]
anchorlock,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderbottom")]
borderbottom,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderleft")]
borderleft,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderright")]
borderright,
[XmlEnum("urn:schemas-microsoft-com:office:word:bordertop")]
bordertop,
[XmlEnum("urn:schemas-microsoft-com:office:word:wrap")]
wrap,
fill,
formulas,
handles,
imagedata,
path,
shadow,
stroke,
textbox,
textpath,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Rect {
private List<object> itemsField;
private ItemsChoiceType4[] itemsElementNameField;
//[XmlElement("ClientData", typeof(CT_ClientData), Namespace="urn:schemas-microsoft-com:office:excel")]
//[XmlElement("textdata", typeof(CT_Rel), Namespace="urn:schemas-microsoft-com:office:powerpoint")]
//[XmlElement("anchorlock", typeof(CT_AnchorLock), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("borderbottom", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("borderleft", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("borderright", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("bordertop", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("wrap", typeof(CT_Wrap), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("fill", typeof(CT_Fill))]
//[XmlElement("formulas", typeof(CT_Formulas))]
//[XmlElement("handles", typeof(CT_Handles))]
//[XmlElement("imagedata", typeof(CT_ImageData))]
//[XmlElement("path", typeof(CT_Path))]
//[XmlElement("shadow", typeof(CT_Shadow))]
//[XmlElement("stroke", typeof(CT_Stroke))]
//[XmlElement("textbox", typeof(CT_Textbox))]
//[XmlElement("textpath", typeof(CT_TextPath))]
//[XmlChoiceIdentifier("ItemsElementName")]
//public List<object> Items {
// get {
// return this.itemsField;
// }
// set {
// this.itemsField = value;
// }
//}
//[XmlElement("ItemsElementName")]
//[XmlIgnore]
//public ItemsChoiceType4[] ItemsElementName {
// get {
// return this.itemsElementNameField;
// }
// set {
// this.itemsElementNameField = value;
// }
//}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml", IncludeInSchema=false)]
public enum ItemsChoiceType4 {
[XmlEnum("urn:schemas-microsoft-com:office:excel:ClientData")]
ClientData,
[XmlEnum("urn:schemas-microsoft-com:office:powerpoint:textdata")]
textdata,
[XmlEnum("urn:schemas-microsoft-com:office:word:anchorlock")]
anchorlock,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderbottom")]
borderbottom,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderleft")]
borderleft,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderright")]
borderright,
[XmlEnum("urn:schemas-microsoft-com:office:word:bordertop")]
bordertop,
[XmlEnum("urn:schemas-microsoft-com:office:word:wrap")]
wrap,
fill,
formulas,
handles,
imagedata,
path,
shadow,
stroke,
textbox,
textpath,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_RoundRect {
private List<object> itemsField;
private ItemsChoiceType5[] itemsElementNameField;
private string arcsizeField;
//[XmlElement("ClientData", typeof(CT_ClientData), Namespace="urn:schemas-microsoft-com:office:excel")]
//[XmlElement("textdata", typeof(CT_Rel), Namespace="urn:schemas-microsoft-com:office:powerpoint")]
//[XmlElement("anchorlock", typeof(CT_AnchorLock), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("borderbottom", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("borderleft", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("borderright", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("bordertop", typeof(CT_Border), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("wrap", typeof(CT_Wrap), Namespace="urn:schemas-microsoft-com:office:word")]
//[XmlElement("fill", typeof(CT_Fill))]
//[XmlElement("formulas", typeof(CT_Formulas))]
//[XmlElement("handles", typeof(CT_Handles))]
//[XmlElement("imagedata", typeof(CT_ImageData))]
//[XmlElement("path", typeof(CT_Path))]
//[XmlElement("shadow", typeof(CT_Shadow))]
//[XmlElement("stroke", typeof(CT_Stroke))]
//[XmlElement("textbox", typeof(CT_Textbox))]
//[XmlElement("textpath", typeof(CT_TextPath))]
//[XmlChoiceIdentifier("ItemsElementName")]
//public List<object> Items {
// get {
// return this.itemsField;
// }
// set {
// this.itemsField = value;
// }
//}
//[XmlElement("ItemsElementName")]
//[XmlIgnore]
//public ItemsChoiceType5[] ItemsElementName {
// get {
// return this.itemsElementNameField;
// }
// set {
// this.itemsElementNameField = value;
// }
//}
[XmlAttribute]
public string arcsize {
get {
return this.arcsizeField;
}
set {
this.arcsizeField = value;
}
}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml", IncludeInSchema=false)]
public enum ItemsChoiceType5 {
[XmlEnum("urn:schemas-microsoft-com:office:excel:ClientData")]
ClientData,
[XmlEnum("urn:schemas-microsoft-com:office:powerpoint:textdata")]
textdata,
[XmlEnum("urn:schemas-microsoft-com:office:word:anchorlock")]
anchorlock,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderbottom")]
borderbottom,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderleft")]
borderleft,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderright")]
borderright,
[XmlEnum("urn:schemas-microsoft-com:office:word:bordertop")]
bordertop,
[XmlEnum("urn:schemas-microsoft-com:office:word:wrap")]
wrap,
fill,
formulas,
handles,
imagedata,
path,
shadow,
stroke,
textbox,
textpath,
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml", IncludeInSchema=false)]
public enum ItemsChoiceType6 {
[XmlEnum("urn:schemas-microsoft-com:office:excel:ClientData")]
ClientData,
[XmlEnum("urn:schemas-microsoft-com:office:powerpoint:textdata")]
textdata,
[XmlEnum("urn:schemas-microsoft-com:office:word:anchorlock")]
anchorlock,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderbottom")]
borderbottom,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderleft")]
borderleft,
[XmlEnum("urn:schemas-microsoft-com:office:word:borderright")]
borderright,
[XmlEnum("urn:schemas-microsoft-com:office:word:bordertop")]
bordertop,
[XmlEnum("urn:schemas-microsoft-com:office:word:wrap")]
wrap,
arc,
curve,
fill,
formulas,
group,
handles,
image,
imagedata,
line,
oval,
path,
polyline,
rect,
roundrect,
shadow,
shape,
shapetype,
stroke,
textbox,
textpath,
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_EditAs {
canvas,
orgchart,
radial,
cycle,
stacked,
venn,
bullseye,
}
[Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=true)]
public partial class CT_Background {
private CT_Fill fillField;
private string idField;
private ST_TrueFalse filledField;
private bool filledFieldSpecified;
private string fillcolorField;
public CT_Fill fill {
get {
return this.fillField;
}
set {
this.fillField = value;
}
}
[XmlAttribute]
public string id
{
get {
return this.idField;
}
set {
this.idField = value;
}
}
[XmlAttribute]
public ST_TrueFalse filled {
get {
return this.filledField;
}
set {
this.filledField = value;
}
}
[XmlIgnore]
public bool filledSpecified {
get {
return this.filledFieldSpecified;
}
set {
this.filledFieldSpecified = value;
}
}
[XmlAttribute]
public string fillcolor {
get {
return this.fillcolorField;
}
set {
this.fillcolorField = value;
}
}
}
[Serializable]
[XmlType(Namespace="urn:schemas-microsoft-com:vml")]
[XmlRoot(Namespace="urn:schemas-microsoft-com:vml", IsNullable=false)]
public enum ST_Ext
{
NONE,
view,
edit,
backwardCompatible,
}
}
| 25.493557 | 154 | 0.467033 | [
"Apache-2.0"
] | HermanChou/npoi | ooxml/OpenXmlFormats/Vml/Main.cs | 124,638 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("WallpaperTool")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WallpaperTool")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| 42.392857 | 98 | 0.709773 | [
"MIT"
] | cuilishen/WallpaperTool | WallpaperTool/WallpaperTool/Properties/AssemblyInfo.cs | 2,377 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Net;
using Amazon.ElasticBeanstalk.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for UpdateEnvironment operation
/// </summary>
internal class UpdateEnvironmentResponseUnmarshaller : XmlResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
UpdateEnvironmentResponse response = new UpdateEnvironmentResponse();
while (context.Read())
{
if (context.IsStartElement)
{
if(context.TestExpression("UpdateEnvironmentResult", 2))
{
response.UpdateEnvironmentResult = UpdateEnvironmentResultUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
}
}
}
return response;
}
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
return new AmazonElasticBeanstalkException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static UpdateEnvironmentResponseUnmarshaller instance;
public static UpdateEnvironmentResponseUnmarshaller GetInstance()
{
if (instance == null)
{
instance = new UpdateEnvironmentResponseUnmarshaller();
}
return instance;
}
}
}
| 36.376623 | 171 | 0.632631 | [
"Apache-2.0"
] | mahanthbeeraka/dataservices-sdk-dotnet | AWSSDK/Amazon.ElasticBeanstalk/Model/Internal/MarshallTransformations/UpdateEnvironmentResponseUnmarshaller.cs | 2,801 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.AspNet.SignalR.SqlServer
{
internal class DbOperation
{
private List<IDataParameter> _parameters = new List<IDataParameter>();
private readonly IDbProviderFactory _dbProviderFactory;
public DbOperation(string connectionString, string commandText, TraceSource traceSource)
: this(connectionString, commandText, traceSource, SqlClientFactory.Instance.AsIDbProviderFactory())
{
}
public DbOperation(string connectionString, string commandText, TraceSource traceSource, IDbProviderFactory dbProviderFactory)
{
ConnectionString = connectionString;
CommandText = commandText;
Trace = traceSource;
_dbProviderFactory = dbProviderFactory;
}
public DbOperation(string connectionString, string commandText, TraceSource traceSource, params IDataParameter[] parameters)
: this(connectionString, commandText, traceSource)
{
if (parameters != null)
{
_parameters.AddRange(parameters);
}
}
public string TracePrefix { get; set; }
public IList<IDataParameter> Parameters
{
get { return _parameters; }
}
protected TraceSource Trace { get; private set; }
protected string ConnectionString { get; private set; }
protected string CommandText { get; private set; }
public virtual object ExecuteScalar()
{
return Execute(cmd => cmd.ExecuteScalar());
}
public virtual int ExecuteNonQuery()
{
return Execute(cmd => cmd.ExecuteNonQuery());
}
public virtual Task<int> ExecuteNonQueryAsync()
{
var tcs = new TaskCompletionSource<int>();
Execute(cmd => cmd.ExecuteNonQueryAsync(), tcs);
return tcs.Task;
}
public virtual int ExecuteReader(Action<IDataRecord, DbOperation> processRecord)
{
return ExecuteReader(processRecord, null);
}
protected virtual int ExecuteReader(Action<IDataRecord, DbOperation> processRecord, Action<IDbCommand> commandAction)
{
return Execute(cmd =>
{
if (commandAction != null)
{
commandAction(cmd);
}
var reader = cmd.ExecuteReader();
var count = 0;
while (reader.Read())
{
count++;
processRecord(reader, this);
}
return count;
});
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It's the caller's responsibility to dispose as the command is returned"),
SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "General purpose SQL utility command")]
protected virtual IDbCommand CreateCommand(IDbConnection connection)
{
var command = connection.CreateCommand();
command.CommandText = CommandText;
if (Parameters != null && Parameters.Count > 0)
{
for (var i = 0; i < Parameters.Count; i++)
{
command.Parameters.Add(Parameters[i].Clone(_dbProviderFactory));
}
}
return command;
}
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "False positive?")]
private T Execute<T>(Func<IDbCommand, T> commandFunc)
{
T result = default(T);
IDbConnection connection = null;
try
{
connection = _dbProviderFactory.CreateConnection();
connection.ConnectionString = ConnectionString;
var command = CreateCommand(connection);
connection.Open();
TraceCommand(command);
result = commandFunc(command);
}
finally
{
if (connection != null)
{
connection.Dispose();
}
}
return result;
}
private void TraceCommand(IDbCommand command)
{
if (Trace.Switch.ShouldTrace(TraceEventType.Verbose))
{
Trace.TraceVerbose("Created DbCommand: CommandType={0}, CommandText={1}, Parameters={2}", command.CommandType, command.CommandText,
command.Parameters.Cast<IDataParameter>()
.Aggregate(string.Empty, (msg, p) => string.Format(CultureInfo.InvariantCulture, "{0} [Name={1}, Value={2}]", msg, p.ParameterName, p.Value))
);
}
}
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Disposed in async Finally block"),
SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed in async Finally block")]
private void Execute<T>(Func<IDbCommand, Task<T>> commandFunc, TaskCompletionSource<T> tcs)
{
IDbConnection connection = null;
try
{
connection = _dbProviderFactory.CreateConnection();
connection.ConnectionString = ConnectionString;
var command = CreateCommand(connection);
connection.Open();
commandFunc(command)
.Then(result => tcs.SetResult(result))
.Catch(ex => tcs.SetUnwrappedException(ex), Trace)
.Finally(state =>
{
var conn = (DbConnection)state;
if (conn != null)
{
conn.Dispose();
}
}, connection);
}
catch (Exception)
{
if (connection != null)
{
connection.Dispose();
}
throw;
}
}
}
}
| 35.062176 | 186 | 0.558298 | [
"Apache-2.0"
] | AndreasBieber/SignalR | src/Microsoft.AspNet.SignalR.SqlServer/DbOperation.cs | 6,769 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using MongoDB.Bson.Serialization.Attributes;
using Xunit;
namespace Squidex.Infrastructure.MongoDb
{
public class MongoFieldTests
{
public sealed class Entity
{
public string Id { get; set; }
public string Default { get; set; }
[BsonElement("_c")]
public string Custom { get; set; }
}
[Fact]
public void Should_resolve_id_field()
{
var name = Field.Of<Entity>(x => nameof(x.Id));
Assert.Equal("_id", name);
}
[Fact]
public void Should_resolve_default_field()
{
var name = Field.Of<Entity>(x => nameof(x.Default));
Assert.Equal("Default", name);
}
[Fact]
public void Should_resolve_custom_field()
{
var name = Field.Of<Entity>(x => nameof(x.Custom));
Assert.Equal("_c", name);
}
}
}
| 26.24 | 78 | 0.45122 | [
"MIT"
] | Appleseed/squidex | backend/tests/Squidex.Infrastructure.Tests/MongoDb/MongoFieldTests.cs | 1,314 | C# |
using System;
namespace Umbraco.Core.Models.PublishedContent
{
public class PublishedContentWithKeyExtended : PublishedContentExtended, IPublishedContentWithKey
{
// protected for models, internal for PublishedContentExtended static Extend method
protected internal PublishedContentWithKeyExtended(IPublishedContentWithKey content)
: base(content)
{ }
public Guid Key { get { return ((IPublishedContentWithKey) Content).Key; } }
}
}
| 32.8 | 101 | 0.731707 | [
"MIT"
] | Abhith/Umbraco-CMS | src/Umbraco.Core/Models/PublishedContent/PublishedContentWithKeyExtended.cs | 494 | C# |
using Cofoundry.Core.Validation;
using Cofoundry.Domain.CQS;
using System.ComponentModel.DataAnnotations;
namespace Cofoundry.Domain
{
/// <summary>
/// Updates the main properties of an existing page directory. To
/// update properties that affect the route, use <see cref="UpdatePageDirectoryUrlCommand"/>.
/// </summary>
public class UpdatePageDirectoryCommand : IPatchableByIdCommand, ILoggableCommand
{
/// <summary>
/// Database id of the page directory to update.
/// </summary>
[Required]
[PositiveInteger]
public int PageDirectoryId { get; set; }
/// <summary>
/// User friendly display name of the directory.
/// </summary>
[StringLength(200)]
[Display(Name = "Name", Description = "E.g. 'About the team' or 'Our products'")]
public string Name { get; set; }
}
}
| 32.142857 | 97 | 0.634444 | [
"MIT"
] | BearerPipelineTest/cofoundry | src/Cofoundry.Domain/Domain/PageDirectories/Commands/UpdatePageDirectoryCommand.cs | 902 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ILG.Codex.CodexR4.GMLiceseManger
{
public sealed class DSLicenseManager
{
private static volatile DSLicenseManager instance;
private static object syncRoot = new Object();
private DSLicenseManager() { }
public static DSLicenseManager Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new DSLicenseManager();
}
}
return instance;
}
}
#region CryptoGraphy
public static string getHashSha256(string text)
{
byte[] bytes = Encoding.Unicode.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString.ToUpper();
}
public static string getHashSha1(string text)
{
byte[] bytes = Encoding.Unicode.GetBytes(text);
SHA1Managed hashstring = new SHA1Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString.ToUpper();
}
public static string getHashSha384(string text)
{
byte[] bytes = Encoding.Unicode.GetBytes(text);
SHA384Managed hashstring = new SHA384Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString.ToUpper();
}
public static string getHashSha512(string text)
{
byte[] bytes = Encoding.Unicode.GetBytes(text);
SHA512Managed hashstring = new SHA512Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString.ToUpper();
}
#endregion CryptoGraphy
private DSLicenseJsonFile _codexdsLicenseConfiguration;
private string _stringTrialStatus;
private ExpirationDate _expirationDate;
private string _stringOrganization;
private string _stringDepartment;
public string TrialStatus
{
get
{
return _stringTrialStatus;
}
set
{
_stringTrialStatus = value;
}
}
public DateTime Expiration
{
get
{
return new DateTime(_expirationDate.Year, _expirationDate.Month, _expirationDate.Day);
}
}
public string Organizaiton
{
get
{
return _stringOrganization;
}
set { _stringOrganization = value; }
}
public string Department
{
get
{
return _stringDepartment;
}
set { _stringDepartment = value; }
}
public void Initialize(bool readInfo = false)
{
_codexdsLicenseConfiguration = new DSLicenseJsonFile();
if (readInfo == true)
{
CreateIfNotExists();
Read();
}
}
public void Initialize(string Filename, bool readInfo = false)
{
_codexdsLicenseConfiguration = new DSLicenseJsonFile(Filename);
if (readInfo == true)
{
CreateIfNotExists();
Read();
}
}
public void Read()
{
_codexdsLicenseConfiguration.ReadInfo();
_stringOrganization = _codexdsLicenseConfiguration._codexlicensefile.Content.Organization;
_stringDepartment = _codexdsLicenseConfiguration._codexlicensefile.Content.Department;
_expirationDate = new ExpirationDate()
{
Year = _codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Year,
Month = _codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Month,
Day = _codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Day
};
_stringTrialStatus = _codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType;
}
public void Write()
{
CreateIfNotExists();
_codexdsLicenseConfiguration._codexlicensefile.Content.LicId = Guid.NewGuid().ToString();
_codexdsLicenseConfiguration._codexlicensefile.Content.Organization = _stringOrganization;
_codexdsLicenseConfiguration._codexlicensefile.Content.Department = _stringDepartment;
_codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType = _stringTrialStatus;
// _codexdsLicenseConfiguration._codexlicensefile.Content.ExpirationDate = _expirationDate;
_codexdsLicenseConfiguration.SaveInfo();
}
public bool CreateIfNotExists()
{
if (_codexdsLicenseConfiguration.CreateIfNotExists() == true)
{
TrialStatus = "None";
//ExpirationDate = new DateTime(2019, 2, 1);
Organizaiton = "";
Department = "";
Write();
return true;
}
else return false;
}
public void CreateTrialLicense(DateTime pExpirationDate)
{
_codexdsLicenseConfiguration._codexlicensefile.Content.LicId = Guid.NewGuid().ToString();
_codexdsLicenseConfiguration._codexlicensefile.Content.DefId = Guid.NewGuid().ToString();
_codexdsLicenseConfiguration._codexlicensefile.Content.Organization = "For trial, non commercial use";
_codexdsLicenseConfiguration._codexlicensefile.Content.Version = "1.1";
_codexdsLicenseConfiguration._codexlicensefile.Content.Department = "Trial";
_codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType = "TRIAL";
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration = new ExpirationDate()
{
Year = pExpirationDate.Year,
Month = pExpirationDate.Month,
Day = pExpirationDate.Day
};
DSLicneseInformaton sd = new DSLicneseInformaton();
String s = _codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType +
sd.Masters[14] +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Year.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Month.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Day.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Department +
_codexdsLicenseConfiguration._codexlicensefile.Content.LicId +
_codexdsLicenseConfiguration._codexlicensefile.Content.Organization +
_codexdsLicenseConfiguration._codexlicensefile.Content.Version +
sd.Masters[17] +
_codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Day.ToString() +
sd.Masters[3] +
sd.Masters[13];
String H1 = getHashSha512(getHashSha512(s));
String H2 = getHashSha512(s+ getHashSha256(H1))+ getHashSha384(s)+ getHashSha512(s); ;
String H3 = getHashSha512(getHashSha512(H2)+H1);
_codexdsLicenseConfiguration._codexlicensefile.Content.License = H3+H2;
String H4 = getHashSha512(H3 + getHashSha256(H2)) + getHashSha384(H1);
String H5 = getHashSha512(getHashSha256(_codexdsLicenseConfiguration._codexlicensefile.Content.DefId + H4));
_codexdsLicenseConfiguration._codexlicensefile.Content.DefCode = H5 + H1;
_codexdsLicenseConfiguration.SaveInfo();
}
public void CreateRetailLicense(string OrganizationName, string Department)
{
_codexdsLicenseConfiguration._codexlicensefile.Content.LicId = Guid.NewGuid().ToString();
_codexdsLicenseConfiguration._codexlicensefile.Content.DefId = Guid.NewGuid().ToString();
_codexdsLicenseConfiguration._codexlicensefile.Content.Organization = OrganizationName;
_codexdsLicenseConfiguration._codexlicensefile.Content.Version = "1.1";
_codexdsLicenseConfiguration._codexlicensefile.Content.Department = Department;
_codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType = "ENTERPRISE";
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration = new ExpirationDate()
{
Year = 0,
Month = 0,
Day = 0
};
DSLicneseInformaton sd = new DSLicneseInformaton();
String s = _codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType +
sd.Masters[14] +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Year.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Month.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Day.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Department +
_codexdsLicenseConfiguration._codexlicensefile.Content.LicId +
_codexdsLicenseConfiguration._codexlicensefile.Content.Organization +
_codexdsLicenseConfiguration._codexlicensefile.Content.Version +
sd.Masters[17] +
_codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Day.ToString() +
sd.Masters[3] +
sd.Masters[13];
String H1 = getHashSha512(getHashSha512(s));
String H2 = getHashSha512(s + getHashSha256(H1)) + getHashSha384(s) + getHashSha512(s); ;
String H3 = getHashSha512(getHashSha512(H2) + H1);
_codexdsLicenseConfiguration._codexlicensefile.Content.License = H3 + H2;
String H4 = getHashSha512(H3 + getHashSha256(H2)) + getHashSha384(H1);
String H5 = getHashSha512(getHashSha256(_codexdsLicenseConfiguration._codexlicensefile.Content.DefId + H4));
_codexdsLicenseConfiguration._codexlicensefile.Content.DefCode = H5 + H1;
_codexdsLicenseConfiguration.SaveInfo();
}
public bool VerifyLicense()
{
_codexdsLicenseConfiguration.ReadInfo();
DSLicneseInformaton sd = new DSLicneseInformaton();
String s = _codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType +
sd.Masters[14] +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Year.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Month.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Day.ToString() +
_codexdsLicenseConfiguration._codexlicensefile.Content.Department +
_codexdsLicenseConfiguration._codexlicensefile.Content.LicId +
_codexdsLicenseConfiguration._codexlicensefile.Content.Organization +
_codexdsLicenseConfiguration._codexlicensefile.Content.Version +
sd.Masters[17] +
_codexdsLicenseConfiguration._codexlicensefile.Content.LicenseType +
_codexdsLicenseConfiguration._codexlicensefile.Content.Expiration.Day.ToString() +
sd.Masters[3] +
sd.Masters[13];
String H1 = getHashSha512(getHashSha512(s));
String H2 = getHashSha512(s + getHashSha256(H1)) + getHashSha384(s) + getHashSha512(s); ;
String H3 = getHashSha512(getHashSha512(H2) + H1);
_codexdsLicenseConfiguration._codexlicensefile.Content.License = H3 + H2;
String H4 = getHashSha512(H3 + getHashSha256(H2)) + getHashSha384(H1);
String H5 = getHashSha512(getHashSha256(_codexdsLicenseConfiguration._codexlicensefile.Content.DefId + H4));
bool Condition1 = (_codexdsLicenseConfiguration._codexlicensefile.Content.License == (H3 + H2));
bool Condition2 = (_codexdsLicenseConfiguration._codexlicensefile.Content.DefCode == (H5 + H1));
return Condition1 && Condition2;
}
}
}
| 39.685714 | 120 | 0.601944 | [
"Unlicense"
] | IrakliLomidze/CodexDS16 | CodexDS16.U1.Prev1/TrialRetialUtility/DSLicenseGenerator/DSLicenseGenerator/DSLicenseManagerInformation.cs | 13,892 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Microsoft.Bot.Connector.Client.Models
{
public partial class Attachment : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(ContentType))
{
writer.WritePropertyName("contentType");
writer.WriteStringValue(ContentType);
}
if (Optional.IsDefined(ContentUrl))
{
writer.WritePropertyName("contentUrl");
writer.WriteStringValue(ContentUrl);
}
if (Optional.IsDefined(Content))
{
writer.WritePropertyName("content");
writer.WriteObjectValue(Content);
}
if (Optional.IsDefined(Name))
{
writer.WritePropertyName("name");
writer.WriteStringValue(Name);
}
if (Optional.IsDefined(ThumbnailUrl))
{
writer.WritePropertyName("thumbnailUrl");
writer.WriteStringValue(ThumbnailUrl);
}
writer.WriteEndObject();
}
}
}
| 29.191489 | 63 | 0.560496 | [
"MIT"
] | EricDahlvang/TempAutoRestV3Connector | src/Microsoft.Bot.Connector.Client/Generated/Models/Attachment.Serialization.cs | 1,372 | C# |
using Synology.FileStation.Common.Results;
namespace Synology.FileStation.List.Results
{
/// <summary>
/// File perm acl result.
/// </summary>
public interface IFilePermAclResult : ITaskFilePermAclResult
{
}
} | 21.454545 | 64 | 0.686441 | [
"Apache-2.0"
] | DotNetDevs/Synology | Synology/FileStation/List/Results/IFilePermAclResult.cs | 238 | C# |
namespace FKgrain {
partial class ComaprisonWindow {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.trackBar1 = new System.Windows.Forms.TrackBar();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.SuspendLayout();
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(1, 1);
this.trackBar1.Maximum = 255;
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(96, 45);
this.trackBar1.TabIndex = 6;
this.trackBar1.Value = 255;
this.trackBar1.Scroll += new System.EventHandler(this.TrackBar_Scroll);
//
// ComaprisonWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(445, 334);
this.Controls.Add(this.trackBar1);
this.Name = "ComaprisonWindow";
this.Text = "ComaprisonWindow";
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TrackBar trackBar1;
// private Emgu.CV.UI.PanAndZoomPictureBox PictureBox1;
}
} | 38.220339 | 107 | 0.580044 | [
"MIT"
] | ncku-arsem/FKgrain | FKgrain/UI/ComaprisonWindow.Designer.cs | 2,257 | C# |
using System;
using System.Runtime.InteropServices;
namespace youtube_center.Classes
{
public static class NativeMethods
{
private const int Restore = 9;
/// <summary>
/// Focus the opened downloader.
/// </summary>
public static void FocusOther()
{
var hwnd = FindWindow(null, "Youtube Center");
ShowWindow(hwnd, Restore);
SetForegroundWindow(hwnd);
}
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string sClassName, string sAppName);
}
}
| 27.6 | 84 | 0.621981 | [
"MIT"
] | dukemiller/youtube-center | youtube-center/Classes/NativeMethods.cs | 830 | 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("CodeCowboy.WebServiceTestHarness")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CodeCowboy.WebServiceTestHarness")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("e1dceee3-124f-4248-b9bf-d56db84c7ee4")]
// 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")]
| 38.837838 | 84 | 0.75087 | [
"MIT"
] | CodeCowboyOrg/WebServiceTestHarness | source/WebServiceTestHarness/CodeCowboy.WebServiceTestHarness/Properties/AssemblyInfo.cs | 1,440 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace realima.asterioidz
{
public class AsteroidBehaviour : MonoBehaviour, IDestroyable
{
[SerializeField] Asteroid _data;
public Asteroid Data => _data;
public AsteroidSpawner spawner { get; set; }
PoolManager _explosionPool;
private void Awake()
{
_explosionPool = PoolManager.Get("SmallExplosion");
}
public int DestroyInstance(IDestroyable destroyer)
{
//Bisect
AsteroidSpawner.Pool.Hide(gameObject);
_explosionPool.Show(offset: transform.position, autoDestroyTime:.5f);
SpawnAsteroidDebris();
return _data.DestructionScore;
}
private void SpawnAsteroidDebris()
{
if (_data.Level - 1 == 0) return;
for (int i = 0; i < _data.DebriCount; i++)
{
spawner.Spawn(_data.Level - 1, transform.position);
}
}
}
}
| 26.55 | 81 | 0.590395 | [
"CC0-1.0"
] | realimatech/AsteroidZ | Assets/_Game/Scripts/Mechanics/Asteroid/AsteroidBehaviour.cs | 1,064 | C# |
using System;
using System.Collections;
using UnityEngine;
public class GongZuoKuangCardLogic : CardLogic
{
public override void Init()
{
base.Init();
this.Color = CardLogicColor.red;
this.displayName = LocalizationMgr.Instance.GetLocalizationWord("CT_N_14");
this.Desc = string.Concat(new string[]
{
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1"),
Mathf.CeilToInt((float)this.CardData.MaxHP * 0.15f).ToString(),
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1"),
Mathf.CeilToInt((float)this.CardData.ATK * (0.75f + 0.25f * (float)base.Layers)).ToString(),
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1"),
(75 + 25 * base.Layers).ToString(),
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1")
});
}
public override void OnShowTips()
{
base.OnShowTips();
this.displayName = LocalizationMgr.Instance.GetLocalizationWord("CT_N_14");
this.Desc = string.Concat(new string[]
{
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1"),
Mathf.CeilToInt((float)this.CardData.MaxHP * 0.15f).ToString(),
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1"),
Mathf.CeilToInt((float)this.CardData.ATK * (0.75f + 0.25f * (float)base.Layers)).ToString(),
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1"),
(75 + 25 * base.Layers).ToString(),
LocalizationMgr.Instance.GetLocalizationWord("CT_D_14_1")
});
}
public override IEnumerator OnUseSkill()
{
base.OnUseSkill();
if (base.GetEnemiesBattleArea() == null)
{
yield break;
}
CardData t = base.GetDefaultTarget();
if (t == null)
{
yield break;
}
yield return DungeonOperationMgr.Instance.Hit(this.CardData, this.CardData, Mathf.CeilToInt((float)this.CardData.MaxHP * 0.15f), 0.2f, false, 0, null, null);
if (DungeonOperationMgr.Instance.CheckCardDead(this.CardData))
{
yield break;
}
yield return DungeonOperationMgr.Instance.Hit(this.CardData, t, Mathf.CeilToInt((float)this.CardData.ATK * (0.75f + 0.25f * (float)base.Layers)), 0.2f, false, 0, null, null);
yield break;
}
}
| 34.016393 | 176 | 0.728193 | [
"Apache-2.0"
] | Shadowrabbit/BigBiaDecompilation | Source/Assembly-CSharp/GongZuoKuangCardLogic.cs | 2,077 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CompanyRoster
{
public class Company_Roster
{
public static void Main()
{
var company = new List<Employee>();
var n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
var input = Console.ReadLine().Split();
var personName = input[0];
var personSalary = double.Parse(input[1]);
var personPosition = input[2];
var department = input[3];
var currentPerson = new Employee(personName, personSalary, personPosition, department);
if (input.Length > 4)
{
int age;
if (int.TryParse(input[4], out age))
{
currentPerson.Age = age;
}
else
{
currentPerson.Email = input[4];
}
}
if (input.Length > 5)
{
currentPerson.Age = int.Parse(input[5]);
}
company.Add(currentPerson);
}
var depart = company.GroupBy(dep => dep.Department)
.Select(gr => new
{
Name = gr.Key,
AverageSalary = gr.Average(x => x.Salary),
Employees = gr
})
.OrderByDescending(gr => gr.AverageSalary)
.FirstOrDefault();
Console.WriteLine($"Highest Average Salary: {depart.Name}");
foreach (var item in depart.Employees.OrderByDescending(x=>x.Salary))
{
Console.WriteLine(item.PrintEmployeeInfo());
}
}
}
}
| 29.6875 | 103 | 0.434211 | [
"MIT"
] | NadiaKaradjova/SoftUni | C# OOP Basics/Defining Classes Exercises/06 Company Roster/StartUp Company Roster .cs | 1,902 | C# |
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace SB_Post_Importer.App.Table
{
public class PostsTable
{
private readonly string tableName;
public PostsTable(string name)
{
tableName = name;
}
public string GetSqlCreateStatement()
{
return "CREATE TABLE " + tableName + @" (
[H] TEXT,
[0] TEXT,
[1] TEXT,
[2] TEXT,
[3] TEXT,
[4] TEXT,
[5] TEXT,
[6] TEXT,
[7] TEXT,
[8] TEXT,
[9] TEXT,
[OI_Hydro] TEXT,
[Hydro] TEXT);";
}
public List<string> GetSqlInsertStatements(DataTable dataTable)
{
var result = new List<string>();
foreach (DataRow row in dataTable.Rows)
{
var values = row.ItemArray
.Select(o => "\"" + o.ToString() + "\"");
var valuesStr = string.Join(", ", values.ToArray());
var sql = $"INSERT INTO {tableName} VALUES ({valuesStr});";
result.Add(sql);
}
return result;
}
}
} | 25.377358 | 75 | 0.418587 | [
"MIT"
] | vsh-odeku/southern-bug-app | SB_Post_Importer/App/Table/PostsTable.cs | 1,347 | C# |
using System;
namespace OkooneBlogger.Models
{
public class Identity
{
public int Id { get; set; }
public DateTime Date { get; set; } = DateTime.Now;
}
} | 18.3 | 58 | 0.601093 | [
"MIT"
] | SomboChea/OkooneBlogger | OkooneBlogger/Models/Identity.cs | 185 | C# |
using Laraue.EfCoreTriggers.Tests;
using Xunit;
namespace Laraue.EfCoreTriggers.SqlServerTests
{
[Collection("SqlServerNativeTests")]
public class SqlServerNativeTests : BaseNativeTests
{
public SqlServerNativeTests() : base(new ContextFactory().CreateDbContext())
{
}
}
} | 24.153846 | 84 | 0.703822 | [
"MIT"
] | Adam-Langley/Laraue.EfCoreTriggers | tests/Laraue.EfCoreTriggers.SqlServerTests/SqlServerNativeTests.cs | 316 | C# |
using System;
using System.Collections.Generic;
namespace WebApp.Models
{
public partial class Appraise
{
public int AppraiseId { get; set; }
public int UsersId { get; set; }
public int ProductId { get; set; }
public string Content { get; set; }
public int Grade { get; set; }
public DateTime RateTime { get; set; }
public virtual Product Product { get; set; }
public virtual Users Users { get; set; }
}
}
| 25.526316 | 52 | 0.604124 | [
"MIT"
] | xiaoqiang-y/change | WebApp/WebApp/Models/Appraise.cs | 487 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace OpenShift.DotNet.Service.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
/// <summary>
/// Represents downward API info for projecting into a projected volume.
/// Note that this is identical to a downwardAPI volume source without
/// the default mode.
/// </summary>
public partial class Iok8skubernetespkgapiv1DownwardAPIProjection
{
/// <summary>
/// Initializes a new instance of the
/// Iok8skubernetespkgapiv1DownwardAPIProjection class.
/// </summary>
public Iok8skubernetespkgapiv1DownwardAPIProjection() { }
/// <summary>
/// Initializes a new instance of the
/// Iok8skubernetespkgapiv1DownwardAPIProjection class.
/// </summary>
public Iok8skubernetespkgapiv1DownwardAPIProjection(IList<Iok8skubernetespkgapiv1DownwardAPIVolumeFile> items = default(IList<Iok8skubernetespkgapiv1DownwardAPIVolumeFile>))
{
Items = items;
}
/// <summary>
/// Items is a list of DownwardAPIVolume file
/// </summary>
[JsonProperty(PropertyName = "items")]
public IList<Iok8skubernetespkgapiv1DownwardAPIVolumeFile> Items { get; set; }
}
}
| 34.431818 | 181 | 0.678548 | [
"MIT"
] | gbraad/OpenShift.Vsix | OpenShift.DotNetStandard/OpenShift API (with Kubernetes)/Models/Iok8skubernetespkgapiv1DownwardAPIProjection.cs | 1,517 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using BuildXL.Utilities;
using BuildXL.Utilities.Qualifier;
using BuildXL.FrontEnd.Script;
using BuildXL.FrontEnd.Script.Values;
namespace BuildXL.FrontEnd.Script.RuntimeModel
{
/// <summary>
/// Result of parsing a package configuration file.
/// </summary>
public sealed class PackageConfigParseResult : SourceFileParseResult
{
internal PackageConfigParseResult(
SourceFile sourceFile,
FileModuleLiteral module,
QualifierSpaceId qualifierSpaceId,
SymbolAtom configurationKeyword)
: base(sourceFile, module, qualifierSpaceId)
{
ConfigurationKeyword = configurationKeyword;
}
internal PackageConfigParseResult(SourceFile sourceFile, FileModuleLiteral module, SymbolAtom configurationKeyword)
: this(sourceFile, module, QualifierSpaceId.Invalid, configurationKeyword)
{
}
internal PackageConfigParseResult(int errorCount)
: base(errorCount)
{ }
/// <summary>
/// The keyword used for configuring the package
/// </summary>
public SymbolAtom ConfigurationKeyword { get; }
}
}
| 33.804878 | 124 | 0.660173 | [
"MIT"
] | MatisseHack/BuildXL | Public/Src/FrontEnd/Script/RuntimeModel/ParseResults/PackageConfigParseResult.cs | 1,386 | C# |
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Windows;
using System.Collections.Generic;
using System.ComponentModel;
using ResourceTypes.Wwise;
namespace ResourceTypes.Wwise.Helpers
{
[TypeConverter(typeof(ExpandableObjectConverter))]
public class FxProp
{
public int ID { get; set; }
public int RTPCAccumulator { get; set; }
public float Value { get; set; }
public FxProp(int iID, int rtpcAccum, float fValue)
{
ID = iID;
RTPCAccumulator = rtpcAccum;
Value = fValue;
}
public FxProp()
{
ID = 0;
RTPCAccumulator = 0;
Value = 0;
}
public void WriteToFile(BinaryWriter bw)
{
bw.Write((byte)ID);
bw.Write((byte)RTPCAccumulator);
bw.Write(Value);
}
}
}
| 22.825 | 59 | 0.568456 | [
"MIT"
] | Greavesy1899/Mafia2Toolk | Mafia2Libs/ResourceTypes/FileTypes/Wwise/HIRC/Helpers/HIRC_FxProp.cs | 915 | C# |
using System;
using Robust.Client.Animations;
using Robust.Client.GameObjects;
using Robust.Shared.Animations;
using Robust.Shared.GameObjects;
using Robust.Shared.Maths;
namespace Content.Client.GameObjects.Components
{
[RegisterComponent]
public sealed class AnimationsTestComponent : Component
{
public override string Name => "AnimationsTest";
public override void Initialize()
{
base.Initialize();
var animations = Owner.GetComponent<AnimationPlayerComponent>();
animations.Play(new Animation
{
Length = TimeSpan.FromSeconds(20),
AnimationTracks =
{
new AnimationTrackComponentProperty
{
ComponentType = typeof(ITransformComponent),
Property = nameof(ITransformComponent.LocalRotation),
InterpolationMode = AnimationInterpolationMode.Linear,
KeyFrames =
{
new AnimationTrackProperty.KeyFrame(Angle.Zero, 0),
new AnimationTrackProperty.KeyFrame(Angle.FromDegrees(1440), 20)
}
},
new AnimationTrackComponentProperty
{
ComponentType = typeof(ISpriteComponent),
Property = "layer/0/texture",
KeyFrames =
{
new AnimationTrackProperty.KeyFrame("Objects/toolbox_r.png", 0),
new AnimationTrackProperty.KeyFrame("Objects/Toolbox_b.png", 5),
new AnimationTrackProperty.KeyFrame("Objects/Toolbox_y.png", 5),
new AnimationTrackProperty.KeyFrame("Objects/toolbox_r.png", 5),
}
}
}
}, "yes");
}
}
}
| 38.056604 | 92 | 0.516609 | [
"MIT"
] | BingoJohnson/space-station-14 | Content.Client/GameObjects/Components/AnimationsTestComponent.cs | 2,017 | C# |
/**
* Copyright 2015 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: jmis $
* Last modified: $LastChangedDate: 2015-09-15 11:07:32 -0400 (Tue, 15 Sep 2015) $
* Revision: $LastChangedRevision: 9795 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Interaction {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Model;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Mcci_mt002100ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Quqi_mt020002ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Lab.Polb_mt320000ca;
/**
* <summary>Business Name: POLB_IN354005CA: Request Query
* Results Provider or Location</summary>
*
* <p>This interaction is used to query lab results from a lab
* system, by location or provider.</p> Message:
* MCCI_MT002100CA.Message Control Act:
* QUQI_MT020002CA.ControlActEvent --> Payload:
* POLB_MT320000CA.ParameterList
*/
[Hl7PartTypeMappingAttribute(new string[] {"POLB_IN354005CA"})]
public class RequestQueryResultsProviderOrLocation : HL7Message<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Quqi_mt020002ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Lab.Polb_mt320000ca.ParameterList>>, IInteraction {
public RequestQueryResultsProviderOrLocation() {
}
}
} | 45.446809 | 262 | 0.729401 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-r02_04_02/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_04_02/Interaction/RequestQueryResultsProviderOrLocation.cs | 2,136 | 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 mediaconvert-2017-08-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MediaConvert.Model
{
/// <summary>
/// Provides messages from the service about jobs that you have already successfully submitted.
/// </summary>
public partial class JobMessages
{
private List<string> _info = new List<string>();
private List<string> _warning = new List<string>();
/// <summary>
/// Gets and sets the property Info. List of messages that are informational only and
/// don't indicate a problem with your job.
/// </summary>
public List<string> Info
{
get { return this._info; }
set { this._info = value; }
}
// Check to see if Info property is set
internal bool IsSetInfo()
{
return this._info != null && this._info.Count > 0;
}
/// <summary>
/// Gets and sets the property Warning. List of messages that warn about conditions that
/// might cause your job not to run or to fail.
/// </summary>
public List<string> Warning
{
get { return this._warning; }
set { this._warning = value; }
}
// Check to see if Warning property is set
internal bool IsSetWarning()
{
return this._warning != null && this._warning.Count > 0;
}
}
} | 31.236111 | 110 | 0.632726 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/MediaConvert/Generated/Model/JobMessages.cs | 2,249 | C# |
/*
* Adornments - Adornments are the basis for overlays and decorations -- things that can be rendered over the top of a ListView
*
* Author: Phillip Piper
* Date: 16/08/2009 1:02 AM
*
* Change log:
* v2.3
* 2009-09-22 JPP - Added Wrap property to TextAdornment, to allow text wrapping to be disabled
* - Added ShrinkToWidth property to ImageAdornment
* 2009-08-17 JPP - Initial version
*
* To do:
* - Use IPointLocator rather than Corners
* - Add RotationCenter property ratherr than always using middle center
*
* Copyright (C) 2009-2012 Phillip Piper
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace BrightIdeasSoftware
{
/// <summary>
/// An adorment is the common base for overlays and decorations.
/// </summary>
public class GraphicAdornment
{
#region Public properties
/// <summary>
/// Gets or sets the corner of the adornment that will be positioned at the reference corner
/// </summary>
[Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Drawing.ContentAlignment AdornmentCorner {
get { return this.adornmentCorner; }
set { this.adornmentCorner = value; }
}
private System.Drawing.ContentAlignment adornmentCorner = System.Drawing.ContentAlignment.MiddleCenter;
/// <summary>
/// Gets or sets location within the reference rectange where the adornment will be drawn
/// </summary>
/// <remarks>This is a simplied interface to ReferenceCorner and AdornmentCorner </remarks>
[Category("ObjectListView"),
Description("How will the adornment be aligned"),
DefaultValue(System.Drawing.ContentAlignment.BottomRight),
NotifyParentProperty(true)]
public System.Drawing.ContentAlignment Alignment {
get { return this.alignment; }
set {
this.alignment = value;
this.ReferenceCorner = value;
this.AdornmentCorner = value;
}
}
private System.Drawing.ContentAlignment alignment = System.Drawing.ContentAlignment.BottomRight;
/// <summary>
/// Gets or sets the offset by which the position of the adornment will be adjusted
/// </summary>
[Category("ObjectListView"),
Description("The offset by which the position of the adornment will be adjusted"),
DefaultValue(typeof(Size), "0,0")]
public Size Offset {
get { return this.offset; }
set { this.offset = value; }
}
private Size offset = new Size();
/// <summary>
/// Gets or sets the point of the reference rectangle to which the adornment will be aligned.
/// </summary>
[Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Drawing.ContentAlignment ReferenceCorner {
get { return this.referenceCorner; }
set { this.referenceCorner = value; }
}
private System.Drawing.ContentAlignment referenceCorner = System.Drawing.ContentAlignment.MiddleCenter;
/// <summary>
/// Gets or sets the degree of rotation by which the adornment will be transformed.
/// The centre of rotation will be the center point of the adornment.
/// </summary>
[Category("ObjectListView"),
Description("The degree of rotation that will be applied to the adornment."),
DefaultValue(0),
NotifyParentProperty(true)]
public int Rotation {
get { return this.rotation; }
set { this.rotation = value; }
}
private int rotation;
/// <summary>
/// Gets or sets the transparency of the overlay.
/// 0 is completely transparent, 255 is completely opaque.
/// </summary>
[Category("ObjectListView"),
Description("The transparency of this adornment. 0 is completely transparent, 255 is completely opaque."),
DefaultValue(128)]
public int Transparency {
get { return this.transparency; }
set { this.transparency = Math.Min(255, Math.Max(0, value)); }
}
private int transparency = 128;
#endregion
#region Calculations
/// <summary>
/// Calculate the location of rectangle of the given size,
/// so that it's indicated corner would be at the given point.
/// </summary>
/// <param name="pt">The point</param>
/// <param name="size"></param>
/// <param name="corner">Which corner will be positioned at the reference point</param>
/// <returns></returns>
/// <example>CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.TopLeft) -> Point(50, 100)</example>
/// <example>CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.MiddleCenter) -> Point(45, 90)</example>
/// <example>CalculateAlignedPosition(new Point(50, 100), new Size(10, 20), System.Drawing.ContentAlignment.BottomRight) -> Point(40, 80)</example>
public Point CalculateAlignedPosition(Point pt, Size size, System.Drawing.ContentAlignment corner) {
switch (corner) {
case System.Drawing.ContentAlignment.TopLeft:
return pt;
case System.Drawing.ContentAlignment.TopCenter:
return new Point(pt.X - (size.Width / 2), pt.Y);
case System.Drawing.ContentAlignment.TopRight:
return new Point(pt.X - size.Width, pt.Y);
case System.Drawing.ContentAlignment.MiddleLeft:
return new Point(pt.X, pt.Y - (size.Height / 2));
case System.Drawing.ContentAlignment.MiddleCenter:
return new Point(pt.X - (size.Width / 2), pt.Y - (size.Height / 2));
case System.Drawing.ContentAlignment.MiddleRight:
return new Point(pt.X - size.Width, pt.Y - (size.Height / 2));
case System.Drawing.ContentAlignment.BottomLeft:
return new Point(pt.X, pt.Y - size.Height);
case System.Drawing.ContentAlignment.BottomCenter:
return new Point(pt.X - (size.Width / 2), pt.Y - size.Height);
case System.Drawing.ContentAlignment.BottomRight:
return new Point(pt.X - size.Width, pt.Y - size.Height);
}
// Should never reach here
return pt;
}
/// <summary>
/// Calculate a rectangle that has the given size which is positioned so that
/// its alignment point is at the reference location of the given rect.
/// </summary>
/// <param name="r"></param>
/// <param name="sz"></param>
/// <returns></returns>
public Rectangle CreateAlignedRectangle(Rectangle r, Size sz) {
return this.CreateAlignedRectangle(r, sz, this.ReferenceCorner, this.AdornmentCorner, this.Offset);
}
/// <summary>
/// Create a rectangle of the given size which is positioned so that
/// its indicated corner is at the indicated corner of the reference rect.
/// </summary>
/// <param name="r"></param>
/// <param name="sz"></param>
/// <param name="corner"></param>
/// <param name="referenceCorner"></param>
/// <param name="offset"></param>
/// <returns></returns>
/// <remarks>
/// <para>Creates a rectangle so that its bottom left is at the centre of the reference:
/// corner=BottomLeft, referenceCorner=MiddleCenter</para>
/// <para>This is a powerful concept that takes some getting used to, but is
/// very neat once you understand it.</para>
/// </remarks>
public Rectangle CreateAlignedRectangle(Rectangle r, Size sz,
System.Drawing.ContentAlignment corner, System.Drawing.ContentAlignment referenceCorner, Size offset) {
Point referencePt = this.CalculateCorner(r, referenceCorner);
Point topLeft = this.CalculateAlignedPosition(referencePt, sz, corner);
return new Rectangle(topLeft + offset, sz);
}
/// <summary>
/// Return the point at the indicated corner of the given rectangle (it doesn't
/// have to be a corner, but a named location)
/// </summary>
/// <param name="r">The reference rectangle</param>
/// <param name="corner">Which point of the rectangle should be returned?</param>
/// <returns>A point</returns>
/// <example>CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.TopLeft) -> Point(0, 0)</example>
/// <example>CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.MiddleCenter) -> Point(25, 50)</example>
/// <example>CalculateReferenceLocation(new Rectangle(0, 0, 50, 100), System.Drawing.ContentAlignment.BottomRight) -> Point(50, 100)</example>
public Point CalculateCorner(Rectangle r, System.Drawing.ContentAlignment corner) {
switch (corner) {
case System.Drawing.ContentAlignment.TopLeft:
return new Point(r.Left, r.Top);
case System.Drawing.ContentAlignment.TopCenter:
return new Point(r.X + (r.Width / 2), r.Top);
case System.Drawing.ContentAlignment.TopRight:
return new Point(r.Right, r.Top);
case System.Drawing.ContentAlignment.MiddleLeft:
return new Point(r.Left, r.Top + (r.Height / 2));
case System.Drawing.ContentAlignment.MiddleCenter:
return new Point(r.X + (r.Width / 2), r.Top + (r.Height / 2));
case System.Drawing.ContentAlignment.MiddleRight:
return new Point(r.Right, r.Top + (r.Height / 2));
case System.Drawing.ContentAlignment.BottomLeft:
return new Point(r.Left, r.Bottom);
case System.Drawing.ContentAlignment.BottomCenter:
return new Point(r.X + (r.Width / 2), r.Bottom);
case System.Drawing.ContentAlignment.BottomRight:
return new Point(r.Right, r.Bottom);
}
// Should never reach here
return r.Location;
}
/// <summary>
/// Given the item and the subitem, calculate its bounds.
/// </summary>
/// <param name="item"></param>
/// <param name="subItem"></param>
/// <returns></returns>
public Rectangle CalculateItemBounds(OLVListItem item, OLVListSubItem subItem) {
if (item == null)
return Rectangle.Empty;
if (subItem == null)
return item.Bounds;
else
return item.GetSubItemBounds(item.SubItems.IndexOf(subItem));
}
#endregion
#region Commands
/// <summary>
/// Apply any specified rotation to the Graphic content.
/// </summary>
/// <param name="g">The Graphics to be transformed</param>
/// <param name="r">The rotation will be around the centre of this rect</param>
protected void ApplyRotation(Graphics g, Rectangle r) {
if (this.Rotation == 0)
return;
// THINK: Do we want to reset the transform? I think we want to push a new transform
g.ResetTransform();
Matrix m = new Matrix();
m.RotateAt(this.Rotation, new Point(r.Left + r.Width / 2, r.Top + r.Height / 2));
g.Transform = m;
}
/// <summary>
/// Reverse the rotation created by ApplyRotation()
/// </summary>
/// <param name="g"></param>
protected void UnapplyRotation(Graphics g) {
if (this.Rotation != 0)
g.ResetTransform();
}
#endregion
}
/// <summary>
/// An overlay that will draw an image over the top of the ObjectListView
/// </summary>
public class ImageAdornment : GraphicAdornment
{
#region Public properties
/// <summary>
/// Gets or sets the image that will be drawn
/// </summary>
[Category("ObjectListView"),
Description("The image that will be drawn"),
DefaultValue(null),
NotifyParentProperty(true)]
public Image Image {
get { return this.image; }
set { this.image = value; }
}
private Image image;
/// <summary>
/// Gets or sets if the image will be shrunk to fit with its horizontal bounds
/// </summary>
[Category("ObjectListView"),
Description("Will the image be shrunk to fit within its width?"),
DefaultValue(false)]
public bool ShrinkToWidth {
get { return this.shrinkToWidth; }
set { this.shrinkToWidth = value; }
}
private bool shrinkToWidth;
#endregion
#region Commands
/// <summary>
/// Draw the image in its specified location
/// </summary>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The bounds of the rendering</param>
public void DrawImage(Graphics g, Rectangle r) {
if (this.ShrinkToWidth)
this.DrawScaledImage(g, r, this.Image, this.Transparency);
else
this.DrawImage(g, r, this.Image, this.Transparency);
}
/// <summary>
/// Draw the image in its specified location
/// </summary>
/// <param name="image">The image to be drawn</param>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The bounds of the rendering</param>
/// <param name="transparency">How transparent should the image be (0 is completely transparent, 255 is opaque)</param>
public void DrawImage(Graphics g, Rectangle r, Image image, int transparency) {
if (image != null)
this.DrawImage(g, r, image, image.Size, transparency);
}
/// <summary>
/// Draw the image in its specified location
/// </summary>
/// <param name="image">The image to be drawn</param>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The bounds of the rendering</param>
/// <param name="sz">How big should the image be?</param>
/// <param name="transparency">How transparent should the image be (0 is completely transparent, 255 is opaque)</param>
public void DrawImage(Graphics g, Rectangle r, Image image, Size sz, int transparency) {
if (image == null)
return;
Rectangle adornmentBounds = this.CreateAlignedRectangle(r, sz);
try {
this.ApplyRotation(g, adornmentBounds);
this.DrawTransparentBitmap(g, adornmentBounds, image, transparency);
}
finally {
this.UnapplyRotation(g);
}
}
/// <summary>
/// Draw the image in its specified location, scaled so that it is not wider
/// than the given rectangle. Height is scaled proportional to the width.
/// </summary>
/// <param name="image">The image to be drawn</param>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The bounds of the rendering</param>
/// <param name="transparency">How transparent should the image be (0 is completely transparent, 255 is opaque)</param>
public void DrawScaledImage(Graphics g, Rectangle r, Image image, int transparency) {
if (image == null)
return;
// If the image is too wide to be drawn in the space provided, proportionally scale it down.
// Too tall images are not scaled.
Size size = image.Size;
if (image.Width > r.Width) {
float scaleRatio = (float)r.Width / (float)image.Width;
size.Height = (int)((float)image.Height * scaleRatio);
size.Width = r.Width - 1;
}
this.DrawImage(g, r, image, size, transparency);
}
/// <summary>
/// Utility to draw a bitmap transparenly.
/// </summary>
/// <param name="g"></param>
/// <param name="r"></param>
/// <param name="image"></param>
/// <param name="transparency"></param>
protected void DrawTransparentBitmap(Graphics g, Rectangle r, Image image, int transparency) {
ImageAttributes imageAttributes = null;
if (transparency != 255) {
imageAttributes = new ImageAttributes();
float a = (float)transparency / 255.0f;
float[][] colorMatrixElements = {
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, a, 0},
new float[] {0, 0, 0, 0, 1}};
imageAttributes.SetColorMatrix(new ColorMatrix(colorMatrixElements));
}
g.DrawImage(image,
r, // destination rectangle
0, 0, image.Size.Width, image.Size.Height, // source rectangle
GraphicsUnit.Pixel,
imageAttributes);
}
#endregion
}
/// <summary>
/// An adornment that will draw text
/// </summary>
public class TextAdornment : GraphicAdornment
{
#region Public properties
/// <summary>
/// Gets or sets the background color of the text
/// Set this to Color.Empty to not draw a background
/// </summary>
[Category("ObjectListView"),
Description("The background color of the text"),
DefaultValue(typeof(Color), "")]
public Color BackColor {
get { return this.backColor; }
set { this.backColor = value; }
}
private Color backColor = Color.Empty;
/// <summary>
/// Gets the brush that will be used to paint the text
/// </summary>
[Browsable(false)]
public Brush BackgroundBrush {
get {
return new SolidBrush(Color.FromArgb(this.WorkingTransparency, this.BackColor));
}
}
/// <summary>
/// Gets or sets the color of the border around the billboard.
/// Set this to Color.Empty to remove the border
/// </summary>
[Category("ObjectListView"),
Description("The color of the border around the text"),
DefaultValue(typeof(Color), "")]
public Color BorderColor {
get { return this.borderColor; }
set { this.borderColor = value; }
}
private Color borderColor = Color.Empty;
/// <summary>
/// Gets the brush that will be used to paint the text
/// </summary>
[Browsable(false)]
public Pen BorderPen {
get {
return new Pen(Color.FromArgb(this.WorkingTransparency, this.BorderColor), this.BorderWidth);
}
}
/// <summary>
/// Gets or sets the width of the border around the text
/// </summary>
[Category("ObjectListView"),
Description("The width of the border around the text"),
DefaultValue(0.0f)]
public float BorderWidth {
get { return this.borderWidth; }
set { this.borderWidth = value; }
}
private float borderWidth;
/// <summary>
/// How rounded should the corners of the border be? 0 means no rounding.
/// </summary>
/// <remarks>If this value is too large, the edges of the border will appear odd.</remarks>
[Category("ObjectListView"),
Description("How rounded should the corners of the border be? 0 means no rounding."),
DefaultValue(16.0f),
NotifyParentProperty(true)]
public float CornerRounding {
get { return this.cornerRounding; }
set { this.cornerRounding = value; }
}
private float cornerRounding = 16.0f;
/// <summary>
/// Gets or sets the font that will be used to draw the text
/// </summary>
[Category("ObjectListView"),
Description("The font that will be used to draw the text"),
DefaultValue(null),
NotifyParentProperty(true)]
public Font Font {
get { return this.font; }
set { this.font = value; }
}
private Font font;
/// <summary>
/// Gets the font that will be used to draw the text or a reasonable default
/// </summary>
[Browsable(false)]
public Font FontOrDefault {
get {
return this.Font ?? new Font("Tahoma", 16);
}
}
/// <summary>
/// Does this text have a background?
/// </summary>
[Browsable(false)]
public bool HasBackground {
get {
return this.BackColor != Color.Empty;
}
}
/// <summary>
/// Does this overlay have a border?
/// </summary>
[Browsable(false)]
public bool HasBorder {
get {
return this.BorderColor != Color.Empty && this.BorderWidth > 0;
}
}
/// <summary>
/// Gets or sets the maximum width of the text. Text longer than this will wrap.
/// 0 means no maximum.
/// </summary>
[Category("ObjectListView"),
Description("The maximum width the text (0 means no maximum). Text longer than this will wrap"),
DefaultValue(0)]
public int MaximumTextWidth {
get { return this.maximumTextWidth; }
set { this.maximumTextWidth = value; }
}
private int maximumTextWidth;
/// <summary>
/// Gets or sets the formatting that should be used on the text
/// </summary>
[Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public StringFormat StringFormat {
get {
if (this.stringFormat == null) {
this.stringFormat = new StringFormat();
this.stringFormat.Alignment = StringAlignment.Center;
this.stringFormat.LineAlignment = StringAlignment.Center;
this.stringFormat.Trimming = StringTrimming.EllipsisCharacter;
if (!this.Wrap)
this.stringFormat.FormatFlags = StringFormatFlags.NoWrap;
}
return this.stringFormat;
}
set { this.stringFormat = value; }
}
private StringFormat stringFormat;
/// <summary>
/// Gets or sets the text that will be drawn
/// </summary>
[Category("ObjectListView"),
Description("The text that will be drawn over the top of the ListView"),
DefaultValue(null),
NotifyParentProperty(true),
Localizable(true)]
public string Text {
get { return this.text; }
set { this.text = value; }
}
private string text;
/// <summary>
/// Gets the brush that will be used to paint the text
/// </summary>
[Browsable(false)]
public Brush TextBrush {
get {
return new SolidBrush(Color.FromArgb(this.WorkingTransparency, this.TextColor));
}
}
/// <summary>
/// Gets or sets the color of the text
/// </summary>
[Category("ObjectListView"),
Description("The color of the text"),
DefaultValue(typeof(Color), "DarkBlue"),
NotifyParentProperty(true)]
public Color TextColor {
get { return this.textColor; }
set { this.textColor = value; }
}
private Color textColor = Color.DarkBlue;
/// <summary>
/// Gets or sets whether the text will wrap when it exceeds its bounds
/// </summary>
[Category("ObjectListView"),
Description("Will the text wrap?"),
DefaultValue(true)]
public bool Wrap {
get { return this.wrap; }
set { this.wrap = value; }
}
private bool wrap = true;
#endregion
#region Implementation
/// <summary>
/// Draw our text with our stored configuration in relation to the given
/// reference rectangle
/// </summary>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The reference rectangle in relation to which the text will be drawn</param>
public void DrawText(Graphics g, Rectangle r) {
this.DrawText(g, r, this.Text, this.Transparency);
}
/// <summary>
/// Draw the given text with our stored configuration
/// </summary>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="r">The reference rectangle in relation to which the text will be drawn</param>
/// <param name="text">The text to draw</param>
/// <param name="transparency">How opaque should be text be</param>
public void DrawText(Graphics g, Rectangle r, string text, int transparency) {
if (String.IsNullOrEmpty(text))
return;
Rectangle textRect = this.CalculateTextBounds(g, r, text);
this.DrawBorderedText(g, textRect, text, transparency);
}
/// <summary>
/// Draw the text with a border
/// </summary>
/// <param name="g">The Graphics used for drawing</param>
/// <param name="textRect">The bounds within which the text should be drawn</param>
/// <param name="text">The text to draw</param>
/// <param name="transparency">How opaque should be text be</param>
protected void DrawBorderedText(Graphics g, Rectangle textRect, string text, int transparency) {
Rectangle borderRect = textRect;
borderRect.Inflate((int)this.BorderWidth / 2, (int)this.BorderWidth / 2);
borderRect.Y -= 1; // Looker better a little higher
try {
this.ApplyRotation(g, textRect);
using (GraphicsPath path = this.GetRoundedRect(borderRect, this.CornerRounding)) {
this.WorkingTransparency = transparency;
if (this.HasBackground)
g.FillPath(this.BackgroundBrush, path);
g.DrawString(text, this.FontOrDefault, this.TextBrush, textRect, this.StringFormat);
if (this.HasBorder)
g.DrawPath(this.BorderPen, path);
}
}
finally {
this.UnapplyRotation(g);
}
}
/// <summary>
/// Return the rectangle that will be the precise bounds of the displayed text
/// </summary>
/// <param name="g"></param>
/// <param name="r"></param>
/// <param name="text"></param>
/// <returns>The bounds of the text</returns>
protected Rectangle CalculateTextBounds(Graphics g, Rectangle r, string text) {
int maxWidth = this.MaximumTextWidth <= 0 ? r.Width : this.MaximumTextWidth;
SizeF sizeF = g.MeasureString(text, this.FontOrDefault, maxWidth, this.StringFormat);
Size size = new Size(1 + (int)sizeF.Width, 1 + (int)sizeF.Height);
return this.CreateAlignedRectangle(r, size);
}
/// <summary>
/// Return a GraphicPath that is a round cornered rectangle
/// </summary>
/// <param name="rect">The rectangle</param>
/// <param name="diameter">The diameter of the corners</param>
/// <returns>A round cornered rectagle path</returns>
/// <remarks>If I could rely on people using C# 3.0+, this should be
/// an extension method of GraphicsPath.</remarks>
protected GraphicsPath GetRoundedRect(Rectangle rect, float diameter) {
GraphicsPath path = new GraphicsPath();
if (diameter > 0) {
RectangleF arc = new RectangleF(rect.X, rect.Y, diameter, diameter);
path.AddArc(arc, 180, 90);
arc.X = rect.Right - diameter;
path.AddArc(arc, 270, 90);
arc.Y = rect.Bottom - diameter;
path.AddArc(arc, 0, 90);
arc.X = rect.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
} else {
path.AddRectangle(rect);
}
return path;
}
#endregion
private int WorkingTransparency;
}
}
| 41.164179 | 156 | 0.575681 | [
"MIT"
] | artizzan/WurmAssistant3 | lib/ObjectListView/ObjectListView/ObjectListView/Rendering/Adornments.cs | 30,340 | C# |
#region License
// Copyright (c) 2009, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ClearCanvas Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
#endregion
using System;
using System.Globalization;
using ClearCanvas.Common.Utilities;
using System.ComponentModel;
namespace ClearCanvas.Dicom.Iod
{
public enum PersonNameComparisonOptions
{
CaseSensitive,
CaseInsensitive,
}
/// <summary>
/// <see cref="TypeConverter"/> for <see cref="PersonName"/> class.
/// </summary>
public class PersonNameConverter : TypeConverter
{
/// <summary>
/// Constructor.
/// </summary>
public PersonNameConverter()
{
}
/// <summary>
/// Override of <see cref="TypeConverter.CanConvertTo"/>.
/// </summary>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertFrom(context, destinationType);
}
/// <summary>
/// Override of <see cref="TypeConverter.CanConvertFrom"/>.
/// </summary>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Override of <see cref="TypeConverter.ConvertFrom(ITypeDescriptorContext,CultureInfo,object)"/>.
/// </summary>
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
return new PersonName(value as string);
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// Override of <see cref="TypeConverter.ConvertTo(ITypeDescriptorContext,CultureInfo,object,Type)"/>.
/// </summary>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (value is PersonName && destinationType == typeof(string))
return value.ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}
/// <summary>
/// Encapsulates the DICOM Person's Name.
/// </summary>
[TypeConverter(typeof(PersonNameConverter))]
public class PersonName : IEquatable<PersonName>, IFormattable
{
private string _personsName;
private string _formattedName;
private readonly ComponentGroup[] _componentGroups = { ComponentGroup.GetEmptyComponentGroup(),
ComponentGroup.GetEmptyComponentGroup(),
ComponentGroup.GetEmptyComponentGroup() };
/// <summary>
/// Protected constructor.
/// </summary>
protected PersonName()
{
SetInternalPersonName("");
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="personsName">The Person's Name as a string.</param>
public PersonName(string personsName)
{
SetInternalPersonName(personsName);
}
/// <summary>
/// Gets whether or not the value is empty.
/// </summary>
public bool IsEmpty
{
get { return String.IsNullOrEmpty(InternalPersonName); }
}
/// <summary>
/// Gets or sets the internal person name value, unparsed.
/// </summary>
protected virtual string InternalPersonName
{
get { return _personsName; }
set { SetInternalPersonName(value); }
}
#region Public Properties
/// <summary>
/// Gets the patient's last (family) name.
/// </summary>
public String LastName
{
get { return this.SingleByte.FamilyName; }
}
/// <summary>
/// Gets the patient's first (given) name.
/// </summary>
public String FirstName
{
get { return this.SingleByte.GivenName; }
}
/// <summary>
/// Gets the patient's middle name.
/// </summary>
public String MiddleName
{
get { return this.SingleByte.MiddleName; }
}
/// <summary>
/// Gets the patient's title.
/// </summary>
public String Title
{
get { return this.SingleByte.Prefix; }
}
/// <summary>
/// Gets the patient's name, formatted like: Last Name, First Name.
/// </summary>
public String FormattedName
{
get { return _formattedName; }
}
/// <summary>
/// Gets the single byte <see cref="ComponentGroup"/> in the <see cref="PersonName"/>.
/// </summary>
public ComponentGroup SingleByte
{
get
{
return _componentGroups[0];
}
}
/// <summary>
/// Gets the ideographic <see cref="ComponentGroup"/> in the <see cref="PersonName"/>.
/// </summary>
public ComponentGroup Ideographic
{
get
{
return _componentGroups[1];
}
}
/// <summary>
/// Gets the phonetic <see cref="ComponentGroup"/> in the <see cref="PersonName"/>.
/// </summary>
public ComponentGroup Phonetic
{
get
{
return _componentGroups[2];
}
}
#endregion
/// <summary>
/// Gets the Person's Name as a string.
/// </summary>
/// <returns>A string representation of the Person's Name.</returns>
public override string ToString()
{
return _personsName;
}
/// <summary>
/// Implicit cast to a String object, for ease of use.
/// </summary>
public static implicit operator String(PersonName pn)
{
return pn.ToString();
}
/// <summary>
/// Serves as a hash function for a particular type. <see cref="M:System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"></see>.
/// </returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Returns a value indicating whether two <see cref="PersonName"/> are the same.
/// </summary>
/// <param name="other">Another <see cref="PersonName"/> to compare with</param>
/// <param name="options">Comparison option</param>
/// <returns>
/// <b>true</b> if this person's name is the same as the other. <b>false</b> otherwise.
/// </returns>
public bool AreSame(PersonName other, PersonNameComparisonOptions options)
{
if (other == null)
return false;
return
SingleByte.AreSame(other.SingleByte, options) &&
Phonetic.AreSame(other.Phonetic, options) &&
Ideographic.AreSame(other.Ideographic, options);
}
public override bool Equals(object obj)
{
if (obj == this)
return true;
if (obj is PersonName)
return this.Equals((PersonName)obj);
return false;
}
#region IEquatable<PersonName> Members
public bool Equals(PersonName other)
{
if (other == null)
return false;
return InternalPersonName == other.InternalPersonName;
}
#endregion
#region IFormattable Members
public string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider != null)
{
ICustomFormatter formatter = formatProvider.GetFormat(this.GetType()) as ICustomFormatter;
if (formatter != null)
return formatter.Format(format, this, formatProvider);
}
return ToString();
}
#endregion
private void SetInternalPersonName(string personsName)
{
_personsName = personsName ?? "";
BreakApartIntoComponentGroups();
SetFormattedName();
}
private void BreakApartIntoComponentGroups()
{
// if there's no name, don't do anything
if (String.IsNullOrEmpty(this.InternalPersonName))
return;
string[] componentGroupsStrings = this.InternalPersonName.Split('=');
if (componentGroupsStrings.GetUpperBound(0) >= 0 && componentGroupsStrings[0] != string.Empty)
_componentGroups[0] = new ComponentGroup(componentGroupsStrings[0]);
if (componentGroupsStrings.GetUpperBound(0) > 0 && componentGroupsStrings[1] != string.Empty)
_componentGroups[1] = new ComponentGroup(componentGroupsStrings[1]);
if (componentGroupsStrings.GetUpperBound(0) > 1 && componentGroupsStrings[2] != string.Empty)
_componentGroups[2] = new ComponentGroup(componentGroupsStrings[2]);
}
private void SetFormattedName()
{
//by default, the formatted name is LastName, FirstName
_formattedName = StringUtilities.Combine<string>(new string[] { this.LastName, this.FirstName }, ", ");
}
}
}
| 31.110465 | 183 | 0.61951 | [
"Apache-2.0"
] | econmed/ImageServer20 | Dicom/Iod/PersonName.cs | 10,704 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace snap_lab_04_Exam
{
using System;
using System.Collections.Generic;
public partial class Order_Detail
{
public int OrderID { get; set; }
public int ProductID { get; set; }
public decimal UnitPrice { get; set; }
public short Quantity { get; set; }
public float Discount { get; set; }
public virtual Order Order { get; set; }
public virtual Product Product { get; set; }
}
}
| 33.037037 | 85 | 0.524664 | [
"MIT"
] | ajohnson96/2019-06-c-sharp-labs | labs/snap_lab_04_Exam/Order_Detail.cs | 892 | C# |
using Cake.Frosting;
using Cake.Issues.Reporting;
using Cake.Issues.Reporting.Generic;
[TaskName("Create-Reports-HtmlDxDataGrid-Theme-MaterialPurpleDark")]
[IsDependentOn(typeof(AnalyzeTask))]
public class CreateReportsHtmlDxDataGridThemeMaterialPurpleDarkTask : FrostingTask<BuildContext>
{
public override void Run(BuildContext context)
{
context.CreateIssueReport(
context.Issues,
context.GenericIssueReportFormatFromEmbeddedTemplate(
GenericIssueReportTemplate.HtmlDxDataGrid,
settings =>
settings
.WithOption(HtmlDxDataGridOption.Theme, DevExtremeTheme.MaterialPurpleDark)),
context.RepoRootFolder,
context.TemplateGalleryFolder.CombineWithFilePath("htmldxdatagrid-demo-theme-materialpurpledark.html"));
}
} | 39.045455 | 116 | 0.714785 | [
"Apache-2.0",
"Unlicense"
] | pascalberger/Cake.Issues.Reporting.Generic | demos/frosting/build/tasks/create-reports/CreateReportsHtmlDxDataGridThemeMaterialPurpleDarkTask.cs | 859 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using TestIT.Models;
namespace TestIT.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LoginModel : PageModel
{
private readonly UserManager<TestIT.Models.ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger,UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_logger = logger;
_userManager = userManager;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required(ErrorMessage = "Email polje mora biti popunjeno")]
[EmailAddress(ErrorMessage = "Email nije validan")]
public string Email { get; set; }
[Required(ErrorMessage = "Polje za šifru mora biti popunjeno")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Sacuvaj informacije za prijavu")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl = returnUrl ?? Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var user = await _userManager.FindByEmailAsync(Input.Email.ToUpper());
if(user!=null)
{
var result = await _signInManager.PasswordSignInAsync(user.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Nevalidan pokušaj prijavljivanja.");
return Page();
}
}
else
{
ModelState.AddModelError(string.Empty, "Nalog sa ovim mejlom ne postoji");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}
| 36.482759 | 147 | 0.576323 | [
"MIT"
] | Mr-357/TestIT | TestIT/TestIT/Areas/Identity/Pages/Account/Login.cshtml.cs | 4,234 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Foundation.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace FutekUSB220
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
public Logger logger { get; }
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
this.Resuming += App_Resuming;
this.logger = new Logger();
}
private void App_Resuming(object sender, object e)
{
logger.OpenAsync();
logger.Log("App.OnResuming", LoggingLevel.Information);
}
protected override void OnActivated(IActivatedEventArgs args)
{
logger.OpenAsync();
base.OnActivated(args);
logger.Log("App.OnActivated", LoggingLevel.Information);
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
logger.OpenAsync();
logger.Log("App.OnLaunched", LoggingLevel.Information);
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
logger.Log("App.OnSuspending", LoggingLevel.Information);
await logger.WriteLogBlock();
deferral.Complete();
}
}
}
| 37.674797 | 99 | 0.610272 | [
"MIT"
] | Roger-random/UWPTest | FutekUSB220/App.xaml.cs | 4,636 | 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("PrintAsciiTable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PrintAsciiTable")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("08f05d78-86b8-49f8-baf3-19c8c63d5c32")]
// 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.918919 | 84 | 0.746258 | [
"MIT"
] | sholev/SoftUni | Fundamentals-2.0/C#-Basics/Homework/Primitive-Data-Types-and-Variables-Homework/PrintAsciiTable/Properties/AssemblyInfo.cs | 1,406 | C# |
using SrcomLib.Clients.Queries.Interfaces;
using SrcomLib.ResponseObjects;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SrcomLib.Clients.Queries
{
/// <summary>
/// Interface for building and submitting a Series Serach Query
/// </summary>
public class SeriesClientSearchQuery : ISeriesClientSearchQuery
{
private readonly SeriesClient _seriessClient;
internal SeriesClientSearchQuery(SeriesClient seriessClient)
{
_seriessClient = seriessClient;
}
/// <inheritdoc/>
public ISeriesClientSearchQuery WithSearch(SeriesSearchField field, string searchValue)
{
_seriessClient.WithSearch(field, searchValue);
return this;
}
/// <inheritdoc/>
public ISeriesClientSearchQuery WithSearch(IDictionary<SeriesSearchField, string> searchParameters)
{
_seriessClient.WithSearch(searchParameters);
return this;
}
/// <inheritdoc/>
public ISeriesClientSearchQuery WithMaxRecordsReturned(uint maxRecords)
{
_seriessClient.WithMaxRecordsReturned(maxRecords);
return this;
}
/// <inheritdoc/>
public ISeriesClientSearchQuery IncludeEmbed(SeriesEmbed embed)
{
_seriessClient.IncludeEmbed(embed);
return this;
}
/// <inheritdoc/>
public ISeriesClientSearchQuery WithSort(SeriesSortField orderBy)
{
_seriessClient.WithSort(orderBy);
return this;
}
/// <inheritdoc/>
public ISeriesClientSearchQuery WithSortDescending(SeriesSortField orderBy)
{
_seriessClient.WithSortDescending(orderBy);
return this;
}
/// <inheritdoc/>
public async Task<IReadOnlyList<Series>> ExecuteSearchAsync(bool ignoreCache = false, CancellationToken cancellationToken = default)
{
return await _seriessClient.ExecuteSearchAsync(ignoreCache, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public IReadOnlyList<Series> ExecuteSearch(bool ignoreCache = false)
{
return _seriessClient.ExecuteSearch(ignoreCache);
}
}
} | 31.594595 | 140 | 0.645851 | [
"MIT"
] | eonHck/SrcomLib | SrcomLib/Clients/Queries/SeriesClientSearchQuery.cs | 2,340 | C# |
namespace Nancy.Tests.Fakes
{
using System.Collections.Generic;
using System.IO;
using IO;
public class FakeRequest : Request
{
public FakeRequest(string method, string path)
: this(method, path, new Dictionary<string, IEnumerable<string>>(), RequestStream.FromStream(new MemoryStream()), "http", string.Empty)
{
}
public FakeRequest(string method, string path, IDictionary<string, IEnumerable<string>> headers)
: this(method, path, headers, RequestStream.FromStream(new MemoryStream()), "http", string.Empty)
{
}
public FakeRequest(string method, string path, string query)
: this(method, path, new Dictionary<string, IEnumerable<string>>(), RequestStream.FromStream(new MemoryStream()), "http", query)
{
}
public FakeRequest(string method, string path, IDictionary<string, IEnumerable<string>> headers, RequestStream body, string protocol, string query)
: base(method, path, headers, body, protocol, query)
{
}
}
} | 38.517241 | 156 | 0.631155 | [
"MIT"
] | BilalHasanKhan/Nancy | src/Nancy.Tests/Fakes/FakeRequest.cs | 1,119 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SeoSchema;
using SeoSchema.Enumerations;
using SuperStructs;
namespace SeoSchema.Entities
{
/// <summary>
/// A music video file.
/// <see cref="https://schema.org/MusicVideoObject"/>
/// </summary>
public class MusicVideoObject : IEntity
{
/// A NewsArticle associated with the Media Object.
public Or<NewsArticle>? AssociatedArticle { get; set; }
/// The bitrate of the media object.
public Or<string>? Bitrate { get; set; }
/// File size in (mega/kilo) bytes.
public Or<string>? ContentSize { get; set; }
/// Actual bytes of the media object, for example the image file or video file.
public Or<Uri>? ContentUrl { get; set; }
/// The duration of the item (movie, audio recording, event, etc.) in ISO 8601 date format.
public Or<Duration>? Duration { get; set; }
/// A URL pointing to a player for a specific video. In general, this is the information in the src element of an embed tag and should not be the same as the content of the loc tag.
public Or<Uri>? EmbedUrl { get; set; }
/// The CreativeWork encoded by this media object.
public Or<CreativeWork>? EncodesCreativeWork { get; set; }
/// Media type typically expressed using a MIME format (see IANA site and MDN reference) e.g. application/zip for a SoftwareApplication binary, audio/mpeg for .mp3 etc.).
///
/// In cases where a CreativeWork has several media type representations, encoding can be used to indicate each MediaObject alongside particular encodingFormat information.
///
/// Unregistered or niche encoding and file formats can be indicated instead via the most appropriate URL, e.g. defining Web page or a Wikipedia/Wikidata entry. Supersedes fileFormat.
public Or<string, Uri>? EncodingFormat { get; set; }
/// The height of the item.
public Or<Distance, QuantitativeValue>? Height { get; set; }
/// Player type required—for example, Flash or Silverlight.
public Or<string>? PlayerType { get; set; }
/// The production company or studio responsible for the item e.g. series, video game, episode etc.
public Or<Organization>? ProductionCompany { get; set; }
/// The regions where the media is allowed. If not specified, then it's assumed to be allowed everywhere. Specify the countries in ISO 3166 format.
public Or<Place>? RegionsAllowed { get; set; }
/// Indicates if use of the media require a subscription (either paid or free). Allowed values are true or false (note that an earlier version had 'yes', 'no').
public Or<bool, MediaSubscription>? RequiresSubscription { get; set; }
/// Date when this media object was uploaded to this site.
public Or<SuperStructs.Date>? UploadDate { get; set; }
/// The width of the item.
public Or<Distance, QuantitativeValue>? Width { get; set; }
/// The subject matter of the content. Inverse property: subjectOf.
public Or<Thing>? About { get; set; }
/// The human sensory perceptual system or cognitive faculty through which a person may process or perceive information. Expected values include: auditory, tactile, textual, visual, colorDependent, chartOnVisual, chemOnVisual, diagramOnVisual, mathOnVisual, musicOnVisual, textOnVisual.
public Or<string>? AccessMode { get; set; }
/// A list of single or combined accessModes that are sufficient to understand all the intellectual content of a resource. Expected values include: auditory, tactile, textual, visual.
public Or<string>? AccessModeSufficient { get; set; }
/// Indicates that the resource is compatible with the referenced accessibility API (WebSchemas wiki lists possible values).
public Or<string>? AccessibilityAPI { get; set; }
/// Identifies input methods that are sufficient to fully control the described resource (WebSchemas wiki lists possible values).
public Or<string>? AccessibilityControl { get; set; }
/// Content features of the resource, such as accessible media, alternatives and supported enhancements for accessibility (WebSchemas wiki lists possible values).
public Or<string>? AccessibilityFeature { get; set; }
/// A characteristic of the described resource that is physiologically dangerous to some users. Related to WCAG 2.0 guideline 2.3 (WebSchemas wiki lists possible values).
public Or<string>? AccessibilityHazard { get; set; }
/// A human-readable summary of specific accessibility features or deficiencies, consistent with the other accessibility metadata but expressing subtleties such as "short descriptions are present but long descriptions will be needed for non-visual users" or "short descriptions are present and no long descriptions are needed."
public Or<string>? AccessibilitySummary { get; set; }
/// Specifies the Person that is legally accountable for the CreativeWork.
public Or<Person>? AccountablePerson { get; set; }
/// The overall rating, based on a collection of reviews or ratings, of the item.
public Or<AggregateRating>? AggregateRating { get; set; }
/// A secondary title of the CreativeWork.
public Or<string>? AlternativeHeadline { get; set; }
/// A media object that encodes this CreativeWork. This property is a synonym for encoding.
public Or<MediaObject>? AssociatedMedia { get; set; }
/// An intended audience, i.e. a group for whom something was created. Supersedes serviceAudience.
public Or<Audience>? Audience { get; set; }
/// An embedded audio object.
public Or<AudioObject>? Audio { get; set; }
/// The author of this content or rating. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangeably.
public Or<Organization, Person>? Author { get; set; }
/// An award won by or for this item. Supersedes awards.
public Or<string>? Award { get; set; }
/// Fictional person connected with a creative work.
public Or<Person>? Character { get; set; }
/// A citation or reference to another creative work, such as another publication, web page, scholarly article, etc.
public Or<CreativeWork, string>? Citation { get; set; }
/// Comments, typically from users.
public Or<Comment>? Comment { get; set; }
/// The number of comments this CreativeWork (e.g. Article, Question or Answer) has received. This is most applicable to works published in Web sites with commenting system; additional comments may exist elsewhere.
public Or<int>? CommentCount { get; set; }
/// The location depicted or described in the content. For example, the location in a photograph or painting.
public Or<Place>? ContentLocation { get; set; }
/// Official rating of a piece of content—for example,'MPAA PG-13'.
public Or<Rating, string>? ContentRating { get; set; }
/// The specific time described by a creative work, for works (e.g. articles, video objects etc.) that emphasise a particular moment within an Event.
public Or<DateTime>? ContentReferenceTime { get; set; }
/// A secondary contributor to the CreativeWork or Event.
public Or<Organization, Person>? Contributor { get; set; }
/// The party holding the legal copyright to the CreativeWork.
public Or<Organization, Person>? CopyrightHolder { get; set; }
/// The year during which the claimed copyright for the CreativeWork was first asserted.
public Or<double>? CopyrightYear { get; set; }
/// Indicates a correction to a CreativeWork, either via a CorrectionComment, textually or in another document.
public Or<CorrectionComment, string, Uri>? Correction { get; set; }
/// The creator/author of this CreativeWork. This is the same as the Author property for CreativeWork.
public Or<Organization, Person>? Creator { get; set; }
/// The date on which the CreativeWork was created or the item was added to a DataFeed.
public Or<SuperStructs.Date, DateTime>? DateCreated { get; set; }
/// The date on which the CreativeWork was most recently modified or when the item's entry was modified within a DataFeed.
public Or<SuperStructs.Date, DateTime>? DateModified { get; set; }
/// Date of first broadcast/publication.
public Or<SuperStructs.Date>? DatePublished { get; set; }
/// A link to the page containing the comments of the CreativeWork.
public Or<Uri>? DiscussionUrl { get; set; }
/// Specifies the Person who edited the CreativeWork.
public Or<Person>? Editor { get; set; }
/// An alignment to an established educational framework.
public Or<AlignmentObject>? EducationalAlignment { get; set; }
/// The purpose of a work in the context of education; for example, 'assignment', 'group work'.
public Or<string>? EducationalUse { get; set; }
/// A media object that encodes this CreativeWork. This property is a synonym for associatedMedia. Supersedes encodings.
public Or<MediaObject>? Encoding { get; set; }
/// A creative work that this work is an example/instance/realization/derivation of. Inverse property: workExample.
public Or<CreativeWork>? ExampleOfWork { get; set; }
/// Date the content expires and is no longer useful or available. For example a VideoObject or NewsArticle whose availability or relevance is time-limited, or a ClaimReview fact check whose publisher wants to indicate that it may no longer be relevant (or helpful to highlight) after some date.
public Or<SuperStructs.Date>? Expires { get; set; }
/// A person or organization that supports (sponsors) something through some kind of financial contribution.
public Or<Organization, Person>? Funder { get; set; }
/// Genre of the creative work, broadcast channel or group.
public Or<string, Uri>? Genre { get; set; }
/// Indicates an item or CreativeWork that is part of this item, or CreativeWork (in some sense). Inverse property: isPartOf.
public Or<CreativeWork, Trip>? HasPart { get; set; }
/// Headline of the article.
public Or<string>? Headline { get; set; }
/// The language of the content or performance or used in an action. Please use one of the language codes from the IETF BCP 47 standard. See also availableLanguage. Supersedes language.
public Or<Language, string>? InLanguage { get; set; }
/// The number of interactions for the CreativeWork using the WebSite or SoftwareApplication. The most specific child type of InteractionCounter should be used. Supersedes interactionCount.
public Or<InteractionCounter>? InteractionStatistic { get; set; }
/// The predominant mode of learning supported by the learning resource. Acceptable values are 'active', 'expositive', or 'mixed'.
public Or<string>? InteractivityType { get; set; }
/// A flag to signal that the item, event, or place is accessible for free. Supersedes free.
public Or<bool>? IsAccessibleForFree { get; set; }
/// A resource that was used in the creation of this resource. This term can be repeated for multiple sources. For example, http://example.com/great-multiplication-intro.html. Supersedes isBasedOnUrl.
public Or<CreativeWork, Product, Uri>? IsBasedOn { get; set; }
/// Indicates whether this content is family friendly.
public Or<bool>? IsFamilyFriendly { get; set; }
/// Indicates an item or CreativeWork that this item, or CreativeWork (in some sense), is part of. Inverse property: hasPart.
public Or<CreativeWork, Trip>? IsPartOf { get; set; }
/// Keywords or tags used to describe this content. Multiple entries in a keywords list are typically delimited by commas.
public Or<string>? Keywords { get; set; }
/// The predominant type or kind characterizing the learning resource. For example, 'presentation', 'handout'.
public Or<string>? LearningResourceType { get; set; }
/// A license document that applies to this content, typically indicated by URL.
public Or<CreativeWork, Uri>? License { get; set; }
/// The location where the CreativeWork was created, which may not be the same as the location depicted in the CreativeWork.
public Or<Place>? LocationCreated { get; set; }
/// Indicates the primary entity described in some page or other CreativeWork. Inverse property: mainEntityOfPage.
public Or<Thing>? MainEntity { get; set; }
/// A material that something is made from, e.g. leather, wool, cotton, paper.
public Or<Product, string, Uri>? Material { get; set; }
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
public Or<Thing>? Mentions { get; set; }
/// An offer to provide this item—for example, an offer to sell a product, rent the DVD of a movie, perform a service, or give away tickets to an event.
public Or<Offer>? Offers { get; set; }
/// The position of an item in a series or sequence of items.
public Or<int, string>? Position { get; set; }
/// The person or organization who produced the work (e.g. music album, movie, tv/radio series etc.).
public Or<Organization, Person>? Producer { get; set; }
/// The service provider, service operator, or service performer; the goods producer. Another party (a seller) may offer those services or goods on behalf of the provider. A provider may also serve as the seller. Supersedes carrier.
public Or<Organization, Person>? Provider { get; set; }
/// A publication event associated with the item.
public Or<PublicationEvent>? Publication { get; set; }
/// The publisher of the creative work.
public Or<Organization, Person>? Publisher { get; set; }
/// The publishing division which published the comic.
public Or<Organization>? PublisherImprint { get; set; }
/// The publishingPrinciples property indicates (typically via URL) a document describing the editorial principles of an Organization (or individual e.g. a Person writing a blog) that relate to their activities as a publisher, e.g. ethics or diversity policies. When applied to a CreativeWork (e.g. NewsArticle) the principles are those of the party primarily responsible for the creation of the CreativeWork.
///
/// While such policies are most typically expressed in natural language, sometimes related information (e.g. indicating a funder) can be expressed using schema.org terminology.
public Or<CreativeWork, Uri>? PublishingPrinciples { get; set; }
/// The Event where the CreativeWork was recorded. The CreativeWork may capture all or part of the event. Inverse property: recordedIn.
public Or<Event>? RecordedAt { get; set; }
/// The place and time the release was issued, expressed as a PublicationEvent.
public Or<PublicationEvent>? ReleasedEvent { get; set; }
/// A review of the item. Supersedes reviews.
public Or<Review>? Review { get; set; }
/// Indicates (by URL or string) a particular version of a schema used in some CreativeWork. For example, a document could declare a schemaVersion using an URL such as http://schema.org/version/2.0/ if precise indication of schema version was required by some application.
public Or<string, Uri>? SchemaVersion { get; set; }
/// Indicates the date on which the current structured data was generated / published. Typically used alongside sdPublisher
public Or<SuperStructs.Date>? SdDatePublished { get; set; }
/// A license document that applies to this structured data, typically indicated by URL.
public Or<CreativeWork, Uri>? SdLicense { get; set; }
/// Indicates the party responsible for generating and publishing the current structured data markup, typically in cases where the structured data is derived automatically from existing published content but published on a different site. For example, student projects and open data initiatives often re-publish existing content with more explicitly structured metadata. The
/// sdPublisher property helps make such practices more explicit.
public Or<Organization, Person>? SdPublisher { get; set; }
/// The Organization on whose behalf the creator was working.
public Or<Organization>? SourceOrganization { get; set; }
/// The spatialCoverage of a CreativeWork indicates the place(s) which are the focus of the content. It is a subproperty of
/// contentLocation intended primarily for more technical and detailed materials. For example with a Dataset, it indicates
/// areas that the dataset describes: a dataset of New York weather would have spatialCoverage which was the place: the state of New York. Supersedes spatial.
public Or<Place>? SpatialCoverage { get; set; }
/// A person or organization that supports a thing through a pledge, promise, or financial contribution. e.g. a sponsor of a Medical Study or a corporate sponsor of an event.
public Or<Organization, Person>? Sponsor { get; set; }
/// The temporalCoverage of a CreativeWork indicates the period that the content applies to, i.e. that it describes, either as a DateTime or as a textual string indicating a time period in ISO 8601 time interval format. In
/// the case of a Dataset it will typically indicate the relevant time period in a precise notation (e.g. for a 2011 census dataset, the year 2011 would be written "2011/2012"). Other forms of content e.g. ScholarlyArticle, Book, TVSeries or TVEpisode may indicate their temporalCoverage in broader terms - textually or via well-known URL.
/// Written works such as books may sometimes have precise temporal coverage too, e.g. a work set in 1939 - 1945 can be indicated in ISO 8601 interval format format via "1939/1945".
///
/// Open-ended date ranges can be written with ".." in place of the end date. For example, "2015-11/.." indicates a range beginning in November 2015 and with no specified final date. This is tentative and might be updated in future when ISO 8601 is officially updated. Supersedes datasetTimeInterval, temporal.
public Or<DateTime, string, Uri>? TemporalCoverage { get; set; }
/// The textual content of this CreativeWork.
public Or<string>? Text { get; set; }
/// A thumbnail image relevant to the Thing.
public Or<Uri>? ThumbnailUrl { get; set; }
/// Approximate or typical time it takes to work with or through this learning resource for the typical intended target audience, e.g. 'P30M', 'P1H25M'.
public Or<Duration>? TimeRequired { get; set; }
/// The work that this work has been translated from. e.g. 物种起源 is a translationOf “On the Origin of Species” Inverse property: workTranslation.
public Or<CreativeWork>? TranslationOfWork { get; set; }
/// Organization or person who adapts a creative work to different languages, regional differences and technical requirements of a target market, or that translates during some event.
public Or<Organization, Person>? Translator { get; set; }
/// The typical expected age range, e.g. '7-9', '11-'.
public Or<string>? TypicalAgeRange { get; set; }
/// The version of the CreativeWork embodied by a specified resource.
public Or<double, string>? Version { get; set; }
/// An embedded video object.
public Or<VideoObject>? Video { get; set; }
/// Example/instance/realization/derivation of the concept of this creative work. eg. The paperback edition, first edition, or eBook. Inverse property: exampleOfWork.
public Or<CreativeWork>? WorkExample { get; set; }
/// A work that is a translation of the content of this work. e.g. 西遊記 has an English workTranslation “Journey to the West”,a German workTranslation “Monkeys Pilgerfahrt” and a Vietnamese translation Tây du ký bình khảo. Inverse property: translationOfWork.
public Or<CreativeWork>? WorkTranslation { get; set; }
/// An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
public Or<Uri>? AdditionalType { get; set; }
/// An alias for the item.
public Or<string>? AlternateName { get; set; }
/// A description of the item.
public Or<string>? Description { get; set; }
/// A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.
public Or<string>? DisambiguatingDescription { get; set; }
/// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details.
public Or<PropertyValue, string, Uri>? Identifier { get; set; }
/// An image of the item. This can be a URL or a fully described ImageObject.
public Or<ImageObject, Uri>? Image { get; set; }
/// Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details. Inverse property: mainEntity.
public Or<CreativeWork, Uri>? MainEntityOfPage { get; set; }
/// The name of the item.
public Or<string>? Name { get; set; }
/// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
public Or<Action>? PotentialAction { get; set; }
/// URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.
public Or<Uri>? SameAs { get; set; }
/// A CreativeWork or Event about this Thing.. Inverse property: about.
public Or<CreativeWork, Event>? SubjectOf { get; set; }
/// URL of the item.
public Or<Uri>? Url { get; set; }
}
}
| 63.280654 | 427 | 0.695875 | [
"MIT"
] | jefersonsv/SeoSchema | src/SeoSchema/Entities/MusicVideoObject.cs | 23,261 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.