content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VHVisualisation
{
public class ImageExtractor
{
string path;
List<Result> loaded;
Size imgSize = new Size(64, 48);
public static Image ResizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
public ImageExtractor(string path)
{
this.path = path;
loaded = new List<Result>();
ReadAll(Directory.GetFiles(path, "*.JPG"));
}
public ImageExtractor(IEnumerable<string> files)
{
//this.path = path;
loaded = new List<Result>();
ReadAll(files);
}
private void ReadAll(IEnumerable<string> files)
{
Parallel.ForEach(files, (imgPath) =>
{
string tempPath = imgPath + ".temp";
Result res = null;
if (File.Exists(tempPath))
{
res = ReadFromBinaryFile<Result>(tempPath);
}
else if (File.Exists(imgPath) && imgPath.EndsWith(".temp"))
{
res = ReadFromBinaryFile<Result>(imgPath);
}
else if (imgPath.EndsWith("jpg") || imgPath.EndsWith("JPG"))
{
using (Image image = Image.FromFile(imgPath))
{
//Frame Frame = new Frame(image);
res = new Result(ResizeImage(image, imgSize), imgPath);
//ci++;
}
WriteToBinaryFile<Result>(tempPath, res, false);
}
else
{
//MessageBoxResult mbr = MessageBox.Show("File format not supported.");
}
loaded.Add(res);
});
}
public Result[] GetResArr()
{
return loaded.ToArray();
}
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the XML file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
}
}
| 38.66055 | 152 | 0.534884 | [
"MIT"
] | ixometac/VHVisualization | SearchEngine/ImageExtractor.cs | 4,216 | C# |
using Khernet.UI.IoC;
using System;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Linq;
namespace Khernet.UI.Cache
{
public class ChatCache : IChatList
{
/// <summary>
/// Contains the chat list of users.
/// </summary>
private ConcurrentDictionary<UserChatContext, ObservableCollection<ChatMessageItemViewModel>> messageList;
/// <summary>
/// Adds a chat list for given token.
/// </summary>
/// <param name="token">The token of user.</param>
/// <param name="chatList">The chat list.</param>
public void AddChatList(UserItemViewModel user)
{
if (user == null)
throw new ArgumentException($"Parameter {nameof(user)} cannot be null");
if (messageList == null)
messageList = new ConcurrentDictionary<UserChatContext, ObservableCollection<ChatMessageItemViewModel>>();
UserChatContext chatContext = new UserChatContext(user);
ObservableCollection<ChatMessageItemViewModel> chatList = new ObservableCollection<ChatMessageItemViewModel>();
messageList.AddOrUpdate(chatContext, chatList, UpdateChatList);
}
/// <summary>
/// Verify if list should be updated or added.
/// </summary>
/// <param name="token">The context of user.</param>
/// <param name="chatList">The chat list.</param>
/// <returns></returns>
private ObservableCollection<ChatMessageItemViewModel> UpdateChatList(UserChatContext chatContext, ObservableCollection<ChatMessageItemViewModel> chatList)
{
return chatList;
}
/// <summary>
/// Get a chat list for given token.
/// </summary>
/// <param name="token">The token of user.</param>
/// <returns>The chat list.</returns>
public ObservableCollection<ChatMessageItemViewModel> GetChat(UserItemViewModel user)
{
if (messageList == null)
return null;
var chatList = messageList.FirstOrDefault((chatContext) => { return chatContext.Key.User == user; });
return chatList.Value;
}
public ObservableCollection<ChatMessageItemViewModel> GetChat(string token)
{
if (messageList == null)
return null;
var chatList = messageList.FirstOrDefault((chatContext) => { return chatContext.Key.User.Token == token; });
return chatList.Value;
}
public UserChatContext GetUserContext(UserItemViewModel user)
{
if (messageList == null)
return null;
var userContext = messageList.FirstOrDefault((chatContext) => { return chatContext.Key.User == user; });
return userContext.Key;
}
/// <summary>
/// Clears the chat cache.
/// </summary>
public void Clear()
{
if (messageList != null)
messageList.Clear();
}
}
}
| 33.608696 | 163 | 0.602199 | [
"MIT"
] | lemalcs/Khernet | Khernet.UI/Khernet.UI.Presentation/Cache/ChatCache.cs | 3,094 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.ContractsLight;
using System.Linq.Expressions;
namespace BuildXL.Cache.ContentStore.Interfaces.Results
{
/// <summary>
/// Result of a failed operation.
/// </summary>
public class ErrorResult : ResultBase, IEquatable<ErrorResult>
{
/// <summary>
/// Original optional message provided via constructor.
/// </summary>
public string Message { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ErrorResult"/> class.
/// </summary>
public ErrorResult(string errorMessage, string diagnostics = null)
: base(errorMessage, diagnostics)
{
Contract.Requires(!string.IsNullOrEmpty(errorMessage));
Message = errorMessage;
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorResult" /> class.
/// </summary>
public ErrorResult(Exception exception, string message = null)
: base(exception, message)
{
Message = message;
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorResult" /> class.
/// </summary>
public ErrorResult(ResultBase other, string message = null)
: base(other, message)
{
Message = message;
}
/// <inheritdoc />
public override bool Succeeded => false;
/// <inheritdoc />
public bool Equals(ErrorResult other)
{
return EqualsBase(other) && other != null;
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return obj is ErrorResult other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
return ErrorMessage?.GetHashCode() ?? 0;
}
/// <inheritdoc />
public override string ToString()
{
return GetErrorString();
}
/// <summary>
/// Overloads & operator to behave as AND operator.
/// </summary>
public static ErrorResult operator &(ErrorResult result1, ErrorResult result2)
{
return new ErrorResult(
Merge(result1.ErrorMessage, result2.ErrorMessage, ", "),
Merge(result1.Diagnostics, result2.Diagnostics, ", "));
}
/// <summary>
/// Overloads | operator to behave as OR operator.
/// </summary>
public static ErrorResult operator |(ErrorResult result1, ErrorResult result2)
{
return new ErrorResult(
Merge(result1.ErrorMessage, result2.ErrorMessage, ", "),
Merge(result1.Diagnostics, result2.Diagnostics, ", "));
}
/// <summary>
/// Merges two strings.
/// </summary>
private static string Merge(string s1, string s2, string separator = null)
{
if (s1 == null)
{
return s2;
}
if (s2 == null)
{
return s1;
}
separator = separator ?? string.Empty;
return $"{s1}{separator}{s2}";
}
/// <summary>
/// Converts the error result to the given result type.
/// </summary>
public TResult AsResult<TResult>() where TResult : ResultBase
{
if (ErrorResultConverter<TResult>.TryGetConverter(out var converter, out string error))
{
return converter(this);
}
throw new InvalidOperationException(error);
}
private static class ErrorResultConverter<TResult>
where TResult : ResultBase
{
private static readonly Func<ErrorResult, TResult> Convert;
private static readonly string ErrorMessage;
static ErrorResultConverter()
{
// It is important to call this method from a static constructor
// and have another method that will just get the data from the fields
// to avoid expression generation every time.
TryGenerateConverter(out Convert, out ErrorMessage);
}
public static bool TryGetConverter(out Func<ErrorResult, TResult> result, out string errorMessage)
{
result = Convert;
errorMessage = ErrorMessage;
return result != null;
}
private static bool TryGenerateConverter(out Func<ErrorResult, TResult> result, out string errorMessage)
{
var errorResultParameter = Expression.Parameter(typeof(ErrorResult));
var type = typeof(TResult).Name;
// Generating the following constructor invocation:
// new TResult(other: errorResult)
var constructorInfo = typeof(TResult).GetConstructor(new[] { typeof(ResultBase), typeof(string) });
if (constructorInfo == null)
{
result = null;
errorMessage = $"Constructor '{type}(ResultBase, string)' is not defined for type '{type}'.";
return false;
}
try
{
var convertExpression = Expression.Lambda<Func<ErrorResult, TResult>>(
body: Expression.New(
constructor: constructorInfo,
arguments: new Expression[]
{
errorResultParameter,
Expression.Constant(null, typeof(string)),
}),
parameters: new[] { errorResultParameter });
result = convertExpression.Compile();
errorMessage = null;
return true;
}
catch (Exception e)
{
result = null;
errorMessage = $"Failed creating type converter to '{type}'. Exception: {e}";
return false;
}
}
}
}
}
| 35.544974 | 117 | 0.50387 | [
"MIT"
] | AzureMentor/BuildXL | Public/Src/Cache/ContentStore/Interfaces/Results/ErrorResult.cs | 6,718 | C# |
using AutoMapper;
using Sfa.Tl.Matching.Application.Mappers.Resolver;
using Sfa.Tl.Matching.Domain.Models;
using Sfa.Tl.Matching.Models.ViewModel;
namespace Sfa.Tl.Matching.Application.Mappers
{
public class ServiceStatusHistoryMapper : Profile
{
public ServiceStatusHistoryMapper()
{
CreateMap<ServiceStatusHistoryViewModel, ServiceStatusHistory>()
.ForMember(m => m.IsOnline, config => config.MapFrom(s => s.IsOnline))
.ForMember(m => m.CreatedBy, config => config.MapFrom<LoggedInUserNameResolver<ServiceStatusHistoryViewModel, ServiceStatusHistory>>())
.ForAllOtherMembers(config => config.Ignore());
}
}
} | 39.277778 | 151 | 0.695898 | [
"MIT"
] | SkillsFundingAgency/tl-matching | src/Sfa.Tl.Matching.Application/Mappers/ServiceStatusHistoryMapper.cs | 709 | C# |
using qBittorrentTray.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Reflection;
using System.Threading;
using System.Windows;
namespace qBittorrentTray
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
//private TaskbarIcon notifyIcon;
private Main main;
private static readonly string id = "{8F6F0AC4-B9A2-45fd-A8CF-72F03E7BDE5F}";
static Mutex mutex = new Mutex(true, id);
private Thread listen;
/// <summary>
/// Creates tray icon and starts listening for input.
/// </summary>
/// <param name="e"></param>
[STAThread]
protected override void OnStartup(StartupEventArgs e)
{
List<string> filePaths = new List<string>();
if (e.Args != null)
filePaths = new List<string>(e.Args);
// Exit application if already running.
if (!mutex.WaitOne(TimeSpan.Zero, true))
{
if (e.Args != null)
{
using (var client = new NamedPipeClientStream(id))
using (var writer = new BinaryWriter(client))
{
if (filePaths.Count != 0)
{
client.Connect(3000);
string filePathsString = "";
foreach (string filePath in filePaths)
filePathsString += filePath + "\n";
filePathsString = filePathsString.Remove(filePathsString.Length - 1);
writer.Write(filePathsString);
}
}
}
Current.Shutdown();
}
else
{
base.OnStartup(e);
main = new Main(new List<string>(e.Args));
listen = new Thread(() =>
{
while (true)
{
using (NamedPipeServerStream server = new NamedPipeServerStream(id))
{
server.WaitForConnection();
using (var reader = new BinaryReader(server))
{
string arguments = reader.ReadString();
filePaths = new List<string>(arguments.Split('\n'));
main.AddTorrents(filePaths);
}
}
}
});
listen.IsBackground = true;
listen.Start();
}
}
/// <summary>
/// Makes sure tray icon is removed when application exits.
/// </summary>
/// <param name="e"></param>
protected override void OnExit(ExitEventArgs e)
{
main.notifyIcon.Dispose();
base.OnExit(e);
}
}
} | 23.795918 | 79 | 0.607204 | [
"MIT"
] | teug91/qBittorrentTray | qBittorrentTray/App.xaml.cs | 2,334 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Modularity.Core.Configurations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Modularity.AspNetCore.Configuration
{
public static class ConfigurationExtensions
{
internal static ModularityOptions ModularityOptions { get; set; } = new ModularityOptions();
public static IMvcBuilder AddModularity(this IMvcBuilder builder, Action<ModularityOptions> action = null)
{
action?.Invoke(ModularityOptions);
AspNetCoreModulesManager.Current.LoadModules(ModularityOptions);
foreach (var module in AspNetCoreModulesManager.Current.Modules)
if (module.Assembly != null)
builder.AddApplicationPart(module.Assembly);
return builder;
}
public static IServiceCollection AddModuleServices(this IServiceCollection services, IConfiguration configuration)
{
foreach (var startup in AspNetCoreModulesManager.Current.ModuleStartups)
{
startup.Initialize(configuration);
startup.ConfigureServices(services);
}
return services;
}
public static IApplicationBuilder UseModulartiy(this IApplicationBuilder app, IWebHostEnvironment env)
{
foreach (var startup in AspNetCoreModulesManager.Current.ModuleStartups)
{
startup.Configure(app, env);
}
return app;
}
}
}
| 34.58 | 122 | 0.670908 | [
"MIT"
] | enisn/AspNetCore.Modularity | src/Modularity.AspNetCore/Configuration/ConfigurationExtensions.cs | 1,731 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Trollbridge.WebApi.Areas.HelpPage.ModelDescriptions
{
public class EnumTypeModelDescription : ModelDescription
{
public EnumTypeModelDescription()
{
Values = new Collection<EnumValueDescription>();
}
public Collection<EnumValueDescription> Values { get; private set; }
}
} | 27.466667 | 76 | 0.711165 | [
"Apache-2.0"
] | trollbridge/trollbridge-webapi | src/Trollbridge.WebApi/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs | 412 | C# |
using UnityEditor;
using UnityEngine;
namespace AutoCustomEditor
{
public class TextureAreaItemDrawer : SerializedPropertyItemDrawerBase
{
private float _width;
private float _height;
public TextureAreaItemDrawer(ItemParameter parameter, SerializedObject target) : base(parameter, target)
{
_width = GetValueFromIndex(parameter.Floats, 0);
_height = GetValueFromIndex(parameter.Floats, 1);
}
public override void Draw(GUICustomEditorState state)
{
if (_property == null)
{
return;
}
EditorGUILayout.ObjectField (_property, typeof(Texture), GUIContent.none, GUILayout.Width(_width + state.IntentLevel * 15f), GUILayout.Height(_height));
}
}
}
| 27.965517 | 164 | 0.638718 | [
"MIT"
] | Tanakancolle/AutoCustomEditor | Assets/GUICustomEditor/Editor/Item/ItemDrawer/SerializedPropertyItemDrawers/TextureAreaItemDrawer.cs | 813 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.CortexM3OnCMSISCore.Drivers
{
using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM3;
public abstract class InterruptController : ChipsetModel.Drivers.InterruptController
{
}
}
| 19.6 | 88 | 0.748299 | [
"MIT"
] | NETMF/llilum | Zelig/Zelig/RunTime/DeviceModels/CortexM3OnCMSIS-Core/HardwareModel/Drivers/InterruptController.cs | 296 | C# |
//
// HttpResponse.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Xamarin.WebTests.HttpFramework
{
public class HttpResponse : HttpMessage
{
public HttpStatusCode StatusCode {
get; private set;
}
public string StatusMessage {
get; private set;
}
public bool IsSuccess {
get { return StatusCode == HttpStatusCode.OK; }
}
public bool? KeepAlive {
get { return keepAlive; }
set {
if (responseWritten)
throw new InvalidOperationException ();
if (!value.HasValue)
throw new InvalidOperationException ();
keepAlive = value.Value;
}
}
bool? keepAlive;
bool responseWritten;
public HttpResponse (HttpStatusCode status, HttpContent content = null)
{
Protocol = HttpProtocol.Http11;
StatusCode = status;
StatusMessage = status.ToString ();
Body = content;
}
public HttpResponse (HttpStatusCode status, HttpProtocol protocol, string statusMessage, HttpContent content = null)
{
Protocol = protocol;
StatusCode = status;
StatusMessage = statusMessage;
Body = content;
}
HttpResponse ()
: base ()
{
}
internal static async Task<HttpResponse> Read (HttpStreamReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested ();
try {
var response = new HttpResponse ();
await response.InternalRead (reader, cancellationToken).ConfigureAwait (false);
return response;
} catch (Exception ex) {
return CreateError (ex);
}
}
void CheckHeaders ()
{
if (Body != null)
Body.AddHeadersTo (this);
if (Protocol == HttpProtocol.Http11 && !Headers.ContainsKey ("Connection"))
AddHeader ("Connection", (KeepAlive ?? false) ? "keep-alive" : "close");
}
public static bool ParseResponseHeader (string header, out HttpProtocol protocol, out HttpStatusCode status)
{
var fields = header.Split (new char[] { ' ' }, StringSplitOptions.None);
if (fields.Length < 2) {
protocol = HttpProtocol.Http10;
status = HttpStatusCode.InternalServerError;
return false;
}
try {
protocol = ProtocolFromString (fields [0]);
status = (HttpStatusCode)int.Parse (fields [1]);
return true;
} catch {
protocol = HttpProtocol.Http10;
status = HttpStatusCode.InternalServerError;
return false;
}
}
async Task InternalRead (HttpStreamReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested ();
var header = await reader.ReadLineAsync (cancellationToken).ConfigureAwait (false);
var fields = header.Split (new char[] { ' ' }, StringSplitOptions.None);
if (fields.Length < 2 || fields.Length > 3)
throw new InvalidOperationException ();
Protocol = ProtocolFromString (fields [0]);
StatusCode = (HttpStatusCode)int.Parse (fields [1]);
StatusMessage = fields.Length == 3 ? fields [2] : string.Empty;
cancellationToken.ThrowIfCancellationRequested ();
await ReadHeaders (reader, cancellationToken);
cancellationToken.ThrowIfCancellationRequested ();
Body = await ReadBody (reader, cancellationToken);
}
public async Task Write (StreamWriter writer, CancellationToken cancellationToken)
{
CheckHeaders ();
responseWritten = true;
cancellationToken.ThrowIfCancellationRequested ();
var message = StatusMessage ?? ((HttpStatusCode)StatusCode).ToString ();
await writer.WriteAsync (string.Format ("{0} {1} {2}\r\n", ProtocolToString (Protocol), (int)StatusCode, message));
await WriteHeaders (writer, cancellationToken);
if (Body != null)
await Body.WriteToAsync (writer);
await writer.FlushAsync ();
}
public static HttpResponse CreateSimple (HttpStatusCode status, string body = null)
{
return new HttpResponse (status, body != null ? new StringContent (body) : null);
}
public static HttpResponse CreateRedirect (HttpStatusCode code, Uri uri)
{
var response = new HttpResponse (code);
response.AddHeader ("Location", uri);
return response;
}
public static HttpResponse CreateSuccess (string body = null)
{
return new HttpResponse (HttpStatusCode.OK, body != null ? new StringContent (body) : null);
}
public static HttpResponse CreateError (string message, params object[] args)
{
return new HttpResponse (HttpStatusCode.InternalServerError, new StringContent (string.Format (message, args)));
}
public static HttpResponse CreateError (Exception error)
{
return new HttpResponse (HttpStatusCode.InternalServerError, new StringContent (string.Format ("Got exception: {0}", error)));
}
public override string ToString ()
{
return string.Format ("[HttpResponse: StatusCode={0}, StatusMessage={1}, Body={2}]", StatusCode, StatusMessage, Body);
}
}
}
| 31.227979 | 129 | 0.717604 | [
"MIT"
] | stefb965/web-tests | Xamarin.WebTests.Framework/Xamarin.WebTests.HttpFramework/HttpResponse.cs | 6,031 | C# |
// © 2021 Steve Cheng.
// See LICENSE.txt for copyright licensing of this work.
using System;
using System.Runtime.CompilerServices;
namespace GoldSaucer.BTree
{
internal static partial class BTreeCore
{
/// <summary>
/// Delete an entry at the given index in a node without regard to the number
/// of entries remaining.
/// </summary>
/// <param name="node">The node to delete the entry from. </param>
/// <param name="deleteIndex">The index of the entry to delete. </param>
/// <param name="numEntries">The variable holding the number of active entries
/// in the node; it will be decremented by one. </param>
public static void DeleteEntryWithinNode<TKey, TValue>(Entry<TKey, TValue>[] node,
int deleteIndex,
ref int numEntries)
{
var entries = node.AsSpan();
entries[(deleteIndex + 1)..numEntries].CopyTo(entries[deleteIndex..]);
entries[--numEntries] = default;
}
/// <summary>
/// Delete an entry from a node, and then shift entries with a neighboring
/// node.
/// </summary>
/// <param name="leftNode">The left node in this operation: the
/// node whose entries has keys that immediately
/// precede those of the right node.
/// </param>
/// <param name="rightNode">The right node in this operation:
/// the node whose entries has keys that immediately
/// follow those of the left node. It necessarily must be at
/// the same level of the B+Tree as the left node.
/// </param>
/// <param name="leftEntriesCount">The number of active entries
/// in the left node. Will be updated when this method returns.
/// </param>
/// <param name="rightEntriesCount">The number of active entries
/// in the right node. Will be updated when this method returns.</param>
/// <param name="deleteIndex">The index of the one entry to delete,
/// from the left node if <paramref name="deleteFromLeft" /> is true,
/// otherwise from the right node. This index must refer to an active
/// entry slot for the containing node.
/// </param>
/// <param name="shiftIndex">If non-negative, this parameter
/// is the number of entries to shift from the other node to the
/// node that has one existing entry deleted. If negative,
/// the node that has its one existing entry deleted will have
/// the rest of its entries shifted to the other node.
/// </param>
/// <param name="deleteFromLeft">Whether to delete the entry
/// to delete is in the left node or right node.
/// </param>
/// <param name="pivotKey">
/// The final comparison key in the B+Tree that separates the left
/// node from the right node. This key is present in the closest
/// common ancestor node of the left and right nodes. As the entries
/// are shifted and deleted between the left and right nodes,
/// a new key will be promoted to be the pivot key. At the same
/// time the old pivot key will be demoted and stored into either
/// the left or right node.
/// </param>
/// <returns>
/// The index of the entry that follows the one being deleted,
/// after re-balancing its containing node. If <paramref name="shiftIndex" />
/// is negative, the index is for the neighboring node which now
/// contains all the entries of the node that the entry was being
/// deleted from. This index is used to update <see cref="BTreePath" />
/// to remain valid after deletion of the entry.
/// </returns>
public static int DeleteEntryAndShift<TKey, TValue>(Entry<TKey, TValue>[] leftNode,
Entry<TKey, TValue>[] rightNode,
ref int leftEntriesCount,
ref int rightEntriesCount,
ref TKey pivotKey,
int deleteIndex,
int shiftIndex,
bool deleteFromLeft)
{
var leftEntries = leftNode.AsSpan();
var rightEntries = rightNode.AsSpan();
int movedCount;
int nextIndex;
// Copy values locally to help compiler optimize
int leftCount = leftEntriesCount;
int rightCount = rightEntriesCount;
if (deleteFromLeft)
{
if (shiftIndex >= 0) // delete from left and shift from right
{
// Delete entry from left
leftEntries[(deleteIndex + 1)..leftCount].CopyTo(leftEntries[deleteIndex..]);
// Move entries from right to left
rightEntries[0..shiftIndex].CopyTo(leftEntries[(leftCount - 1)..]);
rightEntries[shiftIndex..rightCount].CopyTo(rightEntries[0..]);
rightEntries[(rightCount - shiftIndex)..rightCount].Clear();
// Update counts
movedCount = shiftIndex;
leftEntriesCount = (leftCount += movedCount - 1);
rightEntriesCount = (rightCount -= movedCount);
}
else // delete from left and shift to right
{
movedCount = leftCount - 1;
// Make room in the right node for the entries to be shifted from the left
rightEntries[0..rightCount].CopyTo(rightEntries[movedCount..]);
// Move all entries from the left node to the right except the one being deleted
leftEntries[0..deleteIndex].CopyTo(rightEntries);
leftEntries[(deleteIndex + 1)..leftCount].CopyTo(rightEntries[deleteIndex..]);
// Update counts
leftEntriesCount = (leftCount = 0);
rightEntriesCount = (rightCount += movedCount);
}
nextIndex = deleteIndex;
}
else
{
if (shiftIndex >= 0) // delete from right and shift from left
{
movedCount = leftCount - shiftIndex;
// Make room in the right node for the entries to be shifted from
// the left, and at the same time delete the entry at rightIndex.
rightEntries[(deleteIndex + 1)..rightCount].CopyTo(rightEntries[(movedCount + deleteIndex)..]);
rightEntries[0..deleteIndex].CopyTo(rightEntries[movedCount..]);
// Move in entries from the left node to the right node.
var movedEntries = leftEntries[shiftIndex..leftCount];
movedEntries.CopyTo(rightEntries);
movedEntries.Clear();
// Update counts
nextIndex = movedCount + deleteIndex;
leftEntriesCount = (leftCount -= movedCount);
rightEntriesCount = (rightCount += movedCount - 1);
}
else // delete from right and shift to left
{
rightEntries[0..deleteIndex].CopyTo(leftEntries[leftCount..]);
rightEntries[(deleteIndex + 1)..rightCount].CopyTo(leftEntries[(leftCount + deleteIndex)..]);
// Update counts
movedCount = rightCount - 1;
nextIndex = leftCount + deleteIndex;
leftEntriesCount = (leftCount += movedCount);
rightEntriesCount = (rightCount = 0);
}
}
// After shifting entries for interior nodes, rotate the pivot key
// present in the parent node.
if (typeof(TValue) == typeof(NodeLink))
{
if (deleteFromLeft == (shiftIndex < 0))
{
// The old pivot is demoted to the slot in the right node just
// after the entries that were moved from the left node.
rightEntries[movedCount].Key = pivotKey;
}
else
{
// The old pivot key is demoted to the slot in the left node
// that comes from the left-most slot in the right node.
leftEntries[leftCount - movedCount].Key = pivotKey;
}
// The new pivot is the left-most key whose associated link
// now appears as the left-most child of the right node.
ref var slot0Key = ref rightEntries[0].Key;
pivotKey = slot0Key;
slot0Key = default!;
}
// After shifting entries for leaf nodes, if the left node is
// not to be deleted afterwards, update the pivot key between
// the left and right nodes to be the last key in the left node.
//
// If the left node is to be deleted (leftEntriesCount == 0), the
// pivot key should be updated to the same as the pivot key between
// the left node and its preceding node (which must exist according
// to the overall algorithm for deletion). But this function does
// not have access to that key, so we skip handling that case here.
else if (leftEntriesCount > 0)
{
pivotKey = leftEntries[leftCount - 1].Key;
}
return nextIndex;
}
/// <summary>
/// Delete an entry in a node of the B+Tree, and re-balance or merge
/// entries from a neighbor as necessary.
/// </summary>
/// <param name="deleteIndex">
/// The index of the entry to delete from the target node.
/// </param>
/// <param name="nodeLink">
/// Refers to the entry for the target node in its parent node.
/// </param>
/// <param name="leftNeighbor">
/// The left neigbhor to the target node, <paramref name="nodeLink"/>,
/// or null if it does not exist.
/// </param>
/// <param name="rightNeighbor">
/// The right neighbor to the target node, <paramref name="nodeLink"/>,
/// or null if it does not exist.
/// </param>
/// <param name="leftPivotKey">
/// Reference to the slot holding the left pivot key to the target node,
/// or null if it does not exist.
/// </param>
/// <param name="rightPivotKey">
/// Reference to the slot holding the right pivot key to the target node,
/// or null if it does not exist.
/// </param>
/// <param name="leftNeighborHasSameParent">
/// Set to true when the left neighbor exists and has the same
/// parent as the current node. This flag is needed to decide
/// whether to merge entries with the left or right neighbor
/// when recursive deletion happens.
/// </param>
/// <param name="nextIndex">
/// The index of the entry that follows the one being deleted,
/// after re-balancing its containing node. If this function returns
/// true, the containing node of the entry is being deleted also,
/// so the index is for the neighboring node,
/// left if <paramref name="leftNeighborHasSameParent"/> is true,
/// or right otherwise. This index is used to update <see cref="BTreePath" />
/// to remain valid after deletion of the entry.
/// </param>
/// <returns>
/// Whether the entry for the current node needs to be deleted
/// from its parent, because it has merged with a neighbor.
/// </returns>
public static bool DeleteEntryAndRebalanceOneLevel<TKey, TValue>(int deleteIndex,
ref NodeLink nodeLink,
ref NodeLink leftNeighbor,
ref NodeLink rightNeighbor,
ref TKey leftPivotKey,
ref TKey rightPivotKey,
bool leftNeighborHasSameParent,
out int nextIndex)
{
ref var numEntries = ref nodeLink.EntriesCount;
var currentNode = (Entry<TKey, TValue>[])nodeLink.Child!;
var halfLength = (currentNode.Length + 1) >> 1;
// If there are enough entries remaining in the target node, it does not need
// to be re-balanced after deleting the entry.
if (numEntries > halfLength)
{
DeleteEntryWithinNode(currentNode, deleteIndex, ref numEntries);
nextIndex = deleteIndex;
return false;
}
// Check the left neighbor or right neighbor if it has surplus entries.
// If so, make it donate those entries to the target node.
if (!Unsafe.IsNullRef(ref leftNeighbor) && leftNeighbor.EntriesCount > halfLength)
{
nextIndex = DeleteEntryAndShift((Entry<TKey, TValue>[])leftNeighbor.Child!,
currentNode,
ref leftNeighbor.EntriesCount,
ref numEntries,
ref leftPivotKey,
deleteIndex,
shiftIndex: leftNeighbor.EntriesCount - halfLength,
deleteFromLeft: false);
return false;
}
else if (!Unsafe.IsNullRef(ref rightNeighbor) && rightNeighbor.EntriesCount > halfLength)
{
nextIndex = DeleteEntryAndShift(currentNode,
(Entry<TKey, TValue>[])rightNeighbor.Child!,
ref numEntries,
ref rightNeighbor.EntriesCount,
ref rightPivotKey,
deleteIndex,
shiftIndex: rightNeighbor.EntriesCount - halfLength,
deleteFromLeft: true);
return false;
}
// At this point, all neighbors have too few nodes. Pick the
// neighbor that has the same parent as the target node, which
// must exist, and merge the target node with it. The neighbor
// remains while the target node shall be deleted from its parent.
if (leftNeighborHasSameParent)
{
nextIndex = DeleteEntryAndShift((Entry<TKey, TValue>[])leftNeighbor.Child!,
currentNode,
ref leftNeighbor.EntriesCount,
ref numEntries,
ref leftPivotKey,
deleteIndex,
shiftIndex: -1,
deleteFromLeft: false);
}
else
{
nextIndex = DeleteEntryAndShift(currentNode,
(Entry<TKey, TValue>[])rightNeighbor.Child!,
ref numEntries,
ref rightNeighbor.EntriesCount,
ref rightPivotKey,
deleteIndex,
shiftIndex: -1,
deleteFromLeft: true);
}
return true;
}
}
public partial class BTree<TKey, TValue>
{
/// <summary>
/// Delete the entry in the B+Tree indicated by the given path,
/// and re-balance, recursively, the B+Tree's nodes as necessary.
/// </summary>
/// <remarks>
/// A recursive implementation is necessary to compute the
/// left and right neighbors efficiently as we re-balance the
/// B+Tree, possibly at multiple levels.
/// </remarks>
/// <param name="path">The path to an entry to the leaf node to delete. </param>
/// <param name="level">The current level of the B+Tree being worked on
/// in this recursive method. Initialize at zero to start the recursion.
/// It increases by one for each recursive call, until the depth of the
/// B+Tree is reached, for the "base case".
/// </param>
/// <param name="nodeLink">
/// Points to the node which is along the path, at the given level.
/// Initialize to the root node.
/// </param>
/// <param name="leftNeighbor">
/// The left neigbhor to the current node being worked on, <paramref name="nodeLink"/>.
/// The left neighbor of a node is defined as the node at the same
/// level in the B+Tree that holds the immediately preceding keys.
/// It must exist unless the specified node contains the very first
/// key, for the given level of the B+Tree. Initialize to null.
/// </param>
/// <param name="rightNeighbor">
/// The right neighbor to the current node being worked on, <paramref name="nodeLink"/>.
/// The right neighbor of a node is defined as the node at the same
/// level in the B+Tree that holds the immediately following keys.
/// It must exist unless the specified node contains the very last
/// key, for the given level of the B+Tree. Initialize to null
/// to start the recursion.
/// </param>
/// <param name="leftPivotKey">
/// Reference to the slot holding the left pivot key,
/// defined as the last key in the B+Tree that is compared
/// to select the current node versus its left neighbor.
/// It exists when the left neighbor exists. Initialize to null
/// to start the recursion.
/// </param>
/// <param name="rightPivotKey">
/// Reference to the slot holding the right pivot key,
/// defined as the last key in the B+Tree that is compared
/// to select the current node versus its right neighbor.
/// It exists when the right neighbor exists. Initialize to null
/// to start the recursion.
/// </param>
/// <param name="leftNeighborHasSameParent">
/// Set to true when the left neighbor exists and has the same
/// parent as the current node. This flag is needed to decide
/// whether to merge entries with the left or right neighbor
/// when recursive deletion happens.
/// </param>
/// <returns>
/// Whether the entry for the current node needs to be deleted
/// from its parent, when "coming back up" from the recursion.
/// </returns>
internal bool DeleteEntryAndRecursivelyRebalance(ref BTreePath path,
int level,
ref NodeLink nodeLink,
ref NodeLink leftNeighbor,
ref NodeLink rightNeighbor,
ref TKey leftPivotKey,
ref TKey rightPivotKey,
bool leftNeighborHasSameParent)
{
ref var step = ref path[level];
int deleteIndex = step.Index;
// We reached the level of the leaf nodes.
if (level == path.Depth)
{
if (level > 0)
{
bool deleteInParent = BTreeCore.DeleteEntryAndRebalanceOneLevel<TKey, TValue>(
deleteIndex,
ref nodeLink,
ref leftNeighbor,
ref rightNeighbor,
ref leftPivotKey,
ref rightPivotKey,
leftNeighborHasSameParent,
out step.Index);
if (deleteInParent)
step.Node = leftNeighborHasSameParent ? leftNeighbor.Child
: rightNeighbor.Child;
return deleteInParent;
}
else
{
// A leaf root node never re-balances.
var rootLeafNode = AsLeafNode(nodeLink.Child!);
BTreeCore.DeleteEntryWithinNode(rootLeafNode,
deleteIndex,
ref nodeLink.EntriesCount);
path[level].Index = deleteIndex;
}
}
// This level of the B+Tree holds interior nodes.
else
{
var currentNode = BTreeCore.AsInteriorNode<TKey>(nodeLink.Child!);
// Compute the left neighbor for the node one level down the path.
// It is the left sibling if one exists. If not, then it is found
// by following the right-most link under the current node's left neighbor.
// If the current node is along the left-most path possible in the B+Tree,
// then the left neighbor remains null.
ref NodeLink nextLeftNeighbor = ref (
deleteIndex > 0 ? ref currentNode[deleteIndex - 1].Value :
ref (!Unsafe.IsNullRef(ref leftNeighbor)
? ref BTreeCore.AsInteriorNode<TKey>(leftNeighbor.Child!)[leftNeighbor.EntriesCount - 1].Value
: ref Unsafe.NullRef<NodeLink>())
);
// Compute the left neighbor for the node one level down the path.
// It is the right sibling if one exists. If not, then it is found
// by following the left-most link under the current node's right neighbor.
// If the current node is along the right-most path possible in the B+Tree,
// then the right neighbor remains null.
ref NodeLink nextRightNeigbor = ref (
deleteIndex + 1 < nodeLink.EntriesCount ? ref currentNode[deleteIndex + 1].Value :
ref (!Unsafe.IsNullRef(ref rightNeighbor)
? ref BTreeCore.AsInteriorNode<TKey>(rightNeighbor.Child!)[0].Value
: ref Unsafe.NullRef<NodeLink>())
);
// Locate the left pivot key for the node one level down the path.
// It is obviously the key between the next node and its left sibling, if the
// latter exists; otherwise the left pivot key stays where it is currently.
ref TKey nextLeftPivotKey = ref (
deleteIndex > 0 ? ref currentNode[deleteIndex].Key
: ref leftPivotKey
);
// Locate the right pivot key for the node one level down the path.
// It is obviously the key between the next node and its right sibling, if the
// latter exists; otherwise the right pivot key stays where it is currently.
ref TKey nextRightPivotKey = ref (
deleteIndex + 1 < nodeLink.EntriesCount ? ref currentNode[deleteIndex + 1].Key
: ref rightPivotKey
);
// Recursively process for the next level in the B+Tree.
bool deleteHere = DeleteEntryAndRecursivelyRebalance(
ref path,
level + 1,
ref currentNode[deleteIndex].Value,
ref nextLeftNeighbor,
ref nextRightNeigbor,
ref nextLeftPivotKey,
ref nextRightPivotKey,
leftNeighborHasSameParent: deleteIndex > 0);
if (deleteHere)
{
// Delete the current node as we come back up from the recursion,
// if the B+Tree node at the next lower level in the path
// had just merged with a neighbor.
if (level > 0)
{
bool deleteInParent = BTreeCore.DeleteEntryAndRebalanceOneLevel<TKey, NodeLink>
(deleteIndex,
ref nodeLink,
ref leftNeighbor,
ref rightNeighbor,
ref leftPivotKey,
ref rightPivotKey,
leftNeighborHasSameParent,
out int nextIndex);
// If the node one level below in the path has been merged with its
// left neighbor, as determined by the condition deleteIndex > 0
// above, then the updated index of the path at this level must be
// moved back once. In that case, since the left neighbor
// could not have been empty, nextIndex must be greater than zero.
//
// In the opposite case, that is the node one level below is being
// merged with its right neighbor, then since that right neighbor
// exists with the same parent (being the current node),
// nextIndex will necessarily not exceed nodeLink.EntriesCount.
step.Index = (deleteIndex > 0) ? nextIndex - 1 : nextIndex;
// If the node at this level is to be merged with its left
// or right neighbors, re-set the node reference in BTreePath.
if (deleteInParent)
step.Node = leftNeighborHasSameParent ? leftNeighbor.Child
: rightNeighbor.Child;
return deleteInParent;
}
// An interior root node has no neighbors to re-balance against,
// but it can collapse when it has only one child left.
else
{
BTreeCore.DeleteEntryWithinNode(currentNode,
deleteIndex,
ref nodeLink.EntriesCount);
// Similar indexing as for interior, non-root nodes.
step.Index = (deleteIndex > 0) ? deleteIndex - 1 : 0;
if (nodeLink.EntriesCount == 1)
{
_root = currentNode[0].Value;
Depth--;
// Delete the first step, for the old root node, in the path
path.DecreaseDepth();
}
}
}
}
return false;
}
/// <summary>
/// Delete the entry pointed to by a path in the B+Tree.
/// </summary>
/// <param name="path">Path pointing to the entry to delete. </param>
internal void DeleteAtPath(ref BTreePath path)
{
int version = ++_version;
DeleteEntryAndRecursivelyRebalance(ref path, 0, ref _root,
ref Unsafe.NullRef<NodeLink>(),
ref Unsafe.NullRef<NodeLink>(),
ref Unsafe.NullRef<TKey>(),
ref Unsafe.NullRef<TKey>(),
false);
path.Version = version;
Count--;
}
/// <summary>
/// Remove the (first) entry with the given key, if it exists.
/// </summary>
/// <param name="key">The key of the entry to remove. </param>
/// <returns>Whether the entry with the key existed (and has been removed). </returns>
internal bool DeleteByKey(TKey key)
{
var path = NewPath();
try
{
if (FindKey(key, false, ref path))
{
DeleteAtPath(ref path);
return true;
}
return false;
}
finally
{
path.Dispose();
}
}
}
}
| 52.309365 | 119 | 0.478182 | [
"MIT"
] | SteveKCheng/BTreeDotNet | BTree/BTree.Delete.cs | 31,284 | C# |
namespace Teference.Zoho.Api
{
#region Namespace
using Newtonsoft.Json;
#endregion
internal sealed class ZsAddonJson : ZsErrorJson
{
[JsonProperty("addon")]
public ZsAddon Addon { get; set; }
}
} | 17.071429 | 51 | 0.627615 | [
"MIT"
] | teference/zoho-dotnet | source/Zoho.Api/Internals/ZsAddonJson.cs | 241 | C# |
using System.Diagnostics;
namespace DataGridExtensions
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Threading;
using JetBrains.Annotations;
/// <summary>
/// This class is the control hosting all information needed for filtering of one column.
/// Filtering is enabled by simply adding this control to the header template of the DataGridColumn.
/// </summary>
/// <seealso cref="System.Windows.Controls.Control" />
/// <seealso cref="System.ComponentModel.INotifyPropertyChanged" />
public class DataGridFilterColumnControl : Control, INotifyPropertyChanged
{
[NotNull]
private static readonly BooleanToVisibilityConverter _booleanToVisibilityConverter = new BooleanToVisibilityConverter();
[NotNull]
private static readonly ControlTemplate _emptyControlTemplate = new ControlTemplate();
/// <summary>
/// The active filter for this column.
/// </summary>
[CanBeNull]
private IContentFilter _activeFilter;
static DataGridFilterColumnControl()
{
// ReSharper disable once AssignNullToNotNullAttribute
var templatePropertyDescriptor = DependencyPropertyDescriptor.FromProperty(TemplateProperty, typeof(Control));
if (templatePropertyDescriptor != null)
templatePropertyDescriptor.DesignerCoerceValueCallback = Template_CoerceValue;
}
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:DataGridExtensions.DataGridFilterColumnControl" /> class.
/// </summary>
public DataGridFilterColumnControl()
{
Loaded += Self_Loaded;
Unloaded += Self_Unloaded;
Focusable = false;
DataContext = this;
}
private void Self_Loaded([NotNull] object sender, [NotNull] RoutedEventArgs e)
{
if (FilterHost == null)
{
// Find the ancestor column header and data grid controls.
ColumnHeader = this.FindAncestorOrSelf<DataGridColumnHeader>();
DataGrid = ColumnHeader?.FindAncestorOrSelf<DataGrid>() ?? throw new InvalidOperationException("DataGridFilterColumnControl must be a child element of a DataGridColumnHeader.");
// Find our host and attach ourself.
FilterHost = DataGrid.GetFilter();
}
FilterHost.AddColumn(this);
// ReSharper disable PossibleNullReferenceException
DataGrid.SourceUpdated += DataGrid_SourceOrTargetUpdated;
DataGrid.TargetUpdated += DataGrid_SourceOrTargetUpdated;
DataGrid.RowEditEnding += DataGrid_RowEditEnding;
// ReSharper restore PossibleNullReferenceException
// Must set a non-null empty template here, else we won't get the coerce value callback when the columns attached property is null!
Template = _emptyControlTemplate;
// Bind our IsFilterVisible and Template properties to the corresponding properties attached to the
// DataGridColumnHeader.Column property. Use binding instead of simple assignment since columnHeader.Column is still null at this point.
var isFilterVisiblePropertyPath = new PropertyPath("Column.(0)", DataGridFilterColumn.IsFilterVisibleProperty);
// ReSharper disable once AssignNullToNotNullAttribute
BindingOperations.SetBinding(this, VisibilityProperty, new Binding() { Path = isFilterVisiblePropertyPath, Source = ColumnHeader, Mode = BindingMode.OneWay, Converter = _booleanToVisibilityConverter });
var templatePropertyPath = new PropertyPath("Column.(0)", DataGridFilterColumn.TemplateProperty);
// ReSharper disable once AssignNullToNotNullAttribute
BindingOperations.SetBinding(this, TemplateProperty, new Binding() { Path = templatePropertyPath, Source = ColumnHeader, Mode = BindingMode.OneWay });
var filterPropertyPath = new PropertyPath("Column.(0)", DataGridFilterColumn.FilterProperty);
BindingOperations.SetBinding(this, FilterProperty, new Binding() { Path = filterPropertyPath, Source = ColumnHeader, Mode = BindingMode.TwoWay });
}
private void Self_Unloaded([NotNull] object sender, [NotNull] RoutedEventArgs e)
{
// Detach from host.
// Must check for null, unloaded event might be raised even if no loaded event has been raised before!
FilterHost?.RemoveColumn(this);
var dataGrid = DataGrid;
if (dataGrid != null)
{
dataGrid.SourceUpdated -= DataGrid_SourceOrTargetUpdated;
dataGrid.TargetUpdated -= DataGrid_SourceOrTargetUpdated;
dataGrid.RowEditEnding -= DataGrid_RowEditEnding;
}
// Clear all bindings generated during load.
// ReSharper disable once AssignNullToNotNullAttribute
BindingOperations.ClearBinding(this, VisibilityProperty);
// ReSharper disable once AssignNullToNotNullAttribute
BindingOperations.ClearBinding(this, TemplateProperty);
BindingOperations.ClearBinding(this, FilterProperty);
}
private void DataGrid_SourceOrTargetUpdated([NotNull] object sender, [NotNull] DataTransferEventArgs e)
{
if (e.Property == ItemsControl.ItemsSourceProperty)
{
ValuesUpdated();
}
}
private void DataGrid_RowEditEnding([NotNull] object sender, [NotNull] DataGridRowEditEndingEventArgs e)
{
this.BeginInvoke(DispatcherPriority.Background, ValuesUpdated);
}
/// <summary>
/// The user provided filter (IFilter) or content (usually a string) used to filter this column.
/// If the filter object implements IFilter, it will be used directly as the filter,
/// else the filter object will be passed to the content filter.
/// </summary>
[CanBeNull]
public object Filter
{
get => GetValue(FilterProperty);
set => SetValue(FilterProperty, value);
}
/// <summary>
/// Identifies the Filter dependency property
/// </summary>
[NotNull]
public static readonly DependencyProperty FilterProperty =
// ReSharper disable once PossibleNullReferenceException
DependencyProperty.Register("Filter", typeof(object), typeof(DataGridFilterColumnControl), new FrameworkPropertyMetadata(null, (sender, e) => ((DataGridFilterColumnControl)sender).Filter_Changed(e.NewValue)));
private void Filter_Changed([CanBeNull] object newValue)
{
// Update the effective filter. If the filter is provided as content, the content filter will be recreated when needed.
_activeFilter = newValue as IContentFilter;
// Notify the filter to update the view.
FilterHost?.OnFilterChanged();
}
[CanBeNull]
private static object Template_CoerceValue([NotNull] DependencyObject sender, [CanBeNull] object baseValue)
{
if (baseValue != null)
return baseValue;
var control = sender as DataGridFilterColumnControl;
// Just resolved the binding to the template property attached to the column, and the value has not been set on the column:
// => try to find the default template based on the columns type.
var columnType = control?.ColumnHeader?.Column?.GetType();
if (columnType == null)
return null;
var resourceKey = new ComponentResourceKey(typeof(DataGridFilter), columnType);
return control.DataGrid?.GetResourceLocator()?.FindResource(control, resourceKey) ?? control.TryFindResource(resourceKey);
}
/// <summary>
/// Returns all distinct visible (filtered) values of this column as string.
/// This can be used to e.g. feed the ItemsSource of an AutoCompleteBox to give a hint to the user what to enter.
/// </summary>
/// <remarks>
/// You may need to include "NotifyOnTargetUpdated=true" in the binding of the DataGrid.ItemsSource to get up-to-date
/// values when the source object changes.
/// </remarks>
[NotNull, ItemNotNull]
public IEnumerable<string> Values
{
get
{
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
return InternalValues().Distinct().ToArray();
}
}
/// <summary>
/// Returns all distinct source values of this column as string.
/// This can be used to e.g. feed the ItemsSource of an Excel-like auto-filter that always shows all source values that can be selected.
/// </summary>
/// <remarks>
/// You may need to include "NotifyOnTargetUpdated=true" in the binding of the DataGrid.ItemsSource to get up-to-date
/// values when the source object changes.
/// </remarks>
[NotNull, ItemNotNull]
public IEnumerable<string> SourceValues
{
get
{
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
// use the global filter, if any...
var predicate = FilterHost?.CreatePredicate(null) ?? (_ => true);
return InternalSourceValues(predicate)
.Distinct()
.ToArray();
}
}
/// <summary>
/// Returns all distinct selectable values of this column as string.
/// This can be used to e.g. feed the ItemsSource of an Excel-like auto-filter, that only shows the values that are currently selectable, depending on the other filters.
/// </summary>
/// <remarks>
/// You may need to include "NotifyOnTargetUpdated=true" in the binding of the DataGrid.ItemsSource to get up-to-date
/// values when the source object changes.
/// </remarks>
[NotNull, ItemNotNull]
public IEnumerable<string> SelectableValues
{
get
{
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
// filter by all columns except this.
var predicate = FilterHost?.CreatePredicate(FilterHost.GetColumnFilters(this)) ?? (_ => true);
return InternalSourceValues(predicate)
.Distinct()
.ToArray();
}
}
/// <summary>
/// Returns a flag indicating whether this column has some filter condition to evaluate or not.
/// If there is no filter condition we don't need to invoke this filter.
/// </summary>
public bool IsFiltered => !string.IsNullOrWhiteSpace(Filter?.ToString()) && ColumnHeader?.Column != null;
/// <summary>
/// Returns true if the given item matches the filter condition for this column.
/// </summary>
internal bool Matches([CanBeNull] object item)
{
if ((Filter == null) || (FilterHost == null))
return true;
if (_activeFilter == null)
{
_activeFilter = FilterHost.CreateContentFilter(Filter);
}
return _activeFilter.IsMatch(GetCellContent(item));
}
/// <summary>
/// Notification of the filter that the content of the values might have changed.
/// </summary>
internal void ValuesUpdated()
{
// We simply raise a change event for the properties and create the output on the fly in the getter of the properties;
// if there is no binding to the properties we don't waste resources to compute a list that is never used.
OnPropertyChanged(nameof(Values));
OnPropertyChanged(nameof(SourceValues));
OnPropertyChanged(nameof(SelectableValues));
}
/// <summary>
/// Gets the column this control is hosting the filter for.
/// </summary>
[CanBeNull]
public DataGridColumn Column => ColumnHeader?.Column;
/// <summary>
/// The DataGrid we belong to.
/// </summary>
[CanBeNull]
protected DataGrid DataGrid
{
get;
private set;
}
/// <summary>
/// The filter we belong to.
/// </summary>
[CanBeNull]
protected DataGridFilterHost FilterHost
{
get;
private set;
}
/// <summary>
/// The column header of the column we are filtering. This control must be a child element of the column header.
/// </summary>
[CanBeNull]
protected DataGridColumnHeader ColumnHeader
{
get;
private set;
}
/// <summary>
/// Identifies the CellValue dependency property, a private helper property used to evaluate the property path for the list items.
/// </summary>
[NotNull]
private static readonly DependencyProperty _cellValueProperty =
DependencyProperty.Register("_cellValue", typeof(object), typeof(DataGridFilterColumnControl));
/// <summary>
/// Examines the property path and returns the objects value for this column.
/// Filtering is applied on the SortMemberPath, this is the path used to create the binding.
/// </summary>
[CanBeNull]
protected object GetCellContent([CanBeNull] object item)
{
// ReSharper disable once PossibleNullReferenceException
var propertyPath = ColumnHeader?.Column.SortMemberPath;
if (string.IsNullOrEmpty(propertyPath))
return null;
// Since already the name "SortMemberPath" implies that this might be not only a simple property name but a full property path
// we use binding for evaluation; this will properly handle even complex property paths like e.g. "SubItems[0].Name"
BindingOperations.SetBinding(this, _cellValueProperty, new Binding(propertyPath) { Source = item });
var propertyValue = GetValue(_cellValueProperty);
BindingOperations.ClearBinding(this, _cellValueProperty);
return propertyValue;
}
/// <summary>
/// Gets the cell content of all list items for this column.
/// </summary>
[NotNull, ItemNotNull]
protected IEnumerable<string> InternalValues()
{
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
return DataGrid?.Items
.Cast<object>()
.Select(GetCellContent)
.Select(content => content?.ToString() ?? string.Empty) ?? Enumerable.Empty<string>();
}
/// <summary>
/// Gets the cell content of all list items for this column.
/// </summary>
[NotNull, ItemNotNull]
protected IEnumerable<string> InternalSourceValues([NotNull] Predicate<object> predicate)
{
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
var itemsSource = DataGrid?.ItemsSource;
if (itemsSource == null)
return Enumerable.Empty<string>();
var collectionView = itemsSource as ICollectionView;
var items = collectionView?.SourceCollection ?? itemsSource;
return items.Cast<object>()
.Where(item => predicate(item))
.Select(GetCellContent)
.Select(content => content?.ToString() ?? string.Empty);
}
#region INotifyPropertyChanged Members
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
protected virtual void OnPropertyChanged([NotNull] string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion
[ContractInvariantMethod]
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
[Conditional("CONTRACTS_FULL")]
private void ObjectInvariant()
{
Contract.Invariant((FilterHost == null) || (DataGrid != null));
}
}
} | 42.856448 | 222 | 0.609799 | [
"MIT"
] | anwar-moj/DataGridExtensions | DataGridExtensions/DataGridFilterColumnControl.cs | 17,616 | 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.Immutable;
using System.IO;
namespace Microsoft.Dnx.Compilation.CSharp
{
internal static class SnkUtils
{
const byte PUBLICKEYBLOB = 0x06;
const byte PRIVATEKEYBLOB = 0x07;
private const uint CALG_RSA_SIGN = 0x00002400;
private const uint CALG_SHA = 0x00008004;
private const uint RSA1 = 0x31415352; //"RSA1" publickeyblob
private const uint RSA2 = 0x32415352; //"RSA2" privatekeyblob
private const int VersionOffset = 1;
private const int ModulusLengthOffset = 12;
private const int ExponentOffset = 16;
private const int MagicPrivateKeyOffset = 8;
private const int MagicPublicKeyOffset = 20;
public static ImmutableArray<byte> ExtractPublicKey(byte[] snk)
{
ValidateBlob(snk);
if (snk[0] != PRIVATEKEYBLOB)
{
return ImmutableArray.Create(snk);
}
var version = snk[VersionOffset];
int modulusBitLength = ReadInt32(snk, ModulusLengthOffset);
uint exponent = (uint)ReadInt32(snk, ExponentOffset);
var modulus = new byte[modulusBitLength >> 3];
Array.Copy(snk, 20, modulus, 0, modulus.Length);
return CreatePublicKey(version, exponent, modulus);
}
private static void ValidateBlob(byte[] snk)
{
// 160 - the size of public key
if (snk.Length >= 160)
{
if (snk[0] == PRIVATEKEYBLOB && ReadInt32(snk, MagicPrivateKeyOffset) == RSA2 || // valid private key
snk[12] == PUBLICKEYBLOB && ReadInt32(snk, MagicPublicKeyOffset) == RSA1) // valid public key
{
return;
}
}
throw new InvalidOperationException("Invalid key file.");
}
private static int ReadInt32(byte[] array, int index)
{
return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24;
}
private static ImmutableArray<byte> CreatePublicKey(byte version, uint exponent, byte[] modulus)
{
using (var ms = new MemoryStream(160))
using (var binaryWriter = new BinaryWriter(ms))
{
binaryWriter.Write(CALG_RSA_SIGN);
binaryWriter.Write(CALG_SHA);
// total size of the rest of the blob (20 - size of RSAPUBKEY)
binaryWriter.Write(modulus.Length + 20);
binaryWriter.Write(PUBLICKEYBLOB);
binaryWriter.Write(version);
binaryWriter.Write((ushort)0x00000000); // reserved
binaryWriter.Write(CALG_RSA_SIGN);
binaryWriter.Write(RSA1);
binaryWriter.Write(modulus.Length << 3);
binaryWriter.Write(exponent);
binaryWriter.Write(modulus);
return ImmutableArray.Create(ms.ToArray());
}
}
}
}
| 36.727273 | 117 | 0.582611 | [
"Apache-2.0"
] | aspnet/DNX | src/Microsoft.Dnx.Compilation.CSharp.Common/SnkUtils.cs | 3,234 | C# |
#region
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
#endregion
namespace ESS.Framework.Common.Utilities
{
/// <summary>
/// Represents an ObjectId
/// </summary>
[Serializable]
public struct ObjectId
{
/// <summary>
/// Generates a COMB Guid which solves the fragmented index issue.
/// See: http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy
/// </summary>
public static Guid GetNextGuid()
{
byte[] b = Guid.NewGuid().ToByteArray();
DateTime dateTime = new DateTime(1900, 1, 1);
DateTime now = DateTime.Now;
TimeSpan timeSpan = new TimeSpan(now.Ticks - dateTime.Ticks);
TimeSpan timeOfDay = now.TimeOfDay;
byte[] bytes1 = BitConverter.GetBytes(timeSpan.Days);
byte[] bytes2 = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333));
Array.Reverse(bytes1);
Array.Reverse(bytes2);
Array.Copy(bytes1, bytes1.Length - 2, b, b.Length - 6, 2);
Array.Copy(bytes2, bytes2.Length - 4, b, b.Length - 4, 4);
return new Guid(b);
}
}
} | 31.95122 | 98 | 0.610687 | [
"Apache-2.0"
] | wh-ess/ess | Framework/ESS.Framework.Common/Utilities/ObjectId.cs | 1,312 | C# |
#region License
// Copyright 2022 AppMotor Framework (https://github.com/skrysmanski/AppMotor)
//
// 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.
#endregion
using System.Drawing;
using AppMotor.Core.Extensions;
using JetBrains.Annotations;
namespace AppMotor.Core.Colors;
/// <summary>
/// Represents a color in the CMYK (cyan, magenta, yellow, black) color model.
/// </summary>
/// <remarks>
/// To keep this struct small, the CMYK values are stored internally as <see cref="Half"/>.
/// However, for ease of use, the values are exposed as <c>float</c>.
/// </remarks>
/// <seealso cref="CmyColor"/>
public readonly struct CmykColor : IColor, IEquatable<CmykColor>
{
private static readonly Half HALF_ZERO = (Half)0;
/// <inheritdoc />
public byte A { get; }
/// <summary>
/// The cyan component of this color (0 - 100%).
/// </summary>
public float C => (float)this._c * 100;
private readonly Half _c;
/// <summary>
/// The magenta component of this color (0 - 100%).
/// </summary>
public float M => (float)this._m * 100;
private readonly Half _m;
/// <summary>
/// The yellow component of this color (0 - 100%).
/// </summary>
public float Y => (float)this._y * 100;
private readonly Half _y;
/// <summary>
/// The key/black component of this color (0 - 100%).
/// </summary>
public float K => (float)this._k * 100;
private readonly Half _k;
/// <summary>
/// Constructor. Uses 255 as value for <see cref="A"/>.
/// </summary>
public CmykColor(float c, float m, float y, float k)
: this(a: 255, c, m, y, k)
{
}
/// <summary>
/// Constructor.
/// </summary>
public CmykColor(byte a, float c, float m, float y, float k)
{
if (c < 0 || c > 100)
{
throw new ArgumentOutOfRangeException(nameof(c), $"The value '{c}' is outside the allowed range (0 - 100).");
}
if (m < 0 || m > 100)
{
throw new ArgumentOutOfRangeException(nameof(m), $"The value '{m}' is outside the allowed range (0 - 100).");
}
if (y < 0 || y > 100)
{
throw new ArgumentOutOfRangeException(nameof(y), $"The value '{y}' is outside the allowed range (0 - 100).");
}
if (k < 0 || k > 100)
{
throw new ArgumentOutOfRangeException(nameof(k), $"The value '{k}' is outside the allowed range (0 - 100).");
}
this.A = a;
this._c = (Half)(c / 100.0);
this._m = (Half)(m / 100.0);
this._y = (Half)(y / 100.0);
this._k = (Half)(k / 100.0);
}
/// <summary>
/// Constructor.
/// </summary>
public CmykColor(Color color)
{
this.A = color.A;
var rFloat = color.R / 255.0;
var gFloat = color.G / 255.0;
var bFloat = color.B / 255.0;
double maxRgb = 0;
if (rFloat > maxRgb)
{
maxRgb = rFloat;
}
if (gFloat > maxRgb)
{
maxRgb = gFloat;
}
if (bFloat > maxRgb)
{
maxRgb = bFloat;
}
var kFloat = 1 - maxRgb;
this._k = (Half)kFloat;
if (maxRgb.IsBasicallyEqualTo(0))
{
this._c = HALF_ZERO;
this._m = HALF_ZERO;
this._y = HALF_ZERO;
}
else
{
this._c = (Half)((1 - rFloat - kFloat) / maxRgb);
this._m = (Half)((1 - gFloat - kFloat) / maxRgb);
this._y = (Half)((1 - bFloat - kFloat) / maxRgb);
}
}
/// <summary>
/// Constructor.
/// </summary>
public CmykColor(CmyColor cmyColor)
: this(cmyColor.ToRgb())
{
}
/// <inheritdoc />
public bool Equals(CmykColor other)
{
return this.A == other.A && this._c == other._c && this._m == other._m && this._y == other._y && this._k == other._k;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is CmykColor other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
return HashCode.Combine(this.A, this.C, this.M, this.Y, this.K);
}
/// <summary>
/// The == operator
/// </summary>
public static bool operator ==(CmykColor left, CmykColor right)
{
return left.Equals(right);
}
/// <summary>
/// The != operator
/// </summary>
public static bool operator !=(CmykColor left, CmykColor right)
{
return !left.Equals(right);
}
/// <inheritdoc />
public Color ToRgb()
{
var maxRgb = 1.0 - (double)this._k;
return Color.FromArgb(
this.A,
(byte)Math.Round(255.0 * (1 - (double)this._c) * maxRgb),
(byte)Math.Round(255.0 * (1 - (double)this._m) * maxRgb),
(byte)Math.Round(255.0 * (1 - (double)this._y) * maxRgb)
);
}
/// <summary>
/// Converts this CMYK color into its corresponding CMY color.
/// </summary>
/// <returns></returns>
[MustUseReturnValue]
public CmyColor ToCmy()
{
var maxRgb = 1.0 - this.K / 100;
return new CmyColor(
this.A,
(byte)Math.Round(255 - 255.0 * (1 - (double)this._c) * maxRgb),
(byte)Math.Round(255 - 255.0 * (1 - (double)this._m) * maxRgb),
(byte)Math.Round(255 - 255.0 * (1 - (double)this._y) * maxRgb)
);
}
/// <inheritdoc />
public override string ToString()
{
return $"{nameof(CmykColor)} [A={this.A}, C={Math.Round(this.C)}, M={Math.Round(this.M)}, Y={Math.Round(this.Y)}, K={Math.Round(this.K)}]";
}
}
| 28.539823 | 148 | 0.529302 | [
"Apache-2.0"
] | skrysmanski/AppWeave | src/AppMotor.Core/Colors/CmykColor.cs | 6,452 | C# |
using MediatR;
using Artemis.Web.Shared.EventUpdates;
namespace Artemis.Web.Server.EventUpdates
{
public class GetEventUpdate : IRequest<EventUpdate>
{
public int EventId { get; set; }
public int UpdateId { get; set; }
public int OrganizationId { get; set; }
}
} | 25.916667 | 56 | 0.643087 | [
"MIT"
] | joro550/Artemis | Artemis/Artemis.Web/Server/EventUpdates/GetEventUpdate.cs | 313 | C# |
// Copyright (c) Russlan Akiev. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityBase
{
using System;
using IdentityBase.Services;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
public static class StartupDataLayer
{
public static void ValidateDataLayerServices(
this IServiceCollection services,
ILogger logger)
{
if (!services.IsAdded<IClientStore>())
{
throw new Exception("IClientStore not registered.");
}
if (!services.IsAdded<IResourceStore>())
{
throw new Exception("IResourceStore not registered.");
}
if (!services.IsAdded<ICorsPolicyService>())
{
throw new Exception("ICorsPolicyService not registered.");
}
if (!services.IsAdded<IPersistedGrantStore>())
{
throw new Exception("IPersistedGrantStore not registered.");
}
if (!services.IsAdded<IUserAccountStore>())
{
throw new Exception("IUserAccountStore not registered.");
}
}
}
}
| 30.851064 | 108 | 0.567586 | [
"Apache-2.0"
] | IdentityBaseNet/IdentityBase | src/IdentityBase.Shared/Startup/StartupDataLayer.cs | 1,450 | C# |
using System;
using System.Collections.Generic;
using Game_Snake.Helpers;
using Game_Snake.Interface;
using Game_Snake.Interface.LinkedList.Helpers;
namespace Game_Snake
{
public class Snake : IDrawable
{
public Snake(Possition headPossition, Action spawnFood)
{
this.SpawnFood = spawnFood;
SnakeBody = new LinkedList();
SnakeBody.AddHead(new Node(headPossition));
Foods = new List<Food>();
for (int i = 1; i <= 10; i++)
{
SnakeBody.AddLast(new Node(new Possition(headPossition.X + i, headPossition.Y)));
}
}
public Action SpawnFood { get; set; }
public LinkedList SnakeBody { get; set; }
public List<Food> Foods { get; set; }
public void Draw()
{
SnakeBody.ForEach(node =>
{
var text = "*";
Console.SetCursorPosition(node.Value.X, node.Value.Y);
if (node == SnakeBody.Head)
{
text = "@";
}
ConsoleHelper.Write(node.Value, text);
});
}
public bool CheckSelfCanibalism()
{
HashSet<Possition> set = new HashSet<Possition>();
bool isCanibal = false;
SnakeBody.ForEach(node =>
{
if (set.Contains(node.Value)) isCanibal = true;
set.Add(node.Value);
});
return isCanibal;
}
public void Move(Possition possition)
{
if (possition.X == 0 && possition.Y == 0)
{
return;
}
ConsoleHelper.Clear(SnakeBody.Tail.Value);
SnakeBody.ReverseForEach(node =>
{
if (node.Previous != null)
{
node.Value.X = node.Previous.Value.X;
node.Value.Y = node.Previous.Value.Y;
}
});
SnakeBody.Head.Value.ChangePossition(possition);
for (int i = 0; i < Foods.Count; i++)
{
if (Foods[i].Possition == SnakeBody.Head.Value)
{
Foods[i].EatFood();
Grow(possition);
SpawnFood();
}
}
}
public void Grow(Possition possition)
{
var oldPOssition = SnakeBody.Head.Value;
var newHead = new Node(new Possition(oldPOssition.X, oldPOssition.Y));
//newHead.Value.ChangePossition(possition);
BoundriesHelper.CheckBoundaries(newHead.Value, possition);
SnakeBody.AddHead(newHead);
}
}
}
| 27.156863 | 97 | 0.485199 | [
"MIT"
] | StefanPetrov7/CSharpAdvanceModule | WorkShop/Game_Snake/Snake.cs | 2,772 | C# |
using System;
using System.Linq;
using NUnit.Framework;
namespace JetBlack.Monads.Test
{
[TestFixture]
public class PromiseNoArgsTest
{
[Test]
public void CanResolveSimplePromise()
{
var promise = Promise.Resolved();
var completed = 0;
promise.Then(() => ++completed);
Assert.AreEqual(1, completed);
}
[Test]
public void CanRejectSimplePromise()
{
var ex = new Exception();
var promise = Promise.Rejected(ex);
var errors = 0;
promise.Catch(e =>
{
Assert.AreEqual(ex, e);
++errors;
});
Assert.AreEqual(1, errors);
}
[Test]
public void ExceptionIsThrownForRejectAfterReject()
{
var promise = new Promise();
promise.Reject(new Exception());
Assert.Throws<InvalidOperationException>(() => promise.Reject(new Exception()));
}
[Test]
public void ExceptionIsThrownForRejectAfterResolve()
{
var promise = new Promise();
promise.Resolve();
Assert.Throws<InvalidOperationException>(() => promise.Reject(new Exception()));
}
[Test]
public void ExceptionIsThrownForResolveAfterReject()
{
var promise = new Promise();
promise.Reject(new Exception());
Assert.Throws<InvalidOperationException>(promise.Resolve);
}
[Test]
public void CanResolvePromiseAndTriggerThenHandler()
{
var promise = new Promise();
var completed = 0;
promise.Then(() => ++completed);
promise.Resolve();
Assert.AreEqual(1, completed);
}
[Test]
public void ExceptionIsThrownForResolveAfterResolve()
{
var promise = new Promise();
promise.Resolve();
Assert.Throws<InvalidOperationException>(promise.Resolve);
}
[Test]
public void CanResolvePromiseAndTriggerMultipleThenHandlersInOrder()
{
var promise = new Promise();
var completed = 0;
promise.Then(() => Assert.AreEqual(1, ++completed));
promise.Then(() => Assert.AreEqual(2, ++completed));
promise.Resolve();
Assert.AreEqual(2, completed);
}
[Test]
public void CanResolvePromiseAndTriggerThenHandlerWithCallbackRegistrationAfterResolve()
{
var promise = new Promise();
var completed = 0;
promise.Resolve();
promise.Then(() => ++completed);
Assert.AreEqual(1, completed);
}
[Test]
public void CanRejectPromiseAndTriggerErrorHandler()
{
var promise = new Promise();
var ex = new Exception();
var completed = 0;
promise.Catch(e =>
{
Assert.AreEqual(ex, e);
++completed;
});
promise.Reject(ex);
Assert.AreEqual(1, completed);
}
[Test]
public void CanRejectPromiseAndTriggerMultipleErrorHandlersInOrder()
{
var promise = new Promise();
var ex = new Exception();
var completed = 0;
promise.Catch(e =>
{
Assert.AreEqual(ex, e);
Assert.AreEqual(1, ++completed);
});
promise.Catch(e =>
{
Assert.AreEqual(ex, e);
Assert.AreEqual(2, ++completed);
});
promise.Reject(ex);
Assert.AreEqual(2, completed);
}
[Test]
public void CanRejectPromiseAndTriggerErrorHandlerWithRegistrationAfterReject()
{
var promise = new Promise();
var ex = new Exception();
promise.Reject(ex);
var completed = 0;
promise.Catch(e =>
{
Assert.AreEqual(ex, e);
++completed;
});
Assert.AreEqual(1, completed);
}
[Test]
public void ErrorHandlerIsNotInvokedForResolvedPromised()
{
var promise = new Promise();
promise.Catch(e =>
{
throw new Exception("This shouldn't happen");
});
promise.Resolve();
}
[Test]
public void ThenHandlerIsNotInvokedForRejectedPromise()
{
var promise = new Promise();
promise.Then(() =>
{
throw new Exception("This shouldn't happen");
});
promise.Reject(new Exception("Rejection!"));
}
[Test]
public void ChainMultiplePromisesUsingAll()
{
var promise = new Promise();
var chainedPromise1 = new Promise();
var chainedPromise2 = new Promise();
var completed = 0;
promise
//.ThenAll(() => LinqExts.FromItems(chainedPromise1, chainedPromise2).Cast<IPromise>())
.ThenAll(() => new[] { chainedPromise1, chainedPromise2 })
.Then(() => ++completed);
Assert.AreEqual(0, completed);
promise.Resolve();
Assert.AreEqual(0, completed);
chainedPromise1.Resolve();
Assert.AreEqual(0, completed);
chainedPromise2.Resolve();
Assert.AreEqual(1, completed);
}
[Test]
public void ChainMultiplePromisesUsingAllThatAreResolvedOutOfOrder()
{
var promise = new Promise();
var chainedPromise1 = new Promise<int>();
var chainedPromise2 = new Promise<int>();
const int chainedResult1 = 10;
const int chainedResult2 = 15;
var completed = 0;
promise
//.ThenAll(() => LinqExts.FromItems(chainedPromise1, chainedPromise2).Cast<IPromise<int>>())
.ThenAll(() => new[] { chainedPromise1, chainedPromise2 })
.Then(result =>
{
var items = result.ToArray();
Assert.AreEqual(2, items.Length);
Assert.AreEqual(chainedResult1, items[0]);
Assert.AreEqual(chainedResult2, items[1]);
++completed;
});
Assert.AreEqual(0, completed);
promise.Resolve();
Assert.AreEqual(0, completed);
chainedPromise1.Resolve(chainedResult1);
Assert.AreEqual(0, completed);
chainedPromise2.Resolve(chainedResult2);
Assert.AreEqual(1, completed);
}
[Test]
public void ChainMultipleValuePromisesUsingAllResolvedOutOfOrder()
{
var promise = new Promise();
var chainedPromise1 = new Promise<int>();
var chainedPromise2 = new Promise<int>();
const int chainedResult1 = 10;
const int chainedResult2 = 15;
var completed = 0;
promise
//.ThenAll(() => LinqExts.FromItems(chainedPromise1, chainedPromise2).Cast<IPromise<int>>())
.ThenAll(() => new[] { chainedPromise1, chainedPromise2 })
.Then(result =>
{
var items = result.ToArray();
Assert.AreEqual(2, items.Length);
Assert.AreEqual(chainedResult1, items[0]);
Assert.AreEqual(chainedResult2, items[1]);
++completed;
});
Assert.AreEqual(0, completed);
promise.Resolve();
Assert.AreEqual(0, completed);
chainedPromise2.Resolve(chainedResult2);
Assert.AreEqual(0, completed);
chainedPromise1.Resolve(chainedResult1);
Assert.AreEqual(1, completed);
}
[Test]
public void CombinedPromiseIsResolvedWhenChildrenAreResolved()
{
var promise1 = new Promise();
var promise2 = new Promise();
//var all = Promise.All(LinqExts.FromItems<IPromise>(promise1, promise2));
var all = Promise.All(promise1, promise2);
var completed = 0;
all.Then(() => ++completed);
promise1.Resolve();
promise2.Resolve();
Assert.AreEqual(1, completed);
}
[Test]
public void CombinedPromiseIsRejectedWhenFirstPromiseIsRejected()
{
var promise1 = new Promise();
var promise2 = new Promise();
//var all = Promise.All(LinqExts.FromItems<IPromise>(promise1, promise2));
var all = Promise.All(promise1, promise2);
all.Then(() =>
{
throw new Exception("Shouldn't happen");
});
var errors = 0;
all.Catch(e =>
{
++errors;
});
promise1.Reject(new Exception("Error!"));
promise2.Resolve();
Assert.AreEqual(1, errors);
}
[Test]
public void CombinedPromiseIsRejectedWhenSecondPromiseIsRejected()
{
var promise1 = new Promise();
var promise2 = new Promise();
//var all = Promise.All(LinqExts.FromItems<IPromise>(promise1, promise2));
var all = Promise.All(promise1, promise2);
all.Then(() =>
{
throw new Exception("Shouldn't happen");
});
var errors = 0;
all.Catch(e =>
{
++errors;
});
promise1.Resolve();
promise2.Reject(new Exception("Error!"));
Assert.AreEqual(1, errors);
}
[Test]
public void CombinedPromiseIsRejectedWhenBothPromisesAreRejected()
{
var promise1 = new Promise();
var promise2 = new Promise();
//var all = Promise.All(LinqExts.FromItems<IPromise>(promise1, promise2));
var all = Promise.All(promise1, promise2);
all.Then(() =>
{
throw new Exception("Shouldn't happen");
});
var errors = 0;
all.Catch(e =>
{
++errors;
});
promise1.Reject(new Exception("Error!"));
promise2.Reject(new Exception("Error!"));
Assert.AreEqual(1, errors);
}
[Test]
public void CombinedPromiseIsResolvedIfThereAreNoPromises()
{
//var all = Promise.All(LinqExts.Empty<IPromise>());
var all = Promise.All(new IPromise[0]);
var completed = 0;
all.Then(() => ++completed);
}
[Test]
public void CombinedPromiseIsResolvedWhenAllPromisesAreAlreadyResolved()
{
var promise1 = Promise.Resolved();
var promise2 = Promise.Resolved();
//var all = Promise.All(LinqExts.FromItems(promise1, promise2));
var all = Promise.All(promise1, promise2);
var completed = 0;
all.Then(() =>
{
++completed;
});
Assert.AreEqual(1, completed);
}
[Test]
public void ExceptionThrownDuringTransformRejectsPromise()
{
var promise = new Promise();
var errors = 0;
var ex = new Exception();
var transformedPromise = promise
.Then(() =>
{
throw ex;
})
.Catch(e =>
{
Assert.AreEqual(ex, e);
++errors;
});
promise.Resolve();
Assert.AreEqual(1, errors);
}
[Test]
public void CanChainPromise()
{
var promise = new Promise();
var chainedPromise = new Promise();
var completed = 0;
promise
.Then(() => chainedPromise)
.Then(() => ++completed);
promise.Resolve();
chainedPromise.Resolve();
Assert.AreEqual(1, completed);
}
[Test]
public void CanChainPromiseAndConvertToPromiseThatYieldsSomeValue()
{
var promise = new Promise();
var chainedPromise = new Promise<string>();
const string chainedPromiseValue = "some-value";
var completed = 0;
promise
.Then(() => chainedPromise)
.Then(v =>
{
Assert.AreEqual(chainedPromiseValue, v);
++completed;
});
promise.Resolve();
chainedPromise.Resolve(chainedPromiseValue);
Assert.AreEqual(1, completed);
}
[Test]
public void ExceptionThrownInChainRejectsResultingPromise()
{
var promise = new Promise();
var ex = new Exception();
var errors = 0;
promise
.Then(() =>
{
throw ex;
})
.Catch(e =>
{
Assert.AreEqual(ex, e);
++errors;
});
promise.Resolve();
Assert.AreEqual(1, errors);
}
[Test]
public void RejectionOfSourcePromiseRejectsChainedPromise()
{
var promise = new Promise();
var chainedPromise = new Promise();
var ex = new Exception();
var errors = 0;
promise
.Then(() => chainedPromise)
.Catch(e =>
{
Assert.AreEqual(ex, e);
++errors;
});
promise.Reject(ex);
Assert.AreEqual(1, errors);
}
[Test]
public void RaceIsResolvedWhenFirstPromiseIsResolvedFirst()
{
var promise1 = new Promise();
var promise2 = new Promise();
var completed = 0;
Promise
.Race(promise1, promise2)
.Then(() => ++completed);
promise1.Resolve();
Assert.AreEqual(1, completed);
}
[Test]
public void RaceIsResolvedWhenSecondPromiseIsResolvedFirst()
{
var promise1 = new Promise();
var promise2 = new Promise();
var completed = 0;
Promise
.Race(promise1, promise2)
.Then(() => ++completed);
promise2.Resolve();
Assert.AreEqual(1, completed);
}
[Test]
public void RaceIsRejectedWhenFirstPromiseIsRejectedFirst()
{
var promise1 = new Promise();
var promise2 = new Promise();
Exception ex = null;
Promise
.Race(promise1, promise2)
.Catch(e => ex = e);
var expected = new Exception();
promise1.Reject(expected);
Assert.AreEqual(expected, ex);
}
[Test]
public void RaceIsRejectedWhenSecondPromiseIsRejectedFirst()
{
var promise1 = new Promise();
var promise2 = new Promise();
Exception ex = null;
Promise
.Race(promise1, promise2)
.Catch(e => ex = e);
var expected = new Exception();
promise2.Reject(expected);
Assert.AreEqual(expected, ex);
}
[Test]
public void SequenceWithNoOperationsIsDirectlyResolved()
{
var completed = 0;
Promise
.Sequence(new Func<IPromise>[0])
.Then(() => ++completed);
Assert.AreEqual(1, completed);
}
[Test]
public void SequencedIsNotResolvedWhenOperationIsNotResolved()
{
var completed = 0;
Promise
.Sequence(() => new Promise())
.Then(() => ++completed);
Assert.AreEqual(0, completed);
}
[Test]
public void SequenceIsResolvedWhenOperationIsResolved()
{
var completed = 0;
Promise
.Sequence(Promise.Resolved)
.Then(() => ++completed);
Assert.AreEqual(1, completed);
}
[Test]
public void SequenceIsUnresolvedWhenSomeOperationsAreUnresolved()
{
var completed = 0;
Promise
.Sequence(
Promise.Resolved,
() => new Promise()
)
.Then(() => ++completed);
Assert.AreEqual(0, completed);
}
[Test]
public void SequenceIsResolvedWhenAllOperationsAreResolved()
{
var completed = 0;
Promise
.Sequence(
Promise.Resolved,
Promise.Resolved
)
.Then(() => ++completed);
Assert.AreEqual(1, completed);
}
[Test]
public void SequencedOperationsAreRunInOrderIsDirectlyResolved()
{
var order = 0;
Promise
.Sequence(
() =>
{
Assert.AreEqual(1, ++order);
return Promise.Resolved();
},
() =>
{
Assert.AreEqual(2, ++order);
return Promise.Resolved();
},
() =>
{
Assert.AreEqual(3, ++order);
return Promise.Resolved();
}
);
Assert.AreEqual(3, order);
}
[Test]
public void ExceptionThrownInSequenceRejectsThePromise()
{
var errored = 0;
var completed = 0;
var ex = new Exception();
Promise
.Sequence(() =>
{
throw ex;
})
.Catch(e =>
{
Assert.AreEqual(ex, e);
++errored;
})
.Then(() => ++completed);
Assert.AreEqual(1, errored);
Assert.AreEqual(0, completed);
}
[Test]
public void ExceptionThrownInSequenceStopsFollowingOperationsFromBeingInvoked()
{
var completed = 0;
Promise
.Sequence(
() =>
{
++completed;
return Promise.Resolved();
},
() =>
{
throw new Exception();
},
() =>
{
++completed;
return Promise.Resolved();
}
);
Assert.AreEqual(1, completed);
}
[Test]
public void CanResolvePromiseViaResolverFunction()
{
var promise = new Promise((resolve, reject) => resolve());
var completed = 0;
promise.Then(() =>
{
++completed;
});
Assert.AreEqual(1, completed);
}
[Test]
public void CanRejectPromiseViaRejectFunction()
{
var ex = new Exception();
var promise = new Promise((resolve, reject) => reject(ex));
var completed = 0;
promise.Catch(e =>
{
Assert.AreEqual(ex, e);
++completed;
});
Assert.AreEqual(1, completed);
}
[Test]
public void ExceptionThrownDuringResolverRejectsProimse()
{
var ex = new Exception();
var promise = new Promise((resolve, reject) =>
{
throw ex;
});
var completed = 0;
promise.Catch(e =>
{
Assert.AreEqual(ex, e);
++completed;
});
Assert.AreEqual(1, completed);
}
[Test]
public void UnhandledExceptionIsPropagatedViaEvent()
{
var promise = new Promise();
var ex = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) =>
{
Assert.AreEqual(ex, e.Exception);
++eventRaised;
};
Promise.UnhandledException += handler;
try
{
promise
.Then(() =>
{
throw ex;
})
.Done();
promise.Resolve();
Assert.AreEqual(1, eventRaised);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Test]
public void HandledExceptionIsNotPropagatedViaEvent()
{
var promise = new Promise();
var ex = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) => ++eventRaised;
Promise.UnhandledException += handler;
try
{
promise
.Then(() =>
{
throw ex;
})
.Catch(_ =>
{
// Catch the error.
})
.Done();
promise.Resolve();
Assert.AreEqual(1, eventRaised);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Test]
public void CanHandleDoneOnResolved()
{
var promise = new Promise();
var callback = 0;
promise.Done(() => ++callback);
promise.Resolve();
Assert.AreEqual(1, callback);
}
[Test]
public void CanHandleDoneOnResolvedWithOnReject()
{
var promise = new Promise();
var callback = 0;
var errorCallback = 0;
promise.Done(
() => ++callback,
ex => ++errorCallback
);
promise.Resolve();
Assert.AreEqual(1, callback);
Assert.AreEqual(0, errorCallback);
}
/*todo:
* Also want a test that exception thrown during Then triggers the error handler.
* How do Javascript promises work in this regard?
[Test]
public void exception_during_Done_onResolved_triggers_error_hander()
{
var promise = new Promise();
var callback = 0;
var errorCallback = 0;
var expectedValue = 5;
var expectedException = new Exception();
promise.Done(
value =>
{
Assert.AreEqual(expectedValue, value);
++callback;
throw expectedException;
},
ex =>
{
Assert.AreEqual(expectedException, ex);
++errorCallback;
}
);
promise.Resolve(expectedValue);
Assert.AreEqual(1, callback);
Assert.AreEqual(1, errorCallback);
}
* */
[Test]
public void ExceptionDuringThenOnResolvedTriggersErrorHander()
{
var promise = new Promise();
var callback = 0;
var errorCallback = 0;
var expectedException = new Exception();
promise
.Then(() =>
{
throw expectedException;
return Promise.Resolved();
})
.Done(
() => ++callback,
ex =>
{
Assert.AreEqual(expectedException, ex);
++errorCallback;
}
);
promise.Resolve();
Assert.AreEqual(0, callback);
Assert.AreEqual(1, errorCallback);
}
[Test]
public void InnerExceptionHandledByOuterPromise()
{
var promise = new Promise();
var errorCallback = 0;
var expectedException = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) => ++eventRaised;
Promise.UnhandledException += handler;
try
{
promise
.Then(() => Promise.Resolved().Then(() => { throw expectedException; }))
.Catch(ex =>
{
Assert.AreEqual(expectedException, ex);
++errorCallback;
});
promise.Resolve();
// No "done" in the chain, no generic event handler should be called
Assert.AreEqual(0, eventRaised);
// Instead the catch should have got the exception
Assert.AreEqual(1, errorCallback);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Test]
public void InnerExceptionHandledByOuterPromiseWithResults()
{
var promise = new Promise<int>();
var errorCallback = 0;
var expectedException = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) => ++eventRaised;
Promise.UnhandledException += handler;
try
{
promise
.Then((_) => Promise<int>.Resolved(5).Then((__) => { throw expectedException; }))
.Catch(ex =>
{
Assert.AreEqual(expectedException, ex);
++errorCallback;
});
promise.Resolve(2);
// No "done" in the chain, no generic event handler should be called
Assert.AreEqual(0, eventRaised);
// Instead the catch should have got the exception
Assert.AreEqual(1, errorCallback);
}
finally
{
Promise.UnhandledException -= handler;
}
}
}
}
| 26.201914 | 108 | 0.455754 | [
"MIT"
] | rob-blackbourn/JetBlack.Monads | JetBlack.Monads.Test/PromiseNoArgsTest.cs | 27,383 | C# |
using OrchardCore.DisplayManagement.Manifest;
[assembly: Theme(
Name = "The Agency Theme",
Author = "The Orchard Team",
Website = "http://orchardproject.net",
Version = "2.0.0",
Description = "A theme adapted for agency websites."
)]
| 25.5 | 56 | 0.670588 | [
"BSD-3-Clause"
] | AlexGuedes1986/FutbolCubano | src/OrchardCore.Themes/TheAgencyTheme/Manifest.cs | 255 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the databrew-2017-07-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.GlueDataBrew.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.GlueDataBrew.Model.Internal.MarshallTransformations
{
/// <summary>
/// StatisticsConfiguration Marshaller
/// </summary>
public class StatisticsConfigurationMarshaller : IRequestMarshaller<StatisticsConfiguration, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(StatisticsConfiguration requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetIncludedStatistics())
{
context.Writer.WritePropertyName("IncludedStatistics");
context.Writer.WriteArrayStart();
foreach(var requestObjectIncludedStatisticsListValue in requestObject.IncludedStatistics)
{
context.Writer.Write(requestObjectIncludedStatisticsListValue);
}
context.Writer.WriteArrayEnd();
}
if(requestObject.IsSetOverrides())
{
context.Writer.WritePropertyName("Overrides");
context.Writer.WriteArrayStart();
foreach(var requestObjectOverridesListValue in requestObject.Overrides)
{
context.Writer.WriteObjectStart();
var marshaller = StatisticOverrideMarshaller.Instance;
marshaller.Marshall(requestObjectOverridesListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static StatisticsConfigurationMarshaller Instance = new StatisticsConfigurationMarshaller();
}
} | 36.120482 | 120 | 0.658105 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/GlueDataBrew/Generated/Model/Internal/MarshallTransformations/StatisticsConfigurationMarshaller.cs | 2,998 | C# |
/**
* Point.cs
*
Copyright 2020 Innovatics Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
namespace PDFjet.NET {
/**
* Used to create point objects with different shapes and draw them on a page.
* Please note: When we are mentioning (x, y) coordinates of a point - we are talking about the coordinates of the center of the point.
*
* Please see Example_05.
*/
public class Point : IDrawable {
public static readonly int INVISIBLE = -1;
public static readonly int CIRCLE = 0;
public static readonly int DIAMOND = 1;
public static readonly int BOX = 2;
public static readonly int PLUS = 3;
public static readonly int H_DASH = 4;
public static readonly int V_DASH = 5;
public static readonly int MULTIPLY = 6;
public static readonly int STAR = 7;
public static readonly int X_MARK = 8;
public static readonly int UP_ARROW = 9;
public static readonly int DOWN_ARROW = 10;
public static readonly int LEFT_ARROW = 11;
public static readonly int RIGHT_ARROW = 12;
public static bool CONTROL_POINT = true;
internal float x;
internal float y;
internal float r = 2f;
internal int shape = Point.CIRCLE;
internal int color = Color.black;
internal int align = Align.RIGHT;
internal float lineWidth = 0.3f;
internal String linePattern = "[] 0";
internal bool fillShape = false;
internal bool isControlPoint = false;
internal bool drawPath = false;
private String text;
private int textColor;
private int textDirection;
private String uri;
private float xBox;
private float yBox;
/**
* The default constructor.
*
*/
public Point() {
}
/**
* Constructor for creating point objects.
*
* @param x the x coordinate of this point when drawn on the page.
* @param y the y coordinate of this point when drawn on the page.
*/
public Point(double x, double y) : this((float) x, (float) y) {
}
/**
* Constructor for creating point objects.
*
* @param x the x coordinate of this point when drawn on the page.
* @param y the y coordinate of this point when drawn on the page.
*/
public Point(float x, float y) {
this.x = x;
this.y = y;
}
/**
* Constructor for creating point objects.
*
* @param x the x coordinate of this point when drawn on the page.
* @param y the y coordinate of this point when drawn on the page.
* @param isControlPoint true if this point is one of the points specifying a curve.
*/
public Point(double x, double y, bool isControlPoint) : this((float) x, (float) y, isControlPoint) {
}
/**
* Constructor for creating point objects.
*
* @param x the x coordinate of this point when drawn on the page.
* @param y the y coordinate of this point when drawn on the page.
* @param isControlPoint true if this point is one of the points specifying a curve.
*/
public Point(float x, float y, bool isControlPoint) {
this.x = x;
this.y = y;
this.isControlPoint = isControlPoint;
}
/**
* Sets the position (x, y) of this point.
*
* @param x the x coordinate of this point when drawn on the page.
* @param y the y coordinate of this point when drawn on the page.
*/
public void SetPosition(double x, double y) {
SetPosition((float) x, (float) y);
}
/**
* Sets the position (x, y) of this point.
*
* @param x the x coordinate of this point when drawn on the page.
* @param y the y coordinate of this point when drawn on the page.
*/
public void SetPosition(float x, float y) {
SetLocation(x, y);
}
public void SetXY(float x, float y) {
SetLocation(x, y);
}
/**
* Sets the location (x, y) of this point.
*
* @param x the x coordinate of this point when drawn on the page.
* @param y the y coordinate of this point when drawn on the page.
*/
public void SetLocation(float x, float y) {
this.x = x;
this.y = y;
}
/**
* Sets the x coordinate of this point.
*
* @param x the x coordinate of this point when drawn on the page.
*/
public void SetX(double x) {
this.x = (float) x;
}
/**
* Sets the x coordinate of this point.
*
* @param x the x coordinate of this point when drawn on the page.
*/
public void SetX(float x) {
this.x = x;
}
/**
* Returns the x coordinate of this point.
*
* @return the x coordinate of this point.
*/
public float GetX() {
return x;
}
/**
* Sets the y coordinate of this point.
*
* @param y the y coordinate of this point when drawn on the page.
*/
public void SetY(double y) {
this.y = (float) y;
}
/**
* Sets the y coordinate of this point.
*
* @param y the y coordinate of this point when drawn on the page.
*/
public void SetY(float y) {
this.y = y;
}
/**
* Returns the y coordinate of this point.
*
* @return the y coordinate of this point.
*/
public float GetY() {
return y;
}
/**
* Sets the radius of this point.
*
* @param r the radius.
*/
public void SetRadius(double r) {
this.r = (float) r;
}
/**
* Sets the radius of this point.
*
* @param r the radius.
*/
public void SetRadius(float r) {
this.r = r;
}
/**
* Returns the radius of this point.
*
* @return the radius of this point.
*/
public float GetRadius() {
return r;
}
/**
* Sets the shape of this point.
*
* @param shape the shape of this point. Supported values:
* <pre>
* Point.INVISIBLE
* Point.CIRCLE
* Point.DIAMOND
* Point.BOX
* Point.PLUS
* Point.H_DASH
* Point.V_DASH
* Point.MULTIPLY
* Point.STAR
* Point.X_MARK
* Point.UP_ARROW
* Point.DOWN_ARROW
* Point.LEFT_ARROW
* Point.RIGHT_ARROW
* </pre>
*/
public void SetShape(int shape) {
this.shape = shape;
}
/**
* Returns the point shape code value.
*
* @return the shape code value.
*/
public int GetShape() {
return shape;
}
/**
* Sets the private fillShape variable.
*
* @param fillShape if true - fill the point with the specified brush color.
*/
public void SetFillShape(bool fillShape) {
this.fillShape = fillShape;
}
/**
* Returns the value of the fillShape private variable.
*
* @return the value of the private fillShape variable.
*/
public bool GetFillShape() {
return fillShape;
}
/**
* Sets the pen color for this point.
*
* @param color the color specified as an integer.
* @return the point.
*/
public Point SetColor(int color) {
this.color = color;
return this;
}
/**
* Returns the point color as an integer.
*
* @return the color.
*/
public int GetColor() {
return color;
}
/**
* Sets the width of the lines of this point.
*
* @param lineWidth the line width.
*/
public void SetLineWidth(double lineWidth) {
this.lineWidth = (float) lineWidth;
}
/**
* Sets the width of the lines of this point.
*
* @param lineWidth the line width.
*/
public void SetLineWidth(float lineWidth) {
this.lineWidth = lineWidth;
}
/**
* Returns the width of the lines used to draw this point.
*
* @return the width of the lines used to draw this point.
*/
public float GetLineWidth() {
return lineWidth;
}
/**
*
* The line dash pattern controls the pattern of dashes and gaps used to stroke paths.
* It is specified by a dash array and a dash phase.
* The elements of the dash array are positive numbers that specify the lengths of
* alternating dashes and gaps.
* The dash phase specifies the distance into the dash pattern at which to start the dash.
* The elements of both the dash array and the dash phase are expressed in user space units.
* <pre>
* Examples of line dash patterns:
*
* "[Array] Phase" Appearance Description
* _______________ _________________ ____________________________________
*
* "[] 0" ----------------- Solid line
* "[3] 0" --- --- --- 3 units on, 3 units off, ...
* "[2] 1" - -- -- -- -- 1 on, 2 off, 2 on, 2 off, ...
* "[2 1] 0" -- -- -- -- -- -- 2 on, 1 off, 2 on, 1 off, ...
* "[3 5] 6" --- --- 2 off, 3 on, 5 off, 3 on, 5 off, ...
* "[2 3] 11" - -- -- -- 1 on, 3 off, 2 on, 3 off, 2 on, ...
* </pre>
*
* @param linePattern the line dash pattern.
*/
public void SetLinePattern(String linePattern) {
this.linePattern = linePattern;
}
/**
* Returns the line dash pattern.
*
* @return the line dash pattern.
*/
public String GetLinePattern() {
return linePattern;
}
/**
* Sets this point as the start of a path that will be drawn on the chart.
*
* @return the point.
*/
public Point SetDrawPath() {
this.drawPath = true;
return this;
}
/**
* Sets the URI for the "click point" action.
*
* @param uri the URI
*/
public void SetURIAction(String uri) {
this.uri = uri;
}
/**
* Returns the URI for the "click point" action.
*
* @return the URI for the "click point" action.
*/
public String GetURIAction() {
return uri;
}
/**
* Sets the point text.
*
* @param text the text.
*/
public void SetText(String text) {
this.text = text;
}
/**
* Returns the text associated with this point.
*
* @return the text.
*/
public String GetText() {
return text;
}
/**
* Sets the point's text color.
*
* @param textColor the text color.
*/
public void SetTextColor(int textColor) {
this.textColor = textColor;
}
/**
* Returns the point's text color.
*
* @return the text color.
*/
public int GetTextColor() {
return this.textColor;
}
/**
* Sets the point's text direction.
*
* @param textDirection the text direction.
*/
public void SetTextDirection(int textDirection) {
this.textDirection = textDirection;
}
/**
* Returns the point's text direction.
*
* @return the text direction.
*/
public int GetTextDirection() {
return this.textDirection;
}
/**
* Sets the point alignment.
*
* @param align the alignment value.
*/
public void SetAlignment(int align) {
this.align = align;
}
/**
* Returns the point alignment.
*
* @return align the alignment value.
*/
public int GetAlignment() {
return this.align;
}
/**
* Places this point in the specified box at position (0f, 0f).
*
* @param box the specified box.
*/
public void PlaceIn(Box box) {
PlaceIn(box, 0f, 0f);
}
/**
* Places this point in the specified box.
*
* @param box the specified box.
* @param xOffset the x offset from the top left corner of the box.
* @param yOffset the y offset from the top left corner of the box.
*/
public void PlaceIn(
Box box,
double xOffset,
double yOffset) {
PlaceIn(box, (float) xOffset, (float) yOffset);
}
/**
* Places this point in the specified box.
*
* @param box the specified box.
* @param xOffset the x offset from the top left corner of the box.
* @param yOffset the y offset from the top left corner of the box.
*/
public void PlaceIn(
Box box,
float xOffset,
float yOffset) {
xBox = box.x + xOffset;
yBox = box.y + yOffset;
}
/**
* Draws this point on the specified page.
*
* @param page the page to draw on.
* @return x and y coordinates of the bottom right corner of this component.
* @throws Exception
*/
public float[] DrawOn(Page page) {
page.SetPenWidth(lineWidth);
page.SetLinePattern(linePattern);
if (fillShape) {
page.SetBrushColor(color);
}
else {
page.SetPenColor(color);
}
x += xBox;
y += yBox;
page.DrawPoint(this);
x -= xBox;
y -= yBox;
return new float[] {x + xBox + r, y + yBox + r};
}
} // End of Point.cs
} // End of namespace PDFjet.NET
| 24.482051 | 136 | 0.572825 | [
"MIT"
] | edragoev1/pdfjet | net/pdfjet/Point.cs | 14,322 | 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 Xunit.Sdk;
namespace Xunit
{
// Similar to WpfFactAttribute https://github.com/xunit/samples.xunit/blob/969d9f7e887836f01a6c525324bf3db55658c28f/STAExamples/WpfFactAttribute.cs
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[XunitTestCaseDiscoverer("Xunit." + nameof(ForegroundFactDiscoverer), "Microsoft.VisualStudio.Editor.Razor.Test.Common")]
public class ForegroundFactAttribute : FactAttribute
{
}
}
| 39.8125 | 151 | 0.77865 | [
"Apache-2.0"
] | Chatina73/AspNetCore-Tooling | src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test.Common/Xunit/ForegroundFactAttribute.cs | 639 | C# |
//---------------------------------------------------------------------------
//
// File: TextContainerChangeEventArgs.cs
//
// Description: The arguments sent when a Change event is fired in a TextContainer.
//
//---------------------------------------------------------------------------
using System;
namespace System.Windows.Documents
{
/// <summary>
/// The TextContainerChangeEventArgs defines the event arguments sent when a
/// TextContainer is changed.
/// </summary>
internal class TextContainerChangeEventArgs : EventArgs
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
internal TextContainerChangeEventArgs(ITextPointer textPosition, int count, int charCount, TextChangeType textChange) :
this(textPosition, count, charCount, textChange, null, false)
{
}
internal TextContainerChangeEventArgs(ITextPointer textPosition, int count, int charCount, TextChangeType textChange, DependencyProperty property, bool affectsRenderOnly)
{
_textPosition = textPosition.GetFrozenPointer(LogicalDirection.Forward);
_count = count;
_charCount = charCount;
_textChange = textChange;
_property = property;
_affectsRenderOnly = affectsRenderOnly;
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
// Position of the segment start, expressed as an ITextPointer.
internal ITextPointer ITextPosition
{
get
{
return _textPosition;
}
}
// Number of chars covered by this segment.
internal int IMECharCount
{
get
{
return _charCount;
}
}
internal bool AffectsRenderOnly
{
get
{
return _affectsRenderOnly;
}
}
/// <summary>
///
/// </summary>
internal int Count
{
get
{
return _count;
}
}
/// <summary>
///
/// </summary>
internal TextChangeType TextChange
{
get
{
return _textChange;
}
}
/// <summary>
///
/// </summary>
internal DependencyProperty Property
{
get
{
return _property;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Position of the segment start, expressed as an ITextPointer.
private readonly ITextPointer _textPosition;
// Number of symbols covered by this segment.
private readonly int _count;
// Number of chars covered by this segment.
private readonly int _charCount;
// Type of change.
private readonly TextChangeType _textChange;
private readonly DependencyProperty _property;
private readonly bool _affectsRenderOnly;
#endregion Private Fields
}
}
| 26.107143 | 178 | 0.462654 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/wpf/src/Framework/System/Windows/Documents/TextContainerChangeEventArgs.cs | 3,655 | C# |
namespace Dev.DevKit.Shared.Entities
{
public partial class UII_savedsession
{
#region --- PROPERTIES ---
//public DateTime? DateTime { get { return GetAliasedValue<DateTime?>("c.birthdate"); } }
#endregion
#region --- STATIC METHODS ---
#endregion
}
}
| 18.294118 | 97 | 0.588424 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.12.31/TestAllEntities/All-DEMO/Dev.DevKit.Shared/Entities/UII_savedsession.cs | 313 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Apache.NMS;
using Apache.NMS.AMQP;
using NUnit.Framework;
namespace NMS.AMQP.Test
{
[TestFixture]
public class ConnectionFactoryTest
{
private static readonly string USER = "USER";
private static readonly string PASSWORD = "PASSWORD";
[Test]
public void TestConnectionFactoryCreate()
{
var factory = new NmsConnectionFactory();
Assert.Null(factory.UserName);
Assert.Null(factory.Password);
Assert.NotNull(factory.BrokerUri);
}
[Test]
public void TestConnectionFactoryCreateUsernameAndPassword()
{
NmsConnectionFactory factory = new NmsConnectionFactory(USER, PASSWORD);
Assert.NotNull(factory.UserName);
Assert.That(factory.UserName, Is.EqualTo(USER));
Assert.NotNull(factory.Password);
Assert.That(factory.Password, Is.EqualTo(PASSWORD));
}
[Test]
public void TestConnectionFactoryCreateUsernamePasswordAndBrokerUri()
{
NmsConnectionFactory factory = new NmsConnectionFactory(USER, PASSWORD, "mock://localhost:5000");
Assert.NotNull(factory.UserName);
Assert.That(factory.UserName, Is.EqualTo(USER));
Assert.NotNull(factory.Password);
Assert.That(factory.Password, Is.EqualTo(PASSWORD));
var brokerUri = factory.BrokerUri;
Assert.NotNull(brokerUri);
Assert.That(brokerUri.Authority, Is.EqualTo("localhost:5000"));
Assert.That(brokerUri.Scheme, Is.EqualTo("mock"));
Assert.That(brokerUri.Port, Is.EqualTo(5000));
}
[Test]
public void TestSetPropertiesFromStringUri()
{
string baseUri = "amqp://localhost:1234";
string configuredUri = baseUri +
"?nms.username=user" +
"&nms.password=password" +
"&nms.clientId=client" +
"&nms.connectionIdPrefix=ID:TEST" +
"&nms.clientIDPrefix=clientId" +
"&nms.requestTimeout=1000" +
"&nms.sendTimeout=1000" +
"&nms.localMessageExpiry=false";
NmsConnectionFactory factory = new NmsConnectionFactory(configuredUri);
Assert.AreEqual("user", factory.UserName);
Assert.AreEqual("password", factory.Password);
Assert.AreEqual("client", factory.ClientId);
Assert.AreEqual("ID:TEST", factory.ConnectionIdPrefix);
Assert.AreEqual("clientId", factory.ClientIdPrefix);
Assert.AreEqual(1000, factory.RequestTimeout);
Assert.AreEqual(1000, factory.SendTimeout);
Assert.IsFalse(factory.LocalMessageExpiry);
}
[Test]
public void TestSetPropertiesFromUri()
{
string baseUri = "amqp://localhost:1234";
string configuredUri = baseUri +
"?nms.username=user" +
"&nms.password=password" +
"&nms.clientId=client" +
"&nms.connectionIdPrefix=ID:TEST" +
"&nms.clientIDPrefix=clientId" +
"&nms.requestTimeout=1000" +
"&nms.sendTimeout=1000" +
"&nms.closeTimeout=2000" +
"&nms.localMessageExpiry=false";
NmsConnectionFactory factory = new NmsConnectionFactory(new Uri(configuredUri));
Assert.AreEqual("user", factory.UserName);
Assert.AreEqual("password", factory.Password);
Assert.AreEqual("client", factory.ClientId);
Assert.AreEqual("ID:TEST", factory.ConnectionIdPrefix);
Assert.AreEqual("clientId", factory.ClientIdPrefix);
Assert.AreEqual(1000, factory.RequestTimeout);
Assert.AreEqual(1000, factory.SendTimeout);
Assert.AreEqual(2000, factory.CloseTimeout);
Assert.IsFalse(factory.LocalMessageExpiry);
}
[Test]
public void TestCreateConnectionBadBrokerUri()
{
NmsConnectionFactory factory = new NmsConnectionFactory
{
BrokerUri = new Uri("bad://127.0.0.1:5763")
};
Assert.Throws<NMSException>(() => factory.CreateConnection());
}
[Test]
public void TestCreateConnectionBadProviderString()
{
NmsConnectionFactory factory = new NmsConnectionFactory("bad://127.0.0.1:5763");
Assert.Throws<NMSException>(() => factory.CreateConnection());
}
}
} | 40.671429 | 109 | 0.586758 | [
"Apache-2.0"
] | brudo/activemq-nms-amqp | test/Apache-NMS-AMQP-Test/ConnectionFactoryTest.cs | 5,696 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.R_kvstore.Model.V20150101;
namespace Aliyun.Acs.R_kvstore.Transform.V20150101
{
public class SwitchNetworkResponseUnmarshaller
{
public static SwitchNetworkResponse Unmarshall(UnmarshallerContext _ctx)
{
SwitchNetworkResponse switchNetworkResponse = new SwitchNetworkResponse();
switchNetworkResponse.HttpResponse = _ctx.HttpResponse;
switchNetworkResponse.RequestId = _ctx.StringValue("SwitchNetwork.RequestId");
switchNetworkResponse.TaskId = _ctx.StringValue("SwitchNetwork.TaskId");
return switchNetworkResponse;
}
}
}
| 36.560976 | 82 | 0.757839 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-r-kvstore/R_kvstore/Transform/V20150101/SwitchNetworkResponseUnmarshaller.cs | 1,499 | C# |
using System;
namespace MediatR.Dynamic.Example.Test
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 19.3125 | 69 | 0.614887 | [
"Apache-2.0"
] | BMGDigitalTech/MediatR.Dynamic | src/Example/MediatR.Dynamic.Example.Test/WeatherForecast.cs | 309 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// ReSharper disable CompareOfFloatsByEqualityOperator
namespace ImageFramework.Utility
{
public struct Float2
{
public float X;
public float Y;
public float this[int key]
{
get
{
if (key == 0) return X;
Debug.Assert(key == 1);
return Y;
}
set
{
Debug.Assert(key >= 0 && key <= 1);
if (key == 0) X = value;
if (key == 1) Y = value;
}
}
public Float2(float value = 0.0f)
{
X = value;
Y = value;
}
public Float2(float x, float y)
{
X = x;
Y = y;
}
public static readonly Float2 Zero = new Float2();
public static readonly Float2 One = new Float2(1.0f);
public static readonly Float2 NegOne = new Float2(-1.0f);
public override string ToString()
{
return $"{X}, {Y}";
}
public static bool operator ==(Float2 left, Float2 right)
{
return left.Equals(right);
}
public static bool operator !=(Float2 left, Float2 right)
{
return !(left == right);
}
public static Float2 operator +(Float2 left, Float2 right)
{
return new Float2(left.X + right.X, left.Y + right.Y);
}
public static Float2 operator -(Float2 left, Float2 right)
{
return new Float2(left.X - right.X, left.Y - right.Y);
}
public static Float2 operator *(Float2 left, Float2 right)
{
return new Float2(left.X * right.X, left.Y * right.Y);
}
public static Float2 operator *(Float2 left, float right)
{
return new Float2(left.X * right, left.Y * right);
}
public static Float2 operator *(float left, Float2 right)
{
return new Float2(left * right.X, left * right.Y);
}
public static Float2 operator /(Float2 left, Float2 right)
{
return new Float2(left.X / right.X, left.Y / right.Y);
}
public bool Equals(Float2 other)
{
return X == other.X && Y == other.Y;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Float2 other && Equals(other);
}
public override int GetHashCode()
{
unsafe
{
var hashCode = AsInt(X);
hashCode = (hashCode * 397) ^ AsInt(Y);
return hashCode;
}
}
private unsafe int AsInt(float v)
{
float* fp = &v;
return *(int*)fp;
}
public Size2 ToPixels(Size2 size)
{
return new Size2(
Utility.Clamp((int)(X * size.X), 0, size.X - 1),
Utility.Clamp((int)(Y * size.Y), 0, size.Y - 1)
);
}
public Float2 Clamp(Float2 min, Float2 max)
{
return new Float2(
Utility.Clamp(X, min.X, max.X),
Utility.Clamp(Y, min.Y, max.Y)
);
}
public Float2 Normalize()
{
var len = (float)Math.Sqrt((double)(X * X + Y * Y));
return new Float2(X / len, Y / len);
}
public Float2 RotateCCW()
{
return new Float2(-Y, X);
}
}
}
| 26.22973 | 67 | 0.457754 | [
"MIT"
] | hnjm/ImageViewer | ImageFramework/Utility/Float2.cs | 3,884 | 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.
*
* Key Management Service
* 基于硬件保护密钥的安全数据托管服务
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using JDCloudSDK.Core.Client;
using JDCloudSDK.Core.Http;
using System;
using System.Collections.Generic;
using System.Text;
namespace JDCloudSDK.Kms.Client
{
/// <summary>
/// 使用密钥对数据进行加密,针对非对称密钥:使用公钥进行加密,仅支持RSA_PKCS1_PADDING填充方式,最大加密数据长度为245字节
/// </summary>
public class EncryptExecutor : JdcloudExecutor
{
/// <summary>
/// 使用密钥对数据进行加密,针对非对称密钥:使用公钥进行加密,仅支持RSA_PKCS1_PADDING填充方式,最大加密数据长度为245字节接口的Http 请求方法
/// </summary>
public override string Method
{
get {
return "POST";
}
}
/// <summary>
/// 使用密钥对数据进行加密,针对非对称密钥:使用公钥进行加密,仅支持RSA_PKCS1_PADDING填充方式,最大加密数据长度为245字节接口的Http资源请求路径
/// </summary>
public override string Url
{
get {
return "/key/{keyId}:Encrypt";
}
}
}
}
| 27.35 | 94 | 0.657526 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Kms/Client/EncryptExecutor.cs | 1,995 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementOrStatementStatementAndStatementStatementNotStatementStatementIpSetReferenceStatementIpSetForwardedIpConfigArgs : Pulumi.ResourceArgs
{
/// <summary>
/// - Match status to assign to the web request if the request doesn't have a valid IP address in the specified position. Valid values include: `MATCH` or `NO_MATCH`.
/// </summary>
[Input("fallbackBehavior", required: true)]
public Input<string> FallbackBehavior { get; set; } = null!;
/// <summary>
/// - Name of the HTTP header to use for the IP address.
/// </summary>
[Input("headerName", required: true)]
public Input<string> HeaderName { get; set; } = null!;
/// <summary>
/// - Position in the header to search for the IP address. Valid values include: `FIRST`, `LAST`, or `ANY`. If `ANY` is specified and the header contains more than 10 IP addresses, AWS WAFv2 inspects the last 10.
/// </summary>
[Input("position", required: true)]
public Input<string> Position { get; set; } = null!;
public WebAclRuleStatementOrStatementStatementAndStatementStatementNotStatementStatementIpSetReferenceStatementIpSetForwardedIpConfigArgs()
{
}
}
}
| 43.289474 | 220 | 0.68693 | [
"ECL-2.0",
"Apache-2.0"
] | chivandikwa/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementOrStatementStatementAndStatementStatementNotStatementStatementIpSetReferenceStatementIpSetForwardedIpConfigArgs.cs | 1,645 | C# |
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
using System;
using NetExtender.Types.Network;
namespace NetExtender.Utilities.IO
{
public class UrlUtilities
{
public static Boolean IsValidUrl(String path)
{
return !String.IsNullOrEmpty(path) && Uri.TryCreate(path, UriKind.Absolute, out Uri? uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
}
public static Boolean IsUrlContainData(String path)
{
if (!IsValidUrl(path))
{
return false;
}
using WebClientExtended client = new WebClientExtended
{
HeadOnly = true
};
return !String.IsNullOrEmpty(client.DownloadString(path));
}
}
} | 30.354839 | 175 | 0.599362 | [
"MIT"
] | Rain0Ash/NetExtender | NetExtender.Core/Utilities/IO/UrlUtilities.cs | 941 | C# |
//////////////////////////////////////////////////////////////////////////
// Criacao...........: 06/2014
// Sistema...........: Loja Virtual
// Analistas.........: Marilene Esquiavoni & Denny Paulista Azevedo Filho
// Desenvolvedores...: Marilene Esquiavoni & Denny Paulista Azevedo Filho
// Copyright.........: Marilene Esquiavoni & Denny Paulista Azevedo Filho
//////////////////////////////////////////////////////////////////////////
using System.Web;
using System.Web.Mvc;
using MD.LojaVirtual.Web.V2.HtmlHelpers;
namespace MD.LojaVirtual.Web.V2
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new InjectPageMetadataAttribute());
}
}
}
| 32.708333 | 76 | 0.569427 | [
"MIT"
] | MDsolucoesTI/LojaVirtual | MD.LojaVirtual.Web.V2/App_Start/FilterConfig.cs | 787 | C# |
using Authorization;
using Authorization.Models;
using Moq;
using System.Collections.Generic;
namespace Functions.Tests.Mocks
{
internal static class MockIAccessTokenValidator
{
internal static Mock<IAccessTokenValidator> Get()
{
var mock = new Mock<IAccessTokenValidator>(MockBehavior.Strict);
return mock;
}
internal static void SetupValidateToken(
this Mock<IAccessTokenValidator> mockAccessTokenValidator,
IAccessTokenResult accessTokenResult
)
{
mockAccessTokenValidator.Setup(mock => mock.ValidateToken(It.IsAny<IDictionary<string, string>>()))
.ReturnsAsync(accessTokenResult);
}
}
} | 26.571429 | 111 | 0.657258 | [
"MIT"
] | yuriys-kentico/ConsultingTransfers | Functions.Tests/Mocks/MockIAccessTokenValidator.cs | 746 | C# |
using System;
using System.Collections.Generic;
using EventFly.Aggregates.Snapshot;
using EventFly.Tests.Data.Abstractions;
namespace EventFly.Tests.Data.Domain.Snapshots
{
public class TestAggregateSnapshot : IAggregateSnapshot<TestAggregate, TestAggregateId>
{
public List<TestModel> Tests { get; }
public TestAggregateSnapshot(List<TestModel> tests)
{
Tests = tests;
}
public class TestModel
{
public Guid Id { get; }
public TestModel(Guid id)
{
Id = id;
}
}
}
} | 22.703704 | 91 | 0.597064 | [
"MIT"
] | Sporteco/EventFly | test/EventFly.TestHelpers/Data/Domain/Snapshots/TestAggregateSnapshot.cs | 613 | C# |
#if !NETSTANDARD13
/*
* 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 alexaforbusiness-2017-11-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.AlexaForBusiness.Model
{
/// <summary>
/// Base class for SearchUsers paginators.
/// </summary>
internal sealed partial class SearchUsersPaginator : IPaginator<SearchUsersResponse>, ISearchUsersPaginator
{
private readonly IAmazonAlexaForBusiness _client;
private readonly SearchUsersRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<SearchUsersResponse> Responses => new PaginatedResponse<SearchUsersResponse>(this);
internal SearchUsersPaginator(IAmazonAlexaForBusiness client, SearchUsersRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<SearchUsersResponse> IPaginator<SearchUsersResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
SearchUsersResponse response;
do
{
_request.NextToken = nextToken;
response = _client.SearchUsers(_request);
nextToken = response.NextToken;
yield return response;
}
while (nextToken != null);
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<SearchUsersResponse> IPaginator<SearchUsersResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
SearchUsersResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.SearchUsersAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (nextToken != null);
}
#endif
}
}
#endif | 37.538462 | 150 | 0.657494 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/AlexaForBusiness/Generated/Model/_bcl45+netstandard/SearchUsersPaginator.cs | 3,416 | C# |
/**
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using FullSerializer;
using IBM.Watson.DeveloperCloud.Connection;
using IBM.Watson.DeveloperCloud.Logging;
using IBM.Watson.DeveloperCloud.Utilities;
using IBM.WatsonDeveloperCloud.Assistant.v2;
using System;
using System.Collections.Generic;
using System.Text;
namespace IBM.Watson.DeveloperCloud.Services.Assistant.v2
{
public class Assistant : IWatsonService
{
private const string ServiceId = "AssistantV2";
private fsSerializer _serializer = new fsSerializer();
private Credentials _credentials = null;
/// <summary>
/// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined.
/// </summary>
public Credentials Credentials
{
get { return _credentials; }
set
{
_credentials = value;
if (!string.IsNullOrEmpty(_credentials.Url))
{
_url = _credentials.Url;
}
}
}
private string _url = "https://gateway.watsonplatform.net/assistant/api";
/// <summary>
/// Gets and sets the endpoint URL for the service.
/// </summary>
public string Url
{
get { return _url; }
set { _url = value; }
}
private string _versionDate;
/// <summary>
/// Gets and sets the versionDate of the service.
/// </summary>
public string VersionDate
{
get { return _versionDate; }
set { _versionDate = value; }
}
/// <summary>
/// Assistant constructor.
/// </summary>
/// <param name="credentials">The service credentials.</param>
public Assistant(Credentials credentials)
{
if (credentials.HasCredentials() || credentials.HasIamTokenData())
{
Credentials = credentials;
if (string.IsNullOrEmpty(credentials.Url))
{
credentials.Url = Url;
}
}
else
{
throw new WatsonException("Please provide a username and password or authorization token to use the Assistant service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials");
}
}
#region Callback delegates
/// <summary>
/// Success callback delegate.
/// </summary>
/// <typeparam name="T">Type of the returned object.</typeparam>
/// <param name="response">The returned object.</param>
/// <param name="customData">user defined custom data including raw json.</param>
public delegate void SuccessCallback<T>(T response, Dictionary<string, object> customData);
/// <summary>
/// Fail callback delegate.
/// </summary>
/// <param name="error">The error object.</param>
/// <param name="customData">User defined custom data</param>
public delegate void FailCallback(RESTConnector.Error error, Dictionary<string, object> customData);
#endregion
/// <summary>
/// Create a session.
///
/// Create a new session. A session is used to send user input to a skill and receive responses. It also
/// maintains the state of the conversation.
/// </summary>
/// <param name="successCallback">The function that is called when the operation is successful.</param>
/// <param name="failCallback">The function that is called when the operation fails.</param>
/// <param name="assistantId">Unique identifier of the assistant. You can find the assistant ID of an assistant
/// on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the
/// [documentation](https://console.bluemix.net/docs/services/assistant/create-assistant.html#creating-assistants).
///
/// **Note:** Currently, the v2 API does not support creating assistants.</param>
/// <returns><see cref="SessionResponse" />SessionResponse</returns>
/// <param name="customData">A Dictionary<string, object> of data that will be passed to the callback. The raw
/// json output from the REST call will be passed in this object as the value of the 'json'
/// key.</string></param>
public bool CreateSession(SuccessCallback<SessionResponse> successCallback, FailCallback failCallback, String assistantId, Dictionary<string, object> customData = null)
{
if (successCallback == null)
throw new ArgumentNullException("successCallback");
if (failCallback == null)
throw new ArgumentNullException("failCallback");
CreateSessionRequestObj req = new CreateSessionRequestObj();
req.SuccessCallback = successCallback;
req.FailCallback = failCallback;
req.CustomData = customData == null ? new Dictionary<string, object>() : customData;
if(req.CustomData.ContainsKey(Constants.String.CUSTOM_REQUEST_HEADERS))
{
foreach(KeyValuePair<string, string> kvp in req.CustomData[Constants.String.CUSTOM_REQUEST_HEADERS] as Dictionary<string, string>)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
}
req.Headers["Content-Type"] = "application/json";
req.Parameters["version"] = VersionDate;
req.OnResponse = OnCreateSessionResponse;
req.Post = true;
RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v2/assistants/{0}/sessions", assistantId));
if (connector == null)
return false;
return connector.Send(req);
}
private class CreateSessionRequestObj : RESTConnector.Request
{
/// <summary>
/// The success callback.
/// </summary>
public SuccessCallback<SessionResponse> SuccessCallback { get; set; }
/// <summary>
/// The fail callback.
/// </summary>
public FailCallback FailCallback { get; set; }
/// <summary>
/// Custom data.
/// </summary>
public Dictionary<string, object> CustomData { get; set; }
}
private void OnCreateSessionResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
SessionResponse result = new SessionResponse();
fsData data = null;
Dictionary<string, object> customData = ((CreateSessionRequestObj)req).CustomData;
if (resp.Success)
{
try
{
fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
object obj = result;
r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
customData.Add("json", data);
}
catch (Exception e)
{
Log.Error("Assistant.OnCreateSessionResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
}
if (resp.Success)
{
if (((CreateSessionRequestObj)req).SuccessCallback != null)
((CreateSessionRequestObj)req).SuccessCallback(result, customData);
}
else
{
if (((CreateSessionRequestObj)req).FailCallback != null)
((CreateSessionRequestObj)req).FailCallback(resp.Error, customData);
}
}
/// <summary>
/// Delete session.
///
/// Deletes a session explicitly before it times out.
/// </summary>
/// <param name="successCallback">The function that is called when the operation is successful.</param>
/// <param name="failCallback">The function that is called when the operation fails.</param>
/// <param name="assistantId">Unique identifier of the assistant. You can find the assistant ID of an assistant
/// on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the
/// [documentation](https://console.bluemix.net/docs/services/assistant/create-assistant.html#creating-assistants).
///
/// **Note:** Currently, the v2 API does not support creating assistants.</param>
/// <param name="sessionId">Unique identifier of the session.</param>
/// <returns><see cref="" />object</returns>
/// <param name="customData">A Dictionary<string, object> of data that will be passed to the callback. The raw
/// json output from the REST call will be passed in this object as the value of the 'json'
/// key.</string></param>
public bool DeleteSession(SuccessCallback<object> successCallback, FailCallback failCallback, String assistantId, String sessionId, Dictionary<string, object> customData = null)
{
if (successCallback == null)
throw new ArgumentNullException("successCallback");
if (failCallback == null)
throw new ArgumentNullException("failCallback");
DeleteSessionRequestObj req = new DeleteSessionRequestObj();
req.SuccessCallback = successCallback;
req.FailCallback = failCallback;
req.CustomData = customData == null ? new Dictionary<string, object>() : customData;
if(req.CustomData.ContainsKey(Constants.String.CUSTOM_REQUEST_HEADERS))
{
foreach(KeyValuePair<string, string> kvp in req.CustomData[Constants.String.CUSTOM_REQUEST_HEADERS] as Dictionary<string, string>)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
}
req.Parameters["version"] = VersionDate;
req.OnResponse = OnDeleteSessionResponse;
req.Delete = true;
RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v2/assistants/{0}/sessions/{1}", assistantId, sessionId));
if (connector == null)
return false;
return connector.Send(req);
}
private class DeleteSessionRequestObj : RESTConnector.Request
{
/// <summary>
/// The success callback.
/// </summary>
public SuccessCallback<object> SuccessCallback { get; set; }
/// <summary>
/// The fail callback.
/// </summary>
public FailCallback FailCallback { get; set; }
/// <summary>
/// Custom data.
/// </summary>
public Dictionary<string, object> CustomData { get; set; }
}
private void OnDeleteSessionResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
object result = new object();
fsData data = null;
Dictionary<string, object> customData = ((DeleteSessionRequestObj)req).CustomData;
if (resp.Success)
{
try
{
fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
object obj = result;
r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
customData.Add("json", data);
}
catch (Exception e)
{
Log.Error("Assistant.OnDeleteSessionResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
}
if (resp.Success)
{
if (((DeleteSessionRequestObj)req).SuccessCallback != null)
((DeleteSessionRequestObj)req).SuccessCallback(result, customData);
}
else
{
if (((DeleteSessionRequestObj)req).FailCallback != null)
((DeleteSessionRequestObj)req).FailCallback(resp.Error, customData);
}
}
/// <summary>
/// Send user input to assistant.
///
/// Send user input to an assistant and receive a response.
///
/// There is no rate limit for this operation.
/// </summary>
/// <param name="successCallback">The function that is called when the operation is successful.</param>
/// <param name="failCallback">The function that is called when the operation fails.</param>
/// <param name="assistantId">Unique identifier of the assistant. You can find the assistant ID of an assistant
/// on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the
/// [documentation](https://console.bluemix.net/docs/services/assistant/create-assistant.html#creating-assistants).
///
/// **Note:** Currently, the v2 API does not support creating assistants.</param>
/// <param name="sessionId">Unique identifier of the session.</param>
/// <param name="request">The message to be sent. This includes the user's input, along with optional intents,
/// entities, and context from the last response. (optional)</param>
/// <returns><see cref="MessageResponse" />MessageResponse</returns>
/// <param name="customData">A Dictionary<string, object> of data that will be passed to the callback. The raw
/// json output from the REST call will be passed in this object as the value of the 'json'
/// key.</string></param>
public bool Message(SuccessCallback<MessageResponse> successCallback, FailCallback failCallback, String assistantId, String sessionId, MessageRequest request = null, Dictionary<string, object> customData = null)
{
if (successCallback == null)
throw new ArgumentNullException("successCallback");
if (failCallback == null)
throw new ArgumentNullException("failCallback");
MessageRequestObj req = new MessageRequestObj();
req.SuccessCallback = successCallback;
req.FailCallback = failCallback;
req.CustomData = customData == null ? new Dictionary<string, object>() : customData;
if(req.CustomData.ContainsKey(Constants.String.CUSTOM_REQUEST_HEADERS))
{
foreach(KeyValuePair<string, string> kvp in req.CustomData[Constants.String.CUSTOM_REQUEST_HEADERS] as Dictionary<string, string>)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
}
IDictionary<string, string> requestDict = new Dictionary<string, string>();
int iterator = 0;
StringBuilder stringBuilder = new StringBuilder("{");
foreach (KeyValuePair<string, string> property in requestDict)
{
string delimeter = iterator < requestDict.Count - 1 ? "," : "";
stringBuilder.Append(string.Format("\"{0}\": {1}{2}", property.Key, property.Value, delimeter));
iterator++;
}
stringBuilder.Append("}");
string stringToSend = stringBuilder.ToString();
req.Send = Encoding.UTF8.GetBytes(stringToSend);
req.Headers["Content-Type"] = "application/json";
req.Parameters["version"] = VersionDate;
req.OnResponse = OnMessageResponse;
RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v2/assistants/{0}/sessions/{1}/message", assistantId, sessionId));
if (connector == null)
return false;
return connector.Send(req);
}
private class MessageRequestObj : RESTConnector.Request
{
/// <summary>
/// The success callback.
/// </summary>
public SuccessCallback<MessageResponse> SuccessCallback { get; set; }
/// <summary>
/// The fail callback.
/// </summary>
public FailCallback FailCallback { get; set; }
/// <summary>
/// Custom data.
/// </summary>
public Dictionary<string, object> CustomData { get; set; }
}
private void OnMessageResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
MessageResponse result = new MessageResponse();
fsData data = null;
Dictionary<string, object> customData = ((MessageRequestObj)req).CustomData;
if (resp.Success)
{
try
{
fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
object obj = result;
r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
customData.Add("json", data);
}
catch (Exception e)
{
Log.Error("Assistant.OnMessageResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
}
if (resp.Success)
{
if (((MessageRequestObj)req).SuccessCallback != null)
((MessageRequestObj)req).SuccessCallback(result, customData);
}
else
{
if (((MessageRequestObj)req).FailCallback != null)
((MessageRequestObj)req).FailCallback(resp.Error, customData);
}
}
#region IWatsonService Interface
/// <exclude />
public string GetServiceID()
{
return ServiceId;
}
#endregion
}
}
| 43.670429 | 253 | 0.579293 | [
"Apache-2.0"
] | Juleffel/unity-sdk | Scripts/Services/Assistant/v2/Assistant.cs | 19,346 | C# |
namespace DotNext.Net.Cluster.Consensus.Raft;
/// <summary>
/// Represents buffering options used for batch processing of log entries.
/// </summary>
public class RaftLogEntriesBufferingOptions : RaftLogEntryBufferingOptions
{
private const int DefaultMemoryLimit = 10 * 1024 * 1024;
private int memoryLimit = DefaultMemoryLimit;
/// <summary>
/// The maximum amount of memory that can be allocated for the buffered log entry.
/// </summary>
/// <remarks>
/// If the limit is reached then the log entries will be stored on the disk.
/// </remarks>
public int MemoryLimit
{
get => memoryLimit;
set => memoryLimit = value > 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
}
} | 35.181818 | 103 | 0.669251 | [
"MIT"
] | copenhagenatomics/dotNext | src/cluster/DotNext.Net.Cluster/Net/Cluster/Consensus/Raft/RaftLogEntriesBufferingOptions.cs | 774 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rest-json-test-2016-04-12.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.RestJsonTest.Model;
using Amazon.RestJsonTest.Model.Internal.MarshallTransformations;
using Amazon.RestJsonTest.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.RestJsonTest
{
/// <summary>
/// Implementation for accessing RestJsonTest
///
///
/// </summary>
public partial class AmazonRestJsonTestClient : AmazonServiceClient, IAmazonRestJsonTest
{
private static IServiceMetadata serviceMetadata = new AmazonRestJsonTestMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonRestJsonTestClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonRestJsonTestClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonRestJsonTestConfig()) { }
/// <summary>
/// Constructs AmazonRestJsonTestClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonRestJsonTestClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonRestJsonTestConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonRestJsonTestClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonRestJsonTestClient Configuration Object</param>
public AmazonRestJsonTestClient(AmazonRestJsonTestConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonRestJsonTestClient(AWSCredentials credentials)
: this(credentials, new AmazonRestJsonTestConfig())
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonRestJsonTestClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonRestJsonTestConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Credentials and an
/// AmazonRestJsonTestClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonRestJsonTestClient Configuration Object</param>
public AmazonRestJsonTestClient(AWSCredentials credentials, AmazonRestJsonTestConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonRestJsonTestClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonRestJsonTestConfig())
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonRestJsonTestClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonRestJsonTestConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonRestJsonTestClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonRestJsonTestClient Configuration Object</param>
public AmazonRestJsonTestClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonRestJsonTestConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonRestJsonTestClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonRestJsonTestConfig())
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonRestJsonTestClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonRestJsonTestConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonRestJsonTestClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonRestJsonTestClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonRestJsonTestClient Configuration Object</param>
public AmazonRestJsonTestClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonRestJsonTestConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region NoPayload
/// <summary>
/// Request without a body
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the NoPayload service method.</param>
///
/// <returns>The response from the NoPayload service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/NoPayload">REST API Reference for NoPayload Operation</seealso>
public virtual NoPayloadResponse NoPayload(NoPayloadRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = NoPayloadRequestMarshaller.Instance;
options.ResponseUnmarshaller = NoPayloadResponseUnmarshaller.Instance;
return Invoke<NoPayloadResponse>(request, options);
}
/// <summary>
/// Request without a body
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the NoPayload service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the NoPayload service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/NoPayload">REST API Reference for NoPayload Operation</seealso>
public virtual Task<NoPayloadResponse> NoPayloadAsync(NoPayloadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = NoPayloadRequestMarshaller.Instance;
options.ResponseUnmarshaller = NoPayloadResponseUnmarshaller.Instance;
return InvokeAsync<NoPayloadResponse>(request, options, cancellationToken);
}
#endregion
#region TestBlobPayload
/// <summary>
/// Post a test blob payload request.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestBlobPayload service method.</param>
///
/// <returns>The response from the TestBlobPayload service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/TestBlobPayload">REST API Reference for TestBlobPayload Operation</seealso>
public virtual TestBlobPayloadResponse TestBlobPayload(TestBlobPayloadRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TestBlobPayloadRequestMarshaller.Instance;
options.ResponseUnmarshaller = TestBlobPayloadResponseUnmarshaller.Instance;
return Invoke<TestBlobPayloadResponse>(request, options);
}
/// <summary>
/// Post a test blob payload request.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestBlobPayload service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TestBlobPayload service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/TestBlobPayload">REST API Reference for TestBlobPayload Operation</seealso>
public virtual Task<TestBlobPayloadResponse> TestBlobPayloadAsync(TestBlobPayloadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = TestBlobPayloadRequestMarshaller.Instance;
options.ResponseUnmarshaller = TestBlobPayloadResponseUnmarshaller.Instance;
return InvokeAsync<TestBlobPayloadResponse>(request, options, cancellationToken);
}
#endregion
#region TestBody
/// <summary>
/// Post a test body request.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestBody service method.</param>
///
/// <returns>The response from the TestBody service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/TestBody">REST API Reference for TestBody Operation</seealso>
public virtual TestBodyResponse TestBody(TestBodyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TestBodyRequestMarshaller.Instance;
options.ResponseUnmarshaller = TestBodyResponseUnmarshaller.Instance;
return Invoke<TestBodyResponse>(request, options);
}
/// <summary>
/// Post a test body request.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestBody service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TestBody service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/TestBody">REST API Reference for TestBody Operation</seealso>
public virtual Task<TestBodyResponse> TestBodyAsync(TestBodyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = TestBodyRequestMarshaller.Instance;
options.ResponseUnmarshaller = TestBodyResponseUnmarshaller.Instance;
return InvokeAsync<TestBodyResponse>(request, options, cancellationToken);
}
#endregion
#region TestPayload
/// <summary>
/// Post a test payload request.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestPayload service method.</param>
///
/// <returns>The response from the TestPayload service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/TestPayload">REST API Reference for TestPayload Operation</seealso>
public virtual TestPayloadResponse TestPayload(TestPayloadRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TestPayloadRequestMarshaller.Instance;
options.ResponseUnmarshaller = TestPayloadResponseUnmarshaller.Instance;
return Invoke<TestPayloadResponse>(request, options);
}
/// <summary>
/// Post a test payload request.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestPayload service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TestPayload service method, as returned by RestJsonTest.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/test-2021-05-13/TestPayload">REST API Reference for TestPayload Operation</seealso>
public virtual Task<TestPayloadResponse> TestPayloadAsync(TestPayloadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = TestPayloadRequestMarshaller.Instance;
options.ResponseUnmarshaller = TestPayloadResponseUnmarshaller.Instance;
return InvokeAsync<TestPayloadResponse>(request, options, cancellationToken);
}
#endregion
}
} | 45.004926 | 188 | 0.654335 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/test/Services/RestJsonTest/Generated/_bcl45/AmazonRestJsonTestClient.cs | 18,272 | C# |
/*
* This class was auto-generated from the API references found at
* https://epayments-api.developer-ingenico.com/s2sapi/v1/
*/
using Ingenico.Connect.Sdk.Domain.Definitions;
using System;
using System.Collections.Generic;
namespace Ingenico.Connect.Sdk.Domain.Payment.Definitions
{
public class Order
{
/// <summary>
/// Object containing additional input on the order
/// </summary>
public AdditionalOrderInput AdditionalInput { get; set; } = null;
/// <summary>
/// Object containing amount and ISO currency code attributes
/// </summary>
public AmountOfMoney AmountOfMoney { get; set; } = null;
/// <summary>
/// Object containing the details of the customer
/// </summary>
public Customer Customer { get; set; } = null;
/// <summary>
/// Shopping cart data
/// </summary>
[ObsoleteAttribute("Use shoppingCart.items instead")]
public IList<LineItem> Items { get; set; } = null;
/// <summary>
/// Object that holds all reference properties that are linked to this transaction
/// </summary>
public OrderReferences References { get; set; } = null;
/// <summary>
/// Object containing seller details
/// </summary>
[ObsoleteAttribute("Use Merchant.seller instead")]
public Seller Seller { get; set; } = null;
/// <summary>
/// Object containing information regarding shipping / delivery
/// </summary>
public Shipping Shipping { get; set; } = null;
/// <summary>
/// Shopping cart data, including items and specific amounts.
/// </summary>
public ShoppingCart ShoppingCart { get; set; } = null;
}
}
| 32.071429 | 90 | 0.603007 | [
"MIT"
] | Ingenico-ePayments/connect-sdk-dotnet | connect-sdk-dotnet/Domain/Payment/Definitions/Order.cs | 1,796 | C# |
using System.Collections.Generic;
using System.Linq;
using App.Models;
using App.Models.Project;
using App.Mongo;
using MongoDB.Bson;
using MongoDB.Driver;
namespace App.Services
{
public interface IProjectService
{
ObjectId Create(ProjectModel model);
void AddMember(ObjectId id, RegisterViewModel owner);
List<ProjectListModel> Get(string email);
}
public class ProjectService : IProjectService
{
private readonly MongoDbImplementation _database;
public ProjectService()
{
_database = new MongoDbImplementation(TableNameConstants.Projects);
}
public ObjectId Create(ProjectModel model)
{
_database.Create(model);
return model.Id;
}
public void AddMember(ObjectId id, RegisterViewModel owner)
{
var filter = Builders<ProjectModel>.Filter.Where(x => x.Id == id);
ProjectModel project = _database.FindOne(filter);
if (project.Members == null)
project.Members = new List<RegisterViewModel>();
project.Members.Add(owner);
}
public List<ProjectListModel> Get(string email)
{
var filter = Builders<ProjectModel>.Filter.Where(x => x.Members.Any(y => y.Email == email));
List<ProjectModel> projects = _database.FindAll(filter);
List<ProjectListModel> listing = new List<ProjectListModel>();
foreach (ProjectModel project in projects)
{
ProjectListModel p = new ProjectListModel
{
Id = project.Id,
Title = project.Title,
Members = new List<ProjectMembersModel>()
};
foreach (var member in project.Members)
{
p.Members.Add(new ProjectMembersModel
{
Email = member.Email,
Name = member.Name,
});
}
listing.Add(p);
}
return listing;
}
}
} | 31.173913 | 104 | 0.553231 | [
"Apache-2.0"
] | yrshaikh/Project-Management | App/Services/IProjectService.cs | 2,153 | C# |
using System.Runtime.Serialization;
namespace Slack.NetStandard
{
public enum TextType
{
[EnumMember(Value="plain_text")]
PlainText,
[EnumMember(Value="mrkdwn")]
Markdown
}
} | 18.333333 | 40 | 0.622727 | [
"MIT"
] | AbsShek/Slack.NetStandard | Slack.NetStandard/TextType.cs | 222 | C# |
using System;
using System.IO;
using System.Threading;
using EventStore.Common.Utils;
using EventStore.Projections.Core.v8;
using NUnit.Framework;
namespace EventStore.Projections.Core.Tests.Services.v8
{
[TestFixture]
public class v8_internals
{
private static readonly string _jsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Prelude");
private Action<int, Action> _cancelCallbackFactory;
private Js1.CommandHandlerRegisteredDelegate _commandHandlerRegisteredCallback;
private Js1.ReverseCommandHandlerDelegate _reverseCommandHandlerDelegate;
[Test, Explicit, Category("v8"), Category("Manual")]
public void long_execution_of_non_v8_code_does_not_crash()
{
Assert.Throws<Js1Exception>(() => {
_cancelCallbackFactory = (timeout, action) => ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine("Calling a callback in " + timeout + "ms");
Thread.Sleep(timeout);
action();
});
Action<string, object[]> logger = (m, _) => Console.WriteLine(m);
Func<string, Tuple<string, string>> getModuleSource = name =>
{
var fullScriptFileName = Path.GetFullPath(Path.Combine(_jsPath, name + ".js"));
var scriptSource = File.ReadAllText(fullScriptFileName, Helper.UTF8NoBom);
return Tuple.Create(scriptSource, fullScriptFileName);
};
var preludeSource = getModuleSource("1Prelude");
var prelude = new PreludeScript(preludeSource.Item1, preludeSource.Item2, getModuleSource, _cancelCallbackFactory, logger);
try
{
//var cancelToken = 123;
prelude.ScheduleTerminateExecution();
Thread.Sleep(500);
_commandHandlerRegisteredCallback = (name, handle) => { };
_reverseCommandHandlerDelegate = (name, body) => { };
Js1.CompileQuery(
prelude.GetHandle(), "log(1);", "fn", _commandHandlerRegisteredCallback,
_reverseCommandHandlerDelegate);
prelude.CancelTerminateExecution();
}
catch
{
prelude.Dispose(); // clean up unmanaged resources if failed to create
throw;
}
});
}
}
}
| 40.169231 | 139 | 0.564535 | [
"Apache-2.0",
"CC0-1.0"
] | BertschiAG/EventStore | src/EventStore.Projections.Core.Tests/Services/v8/v8_internals.cs | 2,611 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DasContract.Editor.Entities.Exceptions
{
public class InvalidProcessCountException : EditorContractException
{
public InvalidProcessCountException(string message) : base(message)
{
}
public InvalidProcessCountException(string message, Exception innerException) : base(message, innerException)
{
}
public InvalidProcessCountException()
{
}
}
}
| 23.090909 | 117 | 0.685039 | [
"MIT"
] | drozdik-m/DasContractEditor | DasContract.Editor/DasContract.Editor.Entities/Exceptions/InvalidProcessCountException.cs | 510 | C# |
using System.Collections.Generic;
namespace ITunesLibraryParser.Tests.TestObjects {
public static class TestPlaylist {
public static Playlist Create() {
return new Playlist {
PlaylistId = 456,
Name = "Jazz Ballads",
Tracks = new List<Track> {
new Track {
Album = "Blue Trane",
AlbumArtist = "John Coltrane",
Artist = "John Coltrane",
Genre = "Jazz",
Name = "I'm Old Fashioned"
},
new Track {
Album = "Idle Moments",
AlbumArtist = "Grant Green",
Artist = "Grant Green",
Genre = "Jazz",
Name = "Idle Moments"
}
}
};
}
}
} | 34.071429 | 54 | 0.383648 | [
"MIT"
] | mmedic/iTunesLibraryParser | ITunesLibraryParserTests/TestObjects/TestPlaylist.cs | 956 | C# |
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
using OmniSharp.Services;
namespace OmniSharp.Roslyn
{
[Export]
public class ProjectEventForwarder
{
private readonly OmnisharpWorkspace _workspace;
private readonly IEventEmitter _emitter;
private readonly ISet<SimpleWorkspaceEvent> _queue = new HashSet<SimpleWorkspaceEvent>();
private readonly object _lock = new object();
private readonly IEnumerable<IProjectSystem> _projectSystems;
[ImportingConstructor]
public ProjectEventForwarder(OmnisharpWorkspace workspace, [ImportMany] IEnumerable<IProjectSystem> projectSystems, IEventEmitter emitter)
{
_projectSystems = projectSystems;
_workspace = workspace;
_emitter = emitter;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
}
private void OnWorkspaceChanged(object source, WorkspaceChangeEventArgs args)
{
SimpleWorkspaceEvent e = null;
switch (args.Kind)
{
case WorkspaceChangeKind.ProjectAdded:
e = new SimpleWorkspaceEvent(args.NewSolution.GetProject(args.ProjectId).FilePath, EventTypes.ProjectAdded);
break;
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
e = new SimpleWorkspaceEvent(args.NewSolution.GetProject(args.ProjectId).FilePath, EventTypes.ProjectChanged);
break;
case WorkspaceChangeKind.ProjectRemoved:
e = new SimpleWorkspaceEvent(args.OldSolution.GetProject(args.ProjectId).FilePath, EventTypes.ProjectRemoved);
break;
}
if (e != null)
{
lock (_lock)
{
var removed = _queue.Remove(e);
_queue.Add(e);
if (!removed)
{
Task.Factory.StartNew(async () =>
{
await Task.Delay(500);
object payload = null;
if (e.EventType != EventTypes.ProjectRemoved)
{
payload = await GetProjectInformation(e.FileName);
}
lock (_lock)
{
_queue.Remove(e);
_emitter.Emit(e.EventType, payload);
}
});
}
}
}
}
private async Task<ProjectInformationResponse> GetProjectInformation(string fileName)
{
var response = new ProjectInformationResponse();
foreach (var projectSystem in _projectSystems)
{
var project = await projectSystem.GetProjectModel(fileName);
if (project != null)
{
response.Add($"{projectSystem.Key}Project", project);
}
}
return response;
}
private class SimpleWorkspaceEvent
{
public string FileName { get; private set; }
public string EventType { get; private set; }
public SimpleWorkspaceEvent(string fileName, string eventType)
{
FileName = fileName;
EventType = eventType;
}
public override bool Equals(object obj)
{
var other = obj as SimpleWorkspaceEvent;
return other != null && EventType == other.EventType && FileName == other.FileName;
}
public override int GetHashCode()
{
return EventType?.GetHashCode() * 23 + FileName?.GetHashCode() ?? 0;
}
}
}
}
| 35.568966 | 146 | 0.530538 | [
"MIT"
] | razzmatazz/omnisharp-roslyn | src/OmniSharp.Roslyn/ProjectEventForwarder.cs | 4,126 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Windows;
using Microsoft.Win32;
namespace LoginManager
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private const string registryPath = @"/Software/DianaLoginManager";
public MainWindow()
{
InitializeComponent();
this.Loaded += (s, e) =>
{
var reg = Registry.CurrentUser.OpenSubKey(registryPath);
if (reg == null)
{
InputBox.Visibility = Visibility.Visible;
}
};
registryButton.Click += (s, e) =>
{
var reg = Registry.CurrentUser.OpenSubKey(registryPath, true);
if (reg == null) reg = Registry.CurrentUser.CreateSubKey(registryPath, true);
reg.SetValue("password", HashPassword(InputTextBox.Password));
InputBox.Visibility = Visibility.Hidden;
reg.Close();
};
cancelButton.Click += (s, e) => { this.Close(); };
loginButton.Click += (s, e) =>
{
var reg = Registry.CurrentUser.OpenSubKey(registryPath);
if (reg == null)
{
InputBox.Visibility = Visibility.Visible;
reg.Close();
return;
}
if (VerifyHashedPassword(reg.GetValue("password").ToString(), passwordTextBox.Password))
{
StartupBox.Visibility = Visibility.Visible;
}
else
{
MessageBox.Show("Неверный пароль!", "Ошибка!",MessageBoxButton.OK,MessageBoxImage.Error);
}
reg.Close();
};
exitButton.Click += (s, e) => { this.Close(); };
startButton.Click += (s, e) =>
{
File.WriteAllBytes($"{System.IO.Path.GetTempPath()}Diana.exe", Properties.Resources.Diana_2);
Process.Start($"{System.IO.Path.GetTempPath()}Diana.exe");
this.Close();
};
changePasswordButton.Click += (s, e) =>
{
InputBox.Visibility = Visibility.Visible;
helloTextBlock.Visibility = Visibility.Hidden;
StartupBox.Visibility = Visibility.Hidden;
};
}
public static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
private static bool ByteArraysEqual(byte[] array1, byte[] array2)
{
if (array1.Length != array2.Length) return false;
for (int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i]) return false;
}
return true;
}
}
}
| 33.153285 | 109 | 0.489432 | [
"Unlicense"
] | ololonly/LoginManager | LoginManager/MainWindow.xaml.cs | 4,564 | C# |
namespace PetsLostAndFoundSystem.Domain.Common.Models
{
using Reporting.Models.Reports;
using FluentAssertions;
using Xunit;
public class EntitySpecs
{
[Fact]
public void EntitiesWithEqualIdsShouldBeEqual()
{
// Arrange
var first = new Pet(PetType.Dog, "SomeName", 1, "someRFID", "Description").SetId(1);
var second = new Pet(PetType.Cat, "SomeName", 1, "someRFID", "Description").SetId(1);
// Act
var result = first == second;
// Arrange
result.Should().BeTrue();
}
[Fact]
public void EntitiesWithDifferentIdsShouldNotBeEqual()
{
// Arrange
var first = new Pet(PetType.Dog, "SomeName", 1, "someRFID", "Description").SetId(1);
var second = new Pet(PetType.Cat, "SomeName", 1, "someRFID", "Description").SetId(2);
// Act
var result = first == second;
// Arrange
result.Should().BeFalse();
}
}
internal static class EntityExtensions
{
public static TEntity SetId<TEntity>(this TEntity entity, int id)
where TEntity : Entity<int>
=> (entity.SetId<int>(id) as TEntity)!;
private static Entity<T> SetId<T>(this Entity<T> entity, int id)
where T : struct
{
entity
.GetType()
.BaseType!
.GetProperty(nameof(Entity<T>.Id))!
.GetSetMethod(true)!
.Invoke(entity, new object[] { id });
return entity;
}
}
}
| 28.37931 | 97 | 0.526731 | [
"MIT"
] | Dimitvp/PetsLostAndFoundSystem-DDD | PetsLostAndFoundSystem/Domain/Common/Models/Entity.Specs.cs | 1,648 | C# |
using idb.Backend.DataAccess.Models;
using idb.Backend.Providers;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;
using Tag = idb.Backend.DataAccess.Models.Tag;
namespace idb.Backend.DataAccess.Repositories
{
public interface IUserRepository : IBaseRepository<User>
{
Task<User> GetByEmail(string email);
Task<User> GetByIDThatIWillDeleteSoon(int id);
}
public interface IItemRepository : IBaseRepository<Item>
{
Task<List<Item>> GetBy(string search, List<int> tag_ids, string userId);
}
public interface ITagRepository : IBaseRepository<Tag>
{
Task<Tag> GetById(int tagId);
Task<List<Tag>> GetByIds(List<int> tagIds);
}
public class UserRepository : BaseRepository<User>, IUserRepository
{
public UserRepository(IdbContext context, IDateTimeProvider dateTimeProvider) : base(context, dateTimeProvider) { }
public UserRepository() { }
public async Task<User> GetByEmail(string email)
{
var filter = Builders<User>.Filter.Eq("email", email);
var response = await _dbCollection.FindAsync(filter);
return await response.FirstOrDefaultAsync();
}
public async Task<User> GetByIDThatIWillDeleteSoon(int id)
{
var filter = Builders<User>.Filter.Eq("ID", id);
var response = await _dbCollection.FindAsync(filter);
return await response.FirstOrDefaultAsync();
}
}
public class ItemRepository : BaseRepository<Item>, IItemRepository
{
public ItemRepository(IdbContext context, IDateTimeProvider dateTimeProvider) : base(context, dateTimeProvider) { }
public ItemRepository() { }
public async Task<List<Item>> GetBy(string search, List<int> tag_ids, string userId)
{
FilterDefinition<Item> searchQuery = Builders<Item>.Filter.Empty;
if (!string.IsNullOrEmpty(userId) && !string.IsNullOrWhiteSpace(userId))
searchQuery = Builders<Item>.Filter.And(searchQuery, Builders<Item>.Filter.Eq(x => x.ownerId, userId));
if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
searchQuery = Builders<Item>.Filter.And(searchQuery, Builders<Item>.Filter.Where(x => x.content.ToLower().Contains(search))
| Builders<Item>.Filter.Where(x => x.name.ToLower().Contains(search)));
if (tag_ids.Count > 0)
searchQuery = Builders<Item>.Filter.And(searchQuery, Builders<Item>.Filter.ElemMatch(x => x.tags, Builders<Tag>.Filter.In(x => x.ID, tag_ids)));
var response = await _dbCollection.FindAsync(searchQuery);
return await response.ToListAsync();
}
}
public class TagRepository : BaseRepository<Tag>, ITagRepository
{
public TagRepository(IdbContext context, IDateTimeProvider dateTimeProvider) : base(context, dateTimeProvider) { }
public TagRepository() { }
public async Task<Tag> GetById(int tagId)
{
FilterDefinition<Tag> filter = Builders<Tag>.Filter.Eq("ID", tagId);
var response = await _dbCollection.FindAsync(filter);
return await response.FirstOrDefaultAsync();
}
public async Task<List<Tag>> GetByIds(List<int> tagIds)
{
var tagsQuery = Builders<Tag>.Filter.Where(x => tagIds.Contains(x.ID));
var response = await _dbCollection.FindAsync(tagsQuery);
return await response.ToListAsync();
}
}
}
| 41.883721 | 160 | 0.65769 | [
"MIT"
] | pavlepiramida/idb.Backend | src/DataAccess/Repositories/Repositories.cs | 3,604 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Redshift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Redshift.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateClusterParameterGroup Request Marshaller
/// </summary>
public class CreateClusterParameterGroupRequestMarshaller : IMarshaller<IRequest, CreateClusterParameterGroupRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((CreateClusterParameterGroupRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CreateClusterParameterGroupRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Redshift");
request.Parameters.Add("Action", "CreateClusterParameterGroup");
request.Parameters.Add("Version", "2012-12-01");
if(publicRequest != null)
{
if(publicRequest.IsSetDescription())
{
request.Parameters.Add("Description", StringUtils.FromString(publicRequest.Description));
}
if(publicRequest.IsSetParameterGroupFamily())
{
request.Parameters.Add("ParameterGroupFamily", StringUtils.FromString(publicRequest.ParameterGroupFamily));
}
if(publicRequest.IsSetParameterGroupName())
{
request.Parameters.Add("ParameterGroupName", StringUtils.FromString(publicRequest.ParameterGroupName));
}
if(publicRequest.IsSetTags())
{
int publicRequestlistValueIndex = 1;
foreach(var publicRequestlistValue in publicRequest.Tags)
{
if(publicRequestlistValue.IsSetKey())
{
request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Key", StringUtils.FromString(publicRequestlistValue.Key));
}
if(publicRequestlistValue.IsSetValue())
{
request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Value", StringUtils.FromString(publicRequestlistValue.Value));
}
publicRequestlistValueIndex++;
}
}
}
return request;
}
}
} | 41.612903 | 182 | 0.608786 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/Redshift/Generated/Model/Internal/MarshallTransformations/CreateClusterParameterGroupRequestMarshaller.cs | 3,870 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using IdentityServer4.Stores;
using IdentityServer4.Stores.Serialization;
using System.Collections.Generic;
using System.Linq;
using System;
namespace IdentityServer4.Services
{
/// <summary>
/// Default persisted grant service
/// </summary>
public class DefaultPersistedGrantService : IPersistedGrantService
{
private readonly ILogger<DefaultPersistedGrantService> _logger;
private readonly IPersistedGrantStore _store;
private readonly IPersistentGrantSerializer _serializer;
public DefaultPersistedGrantService(IPersistedGrantStore store,
IPersistentGrantSerializer serializer,
ILogger<DefaultPersistedGrantService> logger)
{
_store = store;
_serializer = serializer;
_logger = logger;
}
public async Task<IEnumerable<Consent>> GetAllGrantsAsync(string subjectId)
{
var grants = (await _store.GetAllAsync(subjectId)).ToArray();
try
{
var consents = grants.Where(x => x.Type == Constants.PersistedGrantTypes.UserConsent)
.Select(x => _serializer.Deserialize<Consent>(x.Data));
var codes = grants.Where(x => x.Type == Constants.PersistedGrantTypes.AuthorizationCode)
.Select(x => _serializer.Deserialize<AuthorizationCode>(x.Data))
.Select(x => new Consent
{
ClientId = x.ClientId,
SubjectId = subjectId,
Scopes = x.RequestedScopes,
CreationTime = x.CreationTime,
Expiration = x.CreationTime.AddSeconds(x.Lifetime)
});
var refresh = grants.Where(x => x.Type == Constants.PersistedGrantTypes.RefreshToken)
.Select(x => _serializer.Deserialize<RefreshToken>(x.Data))
.Select(x => new Consent
{
ClientId = x.ClientId,
SubjectId = subjectId,
Scopes = x.Scopes,
CreationTime = x.CreationTime,
Expiration = x.CreationTime.AddSeconds(x.Lifetime)
});
var access = grants.Where(x => x.Type == Constants.PersistedGrantTypes.ReferenceToken)
.Select(x => _serializer.Deserialize<Token>(x.Data))
.Select(x => new Consent
{
ClientId = x.ClientId,
SubjectId = subjectId,
Scopes = x.Scopes,
CreationTime = x.CreationTime,
Expiration = x.CreationTime.AddSeconds(x.Lifetime)
});
consents = Join(consents, codes);
consents = Join(consents, refresh);
consents = Join(consents, access);
return consents.ToArray();
}
catch (Exception ex)
{
_logger.LogError("Failed processing results from grant store. Exception: {0}", ex.Message);
}
return Enumerable.Empty<Consent>();
}
IEnumerable<Consent> Join(IEnumerable<Consent> first, IEnumerable<Consent> second)
{
var query =
from f in first
let matches = (from s in second where f.ClientId == s.ClientId from scope in s.Scopes select scope)
let scopes = f.Scopes.Union(matches).Distinct()
select new Consent
{
ClientId = f.ClientId,
SubjectId = f.SubjectId,
Scopes = scopes,
CreationTime = f.CreationTime,
Expiration = f.Expiration
};
return query;
}
public Task RemoveAllGrantsAsync(string subjectId, string clientId)
{
return _store.RemoveAllAsync(subjectId, clientId);
}
}
} | 39.223214 | 115 | 0.548372 | [
"Apache-2.0"
] | mathewspjacob/IdentityServer4 | src/IdentityServer4/Services/DefaultPersistedGrantService.cs | 4,395 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CStubMKGui.ViewModel
{
public class ViewModelBase : ViewModelCommonBase
{
/// <summary>
/// Action to notify the result ok.
/// </summary>
public Action<string, string> NotifyOk { get; set; }
/// <summary>
/// Action to notify the result ng.
/// </summary>
public Action<string, string> NotifyNg { get; set; }
}
}
| 24.45 | 61 | 0.572597 | [
"MIT"
] | CountrySideEngineer/CStubMk | dev/dev/CStubMKGui/ViewModel/ViewModelBase.cs | 491 | C# |
using System;
using System.Collections.Generic;
using StackExchange.Redis.MultiplexerPool.Infra.Common;
namespace StackExchange.Redis.MultiplexerPool.Infra.Collections
{
/// <summary>
/// Extension methods for <see cref="IEnumerable{T}"/>
/// </summary>
internal static class EnumerableExtensions
{
/// <summary>
/// Gets the minimal element in <paramref name="source"/> by comparing according to a computed value with default value comparer.
/// </summary>
/// <param name="source">
/// The source collection.
/// </param>
/// <param name="selector">
/// A selector that calculates a value for an element in <paramref name="source"/> that the comparison should be done by.
/// Will receive null arguments if there are nulls in <paramref name="source"/>.
/// </param>
/// <param name="comparer">The comparer to use for comparing between the <typeparamref name="TKey"/></param>
/// <typeparam name="TSource">
/// Type of elements in <paramref name="source"/>.
/// </typeparam>
/// <typeparam name="TKey">
/// Type of value to compare elements by.
/// </typeparam>
/// <returns>
/// The minimal element in <paramref name="source"/>.
/// </returns>
public static TSource MinBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> selector,
IComparer<TKey> comparer = null)
{
Guard.CheckNullArgument(source, nameof(source));
Guard.CheckNullArgument(selector, nameof(selector));
comparer = comparer ?? Comparer<TKey>.Default;
using (var sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence contains no elements");
}
var min = sourceIterator.Current;
var minKey = selector(min);
while (sourceIterator.MoveNext())
{
var candidate = sourceIterator.Current;
var candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, minKey) < 0)
{
min = candidate;
minKey = candidateProjected;
}
}
return min;
}
}
}
}
| 39.484848 | 138 | 0.537606 | [
"MIT"
] | mataness/StackExchange.Redis.MultiplexerPool | src/StackExchange.Redis.MultiplexerPool/Infra/Collections/EnumerableExtensions.cs | 2,608 | C# |
using System;
namespace q58
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter value of A :");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of B :");
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of C:");
int c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Which one,, Do you want to Execute (a,b,c,d,e,f,g,h,i)");
string problemNumber = Console.ReadLine();
Console.WriteLine("Problem # " + problemNumber + " is going to Execute");
switch (problemNumber)
{
case "a":
try
{
++a;
Console.WriteLine("The result is valid and value of a: " + a + " value of B:" + b + " value of C:" + c);
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
break;
case "b":
try
{
Console.WriteLine("The result is invalid");
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
break;
case "c":
try
{
a++;
Console.WriteLine("The result is valid and value of a: " + a + " value of B:" + b + " value of C:" + c);
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
a++;
Console.WriteLine("The result is valid and value of a: " + a + " value of B:" + b + " value of C:" + c);
break;
case "d":
try
{
b += a;
Console.WriteLine("The result is valid and value of a: " + a + " value of B:" + b + " value of C:" + c);
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
break;
case "e":
try
{
b += a * c;
Console.WriteLine("The result is valid and value of a: " + a + " value of B:" + b + " value of C:" + c);
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
break;
case "f":
try
{
Console.WriteLine("The result is invalid");
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
break;
case "g":
try
{
c=a*b;
Console.WriteLine("The result is valid and value of a: " + a + " value of B: " + b + " value of C: " + c);
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
break;
case "h":
try
{
++b;
Console.WriteLine("The result is valid and value of a: " + a + " value of B: " + b + " value of C: " + c);
}
catch (Exception e)
{
Console.WriteLine($"The result is invalid{e.Message}");
}
break;
case "i":
try
{
b = a++ + b++;
Console.WriteLine("The result is valid and value of a: " + a + " value of B: " + b + " value of C: " + c);
}
catch (Exception)
{
Console.WriteLine("The result is invalid");
}
break;
default:
Console.WriteLine("Pls enter right value");
break;
}
}
}
} | 36.766917 | 133 | 0.323926 | [
"MIT"
] | muntahamaqsood/IT | Q58.cs | 4,892 | C# |
/*
* Lyzard Modeling and Simulation System
*
* Copyright 2019 William W. Westlake Jr.
*
* 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.Runtime.Serialization;
using System.Security.Permissions;
using System.Windows;
namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
[Serializable]
public class XshdColor : XshdElement, ISerializable
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
/// <summary>
/// Creates a new XshdColor instance.
/// </summary>
public XshdColor()
{
}
/// <summary>
/// Deserializes an XshdColor.
/// </summary>
protected XshdColor(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
this.Name = info.GetString("Name");
this.Foreground = (HighlightingBrush)info.GetValue("Foreground", typeof(HighlightingBrush));
this.Background = (HighlightingBrush)info.GetValue("Background", typeof(HighlightingBrush));
if (info.GetBoolean("HasWeight"))
this.FontWeight = System.Windows.FontWeight.FromOpenTypeWeight(info.GetInt32("Weight"));
if (info.GetBoolean("HasStyle"))
this.FontStyle = (FontStyle?)new FontStyleConverter().ConvertFromInvariantString(info.GetString("Style"));
this.ExampleText = info.GetString("ExampleText");
}
/// <summary>
/// Serializes this XshdColor instance.
/// </summary>
#if DOTNET4
[System.Security.SecurityCritical]
#else
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
#endif
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("Name", this.Name);
info.AddValue("Foreground", this.Foreground);
info.AddValue("Background", this.Background);
info.AddValue("HasWeight", this.FontWeight.HasValue);
if (this.FontWeight.HasValue)
info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
info.AddValue("HasStyle", this.FontStyle.HasValue);
if (this.FontStyle.HasValue)
info.AddValue("Style", this.FontStyle.Value.ToString());
info.AddValue("ExampleText", this.ExampleText);
}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
| 30.991379 | 110 | 0.700695 | [
"Apache-2.0"
] | wwestlake/Lyzard | ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdColor.cs | 3,597 | C# |
namespace Heat.Elements
{
public class LabelsElement : ILabelsElement
{
public string All { get { return "labels"; } }
public string Icon { get { return "icon"; } }
public ITextElement Text { get { return new TextElement(); } }
}
} | 29.777778 | 70 | 0.608209 | [
"MIT"
] | v-bright/Heat | Heat/Elements/LabelsElement.cs | 270 | 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.AzureNative.GuestConfiguration.V20210125
{
/// <summary>
/// Guest configuration assignment is an association between a machine and guest configuration.
/// </summary>
[AzureNativeResourceType("azure-native:guestconfiguration/v20210125:GuestConfigurationHCRPAssignment")]
public partial class GuestConfigurationHCRPAssignment : Pulumi.CustomResource
{
/// <summary>
/// Region where the VM is located.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Name of the guest configuration assignment.
/// </summary>
[Output("name")]
public Output<string?> Name { get; private set; } = null!;
/// <summary>
/// Properties of the Guest configuration assignment.
/// </summary>
[Output("properties")]
public Output<Outputs.GuestConfigurationAssignmentPropertiesResponse> Properties { get; private set; } = null!;
/// <summary>
/// Azure Resource Manager metadata containing createdBy and modifiedBy information.
/// </summary>
[Output("systemData")]
public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!;
/// <summary>
/// The type of the resource.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a GuestConfigurationHCRPAssignment resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public GuestConfigurationHCRPAssignment(string name, GuestConfigurationHCRPAssignmentArgs args, CustomResourceOptions? options = null)
: base("azure-native:guestconfiguration/v20210125:GuestConfigurationHCRPAssignment", name, args ?? new GuestConfigurationHCRPAssignmentArgs(), MakeResourceOptions(options, ""))
{
}
private GuestConfigurationHCRPAssignment(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:guestconfiguration/v20210125:GuestConfigurationHCRPAssignment", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:guestconfiguration/v20210125:GuestConfigurationHCRPAssignment"},
new Pulumi.Alias { Type = "azure-native:guestconfiguration:GuestConfigurationHCRPAssignment"},
new Pulumi.Alias { Type = "azure-nextgen:guestconfiguration:GuestConfigurationHCRPAssignment"},
new Pulumi.Alias { Type = "azure-native:guestconfiguration/v20181120:GuestConfigurationHCRPAssignment"},
new Pulumi.Alias { Type = "azure-nextgen:guestconfiguration/v20181120:GuestConfigurationHCRPAssignment"},
new Pulumi.Alias { Type = "azure-native:guestconfiguration/v20200625:GuestConfigurationHCRPAssignment"},
new Pulumi.Alias { Type = "azure-nextgen:guestconfiguration/v20200625:GuestConfigurationHCRPAssignment"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing GuestConfigurationHCRPAssignment resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static GuestConfigurationHCRPAssignment Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new GuestConfigurationHCRPAssignment(name, id, options);
}
}
public sealed class GuestConfigurationHCRPAssignmentArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the guest configuration assignment.
/// </summary>
[Input("guestConfigurationAssignmentName")]
public Input<string>? GuestConfigurationAssignmentName { get; set; }
/// <summary>
/// Region where the VM is located.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the ARC machine.
/// </summary>
[Input("machineName", required: true)]
public Input<string> MachineName { get; set; } = null!;
/// <summary>
/// Name of the guest configuration assignment.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Properties of the Guest configuration assignment.
/// </summary>
[Input("properties")]
public Input<Inputs.GuestConfigurationAssignmentPropertiesArgs>? Properties { get; set; }
/// <summary>
/// The resource group name.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public GuestConfigurationHCRPAssignmentArgs()
{
}
}
}
| 44.402778 | 188 | 0.636221 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/GuestConfiguration/V20210125/GuestConfigurationHCRPAssignment.cs | 6,394 | C# |
using System;
namespace Editor_Mono.Cecil
{
internal enum FieldDefinitionTreatment
{
None,
Public
}
}
| 11.8 | 40 | 0.694915 | [
"MIT"
] | 2823896/cshotfix | CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Editor/Injector/MonoCecil/Mono.Cecil/FieldDefinitionTreatment.cs | 118 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the accessanalyzer-2019-11-01.normal.json service model.
*/
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.AccessAnalyzer;
using Amazon.AccessAnalyzer.Model;
using Amazon.AccessAnalyzer.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using Amazon.Util;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public partial class AccessAnalyzerMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("accessanalyzer");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ApplyArchiveRuleMarshallTest()
{
var operation = service_model.FindOperation("ApplyArchiveRule");
var request = InstantiateClassGenerator.Execute<ApplyArchiveRuleRequest>();
var marshaller = new ApplyArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ApplyArchiveRule", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ApplyArchiveRule_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("ApplyArchiveRule");
var request = InstantiateClassGenerator.Execute<ApplyArchiveRuleRequest>();
var marshaller = new ApplyArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ApplyArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ApplyArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ApplyArchiveRule_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ApplyArchiveRule");
var request = InstantiateClassGenerator.Execute<ApplyArchiveRuleRequest>();
var marshaller = new ApplyArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ApplyArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ApplyArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ApplyArchiveRule_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ApplyArchiveRule");
var request = InstantiateClassGenerator.Execute<ApplyArchiveRuleRequest>();
var marshaller = new ApplyArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ApplyArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ApplyArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ApplyArchiveRule_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ApplyArchiveRule");
var request = InstantiateClassGenerator.Execute<ApplyArchiveRuleRequest>();
var marshaller = new ApplyArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ApplyArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ApplyArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ApplyArchiveRule_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ApplyArchiveRule");
var request = InstantiateClassGenerator.Execute<ApplyArchiveRuleRequest>();
var marshaller = new ApplyArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ApplyArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ApplyArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateAnalyzerMarshallTest()
{
var operation = service_model.FindOperation("CreateAnalyzer");
var request = InstantiateClassGenerator.Execute<CreateAnalyzerRequest>();
var marshaller = new CreateAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAnalyzer", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateAnalyzerResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateAnalyzerResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateAnalyzer_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAnalyzer");
var request = InstantiateClassGenerator.Execute<CreateAnalyzerRequest>();
var marshaller = new CreateAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateAnalyzer_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAnalyzer");
var request = InstantiateClassGenerator.Execute<CreateAnalyzerRequest>();
var marshaller = new CreateAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ConflictException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ConflictException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateAnalyzer_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAnalyzer");
var request = InstantiateClassGenerator.Execute<CreateAnalyzerRequest>();
var marshaller = new CreateAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateAnalyzer_ServiceQuotaExceededExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAnalyzer");
var request = InstantiateClassGenerator.Execute<CreateAnalyzerRequest>();
var marshaller = new CreateAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceQuotaExceededException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceQuotaExceededException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateAnalyzer_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAnalyzer");
var request = InstantiateClassGenerator.Execute<CreateAnalyzerRequest>();
var marshaller = new CreateAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateAnalyzer_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAnalyzer");
var request = InstantiateClassGenerator.Execute<CreateAnalyzerRequest>();
var marshaller = new CreateAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRuleMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRule_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRule_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ConflictException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ConflictException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRule_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRule_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRule_ServiceQuotaExceededExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceQuotaExceededException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceQuotaExceededException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRule_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void CreateArchiveRule_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateArchiveRule");
var request = InstantiateClassGenerator.Execute<CreateArchiveRuleRequest>();
var marshaller = new CreateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteAnalyzerMarshallTest()
{
var operation = service_model.FindOperation("DeleteAnalyzer");
var request = InstantiateClassGenerator.Execute<DeleteAnalyzerRequest>();
var marshaller = new DeleteAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAnalyzer", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteAnalyzer_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAnalyzer");
var request = InstantiateClassGenerator.Execute<DeleteAnalyzerRequest>();
var marshaller = new DeleteAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteAnalyzer_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAnalyzer");
var request = InstantiateClassGenerator.Execute<DeleteAnalyzerRequest>();
var marshaller = new DeleteAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteAnalyzer_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAnalyzer");
var request = InstantiateClassGenerator.Execute<DeleteAnalyzerRequest>();
var marshaller = new DeleteAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteAnalyzer_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAnalyzer");
var request = InstantiateClassGenerator.Execute<DeleteAnalyzerRequest>();
var marshaller = new DeleteAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteAnalyzer_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAnalyzer");
var request = InstantiateClassGenerator.Execute<DeleteAnalyzerRequest>();
var marshaller = new DeleteAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteArchiveRuleMarshallTest()
{
var operation = service_model.FindOperation("DeleteArchiveRule");
var request = InstantiateClassGenerator.Execute<DeleteArchiveRuleRequest>();
var marshaller = new DeleteArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteArchiveRule", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteArchiveRule_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteArchiveRule");
var request = InstantiateClassGenerator.Execute<DeleteArchiveRuleRequest>();
var marshaller = new DeleteArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteArchiveRule_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteArchiveRule");
var request = InstantiateClassGenerator.Execute<DeleteArchiveRuleRequest>();
var marshaller = new DeleteArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteArchiveRule_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteArchiveRule");
var request = InstantiateClassGenerator.Execute<DeleteArchiveRuleRequest>();
var marshaller = new DeleteArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteArchiveRule_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteArchiveRule");
var request = InstantiateClassGenerator.Execute<DeleteArchiveRuleRequest>();
var marshaller = new DeleteArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void DeleteArchiveRule_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteArchiveRule");
var request = InstantiateClassGenerator.Execute<DeleteArchiveRuleRequest>();
var marshaller = new DeleteArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzedResourceMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzedResource");
var request = InstantiateClassGenerator.Execute<GetAnalyzedResourceRequest>();
var marshaller = new GetAnalyzedResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzedResource", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetAnalyzedResourceResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetAnalyzedResourceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzedResource_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzedResource");
var request = InstantiateClassGenerator.Execute<GetAnalyzedResourceRequest>();
var marshaller = new GetAnalyzedResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzedResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzedResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzedResource_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzedResource");
var request = InstantiateClassGenerator.Execute<GetAnalyzedResourceRequest>();
var marshaller = new GetAnalyzedResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzedResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzedResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzedResource_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzedResource");
var request = InstantiateClassGenerator.Execute<GetAnalyzedResourceRequest>();
var marshaller = new GetAnalyzedResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzedResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzedResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzedResource_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzedResource");
var request = InstantiateClassGenerator.Execute<GetAnalyzedResourceRequest>();
var marshaller = new GetAnalyzedResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzedResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzedResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzedResource_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzedResource");
var request = InstantiateClassGenerator.Execute<GetAnalyzedResourceRequest>();
var marshaller = new GetAnalyzedResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzedResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzedResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzerMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzer");
var request = InstantiateClassGenerator.Execute<GetAnalyzerRequest>();
var marshaller = new GetAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzer", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetAnalyzerResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetAnalyzerResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzer_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzer");
var request = InstantiateClassGenerator.Execute<GetAnalyzerRequest>();
var marshaller = new GetAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzer_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzer");
var request = InstantiateClassGenerator.Execute<GetAnalyzerRequest>();
var marshaller = new GetAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzer_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzer");
var request = InstantiateClassGenerator.Execute<GetAnalyzerRequest>();
var marshaller = new GetAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzer_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzer");
var request = InstantiateClassGenerator.Execute<GetAnalyzerRequest>();
var marshaller = new GetAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetAnalyzer_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetAnalyzer");
var request = InstantiateClassGenerator.Execute<GetAnalyzerRequest>();
var marshaller = new GetAnalyzerRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetAnalyzer", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetAnalyzerResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetArchiveRuleMarshallTest()
{
var operation = service_model.FindOperation("GetArchiveRule");
var request = InstantiateClassGenerator.Execute<GetArchiveRuleRequest>();
var marshaller = new GetArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetArchiveRule", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetArchiveRuleResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetArchiveRuleResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetArchiveRule_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetArchiveRule");
var request = InstantiateClassGenerator.Execute<GetArchiveRuleRequest>();
var marshaller = new GetArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetArchiveRule_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetArchiveRule");
var request = InstantiateClassGenerator.Execute<GetArchiveRuleRequest>();
var marshaller = new GetArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetArchiveRule_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetArchiveRule");
var request = InstantiateClassGenerator.Execute<GetArchiveRuleRequest>();
var marshaller = new GetArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetArchiveRule_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetArchiveRule");
var request = InstantiateClassGenerator.Execute<GetArchiveRuleRequest>();
var marshaller = new GetArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetArchiveRule_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetArchiveRule");
var request = InstantiateClassGenerator.Execute<GetArchiveRuleRequest>();
var marshaller = new GetArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetFindingMarshallTest()
{
var operation = service_model.FindOperation("GetFinding");
var request = InstantiateClassGenerator.Execute<GetFindingRequest>();
var marshaller = new GetFindingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFinding", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetFindingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetFindingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetFinding_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFinding");
var request = InstantiateClassGenerator.Execute<GetFindingRequest>();
var marshaller = new GetFindingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFinding", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetFindingResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetFinding_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFinding");
var request = InstantiateClassGenerator.Execute<GetFindingRequest>();
var marshaller = new GetFindingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFinding", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetFindingResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetFinding_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFinding");
var request = InstantiateClassGenerator.Execute<GetFindingRequest>();
var marshaller = new GetFindingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFinding", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetFindingResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetFinding_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFinding");
var request = InstantiateClassGenerator.Execute<GetFindingRequest>();
var marshaller = new GetFindingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFinding", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetFindingResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void GetFinding_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFinding");
var request = InstantiateClassGenerator.Execute<GetFindingRequest>();
var marshaller = new GetFindingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFinding", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = GetFindingResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzedResourcesMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzedResources");
var request = InstantiateClassGenerator.Execute<ListAnalyzedResourcesRequest>();
var marshaller = new ListAnalyzedResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzedResources", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListAnalyzedResourcesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListAnalyzedResourcesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzedResources_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzedResources");
var request = InstantiateClassGenerator.Execute<ListAnalyzedResourcesRequest>();
var marshaller = new ListAnalyzedResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzedResources", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzedResourcesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzedResources_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzedResources");
var request = InstantiateClassGenerator.Execute<ListAnalyzedResourcesRequest>();
var marshaller = new ListAnalyzedResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzedResources", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzedResourcesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzedResources_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzedResources");
var request = InstantiateClassGenerator.Execute<ListAnalyzedResourcesRequest>();
var marshaller = new ListAnalyzedResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzedResources", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzedResourcesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzedResources_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzedResources");
var request = InstantiateClassGenerator.Execute<ListAnalyzedResourcesRequest>();
var marshaller = new ListAnalyzedResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzedResources", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzedResourcesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzedResources_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzedResources");
var request = InstantiateClassGenerator.Execute<ListAnalyzedResourcesRequest>();
var marshaller = new ListAnalyzedResourcesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzedResources", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzedResourcesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzersMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzers");
var request = InstantiateClassGenerator.Execute<ListAnalyzersRequest>();
var marshaller = new ListAnalyzersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzers", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListAnalyzersResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListAnalyzersResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzers_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzers");
var request = InstantiateClassGenerator.Execute<ListAnalyzersRequest>();
var marshaller = new ListAnalyzersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzers", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzersResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzers_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzers");
var request = InstantiateClassGenerator.Execute<ListAnalyzersRequest>();
var marshaller = new ListAnalyzersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzers", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzersResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzers_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzers");
var request = InstantiateClassGenerator.Execute<ListAnalyzersRequest>();
var marshaller = new ListAnalyzersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzers", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzersResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListAnalyzers_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAnalyzers");
var request = InstantiateClassGenerator.Execute<ListAnalyzersRequest>();
var marshaller = new ListAnalyzersRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAnalyzers", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAnalyzersResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListArchiveRulesMarshallTest()
{
var operation = service_model.FindOperation("ListArchiveRules");
var request = InstantiateClassGenerator.Execute<ListArchiveRulesRequest>();
var marshaller = new ListArchiveRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListArchiveRules", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListArchiveRulesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListArchiveRulesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListArchiveRules_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListArchiveRules");
var request = InstantiateClassGenerator.Execute<ListArchiveRulesRequest>();
var marshaller = new ListArchiveRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListArchiveRules", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListArchiveRulesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListArchiveRules_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListArchiveRules");
var request = InstantiateClassGenerator.Execute<ListArchiveRulesRequest>();
var marshaller = new ListArchiveRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListArchiveRules", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListArchiveRulesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListArchiveRules_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListArchiveRules");
var request = InstantiateClassGenerator.Execute<ListArchiveRulesRequest>();
var marshaller = new ListArchiveRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListArchiveRules", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListArchiveRulesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListArchiveRules_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListArchiveRules");
var request = InstantiateClassGenerator.Execute<ListArchiveRulesRequest>();
var marshaller = new ListArchiveRulesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListArchiveRules", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListArchiveRulesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListFindingsMarshallTest()
{
var operation = service_model.FindOperation("ListFindings");
var request = InstantiateClassGenerator.Execute<ListFindingsRequest>();
var marshaller = new ListFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindings", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListFindingsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListFindingsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListFindings_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindings");
var request = InstantiateClassGenerator.Execute<ListFindingsRequest>();
var marshaller = new ListFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListFindings_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindings");
var request = InstantiateClassGenerator.Execute<ListFindingsRequest>();
var marshaller = new ListFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListFindings_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindings");
var request = InstantiateClassGenerator.Execute<ListFindingsRequest>();
var marshaller = new ListFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListFindings_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindings");
var request = InstantiateClassGenerator.Execute<ListFindingsRequest>();
var marshaller = new ListFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListFindings_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindings");
var request = InstantiateClassGenerator.Execute<ListFindingsRequest>();
var marshaller = new ListFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListTagsForResourceMarshallTest()
{
var operation = service_model.FindOperation("ListTagsForResource");
var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>();
var marshaller = new ListTagsForResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListTagsForResource", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListTagsForResourceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListTagsForResource_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListTagsForResource");
var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>();
var marshaller = new ListTagsForResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListTagsForResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListTagsForResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListTagsForResource_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListTagsForResource");
var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>();
var marshaller = new ListTagsForResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListTagsForResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListTagsForResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListTagsForResource_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListTagsForResource");
var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>();
var marshaller = new ListTagsForResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListTagsForResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListTagsForResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListTagsForResource_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListTagsForResource");
var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>();
var marshaller = new ListTagsForResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListTagsForResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListTagsForResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void ListTagsForResource_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListTagsForResource");
var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>();
var marshaller = new ListTagsForResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListTagsForResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListTagsForResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void StartResourceScanMarshallTest()
{
var operation = service_model.FindOperation("StartResourceScan");
var request = InstantiateClassGenerator.Execute<StartResourceScanRequest>();
var marshaller = new StartResourceScanRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("StartResourceScan", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void StartResourceScan_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("StartResourceScan");
var request = InstantiateClassGenerator.Execute<StartResourceScanRequest>();
var marshaller = new StartResourceScanRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("StartResourceScan", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = StartResourceScanResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void StartResourceScan_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("StartResourceScan");
var request = InstantiateClassGenerator.Execute<StartResourceScanRequest>();
var marshaller = new StartResourceScanRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("StartResourceScan", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = StartResourceScanResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void StartResourceScan_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("StartResourceScan");
var request = InstantiateClassGenerator.Execute<StartResourceScanRequest>();
var marshaller = new StartResourceScanRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("StartResourceScan", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = StartResourceScanResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void StartResourceScan_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("StartResourceScan");
var request = InstantiateClassGenerator.Execute<StartResourceScanRequest>();
var marshaller = new StartResourceScanRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("StartResourceScan", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = StartResourceScanResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void StartResourceScan_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("StartResourceScan");
var request = InstantiateClassGenerator.Execute<StartResourceScanRequest>();
var marshaller = new StartResourceScanRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("StartResourceScan", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = StartResourceScanResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void TagResourceMarshallTest()
{
var operation = service_model.FindOperation("TagResource");
var request = InstantiateClassGenerator.Execute<TagResourceRequest>();
var marshaller = new TagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("TagResource", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = TagResourceResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as TagResourceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void TagResource_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("TagResource");
var request = InstantiateClassGenerator.Execute<TagResourceRequest>();
var marshaller = new TagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("TagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void TagResource_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("TagResource");
var request = InstantiateClassGenerator.Execute<TagResourceRequest>();
var marshaller = new TagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("TagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void TagResource_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("TagResource");
var request = InstantiateClassGenerator.Execute<TagResourceRequest>();
var marshaller = new TagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("TagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void TagResource_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("TagResource");
var request = InstantiateClassGenerator.Execute<TagResourceRequest>();
var marshaller = new TagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("TagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void TagResource_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("TagResource");
var request = InstantiateClassGenerator.Execute<TagResourceRequest>();
var marshaller = new TagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("TagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UntagResourceMarshallTest()
{
var operation = service_model.FindOperation("UntagResource");
var request = InstantiateClassGenerator.Execute<UntagResourceRequest>();
var marshaller = new UntagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UntagResource", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UntagResourceResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UntagResourceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UntagResource_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("UntagResource");
var request = InstantiateClassGenerator.Execute<UntagResourceRequest>();
var marshaller = new UntagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UntagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UntagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UntagResource_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("UntagResource");
var request = InstantiateClassGenerator.Execute<UntagResourceRequest>();
var marshaller = new UntagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UntagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UntagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UntagResource_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("UntagResource");
var request = InstantiateClassGenerator.Execute<UntagResourceRequest>();
var marshaller = new UntagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UntagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UntagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UntagResource_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("UntagResource");
var request = InstantiateClassGenerator.Execute<UntagResourceRequest>();
var marshaller = new UntagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UntagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UntagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UntagResource_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("UntagResource");
var request = InstantiateClassGenerator.Execute<UntagResourceRequest>();
var marshaller = new UntagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UntagResource", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UntagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateArchiveRuleMarshallTest()
{
var operation = service_model.FindOperation("UpdateArchiveRule");
var request = InstantiateClassGenerator.Execute<UpdateArchiveRuleRequest>();
var marshaller = new UpdateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateArchiveRule", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateArchiveRule_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateArchiveRule");
var request = InstantiateClassGenerator.Execute<UpdateArchiveRuleRequest>();
var marshaller = new UpdateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateArchiveRule_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateArchiveRule");
var request = InstantiateClassGenerator.Execute<UpdateArchiveRuleRequest>();
var marshaller = new UpdateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateArchiveRule_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateArchiveRule");
var request = InstantiateClassGenerator.Execute<UpdateArchiveRuleRequest>();
var marshaller = new UpdateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateArchiveRule_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateArchiveRule");
var request = InstantiateClassGenerator.Execute<UpdateArchiveRuleRequest>();
var marshaller = new UpdateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateArchiveRule_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateArchiveRule");
var request = InstantiateClassGenerator.Execute<UpdateArchiveRuleRequest>();
var marshaller = new UpdateArchiveRuleRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateArchiveRule", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateArchiveRuleResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateFindingsMarshallTest()
{
var operation = service_model.FindOperation("UpdateFindings");
var request = InstantiateClassGenerator.Execute<UpdateFindingsRequest>();
var marshaller = new UpdateFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateFindings", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateFindings_AccessDeniedExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateFindings");
var request = InstantiateClassGenerator.Execute<UpdateFindingsRequest>();
var marshaller = new UpdateFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("AccessDeniedException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","AccessDeniedException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateFindings_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateFindings");
var request = InstantiateClassGenerator.Execute<UpdateFindingsRequest>();
var marshaller = new UpdateFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateFindings_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateFindings");
var request = InstantiateClassGenerator.Execute<UpdateFindingsRequest>();
var marshaller = new UpdateFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ResourceNotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateFindings_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateFindings");
var request = InstantiateClassGenerator.Execute<UpdateFindingsRequest>();
var marshaller = new UpdateFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ThrottlingException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("AccessAnalyzer")]
public void UpdateFindings_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateFindings");
var request = InstantiateClassGenerator.Execute<UpdateFindingsRequest>();
var marshaller = new UpdateFindingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateFindings", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ValidationException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdateFindingsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
} | 49.187778 | 143 | 0.648891 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/test/Services/AccessAnalyzer/UnitTests/Generated/Marshalling/AccessAnalyzerMarshallingTests.cs | 177,076 | C# |
using LocationAPI.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace LocationAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class LocationController : ControllerBase
{
private readonly ILogger<LocationController> _logger;
public LocationController(ILogger<LocationController> logger)
{
_logger = logger;
}
[HttpGet]
public Location Get(double latitude, double longitude)
{
return new Location()
{
Name = "Antwerp",
Latitude = latitude,
Longitude = longitude
};
}
}
} | 24.275862 | 69 | 0.585227 | [
"MIT"
] | Depechie/OpenTelemetryGrafana | LocationAPI/Controllers/LocationController.cs | 706 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("Fit.Natic.MealLogPage.xaml", "MealLogPage.xaml", typeof(global::Fit.Natic.MealLogPage))]
namespace Fit.Natic {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("MealLogPage.xaml")]
public partial class MealLogPage : global::Xamarin.Forms.ContentPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Entry Meal_Name;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Entry Meal_Calories;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Picker Meal_Type;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Entry Meal_Notes;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(MealLogPage));
Meal_Name = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Entry>(this, "Meal_Name");
Meal_Calories = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Entry>(this, "Meal_Calories");
Meal_Type = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Picker>(this, "Meal_Type");
Meal_Notes = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Entry>(this, "Meal_Notes");
}
}
}
| 54.317073 | 151 | 0.649753 | [
"MIT"
] | mmcdermott011/Fit.Natic | Fit.Natic/obj/Debug/netstandard2.0/MealLogPage.xaml.g.cs | 2,227 | C# |
using System.Web;
using System.Web.Mvc;
namespace EPages
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | 19.846154 | 80 | 0.651163 | [
"MIT"
] | MHarisMumtaz/E-Pages | EPages/App_Start/FilterConfig.cs | 260 | C# |
#pragma checksum "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\TeacherFieldCourseResearchAssistants\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "97dd3dc2934e6f7e6d7ba9bcb34b5bacd8ca600b"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_TeacherFieldCourseResearchAssistants_Details), @"mvc.1.0.view", @"/Views/TeacherFieldCourseResearchAssistants/Details.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\_ViewImports.cshtml"
using gis_final;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\_ViewImports.cshtml"
using gis_final.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\_ViewImports.cshtml"
using Microsoft.AspNetCore.Http;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"97dd3dc2934e6f7e6d7ba9bcb34b5bacd8ca600b", @"/Views/TeacherFieldCourseResearchAssistants/Details.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e52aa07f67b8aeecf4d0e15efb533e891e5bb93f", @"/Views/_ViewImports.cshtml")]
public class Views_TeacherFieldCourseResearchAssistants_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<gis_final.Models.TeacherFieldCourseResearchAssistant>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
#nullable restore
#line 3 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\TeacherFieldCourseResearchAssistants\Details.cshtml"
ViewData["Title"] = "Details";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>Details</h1>\r\n\r\n<div>\r\n <h4>TeacherFieldCourseResearchAssistant</h4>\r\n <hr />\r\n <dl class=\"row\">\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 14 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\TeacherFieldCourseResearchAssistants\Details.cshtml"
Write(Html.DisplayNameFor(model => model.AssistantId));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 17 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\TeacherFieldCourseResearchAssistants\Details.cshtml"
Write(Html.DisplayFor(model => model.AssistantId));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 20 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\TeacherFieldCourseResearchAssistants\Details.cshtml"
Write(Html.DisplayNameFor(model => model.TeacherFieldCourse));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 23 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\TeacherFieldCourseResearchAssistants\Details.cshtml"
Write(Html.DisplayFor(model => model.TeacherFieldCourse.Id));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n </dl>\r\n</div>\r\n<div>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "97dd3dc2934e6f7e6d7ba9bcb34b5bacd8ca600b6127", async() => {
WriteLiteral("Edit");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 28 "D:\ders\homeworks\OOP\Final\general_information_system\gis_final\gis_final\Views\TeacherFieldCourseResearchAssistants\Details.cshtml"
WriteLiteral(Model.Id);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(" |\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "97dd3dc2934e6f7e6d7ba9bcb34b5bacd8ca600b8322", async() => {
WriteLiteral("Back to List");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</div>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public IHttpContextAccessor HttpContextAccessor { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<gis_final.Models.TeacherFieldCourseResearchAssistant> Html { get; private set; }
}
}
#pragma warning restore 1591
| 60.866279 | 298 | 0.745821 | [
"MIT"
] | YAVATAN-Official/oop_final | gis_final/obj/Debug/netcoreapp3.1/Razor/Views/TeacherFieldCourseResearchAssistants/Details.cshtml.g.cs | 10,469 | C# |
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace WebApiDoodle.Web.Filters {
public class RequireHttpsAttribute : AuthorizationFilterAttribute {
public override void OnAuthorization(HttpActionContext actionContext) {
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps) {
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden) {
ReasonPhrase = "Forbidden (SSL Required)"
};
}
}
}
} | 29.619048 | 93 | 0.649518 | [
"MIT"
] | WebAPIDoodle/WebAPIDoodle | src/WebApiDoodle.Web/Filters/RequireHttpsAttribute.cs | 624 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatement
{
/// <summary>
/// Statements to combine with `OR` logic. You can use any statements that can be nested. See Statement above for details.
/// </summary>
public readonly ImmutableArray<Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatement> Statements;
[OutputConstructor]
private WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatement(ImmutableArray<Outputs.WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatement> statements)
{
Statements = statements;
}
}
}
| 38.142857 | 194 | 0.752809 | [
"ECL-2.0",
"Apache-2.0"
] | chivandikwa/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatement.cs | 1,068 | C# |
// Copyright (c) Bottlenose Labs Inc. (https://github.com/bottlenoselabs). All rights reserved.
// Licensed under the MIT license. See LICENSE file in the Git repository root directory for full license information.
using System.Collections.Immutable;
namespace C2CS.Contexts.ReadCodeC.Domain.Parse;
public class ClangArgumentsBuilderResult
{
public readonly ImmutableArray<string> Arguments;
public readonly ImmutableDictionary<string, string> LinkedPaths;
public ClangArgumentsBuilderResult(
ImmutableArray<string> arguments,
ImmutableDictionary<string, string> linkedPaths)
{
Arguments = arguments;
LinkedPaths = linkedPaths;
}
}
| 32.761905 | 118 | 0.757267 | [
"MIT"
] | lithiumtoast/c-2-cs | src/cs/production/contexts/C2CS.Contexts.ReadCodeC/Domain/Parse/ClangArgumentsBuilderResult.cs | 688 | C# |
using System.Data.Entity;
using Walltage.Domain.Entities;
namespace Walltage.Domain.Repositories
{
public class WallpaperRepository : Repository<Wallpaper>
{
public WallpaperRepository(DbContext context)
: base(context)
{
}
}
}
| 19.857143 | 60 | 0.661871 | [
"MIT"
] | abdurrahman/walltage | src/Walltage.Domain/Repositories/WallpaperRepository.cs | 280 | C# |
using System;
using System.IO;
using net.r_eg.MvsSln.Projects;
namespace MvsSlnTest._svc
{
internal sealed class TempPackagesConfig: PackagesConfig, IDisposable
{
public TempPackagesConfig(string path, PackagesConfigOptions options)
: base(path, options)
{
}
#region IDisposable
private bool disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool _)
{
if(!disposed)
{
if(IsNew) System.IO.File.Delete(file);
disposed = true;
}
}
#endregion
}
}
| 18.763158 | 77 | 0.534362 | [
"MIT"
] | 3F/MvsSln | MvsSlnTest/_svc/TempPackagesConfig.cs | 715 | C# |
using System.ComponentModel.DataAnnotations;
namespace Accounts.Web.ViewModels.Account
{
public class LoginViewModel
{
[Required]
public string Login { get; set; }
[Required]
public string Password { get; set; }
public bool RememberMe { get; set; }
}
} | 23.538462 | 45 | 0.630719 | [
"MIT"
] | CWISoftware/accounts | src/Accounts.Web/ViewModels/Account/LoginViewModel.cs | 308 | C# |
using HotelService.Domain;
using MediatR;
namespace HotelService.Infrastructure.Requests.CreateHotel;
public record CreateHotelRequest(short Rooms, string Country, string City, string Address) : IRequest<Hotel?>; | 35.666667 | 110 | 0.831776 | [
"Apache-2.0"
] | jokk-itu/BookVacation | HotelService/HotelService.Infrastructure/Requests/CreateHotel/CreateHotelRequest.cs | 214 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenuManager : MonoBehaviour
{
public GameObject newGamePanel;
public GameObject GameDatabase;
// Start is called before the first frame update
void Start()
{
newGamePanel.SetActive(false);
MakeDatabase();
SetDefaults();
}
public void NewGame()
{
Debug.Log("Creating New Game");
newGamePanel.SetActive(true);
}
public void ContinueGame()
{
Debug.Log("Continuing Game");
if (SaveSystem.SaveFound())
{
StartGame();
GameDatabase.GetComponent<SaveManager>().LoadGame();
}
else
{
newGamePanel.SetActive(true);
}
}
public void QuitGame()
{
Debug.Log("Quiting Game");
DeleteInfo();
Application.Quit();
}
public void StartGame()
{
Debug.Log(PlayerPrefs.GetInt(PrefNames.difficulty));
Debug.Log(PlayerPrefs.GetString(PrefNames.playerName));
SceneManager.LoadScene(1);
}
void MakeDatabase()
{
if(GameDatabase != null || GameObject.Find("GameData"))
{
GameDatabase = GameObject.Find("GameData");
return;
}
GameDatabase = new GameObject();
GameDatabase.name = "GameData";
GameDatabase.AddComponent<SaveManager>();
}
// PlayerPref helper functions
public void SetDifficulty(int multiplier)
{
PlayerPrefs.SetInt(PrefNames.difficulty, multiplier);
}
public void SetPlayerName(string pName)
{
PlayerPrefs.SetString(PrefNames.playerName, pName);
}
void SetDefaults()
{
PlayerPrefs.SetInt(PrefNames.difficulty, 0);
PlayerPrefs.SetString(PrefNames.playerName, "Character");
}
void DeleteInfo()
{
PlayerPrefs.DeleteAll();
}
}
| 22.325843 | 65 | 0.600403 | [
"Apache-2.0"
] | Clara0428/Unity-2-RPG-Tempate | Assets/Main/Scripts/UI/MainMenuManager.cs | 1,989 | C# |
using System.Collections;
using NUnit.Framework;
using Unity.InteractiveTutorials;
using Unity.InteractiveTutorials.Tests;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.Windows;
namespace Unity.InteractiveTutorials.Tests
{
public class BuildStartedCriterionTests : CriterionTestBase<BuildStartedCriterion>
{
[UnityTest]
public IEnumerator CustomHandlerIsInvoked_IsCompleted()
{
#if UNITY_EDITOR_WIN
var target = BuildTarget.StandaloneWindows;
var locationPathName = "Test/Test.exe";
#elif UNITY_EDITOR_OSX
var target = BuildTarget.StandaloneOSX;
var locationPathName = "Test/Test";
#else
#error Unsupported platform
#endif
m_Criterion.BuildPlayerCustomHandler(new BuildPlayerOptions
{
scenes = null,
target = target,
locationPathName = locationPathName,
targetGroup = BuildTargetGroup.Unknown
});
yield return null;
Assert.IsTrue(m_Criterion.completed);
// Cleanup
if (Directory.Exists("Test"))
{
Directory.Delete("Test");
}
}
[UnityTest]
public IEnumerator AutoComplete_IsCompleted()
{
yield return null;
Assert.IsTrue(m_Criterion.AutoComplete());
}
}
}
| 27.09434 | 86 | 0.623955 | [
"MIT"
] | CristianCamilo04/tson1 | trod1-game/Library/PackageCache/com.unity.learn.iet-framework@0.2.3-preview.1/Tests/Editor/BuildStartedCriterionTests.cs | 1,438 | C# |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// Characterize the mutual position of some view B (other) relative to view A (this)
/// </summary>
enum MutualViewPosition
{
/// <summary>
/// B contains A(this)
/// </summary>
Contains,
/// <summary>
/// B is containd in A(this), but not vice versa
/// </summary>
ContainedIn,
/// <summary>
/// A and B does not overlap
/// </summary>
NonOverlapping,
/// <summary>
/// A and B overlap, but neither is contained in the other
/// </summary>
Overlapping
}
#region View List Nested class
/// <summary>
/// This class is shared between the linked list and array list implementations.
/// </summary>
/// <typeparam name="V"></typeparam>
class WeakViewList<V> where V : class
{
Node start;
internal class Node
{
internal WeakReference weakview; internal Node prev, next;
internal Node(V view) { weakview = new WeakReference(view); }
}
internal Node Add(V view)
{
Node newNode = new Node(view);
if (start != null) { start.prev = newNode; newNode.next = start; }
start = newNode;
return newNode;
}
internal void Remove(Node n)
{
if (n == start) { start = start.next; if (start != null) start.prev = null; }
else { n.prev.next = n.next; if (n.next != null) n.next.prev = n.prev; }
}
/// <summary>
/// Note that it is safe to call views.Remove(view.myWeakReference) if view
/// is the currently yielded object
/// </summary>
/// <returns></returns>
public SCG.IEnumerator<V> GetEnumerator()
{
Node n = start;
while (n != null)
{
//V view = n.weakview.Target as V; //This provokes a bug in the beta1 verifyer
object o = n.weakview.Target;
V view = o is V ? (V)o : null;
if (view == null)
Remove(n);
else
yield return view;
n = n.next;
}
}
}
#endregion
} | 35.163265 | 94 | 0.592861 | [
"MIT"
] | TrevorDArcyEvans/EllieWare | Code/C5/C5/ViewSupport.cs | 3,446 | C# |
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Rendering;
using BEditor.Models;
namespace BEditor.Views.ManagePlugins
{
public partial class ManagePluginsWindow : FluentWindow
{
public ManagePluginsWindow()
{
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
} | 18.857143 | 59 | 0.655303 | [
"MIT"
] | tomo0611/BEditor | src/executable/BEditor.Avalonia/Views/ManagePlugins/ManagePluginsWindow.axaml.cs | 528 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace RechargeSharp.Entities.Discounts
{
public class DiscountListResponse : IEquatable<DiscountListResponse>
{
public bool Equals(DiscountListResponse other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Discounts.SequenceEqual(other.Discounts);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((DiscountListResponse) obj);
}
public override int GetHashCode()
{
return (Discounts != null ? Discounts.GetHashCode() : 0);
}
public static bool operator ==(DiscountListResponse left, DiscountListResponse right)
{
return Equals(left, right);
}
public static bool operator !=(DiscountListResponse left, DiscountListResponse right)
{
return !Equals(left, right);
}
[JsonProperty("discounts")]
public IEnumerable<Discount> Discounts { get; set; }
}
}
| 30.068182 | 93 | 0.618292 | [
"MIT"
] | mattgenious/RechargeSharp | RechargeSharp/Entities/Discounts/DiscountListResponse.cs | 1,325 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Hotcakes.Modules.Core.Admin.Marketing.Actions {
public partial class AdjustOrderTotalEditor {
/// <summary>
/// OrderTotalAmountField control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox OrderTotalAmountField;
/// <summary>
/// lstOrderTotalAdjustmentType control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList lstOrderTotalAdjustmentType;
}
}
| 35.029412 | 93 | 0.532326 | [
"MIT"
] | HotcakesCommerce/core | Website/DesktopModules/Hotcakes/Core/Admin/Marketing/Actions/AdjustOrderTotalEditor.ascx.designer.cs | 1,193 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Northwind.Dal.Models
{
[Table("Product", Schema = "Production")]
public partial class Product
{
public Product()
{
BillOfMaterialsComponent = new HashSet<BillOfMaterials>();
BillOfMaterialsProductAssembly = new HashSet<BillOfMaterials>();
ProductCostHistory = new HashSet<ProductCostHistory>();
ProductInventory = new HashSet<ProductInventory>();
ProductListPriceHistory = new HashSet<ProductListPriceHistory>();
ProductProductPhoto = new HashSet<ProductProductPhoto>();
ProductReview = new HashSet<ProductReview>();
ProductVendor = new HashSet<ProductVendor>();
PurchaseOrderDetail = new HashSet<PurchaseOrderDetail>();
ShoppingCartItem = new HashSet<ShoppingCartItem>();
SpecialOfferProduct = new HashSet<SpecialOfferProduct>();
TransactionHistory = new HashSet<TransactionHistory>();
WorkOrder = new HashSet<WorkOrder>();
}
[Key]
[Column("ProductID")]
public int ProductId { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(25)]
public string ProductNumber { get; set; }
[Required]
public bool? MakeFlag { get; set; }
[Required]
public bool? FinishedGoodsFlag { get; set; }
[StringLength(15)]
public string Color { get; set; }
public short SafetyStockLevel { get; set; }
public short ReorderPoint { get; set; }
[Column(TypeName = "money")]
public decimal StandardCost { get; set; }
[Column(TypeName = "money")]
public decimal ListPrice { get; set; }
[StringLength(5)]
public string Size { get; set; }
[StringLength(3)]
public string SizeUnitMeasureCode { get; set; }
[StringLength(3)]
public string WeightUnitMeasureCode { get; set; }
[Column(TypeName = "decimal(8, 2)")]
public decimal? Weight { get; set; }
public int DaysToManufacture { get; set; }
[StringLength(2)]
public string ProductLine { get; set; }
[StringLength(2)]
public string Class { get; set; }
[StringLength(2)]
public string Style { get; set; }
[Column("ProductSubcategoryID")]
public int? ProductSubcategoryId { get; set; }
[Column("ProductModelID")]
public int? ProductModelId { get; set; }
[Column(TypeName = "datetime")]
public DateTime SellStartDate { get; set; }
[Column(TypeName = "datetime")]
public DateTime? SellEndDate { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DiscontinuedDate { get; set; }
[Column("rowguid")]
public Guid Rowguid { get; set; }
[Column(TypeName = "datetime")]
public DateTime ModifiedDate { get; set; }
[ForeignKey(nameof(ProductModelId))]
[InverseProperty("Product")]
public virtual ProductModel ProductModel { get; set; }
[ForeignKey(nameof(ProductSubcategoryId))]
[InverseProperty("Product")]
public virtual ProductSubcategory ProductSubcategory { get; set; }
[ForeignKey(nameof(SizeUnitMeasureCode))]
[InverseProperty(nameof(UnitMeasure.ProductSizeUnitMeasureCodeNavigation))]
public virtual UnitMeasure SizeUnitMeasureCodeNavigation { get; set; }
[ForeignKey(nameof(WeightUnitMeasureCode))]
[InverseProperty(nameof(UnitMeasure.ProductWeightUnitMeasureCodeNavigation))]
public virtual UnitMeasure WeightUnitMeasureCodeNavigation { get; set; }
[InverseProperty(nameof(BillOfMaterials.Component))]
public virtual ICollection<BillOfMaterials> BillOfMaterialsComponent { get; set; }
[InverseProperty(nameof(BillOfMaterials.ProductAssembly))]
public virtual ICollection<BillOfMaterials> BillOfMaterialsProductAssembly { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ProductCostHistory> ProductCostHistory { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ProductInventory> ProductInventory { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ProductListPriceHistory> ProductListPriceHistory { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ProductProductPhoto> ProductProductPhoto { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ProductReview> ProductReview { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ProductVendor> ProductVendor { get; set; }
[InverseProperty("Product")]
public virtual ICollection<PurchaseOrderDetail> PurchaseOrderDetail { get; set; }
[InverseProperty("Product")]
public virtual ICollection<ShoppingCartItem> ShoppingCartItem { get; set; }
[InverseProperty("Product")]
public virtual ICollection<SpecialOfferProduct> SpecialOfferProduct { get; set; }
[InverseProperty("Product")]
public virtual ICollection<TransactionHistory> TransactionHistory { get; set; }
[InverseProperty("Product")]
public virtual ICollection<WorkOrder> WorkOrder { get; set; }
}
}
| 46.521008 | 97 | 0.653902 | [
"BSD-3-Clause",
"MIT"
] | MalikWaseemJaved/presentations | .NETCore/WhatsNewInDotNetCore3/Northwind.DAL/Models/Product.cs | 5,538 | C# |
namespace Operations
{
using System;
public class StartUp
{
public static void Main(string[] args)
{
IMathOperations mathOperations = new MathOperations();
Console.WriteLine(mathOperations.Add(2, 3));
Console.WriteLine(mathOperations.Add(2.2, 3.3, 5.5));
Console.WriteLine(mathOperations.Add(2.2M, 3.3M, 4.4M));
}
}
}
| 24.058824 | 68 | 0.586797 | [
"MIT"
] | vesy53/SoftUni | C# Advanced/C# OOP/LabAndExercises/09.PolymorphismLab/Operations/StartUp.cs | 411 | C# |
/***
Copyright (C) 2018-2019. dc-koromo. All Rights Reserved.
Author: Koromo Copy Developer
***/
using Koromo_Copy.Fs;
using Koromo_Copy.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Koromo_Copy.Console.Utility
{
/// <summary>
/// 다운로드 콘솔 옵션입니다.
/// </summary>
public class AutoConsoleOption : IConsoleOption
{
[CommandLine("--help", CommandType.OPTION, Default = true)]
public bool Help;
[CommandLine("-load-dir", CommandType.ARGUMENTS, Help = "use -load-dir <Directory Name>",
Info = "Load directory information.")]
public string[] LoadDir;
[CommandLine("-overlap", CommandType.OPTION, Help = "use -overlap",
Info = "Find overlapping directory names.")]
public bool Overlap;
[CommandLine("-move", CommandType.ARGUMENTS, Help = "use -move <From Directory Name>",
Info = "Load directory information.")]
public string[] Move;
}
/// <summary>
/// Auto 콘솔입니다.
/// </summary>
public class AutoConsole : ILazy<AutoConsole>, IConsole
{
/// <summary>
/// Auto 콘솔 리다이렉트
/// </summary>
static bool Redirect(string[] arguments, string contents)
{
AutoConsoleOption option = CommandLineParser<AutoConsoleOption>.Parse(arguments);
if (option.Error)
{
Console.Instance.WriteLine(option.ErrorMessage);
if (option.HelpMessage != null)
Console.Instance.WriteLine(option.HelpMessage);
return false;
}
else if (option.Help)
{
PrintHelp();
}
else if (option.LoadDir != null)
{
ProcessLoadDir(option.LoadDir);
}
else if (option.Overlap)
{
ProcessOverlap();
}
else if (option.Move != null)
{
ProcessMove(option.Move);
}
return true;
}
bool IConsole.Redirect(string[] arguments, string contents)
{
return Redirect(arguments, contents);
}
static void PrintHelp()
{
Console.Instance.WriteLine(
"Auto Console - Helper for File Management\r\n" +
"\r\n"
);
var builder = new StringBuilder();
CommandLineParser<AutoConsoleOption>.GetFields().ToList().ForEach(
x =>
{
if (!string.IsNullOrEmpty(x.Value.Item2.Help))
builder.Append($" {x.Key} ({x.Value.Item2.Help}) : {x.Value.Item2.Info} [{x.Value.Item1}]\r\n");
else
builder.Append($" {x.Key} : {x.Value.Item2.Info} [{x.Value.Item1}]\r\n");
});
Console.Instance.WriteLine(builder.ToString());
}
static List<string> dirs;
static void ProcessLoadDir(string[] args)
{
Console.Instance.GlobalTask.Add(Task.Run(async () =>
{
if (!Directory.Exists(args[0]))
{
Console.Instance.WriteErrorLine($"'{args[0]}' is not valid directory name.");
return;
}
var indexor = new FileIndexor();
indexor.OnlyListing = true;
await indexor.ListingDirectoryAsync(args[0]);
dirs = indexor.GetDirectories();
}));
}
static void ProcessOverlap()
{
var overlap = new Dictionary<string, List<string>>();
foreach (var dir in dirs)
{
var d = Path.GetFileName(Path.GetDirectoryName(dir));
if (!overlap.ContainsKey(d))
overlap.Add(d, new List<string>());
overlap[d].Add(dir);
}
foreach (var ov in overlap)
{
if (ov.Value.Count > 1)
{
foreach (var dd in ov.Value)
Console.Instance.WriteLine(dd);
Console.Instance.WriteLine("");
}
}
}
/// <summary>
/// 폴더를 옮깁니다.
/// </summary>
/// <param name="args"></param>
static void ProcessMove(string[] args)
{
var overlap = new Dictionary<string, List<string>>();
var valid = new HashSet<string>();
foreach (var dir in dirs)
{
var d = Path.GetFileName(Path.GetDirectoryName(dir));
if (!overlap.ContainsKey(d))
overlap.Add(d, new List<string>());
overlap[d].Add(dir);
valid.Add(d);
}
var indexor = new FileIndexor();
indexor.OnlyListing = true;
Task.Run(async () => await indexor.ListingDirectoryAsync(args[0])).Wait();
foreach (var dir in indexor.GetDirectories())
{
//if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length == 0)
//{
// Directory.Delete(dir);
// Console.Instance.WriteLine("[DELETE] " + dir);
// continue;
//}
var d = Path.GetFileName(Path.GetDirectoryName(dir));
if (valid.Contains(d))
{
if (overlap[d].Count == 1)
{
var del = true;
foreach (string fi in Directory.GetFiles(dir))
{
var filename = Path.GetFileName(fi);
if (File.Exists(Path.Combine(overlap[d][0], filename)))
{
Console.Instance.WriteLine("File already exists " + d + " " + filename);
if (new FileInfo(fi).Length <= new FileInfo(Path.Combine(overlap[d][0], filename)).Length * 1.1)
{
Console.Instance.WriteLine("Same length " + new FileInfo(fi).Length);
File.Delete(fi);
Console.Instance.WriteLine("[DELETE FILE] " + fi);
continue;
}
del = false;
continue;
}
File.Move(fi, Path.Combine(overlap[d][0], filename));
Console.Instance.WriteLine("[MOVE] " + fi + " => " + Path.Combine(overlap[d][0], filename));
}
if (del && Directory.GetDirectories(dir).Length == 0)
{
Directory.Delete(dir);
Console.Instance.WriteLine("[DELETE] " + dir);
}
}
else
{
Console.Instance.WriteLine("Cannot move " + d);
}
}
else
{
Console.Instance.WriteLine("Not found " + d);
}
}
}
}
}
| 33.582222 | 128 | 0.451826 | [
"MIT"
] | Terkiss/Koromo-Copy | Koromo Copy/Console/Utility/AutoConsole.cs | 7,618 | C# |
namespace MagazineProject.Web.Models.Manage
{
using System.ComponentModel.DataAnnotations;
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
} | 36.277778 | 110 | 0.656968 | [
"MIT"
] | Xzq70r4/MagazineProject-Rewritten | Source/Web/MagazineProject.Web.Models/Manage/SetPasswordViewModel.cs | 655 | 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.Portal.V20200901Preview.Outputs
{
[OutputType]
public sealed class ViolationResponseResult
{
/// <summary>
/// Error message.
/// </summary>
public readonly string ErrorMessage;
/// <summary>
/// Id of the item that violates tenant configuration.
/// </summary>
public readonly string Id;
/// <summary>
/// Id of the user who owns violated item.
/// </summary>
public readonly string UserId;
[OutputConstructor]
private ViolationResponseResult(
string errorMessage,
string id,
string userId)
{
ErrorMessage = errorMessage;
Id = id;
UserId = userId;
}
}
}
| 25.674419 | 81 | 0.599638 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Portal/V20200901Preview/Outputs/ViolationResponseResult.cs | 1,104 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Common.Constants;
using Common.Interfaces;
namespace Common.Structs
{
public abstract class BaseCharacter : ICharacter
{
public abstract int Build { get; set; }
public ulong Guid { get; set; }
public string Name { get; set; }
public byte Race { get; set; }
public byte Class { get; set; }
public byte Gender { get; set; }
public byte Skin { get; set; }
public byte Face { get; set; }
public byte HairStyle { get; set; }
public byte HairColor { get; set; }
public byte FacialHair { get; set; }
public uint Level { get; set; } = 11;
public uint Zone { get; set; }
public Location Location { get; set; }
public bool IsOnline { get; set; } = false;
public uint Health { get; set; } = 100;
public uint Mana { get; set; } = 100;
public uint Rage { get; set; } = 1000;
public uint Focus { get; set; } = 100;
public uint Energy { get; set; } = 100;
public uint Strength { get; set; } = 10;
public uint Agility { get; set; } = 10;
public uint Stamina { get; set; } = 10;
public uint Intellect { get; set; } = 10;
public uint Spirit { get; set; } = 10;
public byte PowerType { get; set; } = 1;
public byte RestedState { get; set; } = 3;
public StandState StandState { get; set; } = StandState.STANDING;
public bool IsTeleporting { get; set; } = false;
public uint DisplayId { get; set; }
public uint MountDisplayId { get; set; }
public float Scale { get; set; }
public bool IsFlying { get; set; }
protected SortedList<int, byte[]> FieldData;
protected byte MaskSize;
protected byte[] MaskArray;
public BaseCharacter() => FieldData = new SortedList<int, byte[]>();
#region Methods
public abstract IPacketWriter BuildForceSpeed(float modifier, SpeedType type = SpeedType.Run);
public abstract IPacketWriter BuildMessage(string text);
public abstract IPacketWriter BuildUpdate();
public abstract void Teleport(float x, float y, float z, float o, uint map, ref IWorldManager manager);
public virtual IPacketWriter BuildFly(bool mode) => null;
#endregion
#region Helpers
protected void SetField<TEnum, TValue>(TEnum index, TValue value) where TEnum : Enum where TValue : unmanaged
{
int field = (int)(object)index;
int size = Marshal.SizeOf<TValue>();
FieldData[field] = new byte[size];
MemoryMarshal.Write(FieldData[field], ref value);
for (int i = 0; i < (size / 4); i++)
MaskArray[field / 8] |= (byte)(1 << ((field + i) % 8));
}
protected uint ToUInt32(byte b1 = 0, byte b2 = 0, byte b3 = 0, byte b4 = 0)
{
return (uint)(b1 | (b2 << 8) | (b3 << 16) | (b4 << 24));
}
protected uint ToUInt32(ushort u1 = 0, ushort u2 = 0)
{
return (uint)(u1 | (u2 << 16));
}
#endregion
#region Serialization
internal void Serialize(BinaryWriter bw)
{
bw.Write(Build);
bw.Write(Class);
bw.Write(DisplayId);
bw.Write(Face);
bw.Write(FacialHair);
bw.Write(Gender);
bw.Write(Guid);
bw.Write(HairColor);
bw.Write(HairStyle);
bw.Write(Location.X);
bw.Write(Location.Y);
bw.Write(Location.Z);
bw.Write(Location.O);
bw.Write(Location.Map);
bw.Write(Name);
bw.Write(PowerType);
bw.Write(Race);
bw.Write(Skin);
bw.Write(Zone);
bw.Write(Scale);
bw.Write(IsFlying);
}
internal void Deserialize(BinaryReader br)
{
Build = br.ReadInt32();
Class = br.ReadByte();
DisplayId = br.ReadUInt32();
Face = br.ReadByte();
FacialHair = br.ReadByte();
Gender = br.ReadByte();
Guid = br.ReadUInt64();
HairColor = br.ReadByte();
HairStyle = br.ReadByte();
Location = new Location()
{
X = br.ReadSingle(),
Y = br.ReadSingle(),
Z = br.ReadSingle(),
O = br.ReadSingle(),
Map = br.ReadUInt32(),
};
Name = br.ReadString();
PowerType = br.ReadByte();
Race = br.ReadByte();
Skin = br.ReadByte();
Zone = br.ReadUInt32();
Scale = br.ReadSingle();
IsFlying = br.ReadBoolean();
}
#endregion Serialization
}
}
| 32.559211 | 117 | 0.53041 | [
"MIT"
] | Ghaster/AIO-Sandbox | Common/Structs/BaseCharacter.cs | 4,951 | C# |
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Threading.Tasks;
namespace SalveMariaJf.Models
{
public class Email
{
SmtpClient smtpClient;
public Email() {
smtpClient = new SmtpClient()
{
Host = "smtp.gmail.com",
Port = 587,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["User"], ConfigurationManager.AppSettings["Psw"]),
EnableSsl = true
};
}
public bool Send(Pessoa pessoa)
{
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["User"]);
mailMessage.To.Add(new MailAddress(ConfigurationManager.AppSettings["User"]));
mailMessage.Subject = $"Urgencia para {pessoa.Nome}";
mailMessage.Body = $"Solicitação de socorro para {pessoa.Nome}\r\nCPF: {pessoa.Cpf}\r\nLocal: {pessoa.Local}";
mailMessage.IsBodyHtml = false;
try
{
smtpClient.Send(mailMessage);
}
catch
{
return false;
}
return true;
}
}
} | 30.727273 | 136 | 0.535503 | [
"MIT"
] | filipejesse/HelpButton | SalveMariaJf/SalveMariaJf/Models/Email.cs | 1,356 | C# |
using myClient.service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Services;
using System.Windows.Forms;
namespace myClient
{
public partial class Client : Form
{
public Client()
{
InitializeComponent();
}
//Adding action on click button
private void button1_Click(object sender, EventArgs e)
{
try
{
//Create instance to work with the web service
service.Service1 myClient = new service.Service1();
//Get path of the SVG file to convert with OpenFileDialog
string path = "";
OpenFileDialog getfile = new OpenFileDialog();
getfile.Title = "Open file..";
getfile.Filter = "Images|*.svg";
//If everything OK, save the path
if (getfile.ShowDialog() == DialogResult.OK)
{
path = getfile.FileName;
}
/*Open the file with the path obtained in the previous step
using a FileStream and convert it to an array of bytes with
filestream.Read*/
string filename = path;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, (int)fs.Length);
fs.Close();
/*Declare and initialize an array of bytes to store the
result of calling the web service*/
byte[] result = new byte[100000];
System.Threading.Thread.Sleep(5000);
//Call the web service to convert the SVG file to PNG and transform it
result = myClient.SVGtoPNGandTransform(ImageData);
//Obtain a path to save the PNG file with SaveFileDialog
string savepath = "";
SaveFileDialog setfile = new SaveFileDialog();
setfile.Title = "Save as..";
setfile.Filter = "Images|*.png";
//If everything OK, save the path, the name of the file and the extension of the file
if (setfile.ShowDialog() == DialogResult.OK)
{
string ext = System.IO.Path.GetExtension(setfile.FileName);
savepath = setfile.FileName;
}
//Open a file stream to save the converted and transformed id to the file system
string savefileName = savepath;
FileStream fileStream2 = new FileStream(savefileName, FileMode.Create);
//Write it to the file system
fileStream2.Write(result, 0, result.Length);
//Print the result image in a pictureBox in the app
pictureBox1.Image = System.Drawing.Image.FromStream(fileStream2);
fileStream2.Close();
//If everthing OK, show a message on the richTextBox in the app
richTextBox1.AppendText("Well done!");
}
catch (Exception E)
{
//If any error, print the exception on the richTextBox
richTextBox1.AppendText("error : \n" + E.ToString());
}
}
}
}
| 36.610526 | 101 | 0.549741 | [
"MIT"
] | manglaneso/Webberservice | client/myClient/Form1.cs | 3,480 | C# |
using System;
using System.Text.RegularExpressions;
using IotHome.RaspberryPi.Interface;
using IotHome.RaspberryPi.Interface.Sensor;
using IotHome.RaspberryPi.Model;
using IotHome.RaspberryPi.Model.Exception;
namespace IotHome.RaspberryPi.Implementation.Sensor
{
public class DS18B20Thermometer : ISensor
{
private static readonly Regex TempRegex = new Regex(@"t=\d+", RegexOptions.Compiled);
private readonly IShellHelper _shellHelper;
private readonly string _deviceId;
public DS18B20Thermometer(IShellHelper shellHelper, SensorSettings settings)
{
_shellHelper = shellHelper;
_deviceId = settings.DeviceId;
Name = settings.Name;
}
public ReadingType ReadingType => ReadingType.Temperature;
public string Name { get; }
public decimal ReadValue()
{
// 4b 01 4b 46 7f ff 05 10 e1 : crc=e1 YES
// 4b 01 4b 46 7f ff 05 10 e1 t=20687
var tempFileContent = _shellHelper.ExecuteCommandAsync($"cat /sys/bus/w1/devices/{_deviceId}/w1_slave").Result;
var match = TempRegex.Match(tempFileContent);
if (!match.Success)
{
throw new SensorException($"Unable to find t=XXXXX, sensor DS18B20 ({_deviceId})");
}
var stringTemp = match.Value.Replace("t=", string.Empty);
if (int.TryParse(stringTemp, out var temp))
{
return Math.Round(temp / 1000m, 1);
}
throw new SensorException($"Unable to parse {stringTemp} to int, sensor DS18B20 ({_deviceId})");
}
}
}
| 33.52 | 123 | 0.624702 | [
"MIT"
] | jjankowski87/IotHome.RaspberryPi | IotHome.RaspberryPi.Implementation/Sensor/DS18B20Thermometer.cs | 1,678 | C# |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Ankh.Chocolatey
{
static class NativeMethods
{
const string MsiDll = "Msi.dll";
[DllImport(MsiDll, CharSet = CharSet.Unicode, ExactSpelling = true)]
public extern static uint MsiOpenPackageW(string szPackagePath, out MsiHandle product);
[DllImport(MsiDll, ExactSpelling=true)]
public extern static uint MsiCloseHandle(IntPtr hAny);
[DllImport(MsiDll, CharSet = CharSet.Unicode, ExactSpelling = true)]
static extern uint MsiGetProductPropertyW(MsiHandle hProduct, string szProperty, StringBuilder value, ref int length);
[DllImport(MsiDll, ExactSpelling = true)]
public static extern int MsiSetInternalUI(int value, IntPtr hwnd);
public static uint MsiGetProductProperty(MsiHandle hProduct, string szProperty, out string value)
{
StringBuilder sb = new StringBuilder(1024);
int length = sb.Capacity;
uint err;
value = null;
if(0 == (err = MsiGetProductPropertyW(hProduct, szProperty, sb, ref length)))
{
sb.Length = length;
value = sb.ToString();
return 0;
}
return err;
}
}
}
| 32.380952 | 127 | 0.611765 | [
"Apache-2.0"
] | AnkhSVN/AnkhSVN | src/tools/Ankh.Chocolatey/NativeMethods.cs | 1,362 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using TP.AutoDeploy.Extension;
namespace TP.AutoDeploy.Models
{
public class UserMetadata
{
/// <summary>
/// Gets or sets the common target.
/// </summary>
/// <value>
/// The common target.
/// </value>
[XmlArrayItem("TargetBase")]
public List<TargetInfoBase> CommonTarget {get;set;}
/// <summary>
/// Gets or sets the projects.
/// </summary>
/// <value>
/// The projects.
/// </value>
[XmlArrayItem("Target")]
public List<TargetInfo> Targets { get; set; }
/// <summary>
/// Gets or sets the anonymous data.
/// </summary>
/// <value>
/// The anonymous data.
/// </value>
public AnonymousData AnonymousData { get; set; }
/// <summary>
/// Gets the <see cref="TargetInfo"/> with the specified project name.
/// </summary>
/// <value>
/// The <see cref="TargetInfo"/>.
/// </value>
/// <param name="targetName">Name of the project.</param>
/// <returns></returns>
public TargetInfo this[string targetName]
{
get
{
return this.Targets?.FirstOrDefault(pr => pr.Name.Equals(targetName));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="UserMetadata"/> class.
/// </summary>
public UserMetadata()
{
this.Targets = new List<TargetInfo>();
this.CommonTarget = new List<TargetInfoBase>();
this.AnonymousData = new AnonymousData();
}
/// <summary>
/// Updates the data.
/// </summary>
public void UpdateData()
{
foreach (var target in this.CommonTarget)
{
target.UpdateData(this);
}
foreach (var target in this.Targets)
{
target.UpdateData(this);
}
}
}
}
| 26.768293 | 86 | 0.507062 | [
"Unlicense"
] | phamtuanit/DeployProjectOutputExtensibility | src/DeployProjectOutputExtensibility/Models/UserMetadata.cs | 2,197 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using EasyNetQ.Producer;
using EasyNetQ.Scheduler.Mongo.Core.Logging;
using EasyNetQ.SystemMessages;
using EasyNetQ.Topology;
namespace EasyNetQ.Scheduler.Mongo.Core
{
public class SchedulerService : ISchedulerService
{
private readonly ILog logger = LogProvider.For<SchedulerService>();
private readonly IBus bus;
private readonly ISchedulerServiceConfiguration configuration;
private readonly IScheduleRepository scheduleRepository;
private Timer handleTimeoutTimer;
private Timer publishTimer;
private List<IDisposable> subscriptions;
public SchedulerService(IBus bus, IScheduleRepository scheduleRepository, ISchedulerServiceConfiguration configuration)
{
this.bus = bus;
this.scheduleRepository = scheduleRepository;
this.configuration = configuration;
}
public void Start()
{
logger.Debug("Starting SchedulerService");
subscriptions = new List<IDisposable>
{
bus.PubSub.Subscribe<ScheduleMe>(configuration.SubscriptionId, OnMessage),
bus.PubSub.Subscribe<UnscheduleMe>(configuration.SubscriptionId, OnMessage),
};
publishTimer = new Timer(OnPublishTimerTick, null, TimeSpan.Zero, configuration.PublishInterval);
handleTimeoutTimer = new Timer(OnHandleTimeoutTimerTick, null, TimeSpan.Zero, configuration.HandleTimeoutInterval);
}
public void Stop()
{
logger.Debug("Stopping SchedulerService");
publishTimer?.Dispose();
handleTimeoutTimer?.Dispose();
foreach (var subscription in subscriptions)
{
subscription.Dispose();
}
bus?.Dispose();
}
public void OnHandleTimeoutTimerTick(object state)
{
logger.Debug("Handling failed messages");
scheduleRepository.HandleTimeout();
}
public void OnPublishTimerTick(object state)
{
if (!bus.Advanced.IsConnected) return;
try
{
var published = 0;
while (published < configuration.PublishMaxSchedules)
{
var schedule = scheduleRepository.GetPending();
if (schedule == null)
return;
var exchangeName = schedule.Exchange ?? schedule.BindingKey;
var routingKey = schedule.RoutingKey ?? schedule.BindingKey;
var properties = schedule.BasicProperties ?? new MessageProperties {Type = schedule.BindingKey};
logger.DebugFormat("Publishing Scheduled Message with to exchange '{0}'", exchangeName);
var exchange = bus.Advanced.ExchangeDeclare(exchangeName, schedule.ExchangeType ?? ExchangeType.Topic);
bus.Advanced.Publish(
exchange,
routingKey,
false,
properties,
schedule.InnerMessage
);
scheduleRepository.MarkAsPublished(schedule.Id);
++published;
}
}
catch (Exception exception)
{
logger.ErrorFormat("Error in schedule pol\r\n{0}", exception);
}
}
private void OnMessage(UnscheduleMe message)
{
logger.Debug("Got Unschedule Message");
scheduleRepository.Cancel(message.CancellationKey);
}
private void OnMessage(ScheduleMe message)
{
logger.Debug("Got Schedule Message");
scheduleRepository.Store(new Schedule
{
Id = Guid.NewGuid(),
CancellationKey = message.CancellationKey,
BindingKey = message.BindingKey,
InnerMessage = message.InnerMessage,
State = ScheduleState.Pending,
WakeTime = message.WakeTime,
Exchange = message.Exchange,
ExchangeType = message.ExchangeType,
RoutingKey = message.RoutingKey,
BasicProperties = message.MessageProperties
});
}
}
} | 37.805085 | 127 | 0.578121 | [
"MIT"
] | Eu-JinOoi/EasyNetQ | Source/EasyNetQ.Scheduler.Mongo.Core/SchedulerService.cs | 4,463 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.FinancialManagement
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Get_Budget_Fringe_Rate_Tables_ResponseType : INotifyPropertyChanged
{
private Budget_Fringe_Rate_TableObjectType[] request_ReferencesField;
private Budget_Fringe_Rate_Table_Request_CriteriaType request_CriteriaField;
private Response_FilterType response_FilterField;
private Budget_Fringe_Rate_Table_Response_GroupType response_GroupField;
private Response_ResultsType response_ResultsField;
private Budget_Fringe_Rate_TableType[] response_DataField;
private string versionField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlArray(Order = 0), XmlArrayItem("Fringe_Rate_Table_Reference", IsNullable = false)]
public Budget_Fringe_Rate_TableObjectType[] Request_References
{
get
{
return this.request_ReferencesField;
}
set
{
this.request_ReferencesField = value;
this.RaisePropertyChanged("Request_References");
}
}
[XmlElement(Order = 1)]
public Budget_Fringe_Rate_Table_Request_CriteriaType Request_Criteria
{
get
{
return this.request_CriteriaField;
}
set
{
this.request_CriteriaField = value;
this.RaisePropertyChanged("Request_Criteria");
}
}
[XmlElement(Order = 2)]
public Response_FilterType Response_Filter
{
get
{
return this.response_FilterField;
}
set
{
this.response_FilterField = value;
this.RaisePropertyChanged("Response_Filter");
}
}
[XmlElement(Order = 3)]
public Budget_Fringe_Rate_Table_Response_GroupType Response_Group
{
get
{
return this.response_GroupField;
}
set
{
this.response_GroupField = value;
this.RaisePropertyChanged("Response_Group");
}
}
[XmlElement(Order = 4)]
public Response_ResultsType Response_Results
{
get
{
return this.response_ResultsField;
}
set
{
this.response_ResultsField = value;
this.RaisePropertyChanged("Response_Results");
}
}
[XmlArray(Order = 5), XmlArrayItem("Fringe_Rate_Table", IsNullable = false)]
public Budget_Fringe_Rate_TableType[] Response_Data
{
get
{
return this.response_DataField;
}
set
{
this.response_DataField = value;
this.RaisePropertyChanged("Response_Data");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
this.RaisePropertyChanged("version");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 22.29078 | 136 | 0.739421 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.FinancialManagement/Get_Budget_Fringe_Rate_Tables_ResponseType.cs | 3,143 | C# |
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Persistence.Configurations
{
public class UserFollowingConfiguration : IEntityTypeConfiguration<UserFollowing>
{
public void Configure(EntityTypeBuilder<UserFollowing> builder)
{
builder.HasKey(u => new { u.ObserverId, u.TargetId });
builder.HasOne(u => u.Observer)
.WithMany(a => a.Followings)
.HasForeignKey(u => u.ObserverId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(u => u.Target)
.WithMany(a => a.Followers)
.HasForeignKey(u => u.TargetId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasCheckConstraint("CK_UserFollowing_TargetId", "[TargetId] <> [ObserverId]");
}
}
} | 34.346154 | 98 | 0.628219 | [
"MIT"
] | krzysztoftalar/Instagram | src/Persistence/Configurations/UserFollowingConfiguration.cs | 895 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.PowerShell.EditorServices.VSCode.CustomViews
{
/// <summary>
/// Contains details about the HTML content to be
/// displayed in an IHtmlContentView.
/// </summary>
public class HtmlContent
{
/// <summary>
/// Gets or sets the HTML body content.
/// </summary>
public string BodyContent { get; set; }
/// <summary>
/// Gets or sets the array of JavaScript file paths
/// to be used in the HTML content.
/// </summary>
public string[] JavaScriptPaths { get; set; }
/// <summary>
/// Gets or sets the array of stylesheet (CSS) file
/// paths to be used in the HTML content.
/// </summary>
public string[] StyleSheetPaths { get; set; }
}
}
| 29.875 | 101 | 0.599372 | [
"MIT"
] | APA2527/PowerShellEditorServices | src/PowerShellEditorServices.VSCode/CustomViews/HtmlContent.cs | 956 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static Root;
using static CalcHosts;
using static SFx;
using static ApiClassKind;
partial struct Calcs
{
[MethodImpl(Inline), Factory(Abs), Closures(SignedInts)]
public static Abs<T> abs<T>()
where T : unmanaged
=> default;
[MethodImpl(Inline), Factory(Abs), Closures(SignedInts)]
public static Abs128<T> abs<T>(W128 w)
where T : unmanaged
=> default(Abs128<T>);
[MethodImpl(Inline), Factory(Abs), Closures(SignedInts)]
public static Abs256<T> abs<T>(W256 w)
where T : unmanaged
=> default(Abs256<T>);
[MethodImpl(Inline), Factory(Abs), Closures(SignedInts)]
public static VAbs128<T> vabs<T>(W128 w)
where T : unmanaged
=> default(VAbs128<T>);
[MethodImpl(Inline), Factory(Abs), Closures(SignedInts)]
public static VAbs256<T> vabs<T>(W256 w)
where T : unmanaged
=> default(VAbs256<T>);
[MethodImpl(Inline), Abs, Closures(SignedInts)]
public static Span<T> abs<T>(ReadOnlySpan<T> src, Span<T> dst)
where T : unmanaged
=> apply(Calcs.abs<T>(), src, dst);
[MethodImpl(Inline), Abs, Closures(SignedInts)]
public static ref readonly SpanBlock128<T> abs<T>(in SpanBlock128<T> a, in SpanBlock128<T> dst)
where T : unmanaged
=> ref abs<T>(w128).Invoke(a, dst);
[MethodImpl(Inline), Abs, Closures(SignedInts)]
public static ref readonly SpanBlock256<T> abs<T>(in SpanBlock256<T> a, in SpanBlock256<T> dst)
where T : unmanaged
=> ref abs<T>(w256).Invoke(a, dst);
[MethodImpl(Inline), Abs, Closures(SignedInts)]
public static ref readonly SpanBlock128<T> add<T>(in SpanBlock128<T> a, in SpanBlock128<T> b, in SpanBlock128<T> dst)
where T : unmanaged
=> ref add<T>(w128).Invoke(a, b, dst);
}
} | 37.403226 | 125 | 0.539457 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/calc/src/calcs/abs.cs | 2,319 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using Avalonia;
using Avalonia.Controls;
using Avalonia.LogicalTree;
using Avalonia.Controls.Primitives;
using Avalonia.Threading;
using Material.Styles.Models;
namespace Material.Styles
{
public class SnackbarHost : ContentControl
{
private static HashSet<SnackbarHost> _snackbarHosts;
private ObservableCollection<SnackbarModel> _snackbars;
public ObservableCollection<SnackbarModel> SnackbarModels => _snackbars;
/// <summary>
/// Get the name of host. The name of host can be set only one time.
/// </summary>
public string HostName
{
get => GetValue(HostNameProperty);
set
{
if (HostName == null)
SetValue(HostNameProperty, value);
else
throw new InvalidOperationException("The name of host can be set only one time.");
}
}
public static readonly StyledProperty<string> HostNameProperty =
AvaloniaProperty.Register<SnackbarHost, string>(nameof(HostName));
static SnackbarHost()
{
_snackbarHosts = new HashSet<SnackbarHost>();
}
public SnackbarHost()
{
// Initialize model collection
this._snackbars = new ObservableCollection<SnackbarModel>();
this.TemplateApplied += OnTemplateApplied;
this.AttachedToLogicalTree += OnAttachedToLogicalTree;
this.DetachedFromLogicalTree += OnDetachedFromLogicalTree;
}
private static string GetFirstHostName()
{
if (_snackbarHosts is null)
// THIS IS IMPOSSIBLE TO HAPPEN! But I kept this for any reasons.
throw new NullReferenceException("Snackbar hosts pool is not initialized!");
return _snackbarHosts.First().HostName;
}
private static SnackbarHost GetHost(string name)
{
if (name is null)
throw new ArgumentNullException(nameof(name));
var result = _snackbarHosts.Where(
// Predicate
// And do not asking me, why I'm using delegate here.
// Performance are important too.
delegate(SnackbarHost host)
{
return host.HostName == name;
});
// If exists any matched results.
if (result.Any())
{
return result.First();
}
// or just return null if no any results.
return null;
}
/// <summary>
/// Post an snackbar with message text.
/// </summary>
/// <param name="text">message text.</param>
/// <param name="targetHost">the snackbar host that you wanted to use.</param>
public static void Post(string text, string targetHost = null) => Post(new SnackbarModel(text), targetHost);
/// <summary>
/// Post an snackbar with custom content and button (only one).
/// </summary>
/// <param name="model">snackbar data model.</param>
/// <param name="targetHost">the snackbar host that you wanted to use.</param>
public static void Post(SnackbarModel model, string targetHost = null)
{
if (targetHost is null)
targetHost = GetFirstHostName();
var host = GetHost(targetHost);
if (host is null)
throw new ArgumentNullException(nameof(targetHost), $"The target host named \"{targetHost}\" is not exist.");
ElapsedEventHandler onExpired = null;
onExpired = delegate(object sender, ElapsedEventArgs args)
{
if (sender is Timer timer)
{
// Remove timer.
timer.Stop();
timer.Elapsed -= onExpired;
timer.Dispose();
OnSnackbarDurationExpired(host, model);
}
};
var timer = new Timer(model.Duration.TotalMilliseconds);
timer.Elapsed += onExpired;
timer.Start();
Dispatcher.UIThread.Post(delegate
{
host.SnackbarModels.Add(model);
});
}
private static void OnSnackbarDurationExpired(SnackbarHost host, SnackbarModel model)
{
Dispatcher.UIThread.Post(delegate
{
host.SnackbarModels.Remove(model);
});
}
private void OnAttachedToLogicalTree(object sender, LogicalTreeAttachmentEventArgs e)
{
if (sender is SnackbarHost host)
{
_snackbarHosts.Add(host);
}
}
private void OnDetachedFromLogicalTree(object sender, LogicalTreeAttachmentEventArgs e)
{
if (sender is SnackbarHost host)
{
if (host.HostName is null)
throw new ArgumentNullException(nameof(HostName));
_snackbarHosts.Remove(host);
}
}
private void OnTemplateApplied(object sender, TemplateAppliedEventArgs e)
{
if (sender is SnackbarHost host)
{
host.TemplateApplied -= OnTemplateApplied;
// Initialize snackbar host
if (host.HostName is null)
throw new ArgumentNullException(nameof(HostName));
}
}
}
}
| 33.337143 | 125 | 0.550394 | [
"MIT"
] | hahn-kev/Material.Avalonia | Material.Styles/SnackbarHost.xaml.cs | 5,836 | C# |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//=============================================================================
//
// Class: SynchronizationLockException
//
// Purpose: Wait(), Notify() or NotifyAll() was called from an unsynchronized
// block of code.
//
//=============================================================================
namespace System.Threading
{
using System;
//| <include path='docs/doc[@for="SynchronizationLockException"]/*' />
public class SynchronizationLockException : SystemException {
//| <include path='docs/doc[@for="SynchronizationLockException.SynchronizationLockException"]/*' />
public SynchronizationLockException()
: base("Arg_SynchronizationLockException") {
}
//| <include path='docs/doc[@for="SynchronizationLockException.SynchronizationLockException1"]/*' />
public SynchronizationLockException(String message)
: base(message) {
}
//| <include path='docs/doc[@for="SynchronizationLockException.SynchronizationLockException2"]/*' />
public SynchronizationLockException(String message, Exception innerException)
: base(message, innerException) {
}
}
}
| 33.2 | 109 | 0.558735 | [
"MIT"
] | sphinxlogic/Singularity-RDK-2.0 | base/Applications/Runtime/Full/System/Threading/SynchronizationLockException.cs | 1,328 | C# |
// <Area> Generics - Expressions - specific catch clauses </Area>
// <Title>
// catch type parameters bound by Exception or a subclass of it in the form catch(T)
// </Title>
// <RelatedBugs> </RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class GenException<T> : Exception {}
public class GenExceptionSub<T> : GenException<T> {}
public struct Gen<Ex,T> where Ex : GenException<T>
{
public void ExceptionTest(Ex e)
{
try
{
throw e;
}
catch(Ex E)
{
Test.Eval(Object.ReferenceEquals(e,E));
}
catch
{
Console.WriteLine("Caught Wrong Exception");
Test.Eval(false);
}
}
}
public class Test
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
new Gen<GenException<int>,int>().ExceptionTest(new GenExceptionSub<int>());
new Gen<GenException<string>,string>().ExceptionTest(new GenExceptionSub<string>());
new Gen<GenException<Guid>,Guid>().ExceptionTest(new GenExceptionSub<Guid>());
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
// </Code>
| 18.164384 | 86 | 0.655354 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/baseservices/exceptions/generics/typeparameter012.cs | 1,326 | 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.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore.ModelBuilding
{
public abstract partial class ModelBuilderTest
{
public abstract class ModelBuilderTestBase
{
protected void AssertEqual(
IEnumerable<string> expectedNames,
IEnumerable<string> actualNames,
StringComparer stringComparer = null)
{
stringComparer ??= StringComparer.Ordinal;
Assert.Equal(
new SortedSet<string>(expectedNames, stringComparer),
new SortedSet<string>(actualNames, stringComparer),
stringComparer);
}
protected void AssertEqual(
IEnumerable<IProperty> expectedProperties,
IEnumerable<IProperty> actualProperties,
PropertyComparer propertyComparer = null)
{
propertyComparer ??= new PropertyComparer(compareAnnotations: false);
Assert.Equal(
new SortedSet<IProperty>(expectedProperties, propertyComparer),
new SortedSet<IProperty>(actualProperties, propertyComparer),
propertyComparer);
}
protected void AssertEqual(
IEnumerable<INavigation> expectedNavigations,
IEnumerable<INavigation> actualNavigations,
NavigationComparer navigationComparer = null)
{
navigationComparer ??= new NavigationComparer(compareAnnotations: false);
Assert.Equal(
new SortedSet<INavigation>(expectedNavigations, navigationComparer),
new SortedSet<INavigation>(actualNavigations, navigationComparer),
navigationComparer);
}
protected void AssertEqual(
IEnumerable<IKey> expectedKeys,
IEnumerable<IKey> actualKeys,
TestKeyComparer testKeyComparer = null)
{
testKeyComparer ??= new TestKeyComparer(compareAnnotations: false);
Assert.Equal(
new SortedSet<IKey>(expectedKeys, testKeyComparer),
new SortedSet<IKey>(actualKeys, testKeyComparer),
testKeyComparer);
}
protected void AssertEqual(
IEnumerable<IForeignKey> expectedForeignKeys,
IEnumerable<IForeignKey> actualForeignKeys,
ForeignKeyStrictComparer foreignKeyComparer = null)
{
foreignKeyComparer ??= new ForeignKeyStrictComparer(compareAnnotations: false);
Assert.Equal(
new SortedSet<IForeignKey>(expectedForeignKeys, foreignKeyComparer),
new SortedSet<IForeignKey>(actualForeignKeys, foreignKeyComparer),
foreignKeyComparer);
}
protected void AssertEqual(
IEnumerable<IIndex> expectedIndexes,
IEnumerable<IIndex> actualIndexes,
TestIndexComparer testIndexComparer = null)
{
testIndexComparer ??= new TestIndexComparer(compareAnnotations: false);
Assert.Equal(
new SortedSet<IIndex>(expectedIndexes, testIndexComparer),
new SortedSet<IIndex>(actualIndexes, testIndexComparer),
testIndexComparer);
}
protected virtual TestModelBuilder CreateModelBuilder()
=> CreateTestModelBuilder(InMemoryTestHelpers.Instance);
protected TestModelBuilder HobNobBuilder()
{
var builder = CreateModelBuilder();
builder.Entity<Hob>().HasKey(e => new { e.Id1, e.Id2 });
builder.Entity<Nob>().HasKey(e => new { e.Id1, e.Id2 });
return builder;
}
protected abstract TestModelBuilder CreateTestModelBuilder(TestHelpers testHelpers);
}
public abstract class TestModelBuilder
{
protected TestModelBuilder(TestHelpers testHelpers)
{
var options = new LoggingOptions();
options.Initialize(new DbContextOptionsBuilder().EnableSensitiveDataLogging(false).Options);
ValidationLoggerFactory = new ListLoggerFactory(l => l == DbLoggerCategory.Model.Validation.Name);
var validationLogger = new DiagnosticsLogger<DbLoggerCategory.Model.Validation>(
ValidationLoggerFactory,
options,
new DiagnosticListener("Fake"),
testHelpers.LoggingDefinitions,
new NullDbContextLogger());
ModelLoggerFactory = new ListLoggerFactory(l => l == DbLoggerCategory.Model.Name);
var modelLogger = new DiagnosticsLogger<DbLoggerCategory.Model>(
ModelLoggerFactory,
options,
new DiagnosticListener("Fake"),
testHelpers.LoggingDefinitions,
new NullDbContextLogger());
ModelBuilder = testHelpers.CreateConventionBuilder(modelLogger, validationLogger);
}
public virtual IMutableModel Model => ModelBuilder.Model;
public ModelBuilder ModelBuilder { get; }
public ListLoggerFactory ValidationLoggerFactory { get; }
public ListLoggerFactory ModelLoggerFactory { get; }
public TestModelBuilder HasAnnotation(string annotation, object value)
{
ModelBuilder.HasAnnotation(annotation, value);
return this;
}
public abstract TestEntityTypeBuilder<TEntity> Entity<TEntity>()
where TEntity : class;
public abstract TestEntityTypeBuilder<TEntity> SharedTypeEntity<TEntity>(string name)
where TEntity : class;
public abstract TestOwnedEntityTypeBuilder<TEntity> Owned<TEntity>()
where TEntity : class;
public abstract TestModelBuilder Entity<TEntity>(Action<TestEntityTypeBuilder<TEntity>> buildAction)
where TEntity : class;
public abstract TestModelBuilder SharedTypeEntity<TEntity>(string name, Action<TestEntityTypeBuilder<TEntity>> buildAction)
where TEntity : class;
public abstract TestModelBuilder Ignore<TEntity>()
where TEntity : class;
public virtual IModel FinalizeModel() => ModelBuilder.FinalizeModel();
public virtual string GetDisplayName(Type entityType) => entityType.Name;
public virtual TestModelBuilder UsePropertyAccessMode(PropertyAccessMode propertyAccessMode)
{
ModelBuilder.UsePropertyAccessMode(propertyAccessMode);
return this;
}
}
public abstract class TestEntityTypeBuilder<TEntity>
where TEntity : class
{
public abstract IMutableEntityType Metadata { get; }
public abstract TestEntityTypeBuilder<TEntity> HasAnnotation(string annotation, object value);
public abstract TestEntityTypeBuilder<TEntity> HasBaseType<TBaseEntity>()
where TBaseEntity : class;
public abstract TestEntityTypeBuilder<TEntity> HasBaseType(string baseEntityTypeName);
public abstract TestKeyBuilder<TEntity> HasKey(Expression<Func<TEntity, object>> keyExpression);
public abstract TestKeyBuilder<TEntity> HasKey(params string[] propertyNames);
public abstract TestKeyBuilder<TEntity> HasAlternateKey(Expression<Func<TEntity, object>> keyExpression);
public abstract TestKeyBuilder<TEntity> HasAlternateKey(params string[] propertyNames);
public abstract TestEntityTypeBuilder<TEntity> HasNoKey();
public abstract TestPropertyBuilder<TProperty> Property<TProperty>(
Expression<Func<TEntity, TProperty>> propertyExpression);
public abstract TestPropertyBuilder<TProperty> Property<TProperty>(string propertyName);
public abstract TestPropertyBuilder<TProperty> IndexerProperty<TProperty>(string propertyName);
public abstract TestNavigationBuilder Navigation<TNavigation>(
Expression<Func<TEntity, TNavigation>> propertyExpression);
public abstract TestNavigationBuilder Navigation(string propertyName);
public abstract TestEntityTypeBuilder<TEntity> Ignore(
Expression<Func<TEntity, object>> propertyExpression);
public abstract TestEntityTypeBuilder<TEntity> Ignore(string propertyName);
public abstract TestIndexBuilder<TEntity> HasIndex(Expression<Func<TEntity, object>> indexExpression);
public abstract TestIndexBuilder<TEntity> HasIndex(params string[] propertyNames);
public abstract TestOwnedNavigationBuilder<TEntity, TRelatedEntity> OwnsOne<TRelatedEntity>(string navigationName)
where TRelatedEntity : class;
public abstract TestEntityTypeBuilder<TEntity> OwnsOne<TRelatedEntity>(
string navigationName,
Action<TestOwnedNavigationBuilder<TEntity, TRelatedEntity>> buildAction)
where TRelatedEntity : class;
public abstract TestOwnedNavigationBuilder<TEntity, TRelatedEntity> OwnsOne<TRelatedEntity>(
Expression<Func<TEntity, TRelatedEntity>> navigationExpression)
where TRelatedEntity : class;
public abstract TestEntityTypeBuilder<TEntity> OwnsOne<TRelatedEntity>(
Expression<Func<TEntity, TRelatedEntity>> navigationExpression,
Action<TestOwnedNavigationBuilder<TEntity, TRelatedEntity>> buildAction)
where TRelatedEntity : class;
public abstract TestOwnedNavigationBuilder<TEntity, TRelatedEntity> OwnsMany<TRelatedEntity>(string navigationName)
where TRelatedEntity : class;
public abstract TestEntityTypeBuilder<TEntity> OwnsMany<TRelatedEntity>(
string navigationName,
Action<TestOwnedNavigationBuilder<TEntity, TRelatedEntity>> buildAction)
where TRelatedEntity : class;
public abstract TestOwnedNavigationBuilder<TEntity, TRelatedEntity> OwnsMany<TRelatedEntity>(
Expression<Func<TEntity, IEnumerable<TRelatedEntity>>> navigationExpression)
where TRelatedEntity : class;
public abstract TestEntityTypeBuilder<TEntity> OwnsMany<TRelatedEntity>(
Expression<Func<TEntity, IEnumerable<TRelatedEntity>>> navigationExpression,
Action<TestOwnedNavigationBuilder<TEntity, TRelatedEntity>> buildAction)
where TRelatedEntity : class;
public abstract TestReferenceNavigationBuilder<TEntity, TRelatedEntity> HasOne<TRelatedEntity>(
string navigationName)
where TRelatedEntity : class;
public abstract TestReferenceNavigationBuilder<TEntity, TRelatedEntity> HasOne<TRelatedEntity>(
Expression<Func<TEntity, TRelatedEntity>> navigationExpression = null)
where TRelatedEntity : class;
public abstract TestCollectionNavigationBuilder<TEntity, TRelatedEntity> HasMany<TRelatedEntity>(
string navigationName)
where TRelatedEntity : class;
public abstract TestCollectionNavigationBuilder<TEntity, TRelatedEntity> HasMany<TRelatedEntity>(
Expression<Func<TEntity, IEnumerable<TRelatedEntity>>> navigationExpression = null)
where TRelatedEntity : class;
public abstract TestEntityTypeBuilder<TEntity> HasQueryFilter(Expression<Func<TEntity, bool>> filter);
public abstract TestEntityTypeBuilder<TEntity> HasChangeTrackingStrategy(ChangeTrackingStrategy changeTrackingStrategy);
public abstract TestEntityTypeBuilder<TEntity> UsePropertyAccessMode(PropertyAccessMode propertyAccessMode);
public abstract DataBuilder<TEntity> HasData(params TEntity[] data);
public abstract DataBuilder<TEntity> HasData(params object[] data);
public abstract DataBuilder<TEntity> HasData(IEnumerable<TEntity> data);
public abstract DataBuilder<TEntity> HasData(IEnumerable<object> data);
public abstract TestDiscriminatorBuilder<TDiscriminator> HasDiscriminator<TDiscriminator>(
Expression<Func<TEntity, TDiscriminator>> propertyExpression);
public abstract TestDiscriminatorBuilder<TDiscriminator> HasDiscriminator<TDiscriminator>(string propertyName);
public abstract TestEntityTypeBuilder<TEntity> HasNoDiscriminator();
}
public abstract class TestDiscriminatorBuilder<TDiscriminator>
{
public abstract TestDiscriminatorBuilder<TDiscriminator> IsComplete(bool complete);
public abstract TestDiscriminatorBuilder<TDiscriminator> HasValue(TDiscriminator value);
public abstract TestDiscriminatorBuilder<TDiscriminator> HasValue<TEntity>(TDiscriminator value);
public abstract TestDiscriminatorBuilder<TDiscriminator> HasValue(Type entityType, TDiscriminator value);
public abstract TestDiscriminatorBuilder<TDiscriminator> HasValue(string entityTypeName, TDiscriminator value);
}
public abstract class TestOwnedEntityTypeBuilder<TEntity>
where TEntity : class
{
}
public abstract class TestKeyBuilder<TEntity>
{
public abstract IMutableKey Metadata { get; }
public abstract TestKeyBuilder<TEntity> HasAnnotation(string annotation, object value);
}
public abstract class TestIndexBuilder<TEntity>
{
public abstract IMutableIndex Metadata { get; }
public abstract TestIndexBuilder<TEntity> HasAnnotation(string annotation, object value);
public abstract TestIndexBuilder<TEntity> IsUnique(bool isUnique = true);
}
public abstract class TestPropertyBuilder<TProperty>
{
public abstract IMutableProperty Metadata { get; }
public abstract TestPropertyBuilder<TProperty> HasAnnotation(string annotation, object value);
public abstract TestPropertyBuilder<TProperty> IsRequired(bool isRequired = true);
public abstract TestPropertyBuilder<TProperty> HasMaxLength(int maxLength);
public abstract TestPropertyBuilder<TProperty> IsUnicode(bool unicode = true);
public abstract TestPropertyBuilder<TProperty> IsRowVersion();
public abstract TestPropertyBuilder<TProperty> IsConcurrencyToken(bool isConcurrencyToken = true);
public abstract TestPropertyBuilder<TProperty> ValueGeneratedNever();
public abstract TestPropertyBuilder<TProperty> ValueGeneratedOnAdd();
public abstract TestPropertyBuilder<TProperty> ValueGeneratedOnAddOrUpdate();
public abstract TestPropertyBuilder<TProperty> ValueGeneratedOnUpdate();
public abstract TestPropertyBuilder<TProperty> HasValueGenerator<TGenerator>()
where TGenerator : ValueGenerator;
public abstract TestPropertyBuilder<TProperty> HasValueGenerator(Type valueGeneratorType);
public abstract TestPropertyBuilder<TProperty> HasValueGenerator(Func<IProperty, IEntityType, ValueGenerator> factory);
public abstract TestPropertyBuilder<TProperty> HasField(string fieldName);
public abstract TestPropertyBuilder<TProperty> UsePropertyAccessMode(PropertyAccessMode propertyAccessMode);
public abstract TestPropertyBuilder<TProperty> HasConversion<TProvider>();
public abstract TestPropertyBuilder<TProperty> HasConversion(Type providerClrType);
public abstract TestPropertyBuilder<TProperty> HasConversion<TProvider>(
Expression<Func<TProperty, TProvider>> convertToProviderExpression,
Expression<Func<TProvider, TProperty>> convertFromProviderExpression);
public abstract TestPropertyBuilder<TProperty> HasConversion<TProvider>(ValueConverter<TProperty, TProvider> converter);
public abstract TestPropertyBuilder<TProperty> HasConversion(ValueConverter converter);
}
public abstract class TestNavigationBuilder
{
public abstract TestNavigationBuilder HasAnnotation(string annotation, object value);
public abstract TestNavigationBuilder UsePropertyAccessMode(PropertyAccessMode propertyAccessMode);
}
public abstract class TestCollectionNavigationBuilder<TEntity, TRelatedEntity>
where TEntity : class
where TRelatedEntity : class
{
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> WithOne(string navigationName);
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> WithOne(
Expression<Func<TRelatedEntity, TEntity>> navigationExpression = null);
public abstract TestCollectionCollectionBuilder<TRelatedEntity, TEntity> WithMany(string navigationName);
public abstract TestCollectionCollectionBuilder<TRelatedEntity, TEntity> WithMany(
Expression<Func<TRelatedEntity, IEnumerable<TEntity>>> navigationExpression);
}
public abstract class TestReferenceNavigationBuilder<TEntity, TRelatedEntity>
where TEntity : class
where TRelatedEntity : class
{
public abstract TestReferenceCollectionBuilder<TRelatedEntity, TEntity> WithMany(string navigationName);
public abstract TestReferenceCollectionBuilder<TRelatedEntity, TEntity> WithMany(
Expression<Func<TRelatedEntity, IEnumerable<TEntity>>> navigationExpression = null);
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> WithOne(string navigationName);
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> WithOne(
Expression<Func<TRelatedEntity, TEntity>> navigationExpression = null);
}
public abstract class TestReferenceCollectionBuilder<TEntity, TRelatedEntity>
where TEntity : class
where TRelatedEntity : class
{
public abstract IMutableForeignKey Metadata { get; }
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> HasForeignKey(
Expression<Func<TRelatedEntity, object>> foreignKeyExpression);
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> HasPrincipalKey(
Expression<Func<TEntity, object>> keyExpression);
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> HasForeignKey(
params string[] foreignKeyPropertyNames);
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> HasPrincipalKey(
params string[] keyPropertyNames);
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> HasAnnotation(
string annotation, object value);
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> IsRequired(bool isRequired = true);
public abstract TestReferenceCollectionBuilder<TEntity, TRelatedEntity> OnDelete(DeleteBehavior deleteBehavior);
}
public abstract class TestReferenceReferenceBuilder<TEntity, TRelatedEntity>
where TEntity : class
where TRelatedEntity : class
{
public abstract IMutableForeignKey Metadata { get; }
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> HasAnnotation(
string annotation, object value);
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> HasForeignKey<TDependentEntity>(
Expression<Func<TDependentEntity, object>> foreignKeyExpression)
where TDependentEntity : class;
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> HasPrincipalKey<TPrincipalEntity>(
Expression<Func<TPrincipalEntity, object>> keyExpression)
where TPrincipalEntity : class;
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> HasForeignKey<TDependentEntity>(
params string[] foreignKeyPropertyNames)
where TDependentEntity : class;
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> HasPrincipalKey<TPrincipalEntity>(
params string[] keyPropertyNames)
where TPrincipalEntity : class;
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> IsRequired(bool isRequired = true);
public abstract TestReferenceReferenceBuilder<TEntity, TRelatedEntity> OnDelete(DeleteBehavior deleteBehavior);
}
public abstract class TestCollectionCollectionBuilder<TLeftEntity, TRightEntity>
where TLeftEntity : class
where TRightEntity : class
{
public abstract TestEntityTypeBuilder<TJoinEntity> UsingEntity<TJoinEntity>(
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TLeftEntity, TJoinEntity>> configureRight,
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TRightEntity, TJoinEntity>> configureLeft)
where TJoinEntity : class;
public abstract TestEntityTypeBuilder<TJoinEntity> UsingEntity<TJoinEntity>(
string joinEntityName,
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TLeftEntity, TJoinEntity>> configureRight,
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TRightEntity, TJoinEntity>> configureLeft)
where TJoinEntity : class;
public abstract TestEntityTypeBuilder<TRightEntity> UsingEntity<TJoinEntity>(
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TLeftEntity, TJoinEntity>> configureRight,
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TRightEntity, TJoinEntity>> configureLeft,
Action<TestEntityTypeBuilder<TJoinEntity>> configureJoin)
where TJoinEntity : class;
public abstract TestEntityTypeBuilder<TRightEntity> UsingEntity<TJoinEntity>(
string joinEntityName,
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TLeftEntity, TJoinEntity>> configureRight,
Func<TestEntityTypeBuilder<TJoinEntity>,
TestReferenceCollectionBuilder<TRightEntity, TJoinEntity>> configureLeft,
Action<TestEntityTypeBuilder<TJoinEntity>> configureJoin)
where TJoinEntity : class;
}
public abstract class TestOwnershipBuilder<TEntity, TDependentEntity>
where TEntity : class
where TDependentEntity : class
{
public abstract IMutableForeignKey Metadata { get; }
public abstract TestOwnershipBuilder<TEntity, TDependentEntity> HasAnnotation(
string annotation, object value);
public abstract TestOwnershipBuilder<TEntity, TDependentEntity> HasForeignKey(
params string[] foreignKeyPropertyNames);
public abstract TestOwnershipBuilder<TEntity, TDependentEntity> HasForeignKey(
Expression<Func<TDependentEntity, object>> foreignKeyExpression);
public abstract TestOwnershipBuilder<TEntity, TDependentEntity> HasPrincipalKey(
params string[] keyPropertyNames);
public abstract TestOwnershipBuilder<TEntity, TDependentEntity> HasPrincipalKey(
Expression<Func<TEntity, object>> keyExpression);
}
public abstract class TestOwnedNavigationBuilder<TEntity, TDependentEntity>
where TEntity : class
where TDependentEntity : class
{
public abstract IMutableForeignKey Metadata { get; }
public abstract IMutableEntityType OwnedEntityType { get; }
public abstract TestOwnedNavigationBuilder<TEntity, TDependentEntity> HasAnnotation(
string annotation, object value);
public abstract TestKeyBuilder<TDependentEntity> HasKey(Expression<Func<TDependentEntity, object>> keyExpression);
public abstract TestKeyBuilder<TDependentEntity> HasKey(params string[] propertyNames);
public abstract TestPropertyBuilder<TProperty> Property<TProperty>(string propertyName);
public abstract TestPropertyBuilder<TProperty> IndexerProperty<TProperty>(string propertyName);
public abstract TestPropertyBuilder<TProperty> Property<TProperty>(
Expression<Func<TDependentEntity, TProperty>> propertyExpression);
public abstract TestNavigationBuilder Navigation<TNavigation>(string navigationName);
public abstract TestNavigationBuilder Navigation<TNavigation>(
Expression<Func<TDependentEntity, TNavigation>> navigationExpression);
public abstract TestOwnedNavigationBuilder<TEntity, TDependentEntity> Ignore(string propertyName);
public abstract TestOwnedNavigationBuilder<TEntity, TDependentEntity> Ignore(
Expression<Func<TDependentEntity, object>> propertyExpression);
public abstract TestIndexBuilder<TEntity> HasIndex(params string[] propertyNames);
public abstract TestIndexBuilder<TEntity> HasIndex(Expression<Func<TDependentEntity, object>> indexExpression);
public abstract TestOwnershipBuilder<TEntity, TDependentEntity> WithOwner(string ownerReference);
public abstract TestOwnershipBuilder<TEntity, TDependentEntity> WithOwner(
Expression<Func<TDependentEntity, TEntity>> referenceExpression = null);
public abstract TestOwnedNavigationBuilder<TDependentEntity, TNewRelatedEntity> OwnsOne<TNewRelatedEntity>(
Expression<Func<TDependentEntity, TNewRelatedEntity>> navigationExpression)
where TNewRelatedEntity : class;
public abstract TestOwnedNavigationBuilder<TEntity, TDependentEntity> OwnsOne<TNewRelatedEntity>(
Expression<Func<TDependentEntity, TNewRelatedEntity>> navigationExpression,
Action<TestOwnedNavigationBuilder<TDependentEntity, TNewRelatedEntity>> buildAction)
where TNewRelatedEntity : class;
public abstract TestOwnedNavigationBuilder<TDependentEntity, TNewDependentEntity> OwnsMany<TNewDependentEntity>(
Expression<Func<TDependentEntity, IEnumerable<TNewDependentEntity>>> navigationExpression)
where TNewDependentEntity : class;
public abstract TestOwnedNavigationBuilder<TEntity, TDependentEntity> OwnsMany<TNewDependentEntity>(
Expression<Func<TDependentEntity, IEnumerable<TNewDependentEntity>>> navigationExpression,
Action<TestOwnedNavigationBuilder<TDependentEntity, TNewDependentEntity>> buildAction)
where TNewDependentEntity : class;
public abstract TestReferenceNavigationBuilder<TDependentEntity, TRelatedEntity> HasOne<TRelatedEntity>(
Expression<Func<TDependentEntity, TRelatedEntity>> navigationExpression = null)
where TRelatedEntity : class;
public abstract TestOwnedNavigationBuilder<TEntity, TDependentEntity> HasChangeTrackingStrategy(
ChangeTrackingStrategy changeTrackingStrategy);
public abstract TestOwnedNavigationBuilder<TEntity, TDependentEntity> UsePropertyAccessMode(
PropertyAccessMode propertyAccessMode);
public abstract DataBuilder<TDependentEntity> HasData(params TDependentEntity[] data);
public abstract DataBuilder<TDependentEntity> HasData(params object[] data);
public abstract DataBuilder<TDependentEntity> HasData(IEnumerable<TDependentEntity> data);
public abstract DataBuilder<TDependentEntity> HasData(IEnumerable<object> data);
}
}
}
| 51.573171 | 135 | 0.687228 | [
"Apache-2.0"
] | theolymp/efcore | test/EFCore.Tests/ModelBuilding/ModelBuilderTestBase.cs | 29,603 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.IO;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.PythonTools {
class ProvideFileFilterAttribute : RegistrationAttribute {
private readonly string _id, _name, _filter;
private readonly int _sortPriority;
public ProvideFileFilterAttribute(string projectGuid, string name, string filter, int sortPriority) {
_name = name;
_id = projectGuid;
_filter = filter;
_sortPriority = sortPriority;
}
public override void Register(RegistrationContext context) {
using (var engineKey = context.CreateKey("Projects\\" + _id + "\\Filters\\" + _name)) {
engineKey.SetValue("", _filter);
engineKey.SetValue("SortPriority", _sortPriority);
}
}
public override void Unregister(RegistrationContext context) {
}
}
}
| 39.547619 | 110 | 0.588802 | [
"Apache-2.0"
] | nanshuiyu/pytools | Python/Product/Profiling/ProvideFileFilterAttribute.cs | 1,663 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the wafv2-2019-07-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.WAFV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.WAFV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// JsonBody Marshaller
/// </summary>
public class JsonBodyMarshaller : IRequestMarshaller<JsonBody, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(JsonBody requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetInvalidFallbackBehavior())
{
context.Writer.WritePropertyName("InvalidFallbackBehavior");
context.Writer.Write(requestObject.InvalidFallbackBehavior);
}
if(requestObject.IsSetMatchPattern())
{
context.Writer.WritePropertyName("MatchPattern");
context.Writer.WriteObjectStart();
var marshaller = JsonMatchPatternMarshaller.Instance;
marshaller.Marshall(requestObject.MatchPattern, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetMatchScope())
{
context.Writer.WritePropertyName("MatchScope");
context.Writer.Write(requestObject.MatchScope);
}
if(requestObject.IsSetOversizeHandling())
{
context.Writer.WritePropertyName("OversizeHandling");
context.Writer.Write(requestObject.OversizeHandling);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static JsonBodyMarshaller Instance = new JsonBodyMarshaller();
}
} | 33.411765 | 103 | 0.653169 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/WAFV2/Generated/Model/Internal/MarshallTransformations/JsonBodyMarshaller.cs | 2,840 | C# |
using FluiTec.AppFx.Data.NMemory.Repositories;
using FluiTec.AppFx.Data.NMemory.UnitsOfWork;
using FluiTec.AppFx.Data.Repositories;
using FluiTec.AppFx.Data.TestLibrary.Entities;
using Microsoft.Extensions.Logging;
namespace FluiTec.AppFx.Data.TestLibrary.Repositories
{
/// <summary>
/// A memory date time dummy repository.
/// </summary>
public class NMemoryDateTimeDummyRepository : NMemoryWritableKeyTableDataRepository<DateTimeDummyEntity, int>, IDateTimeDummyRepository
{
/// <summary>
/// Constructor.
/// </summary>
///
/// <param name="unitOfWork"> The unit of work. </param>
/// <param name="logger"> The logger. </param>
public NMemoryDateTimeDummyRepository(NMemoryUnitOfWork unitOfWork, ILogger<IRepository> logger) : base(unitOfWork, logger)
{
}
}
} | 36.25 | 139 | 0.686207 | [
"Apache-2.0",
"MIT"
] | FluiTec/FluiTec.AppFx.Data | src/tests/FluiTec.AppFx.Data.TestLibrary/Repositories/NMemoryDateTimeDummyRepository.cs | 872 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.