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 UnityEngine;
public class LaserSpawner : MonoBehaviour
{
private float _rndAngle;
private float _time;
private float _previousSpawnRotation;
private float _canNotSpawnNewLightningAngle;
private static float _maxTime;
public static float TimeBetweenLaserSpawns
{
get { return _maxTime; }
set { _maxTime = value; }
}
private GameObject _newLaser;
private Quaternion _rotation = Quaternion.identity;
public GameObject Laser;
void Start()
{
_canNotSpawnNewLightningAngle = 15;
_previousSpawnRotation = 0;
_time = _maxTime;
}
void Update()
{
_previousSpawnRotation = _rndAngle;
if (_time >= _maxTime && gameObject.tag == "LaserSpawnerInMenu")
{
SpawnLaser();
}
else if (_time >= _maxTime && InGameGameManager.GamePlaying() && gameObject.tag == "LaserSpawnerInGame")
{
SpawnLaser();
}
_time += Time.deltaTime;
}
public void SpawnLaser()
{
_rndAngle = Random.Range(_previousSpawnRotation + _canNotSpawnNewLightningAngle, 180.0f - _canNotSpawnNewLightningAngle + _previousSpawnRotation);
if (_rndAngle > 180.0f)
{
_rndAngle -= 180.0f;
}
_rotation = Quaternion.Euler(Vector3.forward * _rndAngle);
if (LevelManager.LevelHasChanged)
{
_newLaser = Instantiate(Laser, transform.position, Quaternion.Euler(0, 0, Center.CircleRotation));
}
else
{
_newLaser = Instantiate(Laser, transform.position, _rotation);
}
_time = 0.0f;
}
}
| 27.109375 | 156 | 0.592507 | [
"Unlicense"
] | Arthur-St-06/CircleRoller | Assets/Scripts/LaserSpawner.cs | 1,737 | C# |
namespace MoreCyclopsUpgrades.API
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Common;
using MoreCyclopsUpgrades.API.Charging;
using MoreCyclopsUpgrades.API.General;
using MoreCyclopsUpgrades.API.PDA;
using MoreCyclopsUpgrades.API.Upgrades;
using MoreCyclopsUpgrades.Managers;
/// <summary>
/// The main entry point for all API services provided by MoreCyclopsUpgrades.
/// </summary>
/// <seealso cref="IMCUCrossMod" />
public class MCUServices : IMCUCrossMod, IMCURegistration, IMCUSearch, IMCULogger
{
/// <summary>
/// "Practically zero" for all intents and purposes.<para/>
/// Any energy value lower than this should be considered zero.
/// </summary>
public const float MinimalPowerValue = 0.001f;
private static readonly MCUServices singleton = new MCUServices();
private MCUServices()
{
// Hide constructor
}
#region IMCUCrossMod
/// <summary>
/// Contains methods for asisting with cross-mod compatibility with other Cyclops mod.
/// </summary>
public static IMCUCrossMod CrossMod => singleton;
/// <summary>
/// Gets the steps to "CyclopsModules" crafting tab in the Cyclops Fabricator.<para />
/// This would be necessary for best cross-compatibility with the [VehicleUpgradesInCyclops] mod.<para />
/// Will return null if this mod isn't present, under the assumption that this mod isn't present and it is otherwise find to add crafting nodes to the Cyclops Fabricator root.
/// </summary>
/// <value>
/// The steps to the Cyclops Fabricator's "CyclopsModules" crafting tab if it exists.
/// </value>
public string[] StepsToCyclopsModulesTabInCyclopsFabricator { get; } = Directory.Exists(@"./QMods/VehicleUpgradesInCyclops") ? new[] { "CyclopsModules" } : null;
/// <summary>
/// Gets the <see cref="IPowerRatingManager" /> manging the specified Cyclops sub;
/// </summary>
/// <param name="cyclops"></param>
/// <returns></returns>
public IPowerRatingManager GetPowerRatingManager(SubRoot cyclops)
{
return CyclopsManager.GetManager(ref cyclops)?.Engine;
}
/// <summary>
/// Applies the power rating modifier to the specified Cyclops.
/// </summary>
/// <param name="cyclops">The Cyclops sub to apply the modifier to.</param>
/// <param name="techType">The source of the power rating modifier. Not allowed to be <see cref="TechType.None" />.</param>
/// <param name="modifier">The modifier. Must be a positive value.<para />
/// Values less than <c>1f</c> reduce engine efficienty rating.<para />
/// Values greater than <c>1f</c> improve engine efficienty rating.</param>
public void ApplyPowerRatingModifier(SubRoot cyclops, TechType techType, float modifier)
{
CyclopsManager.GetManager(ref cyclops)?.Engine.ApplyPowerRatingModifier(techType, modifier);
}
/// <summary>
/// Checks whether the Cyclops has the specified upgrade module installed anywhere across all upgrade consoles.
/// </summary>
/// <param name="cyclops">The cyclops to search.</param>
/// <param name="techType">The upgrade module's techtype ID.</param>
/// <returns>
/// <c>true</c> if the upgrade is found installed on the Cyclops; otherwise, <c>false</c>.
/// </returns>
public bool HasUpgradeInstalled(SubRoot cyclops, TechType techType)
{
var mgr = CyclopsManager.GetManager(ref cyclops);
if (mgr == null)
return false;
if (mgr.Upgrade.KnownsUpgradeModules.TryGetValue(techType, out UpgradeHandler handler))
{
return handler.HasUpgrade;
}
return false;
}
/// <summary>
/// Gets the total number of the specified upgrade module currently installed in the Cyclops.
/// </summary>
/// <param name="cyclops">The cyclops to search.</param>
/// <param name="techType">The upgrade module's techtype ID.</param>
/// <returns>
/// The number of upgrade modules of this techtype ID currently in the Cyclops.
/// </returns>
public int GetUpgradeCount(SubRoot cyclops, TechType techType)
{
var mgr = CyclopsManager.GetManager(ref cyclops);
if (mgr == null)
return 0;
if (mgr.Upgrade.KnownsUpgradeModules.TryGetValue(techType, out UpgradeHandler handler))
{
return handler.Count;
}
return 0;
}
#endregion
#region IMCURegistration
/// <summary>
/// Register your upgrades, charger, and managers with MoreCyclopsUpgrades.<para/>
/// WARNING! These methods MUST be invoked during patch time.
/// </summary>
public static IMCURegistration Register => singleton;
/// <summary>
/// Registers a <see cref="CreateCyclopsCharger" /> method that creates a new <see cref="Charging.CyclopsCharger" /> on demand.<para />
/// This method will be invoked only once for each Cyclops sub in the game world.<para />
/// Use this for rechargable batteries and energy drawn from the environment.
/// </summary>
/// <typeparam name="T">Your class that implements <see cref="Charging.CyclopsCharger" />.</typeparam>
/// <param name="createEvent">A method that takes no parameters a returns a new instance of an <see cref="CreateCyclopsCharger" />.</param>
public void CyclopsCharger<T>(CreateCyclopsCharger createEvent)
where T : CyclopsCharger
{
if (ChargeManager.TooLateToRegister)
QuickLogger.Error("CyclopsChargerCreator have already been invoked. This method should only be called during patch time.");
else
ChargeManager.RegisterChargerCreator(createEvent, typeof(T).Name);
}
/// <summary>
/// Registers a <see cref="ICyclopsChargerCreator" /> class that can create a new <see cref="Charging.CyclopsCharger" /> on demand.<para />
/// This method will be invoked only once for each Cyclops sub in the game world.<para />
/// Use this for rechargable batteries and energy drawn from the environment.
/// </summary>
/// <typeparam name="T">Your class that implements <see cref="Charging.CyclopsCharger" />.</typeparam>
/// <param name="chargerCreator">A class that implements the <see cref="ICyclopsChargerCreator.CreateCyclopsCharger(SubRoot)" /> method.</param>
public void CyclopsCharger<T>(ICyclopsChargerCreator chargerCreator)
where T : CyclopsCharger
{
CyclopsCharger<T>(chargerCreator.CreateCyclopsCharger);
}
/// <summary>
/// Registers a <see cref="CreateUpgradeHandler" /> method that creates a new <see cref="UpgradeHandler" /> on demand.<para />
/// This method will be invoked only once for each Cyclops sub in the game world.
/// </summary>
/// <param name="createEvent">A method that takes no parameters a returns a new instance of an <see cref="UpgradeHandler" />.</param>
public void CyclopsUpgradeHandler(CreateUpgradeHandler createEvent)
{
if (UpgradeManager.TooLateToRegister)
QuickLogger.Error("UpgradeHandlerCreators have already been invoked. This method should only be called during patch time.");
else
UpgradeManager.RegisterHandlerCreator(createEvent, Assembly.GetCallingAssembly().GetName().Name);
}
/// <summary>
/// Registers a <see cref="CreateUpgradeHandler" /> class can create a new <see cref="UpgradeHandler" /> on demand.<para />
/// This method will be invoked only once for each Cyclops sub in the game world.
/// </summary>
/// <param name="handlerCreator">A class that implements this <see cref="IUpgradeHandlerCreator.CreateUpgradeHandler(SubRoot)" /> method.</param>
public void CyclopsUpgradeHandler(IUpgradeHandlerCreator handlerCreator)
{
if (UpgradeManager.TooLateToRegister)
QuickLogger.Error("UpgradeHandlerCreators have already been invoked. This method should only be called during patch time.");
else
UpgradeManager.RegisterHandlerCreator(handlerCreator.CreateUpgradeHandler, Assembly.GetCallingAssembly().GetName().Name);
}
/// <summary>
/// Registers a <see cref="CreateAuxCyclopsManager" /> method that creates returns a new <see cref="IAuxCyclopsManager" /> on demand.<para />
/// This method will be invoked only once for each Cyclops sub in the game world.<para />
/// Use this when you simply need to have a class that is attaches one instance per Cyclops.
/// </summary>
/// <typeparam name="T">Your class that implements <see cref="IAuxCyclopsManager" />.</typeparam>
/// <param name="createEvent">The create event.</param>
public void AuxCyclopsManager<T>(CreateAuxCyclopsManager createEvent)
where T : IAuxCyclopsManager
{
if (CyclopsManager.TooLateToRegister)
QuickLogger.Error("AuxCyclopsManagerCreator have already been invoked. This method should only be called during patch time.");
else
CyclopsManager.RegisterAuxManagerCreator(createEvent, typeof(T).Name);
}
/// <summary>
/// Registers a <see cref="IAuxCyclopsManagerCreator" /> class that can create a new <see cref="IAuxCyclopsManager" /> on demand.<para />
/// This method will be invoked only once for each Cyclops sub in the game world.<para />
/// Use this when you simply need to have a class that attaches one instance per Cyclops.
/// </summary>
/// <typeparam name="T">Your class that implements <see cref="IAuxCyclopsManager" />.</typeparam>
/// <param name="managerCreator">The manager creator class instance.</param>
public void AuxCyclopsManager<T>(IAuxCyclopsManagerCreator managerCreator)
where T : IAuxCyclopsManager
{
if (CyclopsManager.TooLateToRegister)
QuickLogger.Error("AuxCyclopsManagerCreator have already been invoked. This method should only be called during patch time.");
else
CyclopsManager.RegisterAuxManagerCreator(managerCreator.CreateAuxCyclopsManager, typeof(T).Name);
}
/// <summary>
/// Registers a <see cref="IIconOverlayCreator" /> class that can create a new <see cref="IconOverlay" /> on demand.<para />
/// This method will be invoked every time the PDA screen opens up on a Cyclops Upgrade Console that contains a module of the specified <see cref="TechType" />.
/// </summary>
/// <param name="techType">The upgrade module's techtype.</param>
/// <param name="overlayCreator">A class that implements a method the <see cref="IIconOverlayCreator.CreateIconOverlay(uGUI_ItemIcon, InventoryItem)" /> method.</param>
public void PdaIconOverlay(TechType techType, IIconOverlayCreator overlayCreator)
{
PdaOverlayManager.RegisterHandlerCreator(techType, overlayCreator.CreateIconOverlay, Assembly.GetCallingAssembly().GetName().Name);
}
/// <summary>
/// Registers a <see cref="CreateIconOverlay" /> method that creates a new <see cref="IconOverlay" /> on demand.<para />
/// This method will be invoked every time the PDA screen opens up on a Cyclops Upgrade Console that contains a module of the specified <see cref="TechType" />.
/// </summary>
/// <param name="techType">The upgrade module's techtype.</param>
/// <param name="createEvent">A method that takes in a <see cref="uGUI_ItemIcon" /> and <see cref="InventoryItem" /> and returns a new <see cref="IconOverlay" />.</param>
public void PdaIconOverlay(TechType techType, CreateIconOverlay createEvent)
{
PdaOverlayManager.RegisterHandlerCreator(techType, createEvent, Assembly.GetCallingAssembly().GetName().Name);
}
#endregion
#region IMCUSearch
/// <summary>
/// Provides methods to find the upgrades, chargers, and managers you registered once the Cyclops sub is running.
/// </summary>
public static IMCUSearch Find => singleton;
/// <summary>
/// Gets the typed <see cref="IAuxCyclopsManager" /> for the specified Cyclops sub.
/// </summary>
/// <typeparam name="T">The class you created that implements <see cref="IAuxCyclopsManager" />.</typeparam>
/// <param name="cyclops">The cyclops to search in.</param>
/// <returns>
/// A type casted <see cref="IAuxCyclopsManager" /> if found; Otherwise returns null if not found.
/// </returns>
/// <seealso cref="CreateAuxCyclopsManager" />
public T AuxCyclopsManager<T>(SubRoot cyclops)
where T : class, IAuxCyclopsManager
{
if (cyclops == null)
return null;
return CyclopsManager.GetManager<T>(ref cyclops, typeof(T).Name);
}
/// <summary>
/// Gets all typed <see cref="IAuxCyclopsManager" />s across all Cyclops subs.
/// </summary>
/// <typeparam name="T">The class you created that implements <see cref="IAuxCyclopsManager" />.</typeparam>
/// <returns>
/// A type casted enumeration of all <see cref="IAuxCyclopsManager" />s found across all Cyclops subs, identified by name.
/// </returns>
public IEnumerable<T> AllAuxCyclopsManagers<T>()
where T : class, IAuxCyclopsManager
{
return CyclopsManager.GetAllManagers<T>(typeof(T).Name);
}
/// <summary>
/// Gets the typed <see cref="Charging.CyclopsCharger" /> at the specified Cyclops sub.<para />
/// Use this if you need to obtain a reference to your <seealso cref="Charging.CyclopsCharger" /> for something else in your mod.
/// </summary>
/// <typeparam name="T">The class created by the <seealso cref="CreateCyclopsCharger" /> you passed into <seealso cref="IMCURegistration.CyclopsCharger(CreateCyclopsCharger)" />.</typeparam>
/// <param name="cyclops">The cyclops to search in.</param>
/// <returns>
/// A type casted <see cref="Charging.CyclopsCharger" /> if found; Otherwise returns null.
/// </returns>
public T CyclopsCharger<T>(SubRoot cyclops) where T : CyclopsCharger
{
return CyclopsManager.GetManager(ref cyclops)?.Charge.GetCharger<T>(typeof(T).Name);
}
/// <summary>
/// Gets the upgrade handler at the specified Cyclops sub for the specified upgrade module <see cref="TechType" />.<para />
/// Use this if you need to obtain a reference to your <seealso cref="UpgradeHandler" /> for something else in your mod.
/// </summary>
/// <param name="cyclops">The cyclops to search in.</param>
/// <param name="upgradeId">The upgrade module techtype ID.</param>
/// <returns>
/// An <see cref="UpgradeHandler" /> if found by techtype; Otherwise returns null.
/// </returns>
public UpgradeHandler CyclopsUpgradeHandler(SubRoot cyclops, TechType upgradeId)
{
return CyclopsManager.GetManager(ref cyclops)?.Upgrade?.GetUpgradeHandler<UpgradeHandler>(upgradeId);
}
/// <summary>
/// Gets the upgrade handler at the specified Cyclops sub for the specified upgrade module <see cref="TechType" />.<para />
/// Use this if you need to obtain a reference to your <seealso cref="UpgradeHandler" /> for something else in your mod.
/// </summary>
/// <typeparam name="T">The class created by the <seealso cref="CreateUpgradeHandler" /> you passed into <seealso cref="IMCURegistration.CyclopsUpgradeHandler(CreateUpgradeHandler)" />.</typeparam>
/// <param name="cyclops">The cyclops to search in.</param>
/// <param name="upgradeId">The upgrade module techtype ID.</param>
/// <returns>
/// A type casted <see cref="UpgradeHandler" /> if found by techtype; Otherwise returns null.
/// </returns>
public T CyclopsUpgradeHandler<T>(SubRoot cyclops, TechType upgradeId) where T : UpgradeHandler
{
return CyclopsManager.GetManager(ref cyclops)?.Upgrade?.GetUpgradeHandler<T>(upgradeId);
}
/// <summary>
/// Gets the upgrade handler at the specified Cyclops sub for the specified upgrade module <see cref="TechType" />.<para />
/// Use this if you need to obtain a reference to your <seealso cref="StackingGroupHandler" /> or <seealso cref="TieredGroupHandler{T}" /> for something else in your mod.
/// </summary>
/// <typeparam name="T">The class created by the <seealso cref="CreateUpgradeHandler" /> you passed into <seealso cref="IMCURegistration.CyclopsUpgradeHandler(CreateUpgradeHandler)" />.</typeparam>
/// <param name="cyclops">The cyclops to search in.</param>
/// <param name="upgradeId">The upgrade module techtype ID.</param>
/// <param name="additionalIds">Additional techtype IDs for a more precise search.</param>
/// <returns>
/// A type casted <see cref="UpgradeHandler" /> if found by techtype; Otherwise returns null.
/// </returns>
public T CyclopsGroupUpgradeHandler<T>(SubRoot cyclops, TechType upgradeId, params TechType[] additionalIds) where T : UpgradeHandler, IGroupHandler
{
return CyclopsManager.GetManager(ref cyclops)?.Upgrade?.GetGroupHandler<T>(upgradeId);
}
#endregion
#region IMCULogger
/// <summary>
/// Provides a set of logging APIs that other mods can use.<para/>
/// Debug level logs will only be printed of MCU's debug logging is enabled.
/// </summary>
public static IMCULogger Logger => singleton;
/// <summary>
/// Gets a value indicating whether calls into <see cref="Debug" /> are handled or ignored.
/// </summary>
/// <value>
/// <c>true</c> if debug level logs enabled; otherwise, <c>false</c>.
/// </value>
public bool DebugLogsEnabled => QuickLogger.DebugLogsEnabled;
/// <summary>
/// Writes an INFO level log to the log file. Can be optionally printed to screen.
/// </summary>
/// <param name="logmessage">The log message to write.</param>
/// <param name="showOnScreen">if set to <c>true</c> the log message will show on screen.</param>
public void Info(string logmessage, bool showOnScreen = false)
{
QuickLogger.Info(logmessage, showOnScreen, Assembly.GetCallingAssembly().GetName());
}
/// <summary>
/// Writes a WARN level log to the log file. Can be optionally printed to screen.
/// </summary>
/// <param name="logmessage">The log message to write.</param>
/// <param name="showOnScreen">if set to <c>true</c> the log message will show on screen.</param>
public void Warning(string logmessage, bool showOnScreen = false)
{
QuickLogger.Warning(logmessage, showOnScreen, Assembly.GetCallingAssembly().GetName());
}
/// <summary>
/// Writes an ERROR level log to the log file. Can be optionally printed to screen.
/// </summary>
/// <param name="logmessage">The log message to write.</param>
/// <param name="showOnScreen">if set to <c>true</c> the log message will show on screen.</param>
public void Error(string logmessage, bool showOnScreen = false)
{
QuickLogger.Error(logmessage, showOnScreen, Assembly.GetCallingAssembly().GetName());
}
/// <summary>
/// Writes <see cref="Exception" /> to an ERROR level log to file.
/// </summary>
/// <param name="ex">The exception to log.</param>
/// <param name="logmessage">The optional additional message.</param>
public void Error(Exception ex, string logmessage = null)
{
if (logmessage == null)
QuickLogger.Error(ex, Assembly.GetCallingAssembly().GetName());
else
QuickLogger.Error(logmessage, ex, Assembly.GetCallingAssembly().GetName());
}
/// <summary>
/// Writes an DEBUG level log to the log file if <see cref="DebugLogsEnabled" /> is enabled. Can be optionally printed to screen.<para />
/// No action taken when <see cref="DebugLogsEnabled" /> is set to <c>false</c>;
/// </summary>
/// <param name="logmessage">The log message to write.</param>
/// <param name="showOnScreen">if set to <c>true</c> the log message will show on screen.</param>
public void Debug(string logmessage, bool showOnScreen = false)
{
QuickLogger.Debug(logmessage, showOnScreen, Assembly.GetCallingAssembly().GetName());
}
#endregion
}
}
| 52.320388 | 205 | 0.638384 | [
"MIT"
] | Denkkar/PrimeSonicSubnauticaMods | MoreCyclopsUpgrades/API/MCUServiceS.cs | 21,558 | 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 System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Apache.NMS;
using Apache.NMS.Util;
using Apache.NMS.AMQP;
using Apache.NMS.AMQP.Util;
namespace Apache.NMS.AMQP.Message.Factory
{
internal abstract class MessageFactory<T> : IMessageFactory where T : ResourceInfo
{
private static readonly IDictionary<Id, IMessageFactory> resgistry;
static MessageFactory()
{
resgistry = new ConcurrentDictionary<Id, IMessageFactory>();
}
public static void Register(NMSResource<T> resource)
{
if (resource is Connection)
{
resgistry.Add(resource.Id, (new AMQPMessageFactory<ConnectionInfo>(resource as Connection)) as IMessageFactory);
}
else
{
throw new NMSException("Invalid Message Factory Type " + resource.GetType().FullName);
}
}
public static void Unregister(NMSResource<T> resource)
{
if(resource != null && resource.Id != null)
{
if(!resgistry.Remove(resource.Id))
{
if(resgistry.ContainsKey(resource.Id))
Tracer.WarnFormat("MessageFactory was not able to unregister resource {0}.", resource.Id);
}
}
}
public static IMessageFactory Instance(Connection resource)
{
IMessageFactory factory = null;
resgistry.TryGetValue(resource.Id, out factory);
if(factory == null)
{
throw new NMSException("Resource "+resource+" is not registered as message factory.");
}
return factory;
}
protected readonly NMSResource<T> parent;
protected MessageFactory(NMSResource<T> resource)
{
parent = resource;
}
public abstract MessageTransformation GetTransformFactory();
public abstract IMessage CreateMessage();
public abstract ITextMessage CreateTextMessage();
public abstract ITextMessage CreateTextMessage(string text);
public abstract IMapMessage CreateMapMessage();
public abstract IObjectMessage CreateObjectMessage(object body);
public abstract IBytesMessage CreateBytesMessage();
public abstract IBytesMessage CreateBytesMessage(byte[] body);
public abstract IStreamMessage CreateStreamMessage();
}
}
| 36.397849 | 128 | 0.651699 | [
"Apache-2.0"
] | Havret/activemq-nms-amqp | src/main/csharp/Message/Factory/MessageFactory.cs | 3,387 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using HandyControl.Data;
using HandyControl.Interactivity;
using HandyControl.Properties.Langs;
using HandyControl.Tools;
using HandyControl.Tools.Extension;
namespace HandyControl.Controls
{
/// <summary>
/// 消息提醒
/// </summary>
[TemplatePart(Name = ElementPanelMore, Type = typeof(Panel))]
[TemplatePart(Name = ElementGridMain, Type = typeof(Grid))]
[TemplatePart(Name = ElementButtonClose, Type = typeof(Button))]
public class Growl : Control
{
#region Constants
private const string ElementPanelMore = "PART_PanelMore";
private const string ElementGridMain = "PART_GridMain";
private const string ElementButtonClose = "PART_ButtonClose";
#endregion Constants
#region Data
private static GrowlWindow GrowlWindow;
private Panel _panelMore;
private Grid _gridMain;
private Button _buttonClose;
private bool _showCloseButton;
private bool _staysOpen;
private int _waitTime = 6;
/// <summary>
/// 计数
/// </summary>
private int _tickCount;
/// <summary>
/// 关闭计时器
/// </summary>
private DispatcherTimer _timerClose;
private static readonly Dictionary<string, Panel> PanelDic = new();
#endregion Data
public Growl()
{
CommandBindings.Add(new CommandBinding(ControlCommands.Close, ButtonClose_OnClick));
CommandBindings.Add(new CommandBinding(ControlCommands.Cancel, ButtonCancel_OnClick));
CommandBindings.Add(new CommandBinding(ControlCommands.Confirm, ButtonOk_OnClick));
}
public static void Register(string token, Panel panel)
{
if (string.IsNullOrEmpty(token) || panel == null) return;
PanelDic[token] = panel;
InitGrowlPanel(panel);
}
public static void Unregister(string token, Panel panel)
{
if (string.IsNullOrEmpty(token) || panel == null) return;
if (PanelDic.ContainsKey(token))
{
if (ReferenceEquals(PanelDic[token], panel))
{
PanelDic.Remove(token);
panel.ContextMenu = null;
panel.SetCurrentValue(PanelElement.FluidMoveBehaviorProperty, DependencyProperty.UnsetValue);
}
}
}
public static void Unregister(Panel panel)
{
if (panel == null) return;
var first = PanelDic.FirstOrDefault(item => ReferenceEquals(panel, item.Value));
if (!string.IsNullOrEmpty(first.Key))
{
PanelDic.Remove(first.Key);
panel.ContextMenu = null;
panel.SetCurrentValue(PanelElement.FluidMoveBehaviorProperty, DependencyProperty.UnsetValue);
}
}
public static void Unregister(string token)
{
if (string.IsNullOrEmpty(token)) return;
if (PanelDic.ContainsKey(token))
{
var panel = PanelDic[token];
PanelDic.Remove(token);
panel.ContextMenu = null;
panel.SetCurrentValue(PanelElement.FluidMoveBehaviorProperty, DependencyProperty.UnsetValue);
}
}
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
_buttonClose.Show(_showCloseButton);
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
_buttonClose.Collapse();
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_panelMore = GetTemplateChild(ElementPanelMore) as Panel;
_gridMain = GetTemplateChild(ElementGridMain) as Grid;
_buttonClose = GetTemplateChild(ElementButtonClose) as Button;
CheckNull();
Update();
}
private void CheckNull()
{
if (_panelMore == null || _gridMain == null || _buttonClose == null) throw new Exception();
}
private Func<bool, bool> ActionBeforeClose { get; set; }
/// <summary>
/// 消息容器
/// </summary>
public static Panel GrowlPanel { get; set; }
internal static readonly DependencyProperty CancelStrProperty = DependencyProperty.Register(
"CancelStr", typeof(string), typeof(Growl), new PropertyMetadata(default(string)));
internal static readonly DependencyProperty ConfirmStrProperty = DependencyProperty.Register(
"ConfirmStr", typeof(string), typeof(Growl), new PropertyMetadata(default(string)));
public static readonly DependencyProperty ShowDateTimeProperty = DependencyProperty.Register(
"ShowDateTime", typeof(bool), typeof(Growl), new PropertyMetadata(ValueBoxes.TrueBox));
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(
"Message", typeof(string), typeof(Growl), new PropertyMetadata(default(string)));
public static readonly DependencyProperty TimeProperty = DependencyProperty.Register(
"Time", typeof(DateTime), typeof(Growl), new PropertyMetadata(default(DateTime)));
public static readonly DependencyProperty IconProperty = DependencyProperty.Register(
"Icon", typeof(Geometry), typeof(Growl), new PropertyMetadata(default(Geometry)));
public static readonly DependencyProperty IconBrushProperty = DependencyProperty.Register(
"IconBrush", typeof(Brush), typeof(Growl), new PropertyMetadata(default(Brush)));
public static readonly DependencyProperty TypeProperty = DependencyProperty.Register(
"Type", typeof(InfoType), typeof(Growl), new PropertyMetadata(default(InfoType)));
public static readonly DependencyProperty TokenProperty = DependencyProperty.RegisterAttached(
"Token", typeof(string), typeof(Growl), new PropertyMetadata(default(string), OnTokenChanged));
private static void OnTokenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is Panel panel)
{
if (e.NewValue == null)
{
Unregister(panel);
}
else
{
Register(e.NewValue.ToString(), panel);
}
}
}
public static void SetToken(DependencyObject element, string value)
=> element.SetValue(TokenProperty, value);
public static string GetToken(DependencyObject element)
=> (string) element.GetValue(TokenProperty);
public static readonly DependencyProperty GrowlParentProperty = DependencyProperty.RegisterAttached(
"GrowlParent", typeof(bool), typeof(Growl), new PropertyMetadata(ValueBoxes.FalseBox, (o, args) =>
{
if ((bool) args.NewValue && o is Panel panel)
{
SetGrowlPanel(panel);
}
}));
public static void SetGrowlParent(DependencyObject element, bool value) => element.SetValue(GrowlParentProperty, ValueBoxes.BooleanBox(value));
public static bool GetGrowlParent(DependencyObject element) => (bool) element.GetValue(GrowlParentProperty);
private static readonly DependencyProperty IsCreatedAutomaticallyProperty = DependencyProperty.RegisterAttached(
"IsCreatedAutomatically", typeof(bool), typeof(Growl), new PropertyMetadata(ValueBoxes.FalseBox));
private static void SetIsCreatedAutomatically(DependencyObject element, bool value)
=> element.SetValue(IsCreatedAutomaticallyProperty, ValueBoxes.BooleanBox(value));
private static bool GetIsCreatedAutomatically(DependencyObject element)
=> (bool) element.GetValue(IsCreatedAutomaticallyProperty);
public InfoType Type
{
get => (InfoType) GetValue(TypeProperty);
set => SetValue(TypeProperty, value);
}
internal string CancelStr
{
get => (string) GetValue(CancelStrProperty);
set => SetValue(CancelStrProperty, value);
}
internal string ConfirmStr
{
get => (string) GetValue(ConfirmStrProperty);
set => SetValue(ConfirmStrProperty, value);
}
public bool ShowDateTime
{
get => (bool) GetValue(ShowDateTimeProperty);
set => SetValue(ShowDateTimeProperty, ValueBoxes.BooleanBox(value));
}
public string Message
{
get => (string) GetValue(MessageProperty);
set => SetValue(MessageProperty, value);
}
public DateTime Time
{
get => (DateTime) GetValue(TimeProperty);
set => SetValue(TimeProperty, value);
}
public Geometry Icon
{
get => (Geometry) GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public Brush IconBrush
{
get => (Brush) GetValue(IconBrushProperty);
set => SetValue(IconBrushProperty, value);
}
/// <summary>
/// 开始计时器
/// </summary>
private void StartTimer()
{
_timerClose = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(1)
};
_timerClose.Tick += delegate
{
if (IsMouseOver)
{
_tickCount = 0;
return;
}
_tickCount++;
if (_tickCount >= _waitTime) Close(true);
};
_timerClose.Start();
}
/// <summary>
/// 消息容器
/// </summary>
/// <param name="panel"></param>
private static void SetGrowlPanel(Panel panel)
{
GrowlPanel = panel;
InitGrowlPanel(panel);
}
private static void InitGrowlPanel(Panel panel)
{
if (panel == null) return;
var menuItem = new MenuItem();
LangProvider.SetLang(menuItem, HeaderedItemsControl.HeaderProperty, LangKeys.Clear);
menuItem.Click += (s, e) =>
{
foreach (var item in panel.Children.OfType<Growl>())
{
item.Close();
}
};
panel.ContextMenu = new ContextMenu
{
Items =
{
menuItem
}
};
PanelElement.SetFluidMoveBehavior(panel, ResourceHelper.GetResourceInternal<FluidMoveBehavior>(ResourceToken.BehaviorXY400));
}
private void Update()
{
if (DesignerHelper.IsInDesignMode) return;
if (Type == InfoType.Ask)
{
_panelMore.IsEnabled = true;
_panelMore.Show();
}
var transform = new TranslateTransform
{
X = FlowDirection == FlowDirection.LeftToRight ? MaxWidth : -MaxWidth
};
_gridMain.RenderTransform = transform;
transform.BeginAnimation(TranslateTransform.XProperty, AnimationHelper.CreateAnimation(0));
if (!_staysOpen) StartTimer();
}
private static void ShowGlobal(GrowlInfo growlInfo)
{
Application.Current.Dispatcher?.Invoke(
#if NET40
new Action(
#endif
() =>
{
if (GrowlWindow == null)
{
GrowlWindow = new GrowlWindow();
GrowlWindow.Show();
InitGrowlPanel(GrowlWindow.GrowlPanel);
GrowlWindow.Init();
}
GrowlWindow.Show(true);
var ctl = new Growl
{
Message = growlInfo.Message,
Time = DateTime.Now,
Icon = ResourceHelper.GetResourceInternal<Geometry>(growlInfo.IconKey),
IconBrush = ResourceHelper.GetResourceInternal<Brush>(growlInfo.IconBrushKey),
_showCloseButton = growlInfo.ShowCloseButton,
ActionBeforeClose = growlInfo.ActionBeforeClose,
_staysOpen = growlInfo.StaysOpen,
ShowDateTime = growlInfo.ShowDateTime,
ConfirmStr = growlInfo.ConfirmStr,
CancelStr = growlInfo.CancelStr,
Type = growlInfo.Type,
_waitTime = Math.Max(growlInfo.WaitTime, 2),
FlowDirection = growlInfo.FlowDirection
};
GrowlWindow.GrowlPanel.Children.Insert(0, ctl);
}
#if NET40
)
#endif
);
}
/// <summary>
/// 显示信息
/// </summary>
/// <param name="growlInfo"></param>
private static void Show(GrowlInfo growlInfo)
{
Application.Current.Dispatcher?.Invoke(
#if NET40
new Action(
#endif
() =>
{
var ctl = new Growl
{
Message = growlInfo.Message,
Time = DateTime.Now,
Icon = ResourceHelper.GetResourceInternal<Geometry>(growlInfo.IconKey),
IconBrush = ResourceHelper.GetResourceInternal<Brush>(growlInfo.IconBrushKey),
_showCloseButton = growlInfo.ShowCloseButton,
ActionBeforeClose = growlInfo.ActionBeforeClose,
_staysOpen = growlInfo.StaysOpen,
ShowDateTime = growlInfo.ShowDateTime,
ConfirmStr = growlInfo.ConfirmStr,
CancelStr = growlInfo.CancelStr,
Type = growlInfo.Type,
_waitTime = Math.Max(growlInfo.WaitTime, 2)
};
if (!string.IsNullOrEmpty(growlInfo.Token))
{
if (PanelDic.TryGetValue(growlInfo.Token, out var panel))
{
panel?.Children.Insert(0, ctl);
}
}
else
{
// GrowlPanel is null, we create it automatically
GrowlPanel ??= CreateDefaultPanel();
GrowlPanel?.Children.Insert(0, ctl);
}
}
#if NET40
)
#endif
);
}
private static Panel CreateDefaultPanel()
{
FrameworkElement element = WindowHelper.GetActiveWindow();
var decorator = VisualHelper.GetChild<AdornerDecorator>(element);
if (decorator != null)
{
var layer = decorator.AdornerLayer;
if (layer != null)
{
var panel = new StackPanel
{
VerticalAlignment = VerticalAlignment.Top
};
InitGrowlPanel(panel);
SetIsCreatedAutomatically(panel, true);
var scrollViewer = new ScrollViewer
{
HorizontalAlignment = HorizontalAlignment.Right,
VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,
IsInertiaEnabled = true,
IsPenetrating = true,
Content = panel
};
var container = new AdornerContainer(layer)
{
Child = scrollViewer
};
layer.Add(container);
return panel;
}
}
return null;
}
private static void RemoveDefaultPanel(Panel panel)
{
FrameworkElement element = WindowHelper.GetActiveWindow();
var decorator = VisualHelper.GetChild<AdornerDecorator>(element);
if (decorator != null)
{
var layer = decorator.AdornerLayer;
var adorner = VisualHelper.GetParent<Adorner>(panel);
if (adorner != null)
{
layer?.Remove(adorner);
}
}
}
private static void InitGrowlInfo(ref GrowlInfo growlInfo, InfoType infoType)
{
if (growlInfo == null) throw new ArgumentNullException(nameof(growlInfo));
growlInfo.Type = infoType;
switch (infoType)
{
case InfoType.Success:
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.SuccessGeometry;
growlInfo.IconBrushKey = ResourceToken.SuccessBrush;
}
else
{
growlInfo.IconKey ??= ResourceToken.SuccessGeometry;
growlInfo.IconBrushKey ??= ResourceToken.SuccessBrush;
}
break;
case InfoType.Info:
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.InfoGeometry;
growlInfo.IconBrushKey = ResourceToken.InfoBrush;
}
else
{
growlInfo.IconKey ??= ResourceToken.InfoGeometry;
growlInfo.IconBrushKey ??= ResourceToken.InfoBrush;
}
break;
case InfoType.Warning:
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.WarningGeometry;
growlInfo.IconBrushKey = ResourceToken.WarningBrush;
}
else
{
growlInfo.IconKey ??= ResourceToken.WarningGeometry;
growlInfo.IconBrushKey ??= ResourceToken.WarningBrush;
}
break;
case InfoType.Error:
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.ErrorGeometry;
growlInfo.IconBrushKey = ResourceToken.DangerBrush;
growlInfo.StaysOpen = true;
}
else
{
growlInfo.IconKey ??= ResourceToken.ErrorGeometry;
growlInfo.IconBrushKey ??= ResourceToken.DangerBrush;
}
break;
case InfoType.Fatal:
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.FatalGeometry;
growlInfo.IconBrushKey = ResourceToken.PrimaryTextBrush;
growlInfo.StaysOpen = true;
growlInfo.ShowCloseButton = false;
}
else
{
growlInfo.IconKey ??= ResourceToken.FatalGeometry;
growlInfo.IconBrushKey ??= ResourceToken.PrimaryTextBrush;
}
break;
case InfoType.Ask:
growlInfo.StaysOpen = true;
growlInfo.ShowCloseButton = false;
if (!growlInfo.IsCustom)
{
growlInfo.IconKey = ResourceToken.AskGeometry;
growlInfo.IconBrushKey = ResourceToken.AccentBrush;
}
else
{
growlInfo.IconKey ??= ResourceToken.AskGeometry;
growlInfo.IconBrushKey ??= ResourceToken.AccentBrush;
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(infoType), infoType, null);
}
}
/// <summary>
/// 成功
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Success(string message, string token = "") => Success(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 成功
/// </summary>
/// <param name="growlInfo"></param>
public static void Success(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Success);
Show(growlInfo);
}
/// <summary>
/// 成功
/// </summary>
/// <param name="message"></param>
public static void SuccessGlobal(string message) => SuccessGlobal(new GrowlInfo
{
Message = message
});
/// <summary>
/// 成功
/// </summary>
/// <param name="growlInfo"></param>
public static void SuccessGlobal(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Success);
ShowGlobal(growlInfo);
}
/// <summary>
/// 消息
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Info(string message, string token = "") => Info(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 消息
/// </summary>
/// <param name="growlInfo"></param>
public static void Info(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Info);
Show(growlInfo);
}
/// <summary>
/// 消息
/// </summary>
/// <param name="message"></param>
public static void InfoGlobal(string message) => InfoGlobal(new GrowlInfo
{
Message = message
});
/// <summary>
/// 消息
/// </summary>
/// <param name="growlInfo"></param>
public static void InfoGlobal(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Info);
ShowGlobal(growlInfo);
}
/// <summary>
/// 警告
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Warning(string message, string token = "") => Warning(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 警告
/// </summary>
/// <param name="growlInfo"></param>
public static void Warning(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Warning);
Show(growlInfo);
}
/// <summary>
/// 警告
/// </summary>
/// <param name="message"></param>
public static void WarningGlobal(string message) => WarningGlobal(new GrowlInfo
{
Message = message
});
/// <summary>
/// 警告
/// </summary>
/// <param name="growlInfo"></param>
public static void WarningGlobal(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Warning);
ShowGlobal(growlInfo);
}
/// <summary>
/// 错误
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Error(string message, string token = "") => Error(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 错误
/// </summary>
/// <param name="growlInfo"></param>
public static void Error(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Error);
Show(growlInfo);
}
/// <summary>
/// 错误
/// </summary>
/// <param name="message"></param>
public static void ErrorGlobal(string message) => ErrorGlobal(new GrowlInfo
{
Message = message
});
/// <summary>
/// 错误
/// </summary>
/// <param name="growlInfo"></param>
public static void ErrorGlobal(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Error);
ShowGlobal(growlInfo);
}
/// <summary>
/// 严重
/// </summary>
/// <param name="message"></param>
/// <param name="token"></param>
public static void Fatal(string message, string token = "") => Fatal(new GrowlInfo
{
Message = message,
Token = token
});
/// <summary>
/// 严重
/// </summary>
/// <param name="growlInfo"></param>
public static void Fatal(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Fatal);
Show(growlInfo);
}
/// <summary>
/// 严重
/// </summary>
/// <param name="message"></param>
public static void FatalGlobal(string message) => FatalGlobal(new GrowlInfo
{
Message = message
});
/// <summary>
/// 严重
/// </summary>
/// <param name="growlInfo"></param>
public static void FatalGlobal(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Fatal);
ShowGlobal(growlInfo);
}
/// <summary>
/// 询问
/// </summary>
/// <param name="message"></param>
/// <param name="actionBeforeClose"></param>
/// <param name="token"></param>
public static void Ask(string message, Func<bool, bool> actionBeforeClose, string token = "") => Ask(new GrowlInfo
{
Message = message,
ActionBeforeClose = actionBeforeClose,
Token = token
});
/// <summary>
/// 询问
/// </summary>
/// <param name="growlInfo"></param>
public static void Ask(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Ask);
Show(growlInfo);
}
/// <summary>
/// 询问
/// </summary>
/// <param name="message"></param>
/// <param name="actionBeforeClose"></param>
public static void AskGlobal(string message, Func<bool, bool> actionBeforeClose) => AskGlobal(new GrowlInfo
{
Message = message,
ActionBeforeClose = actionBeforeClose
});
/// <summary>
/// 询问
/// </summary>
/// <param name="growlInfo"></param>
public static void AskGlobal(GrowlInfo growlInfo)
{
InitGrowlInfo(ref growlInfo, InfoType.Ask);
ShowGlobal(growlInfo);
}
private void ButtonClose_OnClick(object sender, RoutedEventArgs e) => Close(true, false);
/// <summary>
/// 关闭
/// </summary>
private void Close(bool invokeActionBeforeClose = false, bool invokeParam = true)
{
if (invokeActionBeforeClose)
{
if (ActionBeforeClose?.Invoke(invokeParam) == false) return;
}
_timerClose?.Stop();
var transform = new TranslateTransform();
_gridMain.RenderTransform = transform;
var animation = AnimationHelper.CreateAnimation(FlowDirection == FlowDirection.LeftToRight ? ActualWidth : -ActualWidth);
animation.Completed += (s, e) =>
{
if (Parent is Panel panel)
{
panel.Children.Remove(this);
if (GrowlWindow != null)
{
if (GrowlWindow.GrowlPanel != null && GrowlWindow.GrowlPanel.Children.Count == 0)
{
GrowlWindow.Close();
GrowlWindow = null;
}
}
else
{
if (GrowlPanel != null && GrowlPanel.Children.Count == 0 && GetIsCreatedAutomatically(GrowlPanel))
{
// If the count of children is zero, we need to remove the panel, provided that the panel was created automatically
RemoveDefaultPanel(GrowlPanel);
GrowlPanel = null;
}
}
}
};
transform.BeginAnimation(TranslateTransform.XProperty, animation);
}
/// <summary>
/// 清除
/// </summary>
/// <param name="token"></param>
public static void Clear(string token = "")
{
if (!string.IsNullOrEmpty(token))
{
if (PanelDic.TryGetValue(token, out var panel))
{
Clear(panel);
}
}
else
{
Clear(GrowlPanel);
}
}
/// <summary>
/// 清除
/// </summary>
/// <param name="panel"></param>
private static void Clear(Panel panel) => panel?.Children.Clear();
/// <summary>
/// 清除
/// </summary>
public static void ClearGlobal()
{
if (GrowlWindow == null) return;
Clear(GrowlWindow.GrowlPanel);
GrowlWindow.Close();
GrowlWindow = null;
}
private void ButtonCancel_OnClick(object sender, RoutedEventArgs e) => Close(true, false);
private void ButtonOk_OnClick(object sender, RoutedEventArgs e) => Close(true);
}
}
| 33.900979 | 151 | 0.505794 | [
"MIT"
] | JeremyWu917/HandyControl | src/Shared/HandyControl_Shared/Controls/Growl/Growl.cs | 31,325 | C# |
using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;
/// <summary>
/// Base class for importing a sprite atlas from an XML file
/// </summary>
public class OTSpriteAtlasImportXML : OTSpriteAtlasImport
{
protected string AttrS(XmlNode node, string field)
{
try
{
return node.Attributes[field].InnerText;
}
catch (System.Exception)
{
return "";
}
}
protected int AttrI(XmlNode node, string field)
{
try
{
return System.Convert.ToInt16(node.Attributes[field].InnerText);
}
catch (System.Exception)
{
return -1;
}
}
protected override void LocateAtlasData()
{
if (atlasDataFile!=null && texture.name == atlasDataFile.name)
return;
#if UNITY_EDITOR
string path = Path.GetDirectoryName(UnityEditor.AssetDatabase.GetAssetPath(texture))+"/"+texture.name+".xml";
Object o = (UnityEditor.AssetDatabase.LoadAssetAtPath(path,typeof(TextAsset)));
if (o is TextAsset)
_atlasDataFile = (o as TextAsset);
#endif
}
protected XmlDocument xml = new XmlDocument();
/// <summary>
/// Check if xml provided is valid
/// </summary>
/// <returns>Array with atlas frame data</returns>
protected bool ValidXML()
{
try
{
xml.LoadXml(atlasDataFile.text);
return true;
}
catch (System.Exception err)
{
Debug.LogError("Orthello : Atlas XML file could not be read!");
Debug.LogError(err.Message);
}
return false;
}
} | 24.397059 | 111 | 0.592526 | [
"MIT"
] | BuloZB/hotfix | Unity/Assets/Standard Assets/OT/Graphics/Sprites/Atlas/OTSpriteAtlasImportXML.cs | 1,659 | C# |
/*
* Copyright (c) 2008, DIaLOGIKa
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of DIaLOGIKa nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY DIaLOGIKa ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL DIaLOGIKa BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace DIaLOGIKa.b2xtranslator.StructuredStorage.Common
{
/// <summary>
/// Abstract class fo the header of a compound file.
/// Author: math
/// </summary>
abstract internal class AbstractHeader
{
protected const UInt64 MAGIC_NUMBER = 0xE11AB1A1E011CFD0;
protected AbstractIOHandler _ioHandler;
// Sector shift and sector size
private UInt16 _sectorShift;
public UInt16 SectorShift
{
get { return _sectorShift; }
set
{
_sectorShift = value;
// Calculate sector size
_sectorSize = (UInt16)Math.Pow((double)2, (double)_sectorShift);
if (_sectorShift != 9 && _sectorShift != 12)
{
throw new UnsupportedSizeException("SectorShift: " + _sectorShift);
}
}
}
private UInt16 _sectorSize;
public UInt16 SectorSize
{
get { return _sectorSize; }
}
// Minisector shift and Minisector size
private UInt16 _miniSectorShift;
public UInt16 MiniSectorShift
{
get { return _miniSectorShift; }
set
{
_miniSectorShift = value;
// Calculate mini sector size
_miniSectorSize = (UInt16)Math.Pow((double)2, (double)_miniSectorShift);
if (_miniSectorShift != 6)
{
throw new UnsupportedSizeException("MiniSectorShift: " + _miniSectorShift);
}
}
}
private UInt16 _miniSectorSize;
public UInt16 MiniSectorSize
{
get { return _miniSectorSize; }
}
// CSectDir
private UInt32 _noSectorsInDirectoryChain4KB;
public UInt32 NoSectorsInDirectoryChain4KB
{
get { return _noSectorsInDirectoryChain4KB; }
set
{
if (_sectorSize == 512 && value != 0)
{
throw new ValueNotZeroException("_csectDir");
}
_noSectorsInDirectoryChain4KB = value;
}
}
// CSectFat
private UInt32 _noSectorsInFatChain;
public UInt32 NoSectorsInFatChain
{
get { return _noSectorsInFatChain; }
set
{
_noSectorsInFatChain = value;
if (value > _ioHandler.IOStreamSize / SectorSize)
{
throw new InvalidValueInHeaderException("NoSectorsInFatChain");
}
}
}
// SectDirStart
private UInt32 _directoryStartSector;
public UInt32 DirectoryStartSector
{
get { return _directoryStartSector; }
set
{
_directoryStartSector = value;
if (value > _ioHandler.IOStreamSize / SectorSize && value != SectorId.ENDOFCHAIN)
{
throw new InvalidValueInHeaderException("DirectoryStartSector");
}
}
}
// UInt32ULMiniSectorCutoff
private UInt32 _miniSectorCutoff;
public UInt32 MiniSectorCutoff
{
get { return _miniSectorCutoff; }
set
{
_miniSectorCutoff = value;
if (value != 0x1000)
{
throw new UnsupportedSizeException("MiniSectorCutoff");
}
}
}
// SectMiniFatStart
private UInt32 _miniFatStartSector;
public UInt32 MiniFatStartSector
{
get { return _miniFatStartSector; }
set
{
_miniFatStartSector = value;
if (value > _ioHandler.IOStreamSize / SectorSize && value != SectorId.ENDOFCHAIN)
{
throw new InvalidValueInHeaderException("MiniFatStartSector");
}
}
}
// CSectMiniFat
private UInt32 _noSectorsInMiniFatChain;
public UInt32 NoSectorsInMiniFatChain
{
get { return _noSectorsInMiniFatChain; }
set
{
_noSectorsInMiniFatChain = value;
if (value > _ioHandler.IOStreamSize / SectorSize)
{
throw new InvalidValueInHeaderException("NoSectorsInMiniFatChain");
}
}
}
// SectDifStart
private UInt32 _diFatStartSector;
public UInt32 DiFatStartSector
{
get { return _diFatStartSector; }
set
{
_diFatStartSector = value;
if (value > _ioHandler.IOStreamSize / SectorSize && value != SectorId.ENDOFCHAIN && value != SectorId.FREESECT)
{
throw new InvalidValueInHeaderException("DiFatStartSector", String.Format("Details: value={0};_ioHandler.IOStreamSize={1};SectorSize={2}; SectorId.ENDOFCHAIN: {3}", value, _ioHandler.IOStreamSize, SectorSize, SectorId.ENDOFCHAIN));
}
}
}
// CSectDif
private UInt32 _noSectorsInDiFatChain;
public UInt32 NoSectorsInDiFatChain
{
get { return _noSectorsInDiFatChain; }
set
{
_noSectorsInDiFatChain = value;
if (value > _ioHandler.IOStreamSize / SectorSize)
{
throw new InvalidValueInHeaderException("NoSectorsInDiFatChain");
}
}
}
}
}
| 33.647321 | 252 | 0.553536 | [
"BSD-3-Clause"
] | datadiode/B2XTranslator | src/Common/StructuredStorage/Common/AbstractHeader.cs | 7,537 | C# |
using System;
namespace COLID.Graph.TripleStore.DataModels.Sparql
{
internal class SparqlPrefix
{
public string ShortPrefix { get; set; }
public Uri Url { get; set; }
public SparqlPrefix(string shortPrefix, Uri url)
{
ShortPrefix = shortPrefix;
Url = url;
}
}
}
| 20.058824 | 56 | 0.580645 | [
"BSD-3-Clause"
] | Bayer-Group/COLID-Registration-Service | libs/COLID.Graph/TripleStore/DataModels/Sparql/SparqlPrefix.cs | 343 | C# |
using System;
namespace PixelMatrix.Core.Interfaces
{
public interface IMatrixContainer<TMatrix, TValue>
where TMatrix : IMatrix<TValue>
where TValue : struct
{
TMatrix Matrix { get; }
}
}
| 18.916667 | 54 | 0.647577 | [
"MIT"
] | hsytkm/PixelMatrix | source/PixelMatrix.Core/Interfaces/IMatrixContainer.cs | 229 | C# |
using Lucene.Net.Util;
using System;
namespace Lucene.Net.Codecs
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Represents an attribute that is used to name a <see cref="Codec"/>, if a name
/// other than the default <see cref="Codec"/> naming convention is desired.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class CodecNameAttribute : ServiceNameAttribute
{
public CodecNameAttribute(string name)
: base(name)
{
}
}
}
| 39.805556 | 86 | 0.662945 | [
"Apache-2.0"
] | NikolayXHD/Lucene.Net.Contrib | Lucene.Net/Support/Codecs/CodecNameAttribute.cs | 1,435 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CarouselPageNavigation.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CarouselPageNavigation.UWP")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 36.862069 | 84 | 0.746492 | [
"Apache-2.0"
] | 15217711253/xamarin-forms-samples | Navigation/CarouselPage/UWP/Properties/AssemblyInfo.cs | 1,072 | C# |
using AtlasWorkFlows.Jobs;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sprache;
namespace AtlasWorkFlowsTest.Jobs
{
[TestClass]
public class JobPrintTest
{
[TestMethod]
public void ReleaseOutput()
{
var r = new Release() { Name = "Base,2222" };
Assert.AreEqual("release(Base,2222)", r.Print());
var rp = JobParser.ParseRelease.Parse(r.Print());
Assert.AreEqual(r.Name, rp.Name);
}
[TestMethod]
public void CommandOutput()
{
var r = new Command() { CommandLine = "ls" };
Assert.AreEqual("command(ls)", r.Print());
var rp = JobParser.ParseCommand.Parse(r.Print());
Assert.AreEqual(r.CommandLine, rp.CommandLine);
}
[TestMethod]
public void SubmitOutput()
{
var r = new Submit() { SubmitCommand = new Command { CommandLine = "ls" } };
Assert.AreEqual("submit(ls)", r.Print());
var rp = JobParser.ParseSubmit.Parse(r.Print());
Assert.AreEqual(r.SubmitCommand.CommandLine, rp.SubmitCommand.CommandLine);
}
[TestMethod]
public void PackageOutput()
{
var r = new Package() { Name = "pkg", SCTag = "1231" };
Assert.AreEqual("package(pkg,1231)", r.Print());
var rp = JobParser.ParsePackage.Parse(r.Print());
Assert.AreEqual(r.Name, rp.Name);
Assert.AreEqual(r.SCTag, rp.SCTag);
}
[TestMethod]
public void JobOutput()
{
var j = new AtlasJob()
{
Commands = new Command[] { new Command() { CommandLine = "ls" } },
Name = "MyJob",
Version = 1234,
Release = new Release() { Name = "notmyrelease" },
SubmitCommand = new Submit() { SubmitCommand = new Command() { CommandLine = "submit" } },
Packages = new Package[] { new Package() { Name = "hithere", SCTag = "tag" } }
};
Assert.AreEqual("job(MyJob,1234){release(notmyrelease)package(hithere,tag)submit(submit)}", j.Print());
}
[TestMethod]
public void PrintEmptyJob()
{
var j = new AtlasJob() { Name = "hihere", Version = 10 };
var s = j.Print();
Assert.AreEqual("job(hihere,10){}", s);
}
}
}
| 33.671053 | 115 | 0.541618 | [
"MIT"
] | LHCAtlas/AtlasSSH | AtlasWorkFlowsTest/Jobs/JobPrintTest.cs | 2,561 | C# |
using Bitmex.NET.Models;
namespace Bitmex.NET
{
public class BitmexAuthorization : IBitmexAuthorization
{
public BitmexEnvironment BitmexEnvironment { get; set; }
public string Key { get; set; }
public string Secret { get; set; }
}
}
| 20.416667 | 58 | 0.730612 | [
"MIT"
] | AlexejShevchenko/Bitmex.NET | Bitmex.NET/BitmexAuthorization.cs | 247 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MiniOJ.Entity
{
public class JudgeInfo
{
public string Code { set; get; }
public string Lang { set; get; }
public string Title { set; get; }
}
}
| 19.333333 | 41 | 0.648276 | [
"MIT"
] | OmegaZhou/MiniOJ | MiniOJ/Entity/JudgeInfo.cs | 292 | C# |
using System;
using System.Collections.Generic;
namespace Zefugi.DotNet.Optimization
{
public abstract class PooledObjectBase<T> : IPooledObject
where T : class, IPooledObject, new()
{
private static readonly Queue<IPooledObject> _pool = new Queue<IPooledObject>();
public static T CreateOrReuse()
{
if (_pool.Count != 0)
return (T)_pool.Dequeue();
else
return new T();
}
public void Recycle()
{
_pool.Enqueue(this);
}
}
}
| 22.84 | 88 | 0.558669 | [
"MIT"
] | Zefugi/DotNet | Zefugi.DotNet/Zefugi.DotNet/Optimization/PooledObjectBase.cs | 573 | C# |
using NPOI.Util;
using System;
using System.Text;
namespace NPOI.HSSF.Record
{
/// <summary>
/// Section [2.4.324]. The Text record specifies the properties of an attached label and specifies the beginning of
/// a collection of records as defined by the chart sheet substream ABNF. This collection of records specifies an attached label.
/// </summary>
public class TextRecord : StandardRecord
{
public const short sid = 4133;
/// <summary>
/// Left-alignment if iReadingOrder specifies left-to-right reading order; otherwise, right-alignment
/// </summary>
public const byte HORIZONTAL_ALIGNMENT_LEFT = 1;
/// <summary>
/// Center-alignment
/// </summary>
public const byte HORIZONTAL_ALIGNMENT_CENTER = 2;
/// <summary>
/// Right-alignment if iReadingOrder specifies left-to-right reading order; otherwise, left-alignment
/// </summary>
public const byte HORIZONTAL_ALIGNMENT_BOTTOM = 3;
/// <summary>
/// Justify-alignment
/// </summary>
public const byte HORIZONTAL_ALIGNMENT_JUSTIFY = 4;
/// <summary>
/// distributed alignment
/// </summary>
public const byte HORIZONTAL_ALIGNMENT_DISTRIBUTED = 7;
public const byte VERTICAL_ALIGNMENT_TOP = 1;
public const byte VERTICAL_ALIGNMENT_CENTER = 2;
public const byte VERTICAL_ALIGNMENT_BOTTOM = 3;
public const byte VERTICAL_ALIGNMENT_JUSTIFY = 4;
/// <summary>
/// distributed alignment
/// </summary>
public const byte VERTICAL_ALIGNMENT_DISTRIBUTED = 7;
/// <summary>
/// Transparent background
/// </summary>
public const short DISPLAY_MODE_TRANSPARENT = 1;
/// <summary>
/// Opaque background
/// </summary>
public const short DISPLAY_MODE_OPAQUE = 2;
public const short ROTATION_NONE = 0;
public const short ROTATION_TOP_TO_BOTTOM = 1;
public const short ROTATION_ROTATED_90_DEGREES = 2;
public const short ROTATION_ROTATED_90_DEGREES_CLOCKWISE = 3;
public const short DATA_LABEL_PLACEMENT_CHART_DEPENDENT = 0;
public const short DATA_LABEL_PLACEMENT_OUTSIDE = 1;
public const short DATA_LABEL_PLACEMENT_INSIDE = 2;
public const short DATA_LABEL_PLACEMENT_CENTER = 3;
public const short DATA_LABEL_PLACEMENT_AXIS = 4;
public const short DATA_LABEL_PLACEMENT_ABOVE = 5;
public const short DATA_LABEL_PLACEMENT_BELOW = 6;
public const short DATA_LABEL_PLACEMENT_LEFT = 7;
public const short DATA_LABEL_PLACEMENT_RIGHT = 8;
public const short DATA_LABEL_PLACEMENT_AUTO = 9;
public const short DATA_LABEL_PLACEMENT_USER_MOVED = 10;
public const short READING_ORDER_CONTEXT = 0;
public const short READING_ORDER_LTR = 1;
public const short READING_ORDER_RTL = 2;
private byte field_1_horizontalAlignment;
private byte field_2_verticalAlignment;
private short field_3_DisplayMode;
private int field_4_rgbColor;
private int field_5_x;
private int field_6_y;
private int field_7_width;
private int field_8_height;
private short field_9_options1;
private BitField autoColor = BitFieldFactory.GetInstance(1);
private BitField showKey = BitFieldFactory.GetInstance(2);
private BitField showValue = BitFieldFactory.GetInstance(4);
private BitField autoText = BitFieldFactory.GetInstance(16);
private BitField generated = BitFieldFactory.GetInstance(32);
private BitField autoLabelDeleted = BitFieldFactory.GetInstance(64);
private BitField autoBackground = BitFieldFactory.GetInstance(128);
private BitField showCategoryLabelAsPercentage = BitFieldFactory.GetInstance(2048);
private BitField showValueAsPercentage = BitFieldFactory.GetInstance(4096);
private BitField showBubbleSizes = BitFieldFactory.GetInstance(8192);
private BitField showLabel = BitFieldFactory.GetInstance(16384);
private short field_10_IndexOfColorValue;
private short field_11_options2;
private BitField dataLabelPlacement = BitFieldFactory.GetInstance(15);
private BitField readingOrder = BitFieldFactory.GetInstance(49152);
private short field_12_textRotation;
/// Size of record (exluding 4 byte header)
protected override int DataSize => 32;
public override short Sid => 4133;
/// Get the horizontal alignment field for the Text record.
///
/// @return One of
/// HORIZONTAL_ALIGNMENT_LEFT
/// HORIZONTAL_ALIGNMENT_CENTER
/// HORIZONTAL_ALIGNMENT_BOTTOM
/// HORIZONTAL_ALIGNMENT_JUSTIFY
public byte HorizontalAlignment
{
get
{
return field_1_horizontalAlignment;
}
set
{
field_1_horizontalAlignment = value;
}
}
/// Get the vertical alignment field for the Text record.
///
/// @return One of
/// VERTICAL_ALIGNMENT_TOP
/// VERTICAL_ALIGNMENT_CENTER
/// VERTICAL_ALIGNMENT_BOTTOM
/// VERTICAL_ALIGNMENT_JUSTIFY
public byte VerticalAlignment
{
get
{
return field_2_verticalAlignment;
}
set
{
field_2_verticalAlignment = value;
}
}
/// Get the Display mode field for the Text record.
///
/// @return One of
/// DISPLAY_MODE_TRANSPARENT
/// DISPLAY_MODE_OPAQUE
public short DisplayMode
{
get
{
return field_3_DisplayMode;
}
set
{
field_3_DisplayMode = value;
}
}
/// Get the rgbColor field for the Text record.
public int RgbColor
{
get
{
return field_4_rgbColor;
}
set
{
field_4_rgbColor = value;
}
}
/// Get the x field for the Text record.
public int X
{
get
{
return field_5_x;
}
set
{
field_5_x = value;
}
}
/// Get the y field for the Text record.
public int Y
{
get
{
return field_6_y;
}
set
{
field_6_y = value;
}
}
/// Set the width field for the Text record.
public int Width
{
get
{
return field_7_width;
}
set
{
field_7_width = value;
}
}
/// Get the height field for the Text record.
public int Height
{
get
{
return field_8_height;
}
set
{
field_8_height = value;
}
}
/// Get the options1 field for the Text record.
public short Options1
{
get
{
return field_9_options1;
}
set
{
field_9_options1 = value;
}
}
/// Get the index of color value field for the Text record.
public short IndexOfColorValue
{
get
{
return field_10_IndexOfColorValue;
}
set
{
field_10_IndexOfColorValue = value;
}
}
/// Get the options2 field for the Text record.
public short Options2
{
get
{
return field_11_options2;
}
set
{
field_11_options2 = value;
}
}
/// Get the text rotation field for the Text record.
public short TextRotation
{
get
{
return field_12_textRotation;
}
set
{
field_12_textRotation = value;
}
}
/// true = automaticly selected colour, false = user-selected
/// @return the auto color field value.
public bool IsAutoColor
{
get
{
return autoColor.IsSet(field_9_options1);
}
set
{
field_9_options1 = autoColor.SetShortBoolean(field_9_options1, value);
}
}
/// true = draw legend
/// @return the show key field value.
public bool ShowKey
{
get
{
return showKey.IsSet(field_9_options1);
}
set
{
field_9_options1 = showKey.SetShortBoolean(field_9_options1, value);
}
}
/// false = text is category label
/// @return the show value field value.
public bool ShowValue
{
get
{
return showValue.IsSet(field_9_options1);
}
set
{
field_9_options1 = showValue.SetShortBoolean(field_9_options1, value);
}
}
/// @return the auto generated text field value.
public bool IsAutoGeneratedText
{
get
{
return autoText.IsSet(field_9_options1);
}
set
{
field_9_options1 = autoText.SetShortBoolean(field_9_options1, value);
}
}
/// @return the generated field value.
public bool IsGenerated
{
get
{
return generated.IsSet(field_9_options1);
}
set
{
field_9_options1 = generated.SetShortBoolean(field_9_options1, value);
}
}
/// @return the auto label deleted field value.
public bool IsAutoLabelDeleted
{
get
{
return autoLabelDeleted.IsSet(field_9_options1);
}
set
{
field_9_options1 = autoLabelDeleted.SetShortBoolean(field_9_options1, value);
}
}
/// @return the auto background field value.
public bool IsAutoBackground
{
get
{
return autoBackground.IsSet(field_9_options1);
}
set
{
field_9_options1 = autoBackground.SetShortBoolean(field_9_options1, value);
}
}
/// @return the show category label as percentage field value.
public bool ShowCategoryLabelAsPercentage
{
get
{
return showCategoryLabelAsPercentage.IsSet(field_9_options1);
}
set
{
showCategoryLabelAsPercentage.SetShortBoolean(field_9_options1, value);
}
}
/// @return the show value as percentage field value.
public bool ShowValueAsPercentage
{
get
{
return showValueAsPercentage.IsSet(field_9_options1);
}
set
{
field_9_options1 = showValueAsPercentage.SetShortBoolean(field_9_options1, value);
}
}
/// @return the show bubble sizes field value.
public bool ShowBubbleSizes
{
get
{
return showBubbleSizes.IsSet(field_9_options1);
}
set
{
field_9_options1 = showBubbleSizes.SetShortBoolean(field_9_options1, value);
}
}
/// @return the show label field value.
public bool ShowLabel
{
get
{
return showLabel.IsSet(field_9_options1);
}
set
{
field_9_options1 = showLabel.SetShortBoolean(field_9_options1, value);
}
}
/// @return the data label placement field value.
public short DataLabelPlacement
{
get
{
return dataLabelPlacement.GetShortValue(field_11_options2);
}
set
{
field_11_options2 = dataLabelPlacement.SetShortValue(field_11_options2, value);
}
}
public short ReadingOrder
{
get
{
return readingOrder.GetShortValue(field_11_options2);
}
set
{
field_11_options2 = readingOrder.SetShortValue(field_11_options2, value);
}
}
public TextRecord()
{
}
/// Constructs a Text record and Sets its fields appropriately.
///
/// @param in the RecordInputstream to Read the record from
public TextRecord(RecordInputStream in1)
{
field_1_horizontalAlignment = (byte)in1.ReadByte();
field_2_verticalAlignment = (byte)in1.ReadByte();
field_3_DisplayMode = in1.ReadShort();
field_4_rgbColor = in1.ReadInt();
field_5_x = in1.ReadInt();
field_6_y = in1.ReadInt();
field_7_width = in1.ReadInt();
field_8_height = in1.ReadInt();
field_9_options1 = in1.ReadShort();
field_10_IndexOfColorValue = in1.ReadShort();
field_11_options2 = in1.ReadShort();
field_12_textRotation = in1.ReadShort();
}
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("[TEXT]\n");
stringBuilder.Append(" .horizontalAlignment = ").Append("0x").Append(HexDump.ToHex(HorizontalAlignment))
.Append(" (")
.Append(HorizontalAlignment)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .verticalAlignment = ").Append("0x").Append(HexDump.ToHex(VerticalAlignment))
.Append(" (")
.Append(VerticalAlignment)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .DisplayMode = ").Append("0x").Append(HexDump.ToHex(DisplayMode))
.Append(" (")
.Append(DisplayMode)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .rgbColor = ").Append("0x").Append(HexDump.ToHex(RgbColor))
.Append(" (")
.Append(RgbColor)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .x = ").Append("0x").Append(HexDump.ToHex(X))
.Append(" (")
.Append(X)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .y = ").Append("0x").Append(HexDump.ToHex(Y))
.Append(" (")
.Append(Y)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .width = ").Append("0x").Append(HexDump.ToHex(Width))
.Append(" (")
.Append(Width)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .height = ").Append("0x").Append(HexDump.ToHex(Height))
.Append(" (")
.Append(Height)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .options1 = ").Append("0x").Append(HexDump.ToHex(Options1))
.Append(" (")
.Append(Options1)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .autoColor = ").Append(IsAutoColor).Append('\n');
stringBuilder.Append(" .showKey = ").Append(ShowKey).Append('\n');
stringBuilder.Append(" .showValue = ").Append(ShowValue).Append('\n');
stringBuilder.Append(" .autoGeneratedText = ").Append(IsAutoGeneratedText).Append('\n');
stringBuilder.Append(" .generated = ").Append(IsGenerated).Append('\n');
stringBuilder.Append(" .autoLabelDeleted = ").Append(IsAutoLabelDeleted).Append('\n');
stringBuilder.Append(" .autoBackground = ").Append(IsAutoBackground).Append('\n');
stringBuilder.Append(" .showCategoryLabelAsPercentage = ").Append(ShowCategoryLabelAsPercentage).Append('\n');
stringBuilder.Append(" .showValueAsPercentage = ").Append(ShowValueAsPercentage).Append('\n');
stringBuilder.Append(" .showBubbleSizes = ").Append(ShowBubbleSizes).Append('\n');
stringBuilder.Append(" .showLabel = ").Append(ShowLabel).Append('\n');
stringBuilder.Append(" .IndexOfColorValue = ").Append("0x").Append(HexDump.ToHex(IndexOfColorValue))
.Append(" (")
.Append(IndexOfColorValue)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .options2 = ").Append("0x").Append(HexDump.ToHex(Options2))
.Append(" (")
.Append(Options2)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(" .dataLabelPlacement = ").Append(DataLabelPlacement).Append('\n');
stringBuilder.Append(" .readingOrder = ").Append(ReadingOrder).Append('\n');
stringBuilder.Append(" .textRotation = ").Append("0x").Append(HexDump.ToHex(TextRotation))
.Append(" (")
.Append(TextRotation)
.Append(" )");
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append("[/TEXT]\n");
return stringBuilder.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteByte(field_1_horizontalAlignment);
out1.WriteByte(field_2_verticalAlignment);
out1.WriteShort(field_3_DisplayMode);
out1.WriteInt(field_4_rgbColor);
out1.WriteInt(field_5_x);
out1.WriteInt(field_6_y);
out1.WriteInt(field_7_width);
out1.WriteInt(field_8_height);
out1.WriteShort(field_9_options1);
out1.WriteShort(field_10_IndexOfColorValue);
out1.WriteShort(field_11_options2);
out1.WriteShort(field_12_textRotation);
}
public override object Clone()
{
TextRecord textRecord = new TextRecord();
textRecord.field_1_horizontalAlignment = field_1_horizontalAlignment;
textRecord.field_2_verticalAlignment = field_2_verticalAlignment;
textRecord.field_3_DisplayMode = field_3_DisplayMode;
textRecord.field_4_rgbColor = field_4_rgbColor;
textRecord.field_5_x = field_5_x;
textRecord.field_6_y = field_6_y;
textRecord.field_7_width = field_7_width;
textRecord.field_8_height = field_8_height;
textRecord.field_9_options1 = field_9_options1;
textRecord.field_10_IndexOfColorValue = field_10_IndexOfColorValue;
textRecord.field_11_options2 = field_11_options2;
textRecord.field_12_textRotation = field_12_textRotation;
return textRecord;
}
}
}
| 25.488994 | 130 | 0.67997 | [
"MIT"
] | iNeverSleeeeep/NPOI-For-Unity | NPOI.HSSF.Record/TextRecord.cs | 16,211 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
#nullable disable
namespace ScaffoldingTester.Models
{
public partial class Invoice
{
public string ShipName { get; set; }
public string ShipAddress { get; set; }
public string ShipCity { get; set; }
public string ShipRegion { get; set; }
public string ShipPostalCode { get; set; }
public string ShipCountry { get; set; }
public string CustomerId { get; set; }
public string CustomerName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Salesperson { get; set; }
public int OrderId { get; set; }
public DateTime? OrderDate { get; set; }
public DateTime? RequiredDate { get; set; }
public DateTime? ShippedDate { get; set; }
public string ShipperName { get; set; }
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
public short Quantity { get; set; }
public float Discount { get; set; }
public decimal? ExtendedPrice { get; set; }
public decimal? Freight { get; set; }
}
} | 38.421053 | 96 | 0.614384 | [
"MIT"
] | ErikEJ/EFCorePowerTools | test/ScaffoldingTester/ScaffoldingTester5/Models/Invoice.cs | 1,462 | C# |
//-------------------------------------------------------------------
// Copyright © 2012 Kindel Systems, LLC
// http://www.kindel.com
// charlie@kindel.com
//
// Published under the MIT License.
// Source control on SourceForge
// http://sourceforge.net/projects/mcecontroller/
//-------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Resources;
using System.Windows.Forms;
using MCEControl.Properties;
using Microsoft.Win32.Security;
using log4net;
using log4net.Repository.Hierarchy;
using log4net.Core;
using log4net.Appender;
using log4net.Layout;
namespace MCEControl
{
/// <summary>
/// Summary description for MainWindow.
/// </summary>
public class MainWindow : Form
{
// Used to enabled access to AddLogEntry
public static MainWindow MainWnd;
public CommandTable CmdTable;
private log4net.ILog _log4;
// Persisted application settings
public AppSettings Settings;
// Protocol objects
private SocketServer _server;
private SocketClient _client;
private SerialServer _serialServer;
// Indicates whether user hit the close box (minimize)
// or the app is exiting
private bool _shuttingDown;
private CommandWindow _cmdWindow;
// Window controls
private MainMenu _mainMenu;
private MenuItem _menuItemFileMenu;
private MenuItem _menuItemExit;
private MenuItem _menuItemHelpMenu;
private MenuItem _menuItemAbout;
private StatusBar _statusBar;
private NotifyIcon _notifyIcon;
private TextBox _log;
private ContextMenu _notifyMenu;
private MenuItem _notifyMenuItemExit;
private IContainer components;
private MenuItem _menuItemSendAwake;
private MenuItem _menuSeparator2;
private MenuItem _menuSeparator1;
private MenuItem _menuSettings;
private MenuItem _menuSeparator5;
private MenuItem _notifyMenuItemSettings;
private MenuItem _menuSeparator4;
private MenuItem _notifyMenuViewStatus;
private MenuItem _menuItemHelp;
private MenuItem _menuItemSupport;
private MenuItem _menuItemEditCommands;
private MenuItem menuItem2;
private MenuItem menuItem1;
private MenuItem _menuItemCheckVersion;
public SocketClient Client
{
get { return _client; }
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main(string[] args)
{
if (!IsNet45OrNewer())
{
MessageBox.Show(
"MCE Controller requires .NET Framework 4.5 or newer.\r\n\r\nDownload and install from http://www.microsoft.com/net/");
return;
}
MainWnd = new MainWindow();
Application.Run(MainWnd);
}
public static bool IsNet45OrNewer()
{
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
public MainWindow()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
_notifyIcon.Icon = Icon;
// Load AppSettings
Settings = AppSettings.Deserialize(AppSettings.GetSettingsPath());
ShowInTaskbar = true;
SetStatusBar("");
_menuItemSendAwake.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
// When the app exits we need to un-shift any modify keys that might
// have been pressed or they'll still be stuck after exit
SendInputCommand.ShiftKey("shift", false);
SendInputCommand.ShiftKey("ctrl", false);
SendInputCommand.ShiftKey("alt", false);
SendInputCommand.ShiftKey("lwin", false);
SendInputCommand.ShiftKey("rwin", false);
if (components != null)
{
components.Dispose();
}
if (_server != null)
{
// remove our notification handler
_server.Notifications -= HandleSocketServerCallbacks;
_server.Dispose();
}
if (_client != null)
{
// remove our notification handler
_client.Notifications -= HandleClientNotifications;
_client.Dispose();
}
if (_serialServer != null)
{
_serialServer.Notifications -= HandleSerialServerNotifications;
_serialServer.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow));
this._mainMenu = new System.Windows.Forms.MainMenu(this.components);
this._menuItemFileMenu = new System.Windows.Forms.MenuItem();
this._menuItemSendAwake = new System.Windows.Forms.MenuItem();
this._menuSeparator1 = new System.Windows.Forms.MenuItem();
this._menuItemEditCommands = new System.Windows.Forms.MenuItem();
this._menuSeparator2 = new System.Windows.Forms.MenuItem();
this._menuItemExit = new System.Windows.Forms.MenuItem();
this._menuSettings = new System.Windows.Forms.MenuItem();
this._menuItemHelpMenu = new System.Windows.Forms.MenuItem();
this._menuItemHelp = new System.Windows.Forms.MenuItem();
this._menuItemSupport = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this._menuItemCheckVersion = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this._menuItemAbout = new System.Windows.Forms.MenuItem();
this._statusBar = new System.Windows.Forms.StatusBar();
this._notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
this._notifyMenu = new System.Windows.Forms.ContextMenu();
this._notifyMenuViewStatus = new System.Windows.Forms.MenuItem();
this._menuSeparator4 = new System.Windows.Forms.MenuItem();
this._notifyMenuItemSettings = new System.Windows.Forms.MenuItem();
this._menuSeparator5 = new System.Windows.Forms.MenuItem();
this._notifyMenuItemExit = new System.Windows.Forms.MenuItem();
this._log = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// _mainMenu
//
this._mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._menuItemFileMenu,
this._menuSettings,
this._menuItemHelpMenu});
//
// _menuItemFileMenu
//
this._menuItemFileMenu.Index = 0;
this._menuItemFileMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._menuItemSendAwake,
this._menuSeparator1,
this._menuItemEditCommands,
this._menuSeparator2,
this._menuItemExit});
this._menuItemFileMenu.Text = "&File";
//
// _menuItemSendAwake
//
this._menuItemSendAwake.Index = 0;
this._menuItemSendAwake.Text = "Send &Awake Signal";
this._menuItemSendAwake.Click += new System.EventHandler(this.MenuItemSendAwakeClick);
//
// _menuSeparator1
//
this._menuSeparator1.Index = 1;
this._menuSeparator1.Text = "-";
//
// _menuItemEditCommands
//
this._menuItemEditCommands.Index = 2;
this._menuItemEditCommands.Text = "&Open .commands file location...";
this._menuItemEditCommands.Click += new System.EventHandler(this.MenuItemEditCommandsClick);
//
// _menuSeparator2
//
this._menuSeparator2.Index = 3;
this._menuSeparator2.Text = "-";
//
// _menuItemExit
//
this._menuItemExit.Index = 4;
this._menuItemExit.Text = "E&xit";
this._menuItemExit.Click += new System.EventHandler(this.MenuItemExitClick);
//
// _menuSettings
//
this._menuSettings.Index = 1;
this._menuSettings.Text = "&Settings";
this._menuSettings.Click += new System.EventHandler(this.MenuSettingsClick);
//
// _menuItemHelpMenu
//
this._menuItemHelpMenu.Index = 2;
this._menuItemHelpMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._menuItemHelp,
this._menuItemSupport,
this.menuItem2,
this._menuItemCheckVersion,
this.menuItem1,
this._menuItemAbout});
this._menuItemHelpMenu.Text = "&Help";
//
// _menuItemHelp
//
this._menuItemHelp.Index = 0;
this._menuItemHelp.Shortcut = System.Windows.Forms.Shortcut.F1;
this._menuItemHelp.Text = "&Documentation...";
this._menuItemHelp.Click += new System.EventHandler(this.MenuItemHelpClick);
//
// _menuItemSupport
//
this._menuItemSupport.Index = 1;
this._menuItemSupport.Text = "&Get Support...";
this._menuItemSupport.Click += new System.EventHandler(this.MenuItemSupportClick);
//
// menuItem2
//
this.menuItem2.Index = 2;
this.menuItem2.Text = "-";
//
// _menuItemCheckVersion
//
this._menuItemCheckVersion.Index = 3;
this._menuItemCheckVersion.Text = "&Check for a newer version";
this._menuItemCheckVersion.Click += new System.EventHandler(this.menuItemCheckVersion_Click);
//
// menuItem1
//
this.menuItem1.Index = 4;
this.menuItem1.Text = "-";
//
// _menuItemAbout
//
this._menuItemAbout.Index = 5;
this._menuItemAbout.Text = "&About MCE Controller";
this._menuItemAbout.Click += new System.EventHandler(this.MenuItemAboutClick);
//
// _statusBar
//
this._statusBar.Location = new System.Drawing.Point(0, 85);
this._statusBar.Name = "_statusBar";
this._statusBar.Size = new System.Drawing.Size(368, 29);
this._statusBar.TabIndex = 0;
//
// _notifyIcon
//
this._notifyIcon.ContextMenu = this._notifyMenu;
this._notifyIcon.Text = global::MCEControl.Properties.Resources.App_FullName;
this._notifyIcon.Visible = true;
this._notifyIcon.DoubleClick += new System.EventHandler(this.NotifyIconDoubleClick);
//
// _notifyMenu
//
this._notifyMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this._notifyMenuViewStatus,
this._menuSeparator4,
this._notifyMenuItemSettings,
this._menuSeparator5,
this._notifyMenuItemExit});
//
// _notifyMenuViewStatus
//
this._notifyMenuViewStatus.Index = 0;
this._notifyMenuViewStatus.Text = "&View Status...";
this._notifyMenuViewStatus.Click += new System.EventHandler(this.NotifyIconDoubleClick);
//
// _menuSeparator4
//
this._menuSeparator4.Index = 1;
this._menuSeparator4.Text = "-";
//
// _notifyMenuItemSettings
//
this._notifyMenuItemSettings.Index = 2;
this._notifyMenuItemSettings.Text = "&Settings...";
this._notifyMenuItemSettings.Click += new System.EventHandler(this.MenuSettingsClick);
//
// _menuSeparator5
//
this._menuSeparator5.Index = 3;
this._menuSeparator5.Text = "-";
//
// _notifyMenuItemExit
//
this._notifyMenuItemExit.Index = 4;
this._notifyMenuItemExit.Text = "&Exit";
this._notifyMenuItemExit.Click += new System.EventHandler(this.MenuItemExitClick);
//
// _log
//
this._log.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._log.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._log.Location = new System.Drawing.Point(0, 0);
this._log.Multiline = true;
this._log.Name = "_log";
this._log.Size = new System.Drawing.Size(368, 89);
this._log.TabIndex = 1;
this._log.WordWrap = false;
this._log.TextChanged += new System.EventHandler(this.LogTextChanged);
this._log.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.LogKeyPress);
//
// MainWindow
//
this.AutoScaleBaseSize = new System.Drawing.Size(8, 19);
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(368, 114);
this.Controls.Add(this._log);
this.Controls.Add(this._statusBar);
this.HelpButton = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Menu = this._mainMenu;
this.MinimizeBox = false;
this.Name = "MainWindow";
this.Text = "MCE Controller";
this.HelpButtonClicked += new System.ComponentModel.CancelEventHandler(this.MainWindow_HelpButtonClicked);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainWindowClosing);
this.Load += new System.EventHandler(this.MainWindowLoad);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
protected override void WndProc(ref Message m)
{
// If the session is being logged off, or the machine is shutting
// down...
if (m.Msg == 0x11) // WM_QUERYENDSESSION
{
// Allow shut down (m.Result may already be non-zero, but I set it
// just in case)
m.Result = (IntPtr)1;
// Indicate to MainWindow_Closing() that we are shutting down;
// otherwise it will just minimize to the tray
_shuttingDown = true;
}
base.WndProc(ref m);
}
private void MainWindowLoad(object sender, EventArgs e)
{
CheckVersion();
// Location can not be changed in constructor, has to be done here
Location = Settings.WindowLocation;
Size = Settings.WindowSize;
CmdTable = CommandTable.Deserialize(Settings.DisableInternalCommands);
if (CmdTable == null)
{
MessageBox.Show(this, Resources.MCEController_commands_read_error, Resources.App_FullName);
_notifyIcon.Visible = false;
Opacity = 100;
}
else
{
AddLogEntry("MCEC: " + CmdTable.CommandCount + " commands available.");
Opacity = (double)Settings.Opacity / 100;
if (Settings.HideOnStartup)
{
Opacity = 0;
Win32.PostMessage(Handle, (UInt32)WM.SYSCOMMAND, (UInt32)SC.CLOSE, 0);
}
}
if (_cmdWindow == null)
_cmdWindow = new CommandWindow();
//_cmdWindow.Visible = Settings.ShowCommandWindow;
//var t = new System.Timers.Timer() {
// AutoReset = false,
// Interval = 2000
//};
//t.Elapsed += (sender, args) => Start();
//AddLogEntry("Starting services...");
//t.Start();
Start();
}
private void MainWindowClosing(object sender, CancelEventArgs e)
{
if (!_shuttingDown)
{
// If we're NOT shutting down (the user hit the close button or pressed
// CTRL-F4) minimize to tray.
e.Cancel = true;
// Hide the form and make sure the taskbar icon is visible
_notifyIcon.Visible = true;
Hide();
}
}
private void CheckVersion()
{
AddLogEntry(string.Format("MCEC: Version: {0}", Application.ProductVersion));
var lv = new LatestVersion();
lv.GetLatestStableVersionAsync((o, version) =>
{
if (version == null && !string.IsNullOrWhiteSpace(lv.ErrorMessage))
{
AddLogEntry(
string.Format(
"MCEC: Could not access mcec.codeplex.com to see if a newer version is available. {0}",
lv.ErrorMessage));
}
else if (lv.CompareVersions() < 0)
{
AddLogEntry(
string.Format(
"MCEC: A newer version of MCE Controller ({0}) is available at mcec.codeplex.com.", version));
}
else if (lv.CompareVersions() > 0)
{
AddLogEntry(
string.Format(
"MCEC: You are are running a MORE recent version than can be found at mcec.codeplex.com ({0}).",
version));
}
else
{
AddLogEntry("MCEC: You are running the most recent version of MCE Controller.");
}
});
}
private void Start()
{
if (Settings.ActAsServer)
StartServer();
if (Settings.ActAsSerialServer)
StartSerialServer();
if (Settings.ActAsClient)
StartClient();
}
public void ShutDown()
{
AddLogEntry("ShutDown");
_shuttingDown = true;
// hide icon from the systray
_notifyIcon.Visible = false;
StopServer();
StopClient();
StopSerialServer();
// Prevent access to the static MainWnd
MainWnd = null;
// Save the window size/location
Settings.WindowLocation = Location;
Settings.WindowSize = Size;
Settings.Serialize();
Close();
Application.Exit();
}
private void StartServer()
{
if (_server == null)
{
_server = new SocketServer();
_server.Notifications += HandleSocketServerCallbacks;
_server.Start(Settings.ServerPort);
_menuItemSendAwake.Enabled = Settings.WakeupEnabled;
}
else
AddLogEntry("MCEC: Attempt to StartServer() while an instance already exists!");
}
private void StopServer()
{
if (_server != null)
{
// remove our notification handler
_server.Stop();
_server = null;
_menuItemSendAwake.Enabled = false;
}
}
private void StartSerialServer()
{
if (_serialServer == null)
{
_serialServer = new SerialServer();
_serialServer.Notifications += HandleSerialServerNotifications;
_serialServer.Start(Settings.SerialServerPortName,
Settings.SerialServerBaudRate,
Settings.SerialServerParity,
Settings.SerialServerDataBits,
Settings.SerialServerStopBits,
Settings.SerialServerHandshake);
}
else
AddLogEntry("MCEC: Attempt to StartSerialServer() while an instance already exists!");
}
private void StopSerialServer()
{
if (_serialServer != null)
{
// remove our notification handler
_serialServer.Stop();
_serialServer = null;
}
}
private void StartClient(bool delay = false)
{
if (_client == null)
{
_client = new SocketClient(Settings);
_client.Notifications += HandleClientNotifications;
_client.Start(delay);
}
}
private void StopClient()
{
if (_client != null)
{
_cmdWindow.Visible = false;
AddLogEntry("Client: Stopping...");
_client.Stop();
_client = null;
}
}
private delegate void RestartClientCallback();
private void RestartClient()
{
if (_cmdWindow != null)
{
if (this.InvokeRequired)
this.BeginInvoke((RestartClientCallback)RestartClient);
else
{
StopClient();
if (!_shuttingDown && Settings.ActAsClient)
{
AddLogEntry("Client: Reconnecting...");
StartClient(true);
}
}
}
}
private delegate void ShowCommandWindowCallback();
private void ShowCommandWindow()
{
if (this.InvokeRequired)
this.BeginInvoke((ShowCommandWindowCallback)ShowCommandWindow);
else
{
_cmdWindow.Visible = Settings.ShowCommandWindow;
}
}
private delegate void HideCommandWindowCallback();
private void HideCommandWindow()
{
if (this.InvokeRequired)
this.BeginInvoke((HideCommandWindowCallback)HideCommandWindow);
else
{
_cmdWindow.Visible = false;
}
}
private void ReceivedData(Reply reply, string cmd)
{
try
{
CmdTable.Execute(reply, cmd);
}
catch (Exception e)
{
AddLogEntry(string.Format("Command: ({0}) error: {1}", cmd, e));
}
}
private delegate void SetStatusBarCallback(string text);
private void SetStatusBar(string text)
{
if (_statusBar.InvokeRequired)
{
_statusBar.BeginInvoke((SetStatusBarCallback)SetStatusBar, new object[] { text });
}
else
{
_statusBar.Text = text;
_notifyIcon.Text = text;
}
}
//
// Notify callback for the TCP/IP Server
//
public void HandleSocketServerCallbacks(ServiceNotification notification, ServiceStatus status, Reply reply, string msg)
{
if (notification == ServiceNotification.StatusChange)
HandleSocketServerStatusChange(status);
else
HandleSocketServerNotification(notification, status, (SocketServer.ServerReplyContext)reply, msg);
}
private void HandleSocketServerNotification(ServiceNotification notification, ServiceStatus status,
SocketServer.ServerReplyContext serverReplyContext, string msg)
{
string s = "";
switch (notification)
{
case ServiceNotification.ReceivedData:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Server: Received from Client #{0} at {1}: {2}",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint, msg);
AddLogEntry(s);
ReceivedData(serverReplyContext, msg);
return;
case ServiceNotification.Write:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Wrote to Client #{0} at {1}: {2}",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint, msg);
break;
case ServiceNotification.WriteFailed:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Write failed to Client #{0} at {1}: {2}",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint, msg);
break;
case ServiceNotification.ClientConnected:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Client #{0} at {1} connected.",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint);
break;
case ServiceNotification.ClientDisconnected:
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null, notification.ToString());
s = string.Format("Client #{0} at {1} has disconnected.",
serverReplyContext.ClientNumber, serverReplyContext.Socket.RemoteEndPoint);
break;
case ServiceNotification.Wakeup:
s = "Wakeup: " + (string)msg;
break;
case ServiceNotification.Error:
switch (status)
{
case ServiceStatus.Waiting:
case ServiceStatus.Stopped:
case ServiceStatus.Sleeping:
s = string.Format("{0}: {1}", status, msg);
break;
case ServiceStatus.Connected:
if (serverReplyContext != null)
{
Debug.Assert(serverReplyContext.Socket != null);
Debug.Assert(serverReplyContext.Socket.RemoteEndPoint != null);
s = string.Format("(Client #{0} at {1}): {2}",
serverReplyContext.ClientNumber,
serverReplyContext.Socket == null
? "n/a"
: serverReplyContext.Socket.RemoteEndPoint.ToString(),
msg);
}
else
s = msg;
break;
}
s = "Error " + s;
break;
default:
s = "Unknown notification: " + notification;
break;
}
AddLogEntry("Server: " + s);
}
private void HandleSocketServerStatusChange(ServiceStatus status)
{
string s = "";
switch (status)
{
case ServiceStatus.Started:
s = "Starting TCP/IP Server on port " + Settings.ServerPort;
SetStatusBar(s);
if (Settings.WakeupEnabled)
_server.SendAwakeCommand(Settings.WakeupCommand, Settings.WakeupHost,
Settings.WakeupPort);
break;
case ServiceStatus.Waiting:
s = "Waiting for a client to connect";
break;
case ServiceStatus.Connected:
SetStatusBar("Clients connected, waiting for commands...");
return;
case ServiceStatus.Stopped:
s = "Stopped.";
SetStatusBar("Client/Sever Not Active");
if (Settings.WakeupEnabled)
_server.SendAwakeCommand(Settings.ClosingCommand, Settings.WakeupHost,
Settings.WakeupPort);
break;
}
AddLogEntry("Server: " + s);
}
//
// Notify callback for the TCP/IP Client
//
public void HandleClientNotifications(ServiceNotification notify, ServiceStatus status, Reply reply, string msg)
{
string s = null;
switch (notify)
{
case ServiceNotification.StatusChange:
if (status == ServiceStatus.Started)
{
s = "Connecting to " + Settings.ClientHost + ":" + Settings.ClientPort;
SetStatusBar(s);
HideCommandWindow();
}
else if (status == ServiceStatus.Connected)
{
s = "Connected to " + Settings.ClientHost + ":" + Settings.ClientPort;
SetStatusBar(s);
ShowCommandWindow();
}
else if (status == ServiceStatus.Stopped)
{
s = "Stopped.";
SetStatusBar("Client/Sever Not Active");
HideCommandWindow();
}
else if (status == ServiceStatus.Sleeping)
{
s = "Waiting " + (Settings.ClientDelayTime / 1000) +
" seconds to connect.";
SetStatusBar(s);
HideCommandWindow();
}
break;
case ServiceNotification.ReceivedData:
AddLogEntry(string.Format("Client: Received; {0}", msg));
ReceivedData(reply, (string)msg);
return;
case ServiceNotification.Error:
AddLogEntry("Client: Error; " + (string)msg);
RestartClient();
return;
default:
s = "Unknown notification";
break;
}
AddLogEntry("Client: " + s);
}
//
// Notify callback for the Serial Server
//
public void HandleSerialServerNotifications(ServiceNotification notify, ServiceStatus status, Reply reply, string msg)
{
string s = null;
switch (notify)
{
case ServiceNotification.StatusChange:
switch (status)
{
case ServiceStatus.Started:
s = string.Format("SerialServer: Opening port: {0}", msg);
break;
case ServiceStatus.Waiting:
s = string.Format("SerialServer: Waiting for commands on {0}...", msg);
SetStatusBar("Waiting for Serial commands...");
break;
case ServiceStatus.Stopped:
s = "SerialServer: Stopped.";
SetStatusBar("Serial Server Not Active");
break;
}
break;
case ServiceNotification.ReceivedData:
AddLogEntry(string.Format("SerialServer: Received: {0}", msg));
ReceivedData(reply, (string)msg);
return;
case ServiceNotification.Error:
s = string.Format("SerialServer: Error: {0}", msg);
break;
default:
s = "SerialServer: Unknown notification";
break;
}
AddLogEntry(s);
}
public static void AddLogEntry(string text)
{
if (MainWnd == null) return;
if (MainWnd._log4 == null)
{
string logFile = Environment.CurrentDirectory + @"\MCEControl.log";
if (Environment.CurrentDirectory.Contains("Program Files (x86)"))
logFile = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Kindel Systems\MCE Controller\MCEControl.log";
Logger.Setup(logFile);
MainWnd._log4 = log4net.LogManager.GetLogger("MCEControl");
AddLogEntry("MCEC: Log file being written to " + logFile);
}
MainWnd._log4.Info(text);
// Can only update the log in the main window when on the UI thread
if (MainWnd.InvokeRequired || MainWnd._log.InvokeRequired)
MainWnd.BeginInvoke((AddLogEntryUiThreadCallback)AddLogEntryUiThread, new object[] { text });
else
{
AddLogEntryUiThread(text);
}
}
private delegate void AddLogEntryUiThreadCallback(string text);
private static void AddLogEntryUiThread(string text)
{
MainWnd._log.AppendText("[" + DateTime.Now.ToString("yy'-'MM'-'dd' 'HH':'mm':'ss") + "] " + text +
Environment.NewLine);
}
private void MenuItemExitClick(object sender, EventArgs e)
{
ShutDown();
}
private void NotifyIconDoubleClick(object sender, EventArgs e)
{
// Show the form when the user double clicks on the notify icon.
// Set the WindowState to normal if the form is minimized.
if (WindowState == FormWindowState.Minimized)
WindowState = FormWindowState.Normal;
// Activate the form.
_notifyIcon.Visible = false;
Activate();
Show();
Opacity = (double)Settings.Opacity / 100;
}
private void MenuItemAboutClick(object sender, EventArgs e)
{
var a = new AboutBox();
a.ShowDialog(this);
}
private void MenuSettingsClick(object sender, EventArgs e)
{
var d = new SettingsDialog(Settings);
if (d.ShowDialog(this) == DialogResult.OK)
{
Settings = d.Settings;
Opacity = (double)Settings.Opacity / 100;
RestartClient();
StopServer();
StopSerialServer();
if (Settings.ActAsServer)
StartServer();
if (Settings.ActAsSerialServer)
StartSerialServer();
if (Settings.ActAsClient)
{
StartClient();
}
}
}
// Prevent input into the edit box
private void LogKeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
// Keep the end of the log visible and prevent it from overflowing
private void LogTextChanged(object sender, EventArgs e)
{
// We don't want to overrun the size a textbox can handle
// limit to 16k
if (_log.TextLength > (16 * 1024))
{
_log.Text = _log.Text.Remove(0, _log.Text.IndexOf("\r\n", StringComparison.Ordinal) + 2);
_log.Select(_log.TextLength, 0);
}
_log.ScrollToCaret();
}
private void MenuItemSendAwakeClick(object sender, EventArgs e)
{
_server.SendAwakeCommand(Settings.WakeupCommand, Settings.WakeupHost, Settings.WakeupPort);
}
private void MenuItemHelpClick(object sender, EventArgs e)
{
Process.Start("http://mcec.codeplex.com/documentation/");
}
private void MenuItemSupportClick(object sender, EventArgs e)
{
Process.Start("http://mcec.codeplex.com/discussions/");
}
private void MenuItemEditCommandsClick(object sender, EventArgs e)
{
Process.Start(Application.StartupPath);
}
private void MainWindow_HelpButtonClicked(object sender, CancelEventArgs e)
{
Process.Start("http://mcec.codeplex.com/documentation/");
}
private void menuItemCheckVersion_Click(object sender, EventArgs e)
{
CheckVersion();
}
}
public class Logger
{
public static void Setup(string logFile)
{
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date %-5level - %message%newline";
patternLayout.ActivateOptions();
RollingFileAppender roller = new RollingFileAppender
{
AppendToFile = true,
Layout = patternLayout,
MaxSizeRollBackups = 5,
MaximumFileSize = "100KB",
RollingStyle = RollingFileAppender.RollingMode.Size,
StaticLogFileName = true,
File = logFile
};
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
//MemoryAppender memory = new MemoryAppender();
//memory.ActivateOptions();
//hierarchy.Root.AddAppender(memory);
var debugAppender = new ConsoleAppender { Layout = patternLayout };
debugAppender.ActivateOptions();
hierarchy.Root.AddAppender(debugAppender);
hierarchy.Root.Level = Level.All;
hierarchy.Configured = true;
}
}
}
| 38.634816 | 161 | 0.510762 | [
"MIT"
] | jgus/mce-controller | MainWindow.cs | 40,838 | C# |
using UnityEngine;
using System.Collections;
public class Weapon
{
public GunType weaponType;
public float bulletSpeed;
public float shootCD;
public string bulletResPath;
public string propsResPath;
}
public class WeaponSystem : MonoBehaviour, ISystem {
#region ISystem implementation
public void Init ()
{
}
public void Reset ()
{
}
public void LogicUpdate ()
{
if (m_currWeapon == null)
{
return;
}
if (Input.GetMouseButton(0))
{
if (Time.time - previousShootTime >= m_currWeapon.shootCD)
{
previousShootTime = Time.time;
Shoot();
}
}
}
private GameObject m_bulletPrefab;
private Transform m_shootPointTr;
void Shoot()
{
Debug.Log("shoot");
if (m_shootPointTr == null)
{
var playerObj = GameObject.FindWithTag("Player");
m_shootPointTr = playerObj.transform.Find("ShootPoint");
}
var startPos = m_shootPointTr.position;
var dir = m_shootPointTr.forward;
var bulletObj = GameObject.Instantiate(m_bulletPrefab);
var bullet = bulletObj.GetComponent<Bullet>();
bullet.speed = m_currWeapon.bulletSpeed;
bullet.transform.position = startPos;
bullet.transform.forward = dir;
}
public void Release ()
{
}
#endregion
private Weapon m_currWeapon = null;
public Weapon CurrentWeapon
{
get
{
return m_currWeapon;
}
}
public void SetCurrentWeapon(Weapon w)
{
if (m_currWeapon != null)
{
DropCurrentWeapon();
}
m_currWeapon = w;
RefreshCD();
var bulletPath = m_currWeapon.bulletResPath;
m_bulletPrefab = Resources.Load(bulletPath) as GameObject;
if (m_bulletPrefab == null)
{
Debug.LogError("prefab is null:" + bulletPath);
}
}
private float previousShootTime = float.MinValue;
void RefreshCD()
{
previousShootTime = float.MinValue;
}
void DropCurrentWeapon()
{
var p = m_currWeapon.propsResPath;
var prefab = Resources.Load(p);
var obj = GameObject.Instantiate(prefab) as GameObject;
var player = GameObject.FindGameObjectWithTag("Player");
obj.transform.position = player.transform.position - player.transform.forward * 1f;
}
}
| 17.355372 | 85 | 0.70381 | [
"Apache-2.0"
] | xclouder/topdown_shooter_demo | Assets/Scripts/Systems/WeaponSystem.cs | 2,102 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wbs.Everdigm.Database;
namespace Wbs.Everdigm.BLL
{
public class AppBLL : BaseService<TB_Application>
{
public AppBLL() : base(new BaseRepository<TB_Application>())
{
}
public override TB_Application GetObject()
{
return new TB_Application()
{
id = 0,
Useable = false,
CreateTime = DateTime.Now,
Description_en = "",
Description_zh = "",
Download = "",
InternalVersion = 0,
VersionCode = 0,
VersionName = ""
};
}
public override string ToString(TB_Application entity)
{
return string.Format("versionCode: {0}, versionName: {1}, internalVersion: {3}", entity.VersionCode, entity.VersionName, entity.InternalVersion);
}
}
}
| 26.864865 | 157 | 0.541247 | [
"Apache-2.0"
] | wanbangsoftware/Everdigm | Wbs.Everdigm.Web/Wbs.Everdigm.BLL/AppBLL.cs | 996 | C# |
using System;
using System.IO;
using System.Text;
namespace SharpDiff.Formatter
{
public class HtmlFormatter : BaseFormatter
{
private readonly string _outputPath;
public HtmlFormatter(string outputPath)
{
_outputPath = outputPath;
}
public override void Execute(Diff diff)
{
var html = new StringBuilder();
html.AppendLine("<html>");
html.AppendLine("<head>");
html.AppendLine(" <style>");
html.AppendLine(" .created { color: #006400; }");
html.AppendLine(" .deleted { color: #8B0000; }");
html.AppendLine(" table { border: 1px solid #D3D3D3; border-collapse:collapse; }");
html.AppendLine(" td { border-left: 1px solid #D3D3D3; border-right: 1px solid #D3D3D3; }");
html.AppendLine(" tr { color: #141414; }");
html.AppendLine(" tr.section { color: #A9A9A9; background-color: #D3D3D3; }");
html.AppendLine(" tr.addition { color: #000000; background-color: #90EE90; }");
html.AppendLine(" tr.deletion { color: #8B0000; background-color: #FFB6C1; }");
html.AppendLine(" td.lineNumber { color: #A9A9A9; }");
html.AppendLine(" </style>");
html.AppendLine("</head>");
html.AppendLine("<body>");
if (!String.IsNullOrEmpty(Title))
{
html.AppendLine(String.Format("<h1>{0}</h1>", Title));
}
if (!String.IsNullOrEmpty(Summary))
{
html.AppendLine(String.Format("<div class\"summary\">{0}</div>", Summary));
}
foreach (var file in diff.Files)
{
var className = "";
if (file.FileChangeType == FileChangeType.Deleted)
{
className = "deleted";
}
else if (file.FileChangeType == FileChangeType.Created)
{
className = "created";
}
html.AppendLine(" <h2 class=\"" + className + "\">" + file.FileName + "</h2>");
if (file.FileChangeType == FileChangeType.Deleted)
{
if (!ShowDeletedFileContents)
{
html.AppendLine(" <div class=\"" + className + "\">[File Deleted]</div>");
continue;
}
}
if (file.FileChangeType == FileChangeType.Created)
{
if (!ShowCreatedFileContents)
{
html.AppendLine(" <div class=\"" + className + "\">[New File]</div>");
continue;
}
}
html.AppendLine(" <table width=\"100%\">");
foreach (var section in file.FileSections)
{
html.AppendLine(" <tr class=\"section\">");
html.AppendLine(" <td width=\"2%\" class=\"lineNumber\">...</td>");
html.AppendLine(" <td width=\"2%\" class=\"lineNumber\">...</td>");
html.AppendLine(" <td width=\"96%\">" + section.Description + "</td>");
html.AppendLine(" </tr>");
foreach (var line in section.Lines)
{
className = "";
var firstChar = " ";
switch (line.LineChangeType)
{
case LineChangeType.Add:
className = "addition";
firstChar = "+";
break;
case LineChangeType.Delete:
className = "deletion";
firstChar = "-";
break;
}
html.AppendLine(" <tr class=\"" + className + "\">");
html.AppendLine(" <td class=\"lineNumber\">" + line.OldLineNumber + "</td>");
html.AppendLine(" <td class=\"lineNumber\">" + line.NewLineNumber + "</td>");
html.AppendLine(" <td >" + firstChar + line.Text + "</td>");
html.AppendLine(" </tr>");
}
}
html.AppendLine(" </table>");
}
html.AppendLine("</body>");
html.AppendLine("</html>");
if (File.Exists(_outputPath)) File.Delete(_outputPath);
using (var outputFile = File.CreateText(_outputPath))
outputFile.Write(html.ToString());
}
}
}
| 37.9 | 110 | 0.428252 | [
"Apache-2.0"
] | SharpRepository/SharpDiff | SharpDiff.Formatter/HtmlFormatter.cs | 4,929 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloMVP.Presentation
{
public interface IView<TPresenter>
{
TPresenter Presenter { get; set; }
}
}
| 17.714286 | 42 | 0.721774 | [
"MIT"
] | epidemicz/HelloMVP | src/HelloMVP/HelloMVP.Presentation/IView.cs | 250 | C# |
// Copyright (c) Team CharLS.
// SPDX-License-Identifier: BSD-3-Clause
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
| 20.142857 | 40 | 0.758865 | [
"BSD-3-Clause"
] | team-charls/charls-native-dotnet | tests/AssemblyInfo.cs | 141 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using NAudioWpfDemo.ViewModel;
namespace NAudioWpfDemo
{
class MainWindowViewModel : ViewModelBase
{
private IModule selectedModule;
public MainWindowViewModel(IEnumerable<IModule> modules)
{
this.Modules = modules.OrderBy(m => m.Name).ToList();
if (this.Modules.Count > 0)
{
this.SelectedModule = this.Modules[0];
}
}
public List<IModule> Modules { get; private set; }
public IModule SelectedModule
{
get
{
return selectedModule;
}
set
{
if (value != selectedModule)
{
if (selectedModule != null)
{
selectedModule.Deactivate();
}
selectedModule = value;
OnPropertyChanged("SelectedModule");
OnPropertyChanged("UserInterface");
}
}
}
public UserControl UserInterface
{
get
{
if (SelectedModule == null) return null;
return SelectedModule.UserInterface;
}
}
}
}
| 24.607143 | 65 | 0.480406 | [
"MIT"
] | skor98/DtWPF | speechKit/NAudio-master/NAudioWpfDemo/MainWindowViewModel.cs | 1,380 | C# |
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace MSMQ.Messaging.Interop
{
using UnmanagedType = UnmanagedType;
[ComImport, Guid("0FB15084-AF41-11CE-BD2B-204C4F4F5020"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface ITransaction
{
[return: MarshalAs(UnmanagedType.I4)]
[SuppressUnmanagedCodeSecurity()]
[PreserveSig]
int Commit(
[In, MarshalAs(UnmanagedType.I4)]
int fRetaining,
[In, MarshalAs(UnmanagedType.U4)]
int grfTC,
[In, MarshalAs(UnmanagedType.U4)]
int grfRM);
[return: MarshalAs(UnmanagedType.I4)]
[SuppressUnmanagedCodeSecurity()]
[PreserveSig]
int Abort(
[In, MarshalAs(UnmanagedType.U4)]
int pboidReason,
[In, MarshalAs(UnmanagedType.I4)]
int fRetaining,
[In, MarshalAs(UnmanagedType.I4)]
int fAsync);
[return: MarshalAs(UnmanagedType.I4)]
[SuppressUnmanagedCodeSecurity()]
[PreserveSig]
int GetTransactionInfo(
[In, Out]
IntPtr /* XACTTRANSINFO */ pinfo);
}
}
| 26.869565 | 114 | 0.601133 | [
"MIT"
] | kwende/MSMQ.Messaging | src/Messaging/Interop/ITransaction.cs | 1,236 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapDCETModelRandomHelperWrapWrapWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelRandomHelperWrapWrapWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelRandomHelperWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelRandomHelperWrapWrapWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelRandomHelperWrapWrapWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapDCETModelRandomHelperWrapWrapWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 25.863636 | 189 | 0.595431 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapDCETModelRandomHelperWrapWrapWrapWrap.cs | 2,847 | C# |
using UnityEngine;
[RequireComponent(typeof(Rigidbody), typeof(PlayerScript))]
public class PathFollowScript : MonoBehaviour, IAccelMultiplier
{
/******************************************************
* variables
******************************************************/
private static readonly int layerMask = (~0) ^ (1 << 10);
private static readonly int terrainMask = 1 << 8;
public static readonly float NEXT_DISTANCE = 5f;
public static readonly float SMOOTH_MARGIN = 6f;
public static readonly float GAP_MARGIN = 15f;
public static readonly float PIT_MARGIN = 10f;
public static readonly float NUM_OF_INTERVALS = 5f;
public static readonly float INTERVAL_MARGIN = 2f;
public PathPoint pathPoint;
public PathPoint pathPointNextClosest;
public PlayerScript player;
private Transform myTransform;
// is movement allowed?
public bool isMoving = true;
// anti stuck var
private static readonly float STUCK_DISABLE_TIME = 2;
private static readonly float REQUIRED_STUCK_TIME = 1;
private static readonly float REQUIRED_MOVE_RESET = 5;
private bool stuckDisable;
private float stuckDisableTimeCounter;
private float stuckTimeCounter;
private float stuckMoveCounter;
private Vector3 lastUpdatePosition;
/******************************************************
* MonoBehaviour methods, Start
******************************************************/
void Start()
{
pathPoint = PathManager.FindClosestPoint(this.transform.position);
pathPointNextClosest = pathPoint.getNextClosestPathPoint();
player = GetComponent<PlayerScript>();
this.myTransform = transform;
}
/******************************************************
* MonoBehaviour methods, FixedUpdate
******************************************************/
void FixedUpdate()
{
if (isMoving && !stuckDisable)
{
Vector3 current3dPos = myTransform.position;
Vector2 current2dPos = new Vector2(current3dPos.x, current3dPos.z);
float angle = Vector2.Angle(pathPointNextClosest.Pos2d - pathPoint.Pos2d, current2dPos - pathPoint.Pos2d);
//Debug.Log(angle);
// if the distance between current pos to pathpoint + pathpoint to next pathpoint
// is greater than going from current to next pathpoint
if ((Vector2.Distance(pathPoint.Pos2d, current2dPos) +
Vector2.Distance(pathPoint.Pos2d, pathPointNextClosest.Pos2d)
> Vector2.Distance(pathPointNextClosest.Pos2d, current2dPos) + SMOOTH_MARGIN ||
Vector2.Distance(pathPoint.Pos2d, current2dPos) < SMOOTH_MARGIN ||
(angle < 120)) &&
Vector2.Distance(pathPoint.Pos2d, current2dPos) < SMOOTH_MARGIN * 4 ||
(angle < 100)
)
{
pathPoint = pathPoint.getNextWeightedPathPoint();
pathPointNextClosest = pathPoint.getNextClosestPathPoint();
}
Quaternion saveRotation = myTransform.rotation;
Vector2 direction = new Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
Vector3 relativePoint = transform.InverseTransformPoint(pathPoint.transform.position);
Vector3 forward = myTransform.forward;
transform.rotation = saveRotation;
Vector3 targetDir = pathPoint.transform.position - transform.position;
Vector3 normal = rigidbody.velocity.normalized;
angle = Vector3.Angle(targetDir, forward);
bool hasTurned = false;
// collision turning rays
Ray forwardRay = new Ray(current3dPos, rigidbody.velocity.normalized);
Ray forwardDownRay = new Ray(current3dPos + (rigidbody.velocity.normalized * GAP_MARGIN), -Vector3.up);
Ray leftRay = new Ray(current3dPos, -myTransform.right);
Ray leftDownRay = new Ray(current3dPos + (-myTransform.right * GAP_MARGIN), -Vector3.up);
Ray rightRay = new Ray(current3dPos, myTransform.right);
Ray rightDownRay = new Ray(current3dPos + (myTransform.right * GAP_MARGIN), -Vector3.up);
bool forwardTest = Physics.Raycast(forwardRay, GAP_MARGIN, layerMask);
bool forwardDownTest = Physics.Raycast(forwardDownRay, PIT_MARGIN, layerMask);
bool leftTest = Physics.Raycast(leftRay, GAP_MARGIN, layerMask);
bool leftDownTest = Physics.Raycast(leftDownRay, PIT_MARGIN, layerMask);
bool rightTest = Physics.Raycast(rightRay, GAP_MARGIN, layerMask);
bool rightDownTest = Physics.Raycast(rightDownRay, PIT_MARGIN, layerMask);
// pit detection turning
if (!forwardDownTest && !hasTurned)
{
if (!leftDownTest)
{
player.turnRight();
hasTurned = true;
}
else if (!rightDownTest)
{
player.turnLeft();
hasTurned = true;
}
}
// obstacle turning
if (forwardTest && !hasTurned)
{
bool stopLeftTesting = false;
bool stopRightTesting = false;
for (int i = 1; i <= NUM_OF_INTERVALS; i++)
{
if (!stopLeftTesting)
{
if (!Physics.Raycast(leftRay, INTERVAL_MARGIN * i, layerMask))
{
Vector3 leftPoint = current3dPos + (-myTransform.right * INTERVAL_MARGIN * i);
Vector3 leftVector = leftPoint - pathPoint.Pos3d;
Ray leftFollowIntervalRay = new Ray(leftPoint, leftVector.normalized);
if (Physics.Raycast(leftFollowIntervalRay, leftVector.magnitude))
{
Ray leftIntervalDownRay = new Ray(leftPoint, -Vector3.up);
if (!Physics.Raycast(leftIntervalDownRay, PIT_MARGIN))
{
player.turnLeft();
hasTurned = true;
break;
}
}
}
else
{
stopLeftTesting = true;
}
}
if (!stopRightTesting)
{
if (!Physics.Raycast(rightRay, INTERVAL_MARGIN * i, layerMask))
{
Vector3 rightPoint = current3dPos + (myTransform.right * INTERVAL_MARGIN * i);
Vector3 rightVector = rightPoint - pathPoint.Pos3d;
Ray rightIntervalRay = new Ray(rightPoint, rightVector.normalized);
if (Physics.Raycast(rightIntervalRay, rightVector.magnitude))
{
Ray rightIntervalDownRay = new Ray(rightPoint, Vector3.up);
if (!Physics.Raycast(rightIntervalDownRay, PIT_MARGIN))
{
player.turnRight();
hasTurned = true;
break;
}
else
stopRightTesting = true;
}
}
else
{
stopRightTesting = true;
}
}
}
/*
if (!hasTurned)
{
if (!leftTest)
{
if (leftDownTest)
{
player.turnRight();
hasTurned = true;
}
}
else if (!rightTest)
{
if (rightDownTest)
{
player.turnLeft();
hasTurned = true;
}
}
}*/
}
// normal turning
if (!hasTurned)
{
if (relativePoint.x < 0f && angle > 15)
player.turnLeft();
else if (relativePoint.x > 0f && angle > 15)
player.turnRight();
else
player.turnCenter();
}
// normal accelerate
if (angle < 90)
player.applyAcceleration();
else
player.applyIdleMotion();
stuckTimeCounter += Time.deltaTime;
stuckMoveCounter += Vector3.Distance(myTransform.position, lastUpdatePosition);
lastUpdatePosition = myTransform.position;
if (stuckMoveCounter >= REQUIRED_MOVE_RESET)
{
stuckTimeCounter = 0;
stuckMoveCounter = 0;
}
else if (stuckTimeCounter >= REQUIRED_STUCK_TIME)
{
stuckTimeCounter = 0;
stuckMoveCounter = 0;
stuckDisable = true;
}
}
else if(stuckDisable)
{
stuckDisableTimeCounter += Time.deltaTime;
player.applyReverse();
if (stuckDisableTimeCounter >= STUCK_DISABLE_TIME)
{
stuckDisableTimeCounter = 0;
stuckDisable = false;
}
}
else if (isMoving == false){
player.applyIdleMotion();
player.turnCenter();
}
}
/******************************************************
* MonoBehaviour methods, OnDrawGizmos
******************************************************/
void OnDrawGizmos()
{
if (pathPoint != null && (player==null || !player.IsHuman))
{
Gizmos.color = Color.blue;
Gizmos.DrawLine(transform.position, pathPoint.transform.position);
}
Gizmos.color = Color.cyan;
Gizmos.DrawLine(transform.position, transform.position + rigidbody.velocity);
}
/******************************************************
* repathPoints
******************************************************/
/// <summary> set the path to the closest node </summary>
public void repathPoints()
{
pathPoint = PathManager.FindClosestPoint(this.transform.position);
pathPointNextClosest = pathPoint.getNextClosestPathPoint();
}
/******************************************************
* adjustAccelMultiplier
******************************************************/
public float adjustAccelMultiplier(float multiplier)
{
if (enabled && pathPoint != null)
return multiplier * pathPoint.AccelMultiplier;
else
return multiplier;
}
}
| 37.245098 | 118 | 0.482144 | [
"MIT"
] | kidshenlong/warpspeed | Project Files/Assets/Scripts/AI/PathFollowScript.cs | 11,399 | C# |
// ----------------------------------------------------------------------------
// Copyright (c) Aleksey Nemiro, 2014-2015. 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
// If it works, no need to change the code.
// Just use it! ;-)
namespace Nemiro.OAuth.Clients
{
/// <summary>
/// OAuth client for <b>Foursquare</b>.
/// </summary>
/// <remarks>
/// <h1>Register and Configure a Foursquare Application</h1>
/// <list type="table">
/// <item>
/// <term><img src="../img/warning.png" alt="(!)" title="" /></term>
/// <term>
/// <b>Web Management Interface may change over time. Applications registration shown below may differ.</b><br />
/// If the interface is changed, you need to register the application and get <b>Client ID</b> and <b>Client Secret</b>. For web projects, configure <b>return URLs</b>.<br />
/// If you have any problems with this, please <see href="https://github.com/alekseynemiro/nemiro.oauth.dll/issues">visit issues</see>. If you do not find a solution to your problem, you can <see href="https://github.com/alekseynemiro/nemiro.oauth.dll/issues/new">create a new question</see>.
/// </term>
/// </item>
/// </list>
/// <para>Open the <b><see href="https://foursquare.com/oauth">Foursquare App</see></b> and <b>Create app</b>.</para>
/// <para>
/// In the application settings you can found <b>Client ID</b> and <b>Client Secret</b>.
/// Use this for creating an instance of the <see cref="FoursquareClient"/> class.
/// </para>
/// <code lang="C#">
/// OAuthManager.RegisterClient
/// (
/// new FoursquareClient
/// (
/// "LHYZN1KUXN50L141QCQFNNVOYBGUE3G3FCWFZ3EEZTOZHY5Q",
/// "HWXYFLLSS2IUQ0H4XNCDAZEFZKIU3MZRP5G55TNBDHRPNOQT"
/// )
/// );
/// </code>
/// <code lang="VB">
/// OAuthManager.RegisterClient _
/// (
/// New FoursquareClient _
/// (
/// "LHYZN1KUXN50L141QCQFNNVOYBGUE3G3FCWFZ3EEZTOZHY5Q",
/// "HWXYFLLSS2IUQ0H4XNCDAZEFZKIU3MZRP5G55TNBDHRPNOQT"
/// )
/// )
/// </code>
/// <para>
/// For more details, please visit <see href="https://developer.foursquare.com/">Foursquare for Developers</see>.
/// </para>
/// </remarks>
/// <seealso cref="AmazonClient"/>
/// <seealso cref="AssemblaClient"/>
/// <seealso cref="CodeProjectClient"/>
/// <seealso cref="DropboxClient"/>
/// <seealso cref="FacebookClient"/>
/// <seealso cref="FoursquareClient"/>
/// <seealso cref="GitHubClient"/>
/// <seealso cref="GoogleClient"/>
/// <seealso cref="InstagramClient"/>
/// <seealso cref="LinkedInClient"/>
/// <seealso cref="LiveClient"/>
/// <seealso cref="MailRuClient"/>
/// <seealso cref="OdnoklassnikiClient"/>
/// <seealso cref="SoundCloudClient"/>
/// <seealso cref="SourceForgeClient"/>
/// <seealso cref="TumblrClient"/>
/// <seealso cref="TwitterClient"/>
/// <seealso cref="VkontakteClient"/>
/// <seealso cref="YahooClient"/>
/// <seealso cref="YandexClient"/>
public class FoursquareClient : OAuth2Client
{
/// <summary>
/// Unique provider name: <b>Foursquare</b>.
/// </summary>
public override string ProviderName
{
get
{
return "Foursquare";
}
}
/// <summary>
/// Initializes a new instance of the <see cref="FoursquareClient"/>.
/// </summary>
/// <param name="clientId">The <b>Client ID</b> obtained from the <see href="https://foursquare.com/oauth">Foursquare Apps</see>.</param>
/// <param name="clientSecret">The <b>Client Secret</b> obtained from the <see href="https://foursquare.com/oauth">Foursquare Apps</see>.</param>
public FoursquareClient(string clientId, string clientSecret) : base
(
"https://foursquare.com/oauth2/authenticate",
"https://foursquare.com/oauth2/access_token",
clientId,
clientSecret
)
{ }
/// <summary>
/// Gets the user details.
/// </summary>
/// <param name="accessToken">May contain an access token, which will have to be used in obtaining information about the user.</param>
/// <returns>
/// <para>Returns an instance of the <see cref="UserInfo"/> class, containing information about the user.</para>
/// </returns>
public override UserInfo GetUserInfo(AccessToken accessToken = null)
{
// https://developer.foursquare.com/docs/users/users
accessToken = base.GetSpecifiedTokenOrCurrent(accessToken);
// query parameters
var parameters = new NameValueCollection
{
{ "oauth_token", accessToken.Value },
{ "v", "20141025" }
};
// execute the request
var result = OAuthUtility.Get("https://api.foursquare.com/v2/users/self", parameters);
// field mapping
var map = new ApiDataMapping();
map.Add("id", "UserId", typeof(string));
map.Add("firstName", "FirstName");
map.Add("lastName", "LastName");
map.Add
(
"photo", "Userpic",
delegate(UniValue value)
{
if (!value.HasValue || !value.ContainsKey("prefix") || !value.ContainsKey("suffix")) { return null; }
return String.Format("{0}300x300{1}", value["prefix"], value["suffix"]);
}
);
map.Add
(
"contact", "Email",
delegate(UniValue value)
{
return value["email"].ToString();
}
);
map.Add
(
"contact", "Phone",
delegate(UniValue value)
{
return value["phone"].ToString();
}
);
map.Add
(
"gender", "Sex",
delegate(UniValue value)
{
if (value.Equals("male", StringComparison.OrdinalIgnoreCase))
{
return Sex.Male;
}
else if (value.Equals("female", StringComparison.OrdinalIgnoreCase))
{
return Sex.Female;
}
return Sex.None;
}
);
// parse the server response and returns the UserInfo instance
return new UserInfo(result["response"]["user"], map);
}
}
} | 34.607143 | 294 | 0.605484 | [
"Apache-2.0"
] | ivandrofly/nemiro.oauth.dll | src/Nemiro.OAuth/Clients/FoursquareClient.cs | 6,785 | 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.Diagnostics;
using JetBrains.Annotations;
namespace Microsoft.EntityFrameworkCore.Metadata.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public abstract class InternalMetadataItemBuilder<TMetadata> : InternalMetadataBuilder<TMetadata>
where TMetadata : ConventionAnnotatable
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected InternalMetadataItemBuilder([NotNull] TMetadata metadata, [NotNull] InternalModelBuilder modelBuilder)
: base(metadata)
{
ModelBuilder = modelBuilder;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override InternalModelBuilder ModelBuilder { [DebuggerStepThrough] get; }
}
}
| 44.575758 | 120 | 0.685928 | [
"Apache-2.0"
] | MareevOleg/EntityFrameworkCore | src/EFCore/Metadata/Internal/InternalMetadataItemBuilder.cs | 1,471 | C# |
using System;
using LinCms.Blog.UserLikes;
using LinCms.Entities.Blog;
using Xunit;
namespace LinCms.Test.Controller.Blog
{
public class UserLikeControllerTest : BaseControllerTests
{
public UserLikeControllerTest() : base()
{
}
[Fact]
public void Create()
{
CreateUpdateUserLikeDto createUpdateUserLike = new CreateUpdateUserLikeDto()
{
SubjectId = new Guid("5e63dcd7-6e39-36e0-0001-059272461091"),
SubjectType = UserLikeSubjectType.UserLikeComment
};
}
}
}
| 20.1 | 88 | 0.608624 | [
"MIT"
] | KribKing/lin-cms-dotnetcore | test/LinCms.Test/Controller/Blog/UserLikeControllerTest.cs | 605 | C# |
// Copyright (C) 2015-2021 ricimi - All rights reserved.
// This code can only be used under the standard Unity Asset Store End User License Agreement.
// A Copy of the Asset Store EULA is available at http://unity3d.com/company/legal/as_terms.
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace Ricimi
{
// This class is responsible for popup management. Popups follow the traditional behavior of
// automatically blocking the input on elements behind it and adding a background texture.
public class Popup : MonoBehaviour
{
public Color backgroundColor = new Color(10.0f / 255.0f, 10.0f / 255.0f, 10.0f / 255.0f, 0.6f);
public float destroyTime = 0.5f;
private GameObject m_background;
public void Open()
{
AddBackground();
}
public void Close()
{
var animator = GetComponent<Animator>();
if (animator.GetCurrentAnimatorStateInfo(0).IsName("Open"))
animator.Play("Close");
RemoveBackground();
StartCoroutine(RunPopupDestroy());
}
// We destroy the popup automatically 0.5 seconds after closing it.
// The destruction is performed asynchronously via a coroutine. If you
// want to destroy the popup at the exact time its closing animation is
// finished, you can use an animation event instead.
private IEnumerator RunPopupDestroy()
{
yield return new WaitForSeconds(destroyTime);
Destroy(m_background);
Destroy(gameObject);
}
private void AddBackground()
{
var bgTex = new Texture2D(1, 1);
bgTex.SetPixel(0, 0, backgroundColor);
bgTex.Apply();
m_background = new GameObject("PopupBackground");
var image = m_background.AddComponent<Image>();
var rect = new Rect(0, 0, bgTex.width, bgTex.height);
var sprite = Sprite.Create(bgTex, rect, new Vector2(0.5f, 0.5f), 1);
image.material.mainTexture = bgTex;
image.sprite = sprite;
var newColor = image.color;
image.color = newColor;
image.canvasRenderer.SetAlpha(0.0f);
image.CrossFadeAlpha(1.0f, 0.4f, false);
var canvas = GameObject.Find("Canvas");
m_background.transform.localScale = new Vector3(1, 1, 1);
m_background.GetComponent<RectTransform>().sizeDelta = canvas.GetComponent<RectTransform>().sizeDelta;
m_background.transform.SetParent(canvas.transform, false);
m_background.transform.SetSiblingIndex(transform.GetSiblingIndex());
}
private void RemoveBackground()
{
var image = m_background.GetComponent<Image>();
if (image != null)
image.CrossFadeAlpha(0.0f, 0.2f, false);
}
}
}
| 37.177215 | 114 | 0.618999 | [
"MIT"
] | ADustyOldMuffin/Sudoktris | Assets/Imports/GUIPack-Clean&Minimalist/Demo/Scripts/Popup.cs | 2,937 | C# |
using ConcreteMC.MolangSharp.Runtime;
using ConcreteMC.MolangSharp.Runtime.Value;
namespace ConcreteMC.MolangSharp.Parser.Expressions.BinaryOp
{
public class GreaterExpression : BinaryOpExpression
{
/// <inheritdoc />
public GreaterExpression(IExpression l, IExpression r) : base(l, r) { }
/// <inheritdoc />
public override IMoValue Evaluate(MoScope scope, MoLangEnvironment environment)
{
return new DoubleValue(
Left.Evaluate(scope, environment).AsDouble() > Right.Evaluate(scope, environment).AsDouble());
}
/// <inheritdoc />
public override string GetSigil()
{
return ">";
}
}
} | 25.833333 | 98 | 0.729032 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ConcreteMC/MolangSharp | src/MolangSharp/Parser/Expressions/BinaryOp/GreaterExpression.cs | 620 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class latterntrick : MonoBehaviour
{
// Start is called before the first frame update
public string latterntagC;
private Animator myAnim;
private Animator realAnim;
private GameObject latternrealobject;
public Transform latternrealTransform;
private string lattertag;
void Start()
{
lattertag = "lattern" + latterntagC;
//m_playerTransform = GameObject.Find("player1").GetComponent<Transform>()
latternrealobject = GameObject.Find(lattertag);
latternrealTransform = latternrealobject.GetComponent<Transform>();
realAnim = latternrealobject.GetComponent<Animator>();
myAnim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (realAnim.GetBool("Light"))
{
myAnim.SetBool("Light", true);
}
else
{
myAnim.SetBool("Light", false);
}
}
}
| 27.05 | 83 | 0.628466 | [
"MIT"
] | njuxjx/Mirror-world | Mirror/Assets/Scripts/gq5/latterntrick.cs | 1,082 | C# |
using UnityEditor;
using UnityEngine;
namespace InControl
{
using Internal;
[CustomPropertyDrawer( typeof(OptionalInt32) )]
class OptionalInt32PropertyDrawer : PropertyDrawer
{
public override void OnGUI( Rect position, SerializedProperty property, GUIContent label )
{
EditorGUI.BeginProperty( position, label, property );
var serializedProperty = property.Copy();
serializedProperty.NextVisible( true );
var fullWidth = position.width;
position.width = EditorGUIUtility.labelWidth - 10;
var checkValue = EditorGUI.ToggleLeft( position, label, serializedProperty.boolValue, EditorUtility.labelStyle );
serializedProperty.boolValue = checkValue;
position.width = fullWidth;
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
serializedProperty.NextVisible( true );
var valueRect = new Rect(
position.x + EditorGUIUtility.labelWidth,
position.y,
position.width - EditorGUIUtility.labelWidth,
position.height
);
EditorGUI.BeginDisabledGroup( !checkValue );
if (checkValue)
{
EditorGUI.PropertyField( valueRect, serializedProperty, GUIContent.none );
}
else
{
GUI.Label( valueRect, "Empty (Optional Int32)", "TextField" );
}
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
}
}
| 24 | 116 | 0.731399 | [
"MIT"
] | EstasAnt/Estsoul | Assets/InControl/Editor/OptionalTypes/OptionalInt32PropertyDrawer.cs | 1,344 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using AutoDog.Editor.Document;
using AutoDog.Editor.Utils;
namespace AutoDog.Editor.Editing
{
sealed class EmptySelection : Selection
{
public EmptySelection(TextArea textArea) : base(textArea)
{
}
public override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
{
return this;
}
public override TextViewPosition StartPosition {
get { return new TextViewPosition(TextLocation.Empty); }
}
public override TextViewPosition EndPosition {
get { return new TextViewPosition(TextLocation.Empty); }
}
public override ISegment SurroundingSegment {
get { return null; }
}
public override Selection SetEndpoint(TextViewPosition endPosition)
{
throw new NotSupportedException();
}
public override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition)
{
var document = textArea.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return Create(textArea, startPosition, endPosition);
}
public override IEnumerable<SelectionSegment> Segments {
get { return Empty<SelectionSegment>.Array; }
}
public override string GetText()
{
return string.Empty;
}
public override void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException("newText");
newText = AddSpacesIfRequired(newText, textArea.Caret.Position, textArea.Caret.Position);
if (newText.Length > 0) {
if (textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)) {
textArea.Document.Insert(textArea.Caret.Offset, newText);
}
}
textArea.Caret.VisualColumn = -1;
}
public override int Length {
get { return 0; }
}
// Use reference equality because there's only one EmptySelection per text area.
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
public override bool Equals(object obj)
{
return this == obj;
}
}
}
| 26.395349 | 117 | 0.734361 | [
"MIT"
] | devdiv/AutoDog | AutoDog/AutoDog.Editor/Editing/EmptySelection.cs | 2,272 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using OctoBot.Commands;
using OctoBot.Configs;
using OctoBot.Configs.Server;
using OctoBot.Configs.Users;
namespace OctoBot.Automated
{
public class CheckBirthday
{
private static Timer _loopingTimer;
internal static Task CheckTimer()
{
_loopingTimer = new Timer
{
AutoReset = true,
Interval = 60000,
Enabled = true
};
_loopingTimer.Elapsed += CheckAllBirthdays;
return Task.CompletedTask;
}
public static async void CheckAllBirthdays(object sender, ElapsedEventArgs e)
{
try
{
var allServersWithBirthdayRole = ServerAccounts.GetFilteredServerAccounts(s => s.BirthdayRoleId != 0);
var timeUtcNow = DateTime.UtcNow;
var removeLaterList = new List<ServerSettings.BirthdayRoleActive>();
foreach (var server in allServersWithBirthdayRole)
{
var allUserAccounts = UserAccounts.GetOrAddUserAccountsForGuild(server.ServerId);
foreach (var t in allUserAccounts)
{
if (t.Birthday.ToString(CultureInfo.InvariantCulture) == "0001-01-01T00:00:00")
continue;
if(Global.Client.Guilds.All(x => x.Id != server.ServerId))
continue;
var globalAccount = Global.Client.GetUser(t.Id);
if(globalAccount == null)
continue;
var account = UserAccounts.GetAccount(globalAccount, server.ServerId);
var timezone = account.TimeZone ?? "UTC";
try
{
var fftz = TimeZoneInfo.FindSystemTimeZoneById($"{timezone}");
}
catch
{
account.TimeZone = "UTC";
UserAccounts.SaveAccounts(server.ServerId);
Console.WriteLine($"{account.UserName} TimeZone changed to UTC");
continue;
}
var tz = TimeZoneInfo.FindSystemTimeZoneById($"{timezone}");
var timeWhenIsBirthdayByUtc = TimeZoneInfo.ConvertTimeToUtc(account.Birthday, tz);
var roleToGive = Global.Client.GetGuild(server.ServerId).GetRole(server.BirthdayRoleId);
if (roleToGive == null)
{
server.BirthdayRoleId = 0;
ServerAccounts.SaveServerAccounts();
Console.WriteLine($"Birthday Role == NULL ({server.ServerName} - {server.ServerId})");
return;
}
/*
if(account.Id == 181514288278536193)
Console.WriteLine($"account == {account.UserName}\n" +
$"timeUtcNow.Month == {timeUtcNow.Month}\n" +
$"timeWhenIsBirthdayByUtc == {timeWhenIsBirthdayByUtc.Month}\n" +
$"timeUtcNow.Day == {timeUtcNow.Day}\n" +
$"timeWhenIsBirthdayByUtc.Day == {timeWhenIsBirthdayByUtc.Day}\n" +
$"{server.BirthdayRoleList.Any(x => x.UserId != account.Id).ToString()}");
*/
var check = 0;
foreach (var l in server.BirthdayRoleList)
{
if (l.UserId == account.Id)
check = 1;
}
if (timeUtcNow.Month == timeWhenIsBirthdayByUtc.Month &&
timeUtcNow.Day == timeWhenIsBirthdayByUtc.Day
&& check == 0)
{
Console.WriteLine("here");
await Global.Client.GetGuild(server.ServerId).GetUser(account.Id)
.AddRoleAsync(roleToGive);
var newBirthday = new ServerSettings.BirthdayRoleActive(timeUtcNow +
TimeSpan.ParseExact("1d",
ReminderFormat.Formats,
CultureInfo
.CurrentCulture),
account.Id, account.UserName);
server.BirthdayRoleList.Add(newBirthday);
ServerAccounts.SaveServerAccounts();
}
if (server.BirthdayRoleList.Any(x => x.UserId == account.Id))
foreach (var v in server.BirthdayRoleList)
if (timeUtcNow > v.DateToRemoveRole)
{
Console.WriteLine("removed");
await Global.Client.GetGuild(server.ServerId).GetUser(v.UserId)
.RemoveRoleAsync(roleToGive);
removeLaterList.Add(v);
}
}
if (removeLaterList.Any())
{
removeLaterList.ForEach(item => server.BirthdayRoleList.Remove(item));
ServerAccounts.SaveServerAccounts();
}
}
}
catch (Exception error)
{
Console.WriteLine("ERROR!!! Birthday Role(Big try) Does not work: '{0}'", error);
}
}
}
} | 43.6 | 118 | 0.435938 | [
"MIT"
] | mylorik/OctoBot-Core | OctoBot/Automated/CheckBirthday.cs | 6,324 | C# |
using System;
using System.Collections.Generic;
namespace SharpCompress.Common
{
public abstract class Entry : IEntry
{
/// <summary>
/// The File's 32 bit CRC Hash
/// </summary>
public abstract long Crc { get; }
/// <summary>
/// The string key of the file internal to the Archive.
/// </summary>
public abstract string Key { get; }
/// <summary>
/// The target of a symlink entry internal to the Archive. Will be null if not a symlink.
/// </summary>
public abstract string LinkTarget { get; }
/// <summary>
/// The compressed file size
/// </summary>
public abstract long CompressedSize { get; }
/// <summary>
/// The compression type
/// </summary>
public abstract CompressionType CompressionType { get; }
/// <summary>
/// The uncompressed file size
/// </summary>
public abstract long Size { get; }
/// <summary>
/// The entry last modified time in the archive, if recorded
/// </summary>
public abstract DateTime? LastModifiedTime { get; }
/// <summary>
/// The entry create time in the archive, if recorded
/// </summary>
public abstract DateTime? CreatedTime { get; }
/// <summary>
/// The entry last accessed time in the archive, if recorded
/// </summary>
public abstract DateTime? LastAccessedTime { get; }
/// <summary>
/// The entry time when archived, if recorded
/// </summary>
public abstract DateTime? ArchivedTime { get; }
/// <summary>
/// Entry is password protected and encrypted and cannot be extracted.
/// </summary>
public abstract bool IsEncrypted { get; }
/// <summary>
/// Entry is directory.
/// </summary>
public abstract bool IsDirectory { get; }
/// <summary>
/// Entry is split among multiple volumes
/// </summary>
public abstract bool IsSplitAfter { get; }
/// <inheritdoc/>
public override string ToString()
{
return Key;
}
internal abstract IEnumerable<FilePart> Parts { get; }
internal bool IsSolid { get; set; }
internal virtual void Close()
{
}
/// <summary>
/// Entry file attribute.
/// </summary>
public virtual int? Attrib => throw new NotImplementedException();
public int Index { get; set; }
}
}
| 27.819149 | 97 | 0.545315 | [
"MIT"
] | bipinbaglung/sharpcompress | src/SharpCompress/Common/Entry.cs | 2,617 | C# |
namespace Testing.Networking.Objects
{
public class SimpleObject
{
// Default Parameterless Constructor
public SimpleObject()
{
}
public SimpleObject(int arg1, string arg2, double arg3, char arg4, bool arg5)
{
prop1 = arg1;
prop2 = arg2;
prop3 = arg3;
prop4 = arg4;
prop5 = arg5;
}
public int prop1 { get; set; }
public string prop2 { get; set; }
public double prop3 { get; set; }
public char prop4 { get; set; }
public bool prop5 { get; set; }
}
public class ComplexObject
{
public ComplexObject()
{
}
public ComplexObject(SimpleObject arg1, string arg7)
{
prop1 = arg1;
prop2 = arg7;
}
public ComplexObject(int arg1, string arg2, double arg3, char arg4, bool arg5, string arg6)
{
prop1 = new SimpleObject(arg1, arg2, arg3, arg4, arg5);
prop2 = arg6;
}
public SimpleObject prop1 { get; set; }
public string prop2 { get; set; }
}
public class NonSerializableObject
{
public NonSerializableObject(int arg1)
{
prop1 = arg1;
}
public int prop1 { get; set; }
}
public class NonSerializableAttribute
{
public NonSerializableAttribute()
{
}
public NonSerializableAttribute(int arg1, int arg2)
{
prop1 = arg1;
prop2 = new NonSerializableObject(arg1);
}
public int prop1 { get; set; }
public NonSerializableObject prop2 { get; set; }
}
} | 23.465753 | 99 | 0.526562 | [
"MIT"
] | GurunadhPachappagari/meet.me | Testing/Networking/Serialization/Objects.cs | 1,715 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace SCDataManager.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type.
/// </summary>
/// <param name="mediaType">The media type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
ActionName = String.Empty;
ControllerName = String.Empty;
MediaType = mediaType;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
: this(mediaType)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ParameterType = type;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
: this(sampleDirection, controllerName, actionName, parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
MediaType = mediaType;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
| 37.439306 | 175 | 0.569863 | [
"MIT"
] | swcollins92/RetailManager | SCDataManager/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs | 6,477 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation.Tests
{
internal static class TestSettings
{
public static readonly string LocalHost = "localhost";
public const int PingTimeout = 10 * 1000;
public const string PayloadAsString = "'Post hoc ergo propter hoc'. 'After it, therefore because of it'. It means one thing follows the other, therefore it was caused by the other. But it's not always true. In fact it's hardly ever true.";
public static readonly byte[] PayloadAsBytes = Encoding.UTF8.GetBytes(TestSettings.PayloadAsString);
public static async Task<IPAddress> GetLocalIPAddress()
{
IPHostEntry hostEntry = await Dns.GetHostEntryAsync(LocalHost);
IPAddress ret = null;
foreach (IPAddress address in hostEntry.AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
return address;
}
}
// If there's no IPv6 addresses, just take the first (IPv4) address.
if (ret == null && hostEntry.AddressList.Length > 0)
{
return hostEntry.AddressList[0];
}
throw new InvalidOperationException("Unable to discover any addresses for the local host.");
}
}
}
| 38.52381 | 247 | 0.645241 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Net.Ping/tests/FunctionalTests/TestSettings.cs | 1,618 | 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 Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Ram.Model.V20150501;
using System;
using System.Collections.Generic;
namespace Aliyun.Acs.Ram.Transform.V20150501
{
public class DeletePolicyVersionResponseUnmarshaller
{
public static DeletePolicyVersionResponse Unmarshall(UnmarshallerContext context)
{
DeletePolicyVersionResponse deletePolicyVersionResponse = new DeletePolicyVersionResponse();
deletePolicyVersionResponse.HttpResponse = context.HttpResponse;
deletePolicyVersionResponse.RequestId = context.StringValue("DeletePolicyVersion.RequestId");
return deletePolicyVersionResponse;
}
}
} | 38.710526 | 96 | 0.765466 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-ram/Ram/Transform/V20150501/DeletePolicyVersionResponseUnmarshaller.cs | 1,471 | C# |
//
// Signature.cs - Signature implementation for XML Signature
//
// Author:
// Sebastien Pouliot (spouliot@motus.com)
// Tim Coleman (tim@timcoleman.com)
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
//
//
// 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.Collections;
using System.Security.Cryptography;
using System.Xml;
namespace System.Security.Cryptography.Xml {
public class Signature {
static XmlNamespaceManager dsigNsmgr;
static Signature ()
{
dsigNsmgr = new XmlNamespaceManager (new NameTable ());
dsigNsmgr.AddNamespace ("xd", XmlSignature.NamespaceURI);
}
private ArrayList list;
private SignedInfo info;
private KeyInfo key;
private string id;
private byte[] signature;
private XmlElement element;
public Signature ()
{
list = new ArrayList ();
}
public string Id {
get { return id; }
set {
element = null;
id = value;
}
}
public KeyInfo KeyInfo {
get { return key; }
set {
element = null;
key = value;
}
}
public IList ObjectList {
get { return list; }
set { list = ArrayList.Adapter (value); }
}
public byte[] SignatureValue {
get { return signature; }
set {
element = null;
signature = value;
}
}
public SignedInfo SignedInfo {
get { return info; }
set {
element = null;
info = value;
}
}
public void AddObject (DataObject dataObject)
{
list.Add (dataObject);
}
public XmlElement GetXml ()
{
return GetXml (null);
}
internal XmlElement GetXml (XmlDocument document)
{
if (element != null)
return element;
if (info == null)
throw new CryptographicException ("SignedInfo");
if (signature == null)
throw new CryptographicException ("SignatureValue");
if (document == null)
document = new XmlDocument ();
XmlElement xel = document.CreateElement (XmlSignature.ElementNames.Signature, XmlSignature.NamespaceURI);
if (id != null)
xel.SetAttribute (XmlSignature.AttributeNames.Id, id);
XmlNode xn = info.GetXml ();
XmlNode newNode = document.ImportNode (xn, true);
xel.AppendChild (newNode);
if (signature != null) {
XmlElement sv = document.CreateElement (XmlSignature.ElementNames.SignatureValue, XmlSignature.NamespaceURI);
sv.InnerText = Convert.ToBase64String (signature);
xel.AppendChild (sv);
}
if (key != null) {
xn = key.GetXml ();
newNode = document.ImportNode (xn, true);
xel.AppendChild (newNode);
}
if (list.Count > 0) {
foreach (DataObject obj in list) {
xn = obj.GetXml ();
newNode = document.ImportNode (xn, true);
xel.AppendChild (newNode);
}
}
return xel;
}
private string GetAttribute (XmlElement xel, string attribute)
{
XmlAttribute xa = xel.Attributes [attribute];
return ((xa != null) ? xa.InnerText : null);
}
public void LoadXml (XmlElement value)
{
if (value == null)
throw new ArgumentNullException ("value");
if ((value.LocalName == XmlSignature.ElementNames.Signature) && (value.NamespaceURI == XmlSignature.NamespaceURI)) {
id = GetAttribute (value, XmlSignature.AttributeNames.Id);
// LAMESPEC: This library is totally useless against eXtensibly Marked-up document.
int i = NextElementPos (value.ChildNodes, 0, XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI, true);
XmlElement sinfo = (XmlElement) value.ChildNodes [i];
info = new SignedInfo ();
info.LoadXml (sinfo);
i = NextElementPos (value.ChildNodes, ++i, XmlSignature.ElementNames.SignatureValue, XmlSignature.NamespaceURI, true);
XmlElement sigValue = (XmlElement) value.ChildNodes [i];
signature = Convert.FromBase64String (sigValue.InnerText);
// signature isn't required: <element ref="ds:KeyInfo" minOccurs="0"/>
i = NextElementPos (value.ChildNodes, ++i, XmlSignature.ElementNames.KeyInfo, XmlSignature.NamespaceURI, false);
if (i > 0) {
XmlElement kinfo = (XmlElement) value.ChildNodes [i];
key = new KeyInfo ();
key.LoadXml (kinfo);
}
XmlNodeList xnl = value.SelectNodes ("xd:Object", dsigNsmgr);
foreach (XmlElement xn in xnl) {
DataObject obj = new DataObject ();
obj.LoadXml (xn);
AddObject (obj);
}
}
else
throw new CryptographicException ("Malformed element: Signature.");
// if invalid
if (info == null)
throw new CryptographicException ("SignedInfo");
if (signature == null)
throw new CryptographicException ("SignatureValue");
}
private int NextElementPos (XmlNodeList nl, int pos, string name, string ns, bool required)
{
while (pos < nl.Count) {
if (nl [pos].NodeType == XmlNodeType.Element) {
if (nl [pos].LocalName != name || nl [pos].NamespaceURI != ns) {
if (required)
throw new CryptographicException ("Malformed element " + name);
else
return -2;
}
else
return pos;
}
else
pos++;
}
if (required)
throw new CryptographicException ("Malformed element " + name);
return -1;
}
}
}
| 27.774775 | 122 | 0.677911 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Security/System.Security.Cryptography.Xml/Signature.cs | 6,166 | C# |
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace DayHelper
{
/// <summary>
/// The dock position of the window
/// </summary>
public class WindowResizer
{
#region Private Members
/// <summary>
/// The window to handle the resizing for
/// </summary>
private Window mWindow;
#endregion
#region Dll Imports
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr MonitorFromPoint(POINT pt, MonitorOptions dwFlags);
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <param name="window">The window to monitor and correctly maximize</param>
/// <param name="adjustSize">The callback for the host to adjust the maximum available size if needed</param>
public WindowResizer(Window window)
{
mWindow = window;
// Listen out for source initialized to setup
mWindow.SourceInitialized += Window_SourceInitialized;
}
#endregion
#region Initialize
/// <summary>
/// Initialize and hook into the windows message pump
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_SourceInitialized(object sender, System.EventArgs e)
{
// Get the handle of this window
var handle = (new WindowInteropHelper(mWindow)).Handle;
var handleSource = HwndSource.FromHwnd(handle);
// If not found, end
if (handleSource == null)
return;
// Hook into it's Windows messages
handleSource.AddHook(WindowProc);
}
#endregion
#region Windows Proc
/// <summary>
/// Listens out for all windows messages for this window
/// </summary>
/// <param name="hwnd"></param>
/// <param name="msg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <param name="handled"></param>
/// <returns></returns>
private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
// Handle the GetMinMaxInfo of the Window
case 0x0024:/* WM_GETMINMAXINFO */
WmGetMinMaxInfo(hwnd, lParam);
handled = true;
break;
}
return (IntPtr)0;
}
#endregion
/// <summary>
/// Get the min/max window size for this window
/// Correctly accounting for the taskbar size and position
/// </summary>
/// <param name="hwnd"></param>
/// <param name="lParam"></param>
private void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
{
POINT lMousePosition;
GetCursorPos(out lMousePosition);
IntPtr lPrimaryScreen = MonitorFromPoint(new POINT(0, 0), MonitorOptions.MONITOR_DEFAULTTOPRIMARY);
MONITORINFO lPrimaryScreenInfo = new MONITORINFO();
if (GetMonitorInfo(lPrimaryScreen, lPrimaryScreenInfo) == false)
{
return;
}
IntPtr lCurrentScreen = MonitorFromPoint(lMousePosition, MonitorOptions.MONITOR_DEFAULTTONEAREST);
MINMAXINFO lMmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
if (lPrimaryScreen.Equals(lCurrentScreen) == true)
{
lMmi.ptMaxPosition.X = lPrimaryScreenInfo.rcWork.Left;
lMmi.ptMaxPosition.Y = lPrimaryScreenInfo.rcWork.Top;
lMmi.ptMaxSize.X = lPrimaryScreenInfo.rcWork.Right - lPrimaryScreenInfo.rcWork.Left;
lMmi.ptMaxSize.Y = lPrimaryScreenInfo.rcWork.Bottom - lPrimaryScreenInfo.rcWork.Top;
}
else
{
lMmi.ptMaxPosition.X = lPrimaryScreenInfo.rcMonitor.Left;
lMmi.ptMaxPosition.Y = lPrimaryScreenInfo.rcMonitor.Top;
lMmi.ptMaxSize.X = lPrimaryScreenInfo.rcMonitor.Right - lPrimaryScreenInfo.rcMonitor.Left;
lMmi.ptMaxSize.Y = lPrimaryScreenInfo.rcMonitor.Bottom - lPrimaryScreenInfo.rcMonitor.Top;
}
// Now we have the max size, allow the host to tweak as needed
Marshal.StructureToPtr(lMmi, lParam, true);
}
}
#region Dll Helper Structures
enum MonitorOptions : uint
{
MONITOR_DEFAULTTONULL = 0x00000000,
MONITOR_DEFAULTTOPRIMARY = 0x00000001,
MONITOR_DEFAULTTONEAREST = 0x00000002
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MONITORINFO
{
public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
public Rectangle rcMonitor = new Rectangle();
public Rectangle rcWork = new Rectangle();
public int dwFlags = 0;
}
[StructLayout(LayoutKind.Sequential)]
public struct Rectangle
{
public int Left, Top, Right, Bottom;
public Rectangle(int left, int top, int right, int bottom)
{
this.Left = left;
this.Top = top;
this.Right = right;
this.Bottom = bottom;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
};
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
/// <summary>
/// x coordinate of point.
/// </summary>
public int X;
/// <summary>
/// y coordinate of point.
/// </summary>
public int Y;
/// <summary>
/// Construct a point of coordinates (x,y).
/// </summary>
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
#endregion
} | 30.636792 | 117 | 0.578445 | [
"MIT"
] | LessIsMoreMK/DayHelper | DayHelper/Helpers/WindowResizer.cs | 6,497 | C# |
namespace DotNetRevolution.Core.Domain
{
public interface IApply<TDomainEvent>
where TDomainEvent : IDomainEvent
{
void Apply(TDomainEvent domainEvent);
}
}
| 20.666667 | 45 | 0.693548 | [
"MIT"
] | DotNetRevolution/DotNetRevolution-Framework | src/DotNetRevolution.Core/Domain/IApply.cs | 188 | C# |
using DevExpress.XtraEditors;
using OtelYeniProje.Entity;
using OtelYeniProje.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OtelYeniProje.Formlar.WebSite
{
public partial class FrmMesajKarti : Form
{
public FrmMesajKarti()
{
InitializeComponent();
}
DbOtelYeniEntities db = new DbOtelYeniEntities();
Repository<TblMesaj2> repo = new Repository<TblMesaj2>();
Repository<TblMesaj> repoiletisim = new Repository<TblMesaj>();
public int id;
public int id2;
private void FrmMesajKarti_Load(object sender, EventArgs e)
{
if (id!=0)
{
var mesaj = repo.Find(x => x.MesajID == id);
TxtMail.Text = mesaj.Gonderen;
TxtKonu.Text = mesaj.Konu;
TxtMesaj.Text = mesaj.Mesaj;
TxtTarih.Text = mesaj.Tarih.ToString();
var kisi = db.TblYeniKayit.Where(x => x.Mail == mesaj.Gonderen).Select(y => y.AdSoyad).FirstOrDefault();
if (kisi!=null)
{
TxtAdSoyad.Text = kisi.ToString();
}
else
{
TxtAdSoyad.Text = "Admin";
}
}
if (id2 != 0)
{
var mesaj = repoiletisim.Find(x => x.MesajID == id2);
TxtMail.Text = mesaj.Gonderen;
TxtKonu.Text = mesaj.Konu;
TxtMesaj.Text = mesaj.Mesaj;
TxtAdSoyad.Text = mesaj.Gonderen;
}
}
private void BtnVazgec_Click(object sender, EventArgs e)
{
this.Close();
}
private void BtnGonder_Click(object sender, EventArgs e)
{
TblMesaj2 t = new TblMesaj2();
t.Gonderen = "Admin";
t.Alici = TxtMail.Text;
t.Tarih = DateTime.Parse(DateTime.Now.ToShortDateString());
t.Konu = TxtKonu.Text;
t.Mesaj = TxtMesaj.Text;
repo.TAdd(t);
XtraMessageBox.Show("Mesajınız başarılı bir şekilde iletildi.");
}
}
}
| 29.419753 | 120 | 0.534201 | [
"MIT"
] | CaglaT/C-ve-MVC-ile-Otel-Rezervasyon-Projesi | OtelYeniProje/OtelYeniProje/Formlar/WebSite/FrmMesajKarti.cs | 2,391 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
namespace Azure.ResourceManager.Compute.Models
{
/// <summary> Specifies information about the Shared Image Gallery that you want to update. </summary>
public partial class PatchableGalleryData : UpdateResourceDefinition
{
/// <summary> Initializes a new instance of PatchableGalleryData. </summary>
public PatchableGalleryData()
{
}
/// <summary> The description of this Shared Image Gallery resource. This property is updatable. </summary>
public string Description { get; set; }
/// <summary> Describes the gallery unique name. </summary>
internal GalleryIdentifier Identifier { get; set; }
/// <summary> The unique name of the Shared Image Gallery. This name is generated automatically by Azure. </summary>
public string IdentifierUniqueName
{
get => Identifier is null ? default : Identifier.UniqueName;
}
/// <summary> The provisioning state, which only appears in the response. </summary>
public GalleryPropertiesProvisioningState? ProvisioningState { get; }
/// <summary> Profile for gallery sharing to subscription or tenant. </summary>
public SharingProfile SharingProfile { get; set; }
/// <summary> Contains information about the soft deletion policy of the gallery. </summary>
internal SoftDeletePolicy SoftDeletePolicy { get; set; }
/// <summary> Enables soft-deletion for resources in this gallery, allowing them to be recovered within retention time. </summary>
public bool? IsSoftDeleteEnabled
{
get => SoftDeletePolicy is null ? default : SoftDeletePolicy.IsSoftDeleteEnabled;
set
{
if (SoftDeletePolicy is null)
SoftDeletePolicy = new SoftDeletePolicy();
SoftDeletePolicy.IsSoftDeleteEnabled = value;
}
}
}
}
| 44.085106 | 138 | 0.662162 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/PatchableGalleryData.cs | 2,072 | C# |
//-----------------------------------------------------------------------
// <copyright file="AccountController.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2016
// </copyright>
// <summary>Defines the AccountController class.</summary>
//-----------------------------------------------------------------------
// Copyright 2016 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Reference.Storefront.Controllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Web.Mvc;
using Sitecore.Commerce.Connect.CommerceServer;
using Sitecore.Commerce.Connect.CommerceServer.Configuration;
using Sitecore.Commerce.Connect.CommerceServer.Orders.Models;
using Sitecore.Commerce.Contacts;
using Sitecore.Commerce.Entities.Customers;
using Sitecore.Commerce.Entities.Orders;
using Sitecore.Reference.Storefront.Managers;
using Sitecore.Reference.Storefront.Models;
using Sitecore.Reference.Storefront.Models.InputModels;
using Sitecore.Reference.Storefront.Models.JsonResults;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Links;
using Sitecore.Reference.Storefront.ExtensionMethods;
using System.Globalization;
using System.Web.UI;
using Sitecore.Reference.Storefront.Infrastructure;
/// <summary>
/// Used to handle all account actions
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public class AccountController : CSBaseController
{
#region Properties
/// <summary>
/// Initializes a new instance of the <see cref="AccountController" /> class.
/// </summary>
/// <param name="orderManager">The order manager.</param>
/// <param name="accountManager">The account manager.</param>
/// <param name="contactFactory">The contact factory.</param>
public AccountController(
[NotNull] OrderManager orderManager,
[NotNull] AccountManager accountManager,
[NotNull] ContactFactory contactFactory)
: base(accountManager, contactFactory)
{
Assert.ArgumentNotNull(orderManager, "orderManager");
this.OrderManager = orderManager;
}
/// <summary>
/// Gives the various types of messages
/// </summary>
public enum ManageMessageId
{
/// <summary>
/// Indicates a successful password change
/// </summary>
ChangePasswordSuccess,
/// <summary>
/// Indicates a successful password set
/// </summary>
SetPasswordSuccess,
/// <summary>
/// Indicates a successful account delete
/// </summary>
RemoveLoginSuccess,
}
/// <summary>
/// Gets or sets the order manager.
/// </summary>
/// <value>
/// The order manager.
/// </value>
public OrderManager OrderManager { get; protected set; }
#endregion
#region Controller actions
/// <summary>
/// Sends a request to reorder one or more items from a previous order.
/// </summary>
/// <param name="inputModel">The reorder input model.</param>
/// <returns>The result of the operation.</returns>
[Authorize]
[HttpPost]
[ValidateJsonAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult Reorder(ReorderInputModel inputModel)
{
try
{
Assert.ArgumentNotNull(inputModel, "inputModel");
var validationResult = new BaseJsonResult();
this.ValidateModel(validationResult);
if (validationResult.HasErrors)
{
return Json(validationResult, JsonRequestBehavior.AllowGet);
}
var response = this.OrderManager.Reorder(this.CurrentStorefront, this.CurrentVisitorContext, inputModel);
var result = new BaseJsonResult(response.ServiceProviderResult);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("Reorder", this);
return Json(new BaseJsonResult("Reorder", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Sends a request to cancel one or more items from an existing order.
/// </summary>
/// <param name="inputModel">The order cancellation input model.</param>
/// <returns>The result of the operation.</returns>
[Authorize]
[HttpPost]
[ValidateJsonAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult CancelOrder(CancelOrderInputModel inputModel)
{
try
{
Assert.ArgumentNotNull(inputModel, "inputModel");
var validationResult = new CancelOrderBaseJsonResult();
this.ValidateModel(validationResult);
if (validationResult.HasErrors)
{
return Json(validationResult, JsonRequestBehavior.AllowGet);
}
var response = this.OrderManager.CancelOrder(this.CurrentStorefront, this.CurrentVisitorContext, inputModel);
var result = new CancelOrderBaseJsonResult(response.ServiceProviderResult);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("CancelOrder", this);
return Json(new BaseJsonResult("CancelOrder", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// The default action for the main page for the account section
/// </summary>
/// <returns>The view for the section</returns>
[HttpGet]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public override ActionResult Index()
{
if (!Context.User.IsAuthenticated)
{
return Redirect("/login");
}
return View(this.GetRenderingView("Index"));
}
/// <summary>
/// An action to handle displaying the login form
/// </summary>
/// <param name="returnUrl">A location to redirect the user to</param>
/// <returns>The view to display to the user</returns>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "url not required in webpage")]
[HttpGet]
[AllowAnonymous]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View(this.CurrentRenderingView);
}
/// <summary>
/// Handles a user trying to log off
/// </summary>
/// <returns>The view to display to the user after logging off</returns>
[HttpGet]
[AllowAnonymous]
public ActionResult LogOff()
{
this.AccountManager.Logout();
return RedirectToLocal(StorefrontManager.StorefrontHome);
}
/// <summary>
/// Handles displaying a form for the user to login
/// </summary>
/// <returns>The view to display to the user</returns>
[HttpGet]
[AllowAnonymous]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult Register()
{
return View(this.CurrentRenderingView);
}
/// <summary>
/// Addressees this instance.
/// </summary>
/// <returns>The view to display address book</returns>
[HttpGet]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult Addresses()
{
if (!Context.User.IsAuthenticated)
{
return Redirect("/login");
}
return View(this.GetRenderingView("Addresses"));
}
/// <summary>
/// Displays the Profile Edit Page.
/// </summary>
/// <returns>
/// Profile Edit Page
/// </returns>
[HttpGet]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult EditProfile()
{
var model = new ProfileModel();
if (!Context.User.IsAuthenticated)
{
return Redirect("/login");
}
var commerceUser = this.AccountManager.GetUser(Context.User.Name).Result;
if (commerceUser == null)
{
return View(this.GetRenderingView("EditProfile"), model);
}
model.FirstName = commerceUser.FirstName;
model.Email = commerceUser.Email;
model.EmailRepeat = commerceUser.Email;
model.LastName = commerceUser.LastName;
model.TelephoneNumber = commerceUser.GetPropertyValue("Phone") as string;
return View(this.GetRenderingView("EditProfile"), model);
}
/// <summary>
/// Forgots the password.
/// </summary>
/// <returns>The view to display.</returns>
[HttpGet]
[AllowAnonymous]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult ForgotPassword()
{
return View(this.CurrentRenderingView);
}
/// <summary>
/// Changes the password confirmation.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <returns>The forgot password confirmation view.</returns>
[HttpGet]
[AllowAnonymous]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult ForgotPasswordConfirmation(string userName)
{
ViewBag.UserName = userName;
return View(this.CurrentRenderingView);
}
/// <summary>
/// Changes the password.
/// </summary>
/// <returns>Chagne password view</returns>
[HttpGet]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult ChangePassword()
{
if (!Context.User.IsAuthenticated)
{
return Redirect("/login");
}
return View(this.CurrentRenderingView);
}
/// <summary>
/// Handles a user trying to register
/// </summary>
/// <param name="inputModel">The input model.</param>
/// <returns>
/// The view to display to the user after they register
/// </returns>
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult Register(RegisterUserInputModel inputModel)
{
try
{
Assert.ArgumentNotNull(inputModel, "RegisterInputModel");
RegisterBaseJsonResult result = new RegisterBaseJsonResult();
this.ValidateModel(result);
if (result.HasErrors)
{
return Json(result, JsonRequestBehavior.AllowGet);
}
var anonymousVisitorId = this.CurrentVisitorContext.UserId;
var response = this.AccountManager.RegisterUser(this.CurrentStorefront, inputModel);
if (response.ServiceProviderResult.Success && response.Result != null)
{
result.Initialize(response.Result);
this.AccountManager.Login(CurrentStorefront, CurrentVisitorContext, anonymousVisitorId, response.Result.UserName, inputModel.Password, false);
}
else
{
result.SetErrors(response.ServiceProviderResult);
}
return Json(result);
}
catch (Exception e)
{
CommerceLog.Current.Error("Register", this, e);
return Json(new BaseJsonResult("Register", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Handles a user trying to login
/// </summary>
/// <param name="model">The user's login details</param>
/// <returns>The view to display to the user</returns>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "No required for this scenario")]
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult Login(LoginModel model)
{
var anonymousVisitorId = this.CurrentVisitorContext.UserId;
if (ModelState.IsValid && this.AccountManager.Login(CurrentStorefront, CurrentVisitorContext, anonymousVisitorId, UpdateUserName(model.UserName), model.Password, model.RememberMe))
{
return RedirectToLocal(StorefrontManager.StorefrontHome);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
return View(this.GetRenderingView("Login"));
}
/// <summary>
/// Changes the password.
/// </summary>
/// <param name="inputModel">The input model.</param>
/// <returns>
/// The result in Json format.
/// </returns>
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult ChangePassword(ChangePasswordInputModel inputModel)
{
try
{
Assert.ArgumentNotNull(inputModel, "ChangePasswordInputModel");
ChangePasswordBaseJsonResult result = new ChangePasswordBaseJsonResult();
this.ValidateModel(result);
if (result.HasErrors)
{
return Json(result, JsonRequestBehavior.AllowGet);
}
var response = this.AccountManager.UpdateUserPassword(this.CurrentStorefront, this.CurrentVisitorContext, inputModel);
result = new ChangePasswordBaseJsonResult(response.ServiceProviderResult);
if (response.ServiceProviderResult.Success)
{
result.Initialize(this.CurrentVisitorContext.UserName);
}
return Json(result);
}
catch (Exception e)
{
CommerceLog.Current.Error("ChangePassword", this, e);
return Json(new BaseJsonResult("ChangePassword", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Orderses the history.
/// </summary>
/// <returns>
/// The view to display all orders for current user
/// </returns>
[HttpGet]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult MyOrders()
{
if (!Context.User.IsAuthenticated)
{
return Redirect("/login");
}
var commerceUser = this.AccountManager.GetUser(Context.User.Name).Result;
var orders = this.OrderManager.GetOrders(commerceUser.ExternalId, Context.Site.Name).Result;
return View(this.CurrentRenderingView, orders.ToList());
}
/// <summary>
/// Orders the detail.
/// </summary>
/// <param name="id">The order confirmation Id.</param>
/// <returns>
/// The view to display order details
/// </returns>
[HttpGet]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult MyOrder(string id)
{
if (!Context.User.IsAuthenticated)
{
return Redirect("/login");
}
var response = this.OrderManager.GetOrderDetails(CurrentStorefront, CurrentVisitorContext, id);
ViewBag.IsItemShipping = response.Result.Shipping != null && response.Result.Shipping.Count > 1 && response.Result.Lines.Count > 1;
return View(this.CurrentRenderingView, response.Result);
}
/// <summary>
/// Recent Orders PlugIn for Account Management Home Page
/// </summary>
/// <returns>The view to display recent orders</returns>
[HttpPost]
[Authorize]
[ValidateJsonAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult RecentOrders()
{
try
{
var recentOrders = new List<OrderHeader>();
var userResponse = this.AccountManager.GetUser(Context.User.Name);
var result = new OrdersBaseJsonResult(userResponse.ServiceProviderResult);
if (userResponse.ServiceProviderResult.Success && userResponse.Result != null)
{
var commerceUser = userResponse.Result;
var response = this.OrderManager.GetOrders(commerceUser.ExternalId, Context.Site.Name);
result.SetErrors(response.ServiceProviderResult);
if (response.ServiceProviderResult.Success && response.Result != null)
{
var orders = response.Result.ToList();
recentOrders = orders.Where(order => (order as CommerceOrderHeader).LastModified > DateTime.Today.AddDays(-30)).Take(5).ToList();
}
}
result.Initialize(recentOrders);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("RecentOrders", this, e);
return Json(new BaseJsonResult("RecentOrders", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Profile PlugIn for Account Management Home Page
/// </summary>
/// <returns>The view to display profile page</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AccountHomeProfile()
{
if (!Context.User.IsAuthenticated)
{
return Redirect("/login");
}
var model = new ProfileModel();
if (Context.User.IsAuthenticated && !Context.User.Profile.IsAdministrator)
{
var commerceUser = this.AccountManager.GetUser(Context.User.Name).Result;
if (commerceUser != null)
{
model.FirstName = commerceUser.FirstName;
model.Email = commerceUser.Email;
model.LastName = commerceUser.LastName;
model.TelephoneNumber = commerceUser.GetPropertyValue("Phone") as string;
}
}
Item item = Context.Item.Children.SingleOrDefault(p => p.Name == "EditProfile");
if (item != null)
{
//If there is a specially EditProfile then use it
ViewBag.EditProfileLink = LinkManager.GetDynamicUrl(item);
}
else
{
//Else go global Edit Profile
item = Context.Item.Database.GetItem("/sitecore/content/Home/MyAccount/Profile");
ViewBag.EditProfileLink = LinkManager.GetDynamicUrl(item);
}
return View(CurrentRenderingView, model);
}
/// <summary>
/// Address Book in the Home Page
/// </summary>
/// <returns>The list of addresses</returns>
[HttpPost]
[Authorize]
[ValidateJsonAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
[StorefrontSessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public JsonResult AddressList()
{
try
{
var result = new AddressListItemJsonResult();
var addresses = this.AllAddresses(result);
var countries = this.GetAvailableCountries(result);
result.Initialize(addresses, countries);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("AddressList", this, e);
return Json(new BaseJsonResult("AddressList", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Handles deleting of an address and removing it from a user's profile
/// </summary>
/// <param name="model">The model.</param>
/// <returns>
/// The JsonResult with deleting operation status
/// </returns>
[HttpPost]
[Authorize]
[ValidateJsonAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult AddressDelete(DeletePartyInputModelItem model)
{
try
{
Assert.ArgumentNotNull(model, "model");
var validationResult = new BaseJsonResult();
this.ValidateModel(validationResult);
if (validationResult.HasErrors)
{
return Json(validationResult, JsonRequestBehavior.AllowGet);
}
var addresses = new List<CommerceParty>();
var response = this.AccountManager.RemovePartiesFromCurrentUser(this.CurrentStorefront, this.CurrentVisitorContext, model.ExternalId);
var result = new AddressListItemJsonResult(response.ServiceProviderResult);
if (response.ServiceProviderResult.Success)
{
addresses = this.AllAddresses(result);
}
result.Initialize(addresses, null);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("AddressDelete", this, e);
return Json(new BaseJsonResult("AddressDelete", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Handles updates to an address
/// </summary>
/// <param name="model">Any changes to the address</param>
/// <returns>
/// The view to display the updated address
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
[HttpPost]
[Authorize]
[ValidateJsonAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult AddressModify(PartyInputModelItem model)
{
try
{
Assert.ArgumentNotNull(model, "model");
var validationResult = new BaseJsonResult();
this.ValidateModel(validationResult);
if (validationResult.HasErrors)
{
return Json(validationResult, JsonRequestBehavior.AllowGet);
}
var addresses = new List<CommerceParty>();
var userResponse = this.AccountManager.GetUser(Context.User.Name);
var result = new AddressListItemJsonResult(userResponse.ServiceProviderResult);
if (userResponse.ServiceProviderResult.Success && userResponse.Result != null)
{
var commerceUser = userResponse.Result;
var customer = new CommerceCustomer { ExternalId = commerceUser.ExternalId };
var party = new CommerceParty
{
ExternalId = model.ExternalId,
Name = model.Name,
Address1 = model.Address1,
City = model.City,
Country = model.Country,
State = model.State,
ZipPostalCode = model.ZipPostalCode,
PartyId = model.PartyId,
IsPrimary = model.IsPrimary
};
if (string.IsNullOrEmpty(party.ExternalId))
{
// Verify we have not reached the maximum number of addresses supported.
int numberOfAddresses = this.AllAddresses(result).Count;
if (numberOfAddresses >= StorefrontManager.CurrentStorefront.MaxNumberOfAddresses)
{
var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.MaxAddressLimitReached);
result.Errors.Add(string.Format(CultureInfo.InvariantCulture, message, numberOfAddresses));
result.Success = false;
}
else
{
party.ExternalId = Guid.NewGuid().ToString("B");
var response = this.AccountManager.AddParties(this.CurrentStorefront, customer, new List<Sitecore.Commerce.Entities.Party> { party });
result.SetErrors(response.ServiceProviderResult);
if (response.ServiceProviderResult.Success)
{
addresses = this.AllAddresses(result);
}
result.Initialize(addresses, null);
}
}
else
{
var response = this.AccountManager.UpdateParties(this.CurrentStorefront, customer, new List<Sitecore.Commerce.Entities.Party> { party });
result.SetErrors(response.ServiceProviderResult);
if (response.ServiceProviderResult.Success)
{
addresses = this.AllAddresses(result);
}
result.Initialize(addresses, null);
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("AddressModify", this, e);
return Json(new BaseJsonResult("AddressModify", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Updates the profile.
/// </summary>
/// <param name="model">The model.</param>
/// <returns>The result in Json format.</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult UpdateProfile(ProfileModel model)
{
try
{
Assert.ArgumentNotNull(model, "UpdateProfileInputModel");
ProfileBaseJsonResult result = new ProfileBaseJsonResult();
this.ValidateModel(result);
if (result.HasErrors)
{
return Json(result, JsonRequestBehavior.AllowGet);
}
if (!Context.User.IsAuthenticated || Context.User.Profile.IsAdministrator)
{
return Json(result);
}
var response = this.AccountManager.UpdateUser(this.CurrentStorefront, this.CurrentVisitorContext, model);
result.SetErrors(response.ServiceProviderResult);
if (response.ServiceProviderResult.Success && !string.IsNullOrWhiteSpace(model.Password) && !string.IsNullOrWhiteSpace(model.PasswordRepeat))
{
var changePasswordModel = new ChangePasswordInputModel { NewPassword = model.Password, ConfirmPassword = model.PasswordRepeat };
var passwordChangeResponse = this.AccountManager.UpdateUserPassword(this.CurrentStorefront, this.CurrentVisitorContext, changePasswordModel);
result.SetErrors(passwordChangeResponse.ServiceProviderResult);
if (passwordChangeResponse.ServiceProviderResult.Success)
{
result.Initialize(response.ServiceProviderResult);
}
}
return Json(result);
}
catch (Exception e)
{
CommerceLog.Current.Error("UpdateProfile", this, e);
return Json(new BaseJsonResult("UpdateProfile", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Gets the current user.
/// </summary>
/// <returns>The current authenticated user info</returns>
[HttpPost]
[AllowAnonymous]
[ValidateJsonAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
[StorefrontSessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public JsonResult GetCurrentUser()
{
try
{
if (!Context.User.IsAuthenticated || Context.User.Profile.IsAdministrator)
{
var anonymousResult = new UserBaseJsonResult();
anonymousResult.Initialize(new CommerceUser());
return Json(anonymousResult, JsonRequestBehavior.AllowGet);
}
var response = this.AccountManager.GetUser(Context.User.Name);
var result = new UserBaseJsonResult(response.ServiceProviderResult);
if (response.ServiceProviderResult.Success && response.Result != null)
{
result.Initialize(response.Result);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("GetCurrentUser", this, e);
return Json(new BaseJsonResult("GetCurrentUser", e), JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// Forgots the password.
/// </summary>
/// <param name="model">The model.</param>
/// <returns>The result in json format</returns>
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public JsonResult ForgotPassword(ForgotPasswordInputModel model)
{
try
{
Assert.ArgumentNotNull(model, "model");
ForgotPasswordBaseJsonResult result = new ForgotPasswordBaseJsonResult();
this.ValidateModel(result);
if (result.HasErrors)
{
return Json(result, JsonRequestBehavior.AllowGet);
}
var resetResponse = this.AccountManager.ResetUserPassword(this.CurrentStorefront, model);
if (!resetResponse.ServiceProviderResult.Success)
{
return Json(new ForgotPasswordBaseJsonResult(resetResponse.ServiceProviderResult));
}
result.Initialize(model.Email);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
CommerceLog.Current.Error("ForgotPassword", this, e);
return Json(new BaseJsonResult("ForgotPassword", e), JsonRequestBehavior.AllowGet);
}
}
#endregion
#region Helpers
/// <summary>
/// Concats the user name with the current domain if it missing
/// </summary>
/// <param name="userName">The user's user name</param>
/// <returns>The updated user name</returns>
public virtual string UpdateUserName(string userName)
{
var defaultDomain = CommerceServerSitecoreConfig.Current.DefaultCommerceUsersDomain;
if (string.IsNullOrWhiteSpace(defaultDomain))
{
defaultDomain = CommerceConstants.ProfilesStrings.CommerceUsersDomainName;
}
return !userName.StartsWith(defaultDomain, StringComparison.OrdinalIgnoreCase) ? string.Concat(defaultDomain, @"\", userName) : userName;
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("/");
}
private Dictionary<string, string> GetAvailableCountries(AddressListItemJsonResult result)
{
var countries = new Dictionary<string, string>();
var response = OrderManager.GetAvailableCountries();
if (response.ServiceProviderResult.Success && response.Result != null)
{
countries = response.Result;
}
result.SetErrors(response.ServiceProviderResult);
return countries;
}
private List<CommerceParty> AllAddresses(AddressListItemJsonResult result)
{
var addresses = new List<CommerceParty>();
var response = this.AccountManager.GetCurrentCustomerParties(this.CurrentStorefront, this.CurrentVisitorContext);
if (response.ServiceProviderResult.Success && response.Result != null)
{
addresses = response.Result.ToList();
}
result.SetErrors(response.ServiceProviderResult);
return addresses;
}
#endregion
}
}
| 40.835017 | 193 | 0.553403 | [
"Apache-2.0"
] | Sitecore/Reference-Storefront | Storefront/CF/CSF/Controllers/AccountController.cs | 36,386 | C# |
using System;
using System.IO;
namespace Org.BouncyCastle.Crypto.Tls
{
public interface TlsEncryptionCredentials
: TlsCredentials
{
/// <exception cref="IOException"></exception>
byte[] DecryptPreMasterSecret(byte[] encryptedPreMasterSecret);
}
}
| 23 | 72 | 0.658863 | [
"Apache-2.0",
"MIT"
] | flobecker/trudi-koala | src/IVU.BouncyCastle.Crypto/src/crypto/tls/TlsEncryptionCredentials.cs | 301 | C# |
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Sentry.Http;
namespace Sentry.Benchmarks;
internal class FakeHttpClientFactory : ISentryHttpClientFactory
{
public HttpClient Create(SentryOptions options) => new(new FakeMessageHandler());
}
internal class FakeMessageHandler : DelegatingHandler
{
private readonly Task<HttpResponseMessage> _result;
public FakeMessageHandler(HttpStatusCode statusCode = HttpStatusCode.OK)
=> _result = Task.FromResult<HttpResponseMessage>(new StatusCodeResponse(statusCode));
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
=> _result;
}
internal class StatusCodeResponse : HttpResponseMessage
{
public StatusCodeResponse(HttpStatusCode statusCode)
: base(statusCode)
{
if (statusCode == HttpStatusCode.TooManyRequests)
{
Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromHours(24));
}
}
}
| 28.351351 | 94 | 0.744519 | [
"MIT"
] | TawasalMessenger/sentry-dotnet | benchmarks/Sentry.Benchmarks/FakeHttpClientFactory.cs | 1,049 | 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 codeguruprofiler-2019-07-18.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.CodeGuruProfiler;
using Amazon.CodeGuruProfiler.Model;
using Amazon.CodeGuruProfiler.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 CodeGuruProfilerMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("codeguruprofiler");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void AddNotificationChannelsMarshallTest()
{
var operation = service_model.FindOperation("AddNotificationChannels");
var request = InstantiateClassGenerator.Execute<AddNotificationChannelsRequest>();
var marshaller = new AddNotificationChannelsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("AddNotificationChannels", 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 = AddNotificationChannelsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as AddNotificationChannelsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void AddNotificationChannels_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("AddNotificationChannels");
var request = InstantiateClassGenerator.Execute<AddNotificationChannelsRequest>();
var marshaller = new AddNotificationChannelsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("AddNotificationChannels", 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 = AddNotificationChannelsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void AddNotificationChannels_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("AddNotificationChannels");
var request = InstantiateClassGenerator.Execute<AddNotificationChannelsRequest>();
var marshaller = new AddNotificationChannelsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("AddNotificationChannels", 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 = AddNotificationChannelsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void AddNotificationChannels_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("AddNotificationChannels");
var request = InstantiateClassGenerator.Execute<AddNotificationChannelsRequest>();
var marshaller = new AddNotificationChannelsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("AddNotificationChannels", 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 = AddNotificationChannelsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void AddNotificationChannels_ServiceQuotaExceededExceptionMarshallTest()
{
var operation = service_model.FindOperation("AddNotificationChannels");
var request = InstantiateClassGenerator.Execute<AddNotificationChannelsRequest>();
var marshaller = new AddNotificationChannelsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("AddNotificationChannels", 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 = AddNotificationChannelsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void AddNotificationChannels_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("AddNotificationChannels");
var request = InstantiateClassGenerator.Execute<AddNotificationChannelsRequest>();
var marshaller = new AddNotificationChannelsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("AddNotificationChannels", 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 = AddNotificationChannelsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void AddNotificationChannels_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("AddNotificationChannels");
var request = InstantiateClassGenerator.Execute<AddNotificationChannelsRequest>();
var marshaller = new AddNotificationChannelsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("AddNotificationChannels", 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 = AddNotificationChannelsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void BatchGetFrameMetricDataMarshallTest()
{
var operation = service_model.FindOperation("BatchGetFrameMetricData");
var request = InstantiateClassGenerator.Execute<BatchGetFrameMetricDataRequest>();
var marshaller = new BatchGetFrameMetricDataRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("BatchGetFrameMetricData", 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 = BatchGetFrameMetricDataResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as BatchGetFrameMetricDataResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void BatchGetFrameMetricData_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("BatchGetFrameMetricData");
var request = InstantiateClassGenerator.Execute<BatchGetFrameMetricDataRequest>();
var marshaller = new BatchGetFrameMetricDataRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("BatchGetFrameMetricData", 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 = BatchGetFrameMetricDataResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void BatchGetFrameMetricData_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("BatchGetFrameMetricData");
var request = InstantiateClassGenerator.Execute<BatchGetFrameMetricDataRequest>();
var marshaller = new BatchGetFrameMetricDataRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("BatchGetFrameMetricData", 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 = BatchGetFrameMetricDataResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void BatchGetFrameMetricData_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("BatchGetFrameMetricData");
var request = InstantiateClassGenerator.Execute<BatchGetFrameMetricDataRequest>();
var marshaller = new BatchGetFrameMetricDataRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("BatchGetFrameMetricData", 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 = BatchGetFrameMetricDataResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void BatchGetFrameMetricData_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("BatchGetFrameMetricData");
var request = InstantiateClassGenerator.Execute<BatchGetFrameMetricDataRequest>();
var marshaller = new BatchGetFrameMetricDataRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("BatchGetFrameMetricData", 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 = BatchGetFrameMetricDataResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ConfigureAgentMarshallTest()
{
var operation = service_model.FindOperation("ConfigureAgent");
var request = InstantiateClassGenerator.Execute<ConfigureAgentRequest>();
var marshaller = new ConfigureAgentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureAgent", 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 = ConfigureAgentResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ConfigureAgentResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ConfigureAgent_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureAgent");
var request = InstantiateClassGenerator.Execute<ConfigureAgentRequest>();
var marshaller = new ConfigureAgentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureAgent", 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 = ConfigureAgentResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ConfigureAgent_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureAgent");
var request = InstantiateClassGenerator.Execute<ConfigureAgentRequest>();
var marshaller = new ConfigureAgentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureAgent", 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 = ConfigureAgentResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ConfigureAgent_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureAgent");
var request = InstantiateClassGenerator.Execute<ConfigureAgentRequest>();
var marshaller = new ConfigureAgentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureAgent", 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 = ConfigureAgentResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ConfigureAgent_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureAgent");
var request = InstantiateClassGenerator.Execute<ConfigureAgentRequest>();
var marshaller = new ConfigureAgentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureAgent", 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 = ConfigureAgentResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void CreateProfilingGroupMarshallTest()
{
var operation = service_model.FindOperation("CreateProfilingGroup");
var request = InstantiateClassGenerator.Execute<CreateProfilingGroupRequest>();
var marshaller = new CreateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateProfilingGroup", 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 = CreateProfilingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as CreateProfilingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void CreateProfilingGroup_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateProfilingGroup");
var request = InstantiateClassGenerator.Execute<CreateProfilingGroupRequest>();
var marshaller = new CreateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateProfilingGroup", 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 = CreateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void CreateProfilingGroup_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateProfilingGroup");
var request = InstantiateClassGenerator.Execute<CreateProfilingGroupRequest>();
var marshaller = new CreateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateProfilingGroup", 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 = CreateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void CreateProfilingGroup_ServiceQuotaExceededExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateProfilingGroup");
var request = InstantiateClassGenerator.Execute<CreateProfilingGroupRequest>();
var marshaller = new CreateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateProfilingGroup", 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 = CreateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void CreateProfilingGroup_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateProfilingGroup");
var request = InstantiateClassGenerator.Execute<CreateProfilingGroupRequest>();
var marshaller = new CreateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateProfilingGroup", 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 = CreateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void CreateProfilingGroup_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateProfilingGroup");
var request = InstantiateClassGenerator.Execute<CreateProfilingGroupRequest>();
var marshaller = new CreateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateProfilingGroup", 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 = CreateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DeleteProfilingGroupMarshallTest()
{
var operation = service_model.FindOperation("DeleteProfilingGroup");
var request = InstantiateClassGenerator.Execute<DeleteProfilingGroupRequest>();
var marshaller = new DeleteProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteProfilingGroup", 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 = DeleteProfilingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DeleteProfilingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DeleteProfilingGroup_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteProfilingGroup");
var request = InstantiateClassGenerator.Execute<DeleteProfilingGroupRequest>();
var marshaller = new DeleteProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteProfilingGroup", 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 = DeleteProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DeleteProfilingGroup_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteProfilingGroup");
var request = InstantiateClassGenerator.Execute<DeleteProfilingGroupRequest>();
var marshaller = new DeleteProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteProfilingGroup", 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 = DeleteProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DeleteProfilingGroup_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteProfilingGroup");
var request = InstantiateClassGenerator.Execute<DeleteProfilingGroupRequest>();
var marshaller = new DeleteProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteProfilingGroup", 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 = DeleteProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DeleteProfilingGroup_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteProfilingGroup");
var request = InstantiateClassGenerator.Execute<DeleteProfilingGroupRequest>();
var marshaller = new DeleteProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteProfilingGroup", 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 = DeleteProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DeleteProfilingGroup_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteProfilingGroup");
var request = InstantiateClassGenerator.Execute<DeleteProfilingGroupRequest>();
var marshaller = new DeleteProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteProfilingGroup", 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 = DeleteProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DescribeProfilingGroupMarshallTest()
{
var operation = service_model.FindOperation("DescribeProfilingGroup");
var request = InstantiateClassGenerator.Execute<DescribeProfilingGroupRequest>();
var marshaller = new DescribeProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeProfilingGroup", 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 = DescribeProfilingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DescribeProfilingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DescribeProfilingGroup_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeProfilingGroup");
var request = InstantiateClassGenerator.Execute<DescribeProfilingGroupRequest>();
var marshaller = new DescribeProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeProfilingGroup", 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 = DescribeProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DescribeProfilingGroup_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeProfilingGroup");
var request = InstantiateClassGenerator.Execute<DescribeProfilingGroupRequest>();
var marshaller = new DescribeProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeProfilingGroup", 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 = DescribeProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DescribeProfilingGroup_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeProfilingGroup");
var request = InstantiateClassGenerator.Execute<DescribeProfilingGroupRequest>();
var marshaller = new DescribeProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeProfilingGroup", 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 = DescribeProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void DescribeProfilingGroup_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeProfilingGroup");
var request = InstantiateClassGenerator.Execute<DescribeProfilingGroupRequest>();
var marshaller = new DescribeProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeProfilingGroup", 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 = DescribeProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetFindingsReportAccountSummaryMarshallTest()
{
var operation = service_model.FindOperation("GetFindingsReportAccountSummary");
var request = InstantiateClassGenerator.Execute<GetFindingsReportAccountSummaryRequest>();
var marshaller = new GetFindingsReportAccountSummaryRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFindingsReportAccountSummary", 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 = GetFindingsReportAccountSummaryResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as GetFindingsReportAccountSummaryResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetFindingsReportAccountSummary_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFindingsReportAccountSummary");
var request = InstantiateClassGenerator.Execute<GetFindingsReportAccountSummaryRequest>();
var marshaller = new GetFindingsReportAccountSummaryRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFindingsReportAccountSummary", 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 = GetFindingsReportAccountSummaryResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetFindingsReportAccountSummary_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFindingsReportAccountSummary");
var request = InstantiateClassGenerator.Execute<GetFindingsReportAccountSummaryRequest>();
var marshaller = new GetFindingsReportAccountSummaryRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFindingsReportAccountSummary", 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 = GetFindingsReportAccountSummaryResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetFindingsReportAccountSummary_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetFindingsReportAccountSummary");
var request = InstantiateClassGenerator.Execute<GetFindingsReportAccountSummaryRequest>();
var marshaller = new GetFindingsReportAccountSummaryRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetFindingsReportAccountSummary", 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 = GetFindingsReportAccountSummaryResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetNotificationConfigurationMarshallTest()
{
var operation = service_model.FindOperation("GetNotificationConfiguration");
var request = InstantiateClassGenerator.Execute<GetNotificationConfigurationRequest>();
var marshaller = new GetNotificationConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetNotificationConfiguration", 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 = GetNotificationConfigurationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as GetNotificationConfigurationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetNotificationConfiguration_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetNotificationConfiguration");
var request = InstantiateClassGenerator.Execute<GetNotificationConfigurationRequest>();
var marshaller = new GetNotificationConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetNotificationConfiguration", 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 = GetNotificationConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetNotificationConfiguration_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetNotificationConfiguration");
var request = InstantiateClassGenerator.Execute<GetNotificationConfigurationRequest>();
var marshaller = new GetNotificationConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetNotificationConfiguration", 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 = GetNotificationConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetNotificationConfiguration_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetNotificationConfiguration");
var request = InstantiateClassGenerator.Execute<GetNotificationConfigurationRequest>();
var marshaller = new GetNotificationConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetNotificationConfiguration", 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 = GetNotificationConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetNotificationConfiguration_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetNotificationConfiguration");
var request = InstantiateClassGenerator.Execute<GetNotificationConfigurationRequest>();
var marshaller = new GetNotificationConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetNotificationConfiguration", 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 = GetNotificationConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetPolicyMarshallTest()
{
var operation = service_model.FindOperation("GetPolicy");
var request = InstantiateClassGenerator.Execute<GetPolicyRequest>();
var marshaller = new GetPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetPolicy", 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 = GetPolicyResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as GetPolicyResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetPolicy_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetPolicy");
var request = InstantiateClassGenerator.Execute<GetPolicyRequest>();
var marshaller = new GetPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetPolicy", 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 = GetPolicyResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetPolicy_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetPolicy");
var request = InstantiateClassGenerator.Execute<GetPolicyRequest>();
var marshaller = new GetPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetPolicy", 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 = GetPolicyResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetPolicy_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetPolicy");
var request = InstantiateClassGenerator.Execute<GetPolicyRequest>();
var marshaller = new GetPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetPolicy", 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 = GetPolicyResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetProfileMarshallTest()
{
var operation = service_model.FindOperation("GetProfile");
var request = InstantiateClassGenerator.Execute<GetProfileRequest>();
var marshaller = new GetProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetProfile", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"Content-Encoding","Content-Encoding_Value"},
{"Content-Type","Content-Type_Value"},
{"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 = GetProfileResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as GetProfileResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetProfile_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetProfile");
var request = InstantiateClassGenerator.Execute<GetProfileRequest>();
var marshaller = new GetProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetProfile", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerException"));
var webResponse = new WebResponseData
{
Headers = {
{"Content-Encoding","Content-Encoding_Value"},
{"Content-Type","Content-Type_Value"},
{"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 = GetProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetProfile_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetProfile");
var request = InstantiateClassGenerator.Execute<GetProfileRequest>();
var marshaller = new GetProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetProfile", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"Content-Encoding","Content-Encoding_Value"},
{"Content-Type","Content-Type_Value"},
{"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 = GetProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetProfile_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetProfile");
var request = InstantiateClassGenerator.Execute<GetProfileRequest>();
var marshaller = new GetProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetProfile", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ThrottlingException"));
var webResponse = new WebResponseData
{
Headers = {
{"Content-Encoding","Content-Encoding_Value"},
{"Content-Type","Content-Type_Value"},
{"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 = GetProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetProfile_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetProfile");
var request = InstantiateClassGenerator.Execute<GetProfileRequest>();
var marshaller = new GetProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetProfile", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ValidationException"));
var webResponse = new WebResponseData
{
Headers = {
{"Content-Encoding","Content-Encoding_Value"},
{"Content-Type","Content-Type_Value"},
{"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 = GetProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetRecommendationsMarshallTest()
{
var operation = service_model.FindOperation("GetRecommendations");
var request = InstantiateClassGenerator.Execute<GetRecommendationsRequest>();
var marshaller = new GetRecommendationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetRecommendations", 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 = GetRecommendationsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as GetRecommendationsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetRecommendations_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetRecommendations");
var request = InstantiateClassGenerator.Execute<GetRecommendationsRequest>();
var marshaller = new GetRecommendationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetRecommendations", 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 = GetRecommendationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetRecommendations_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetRecommendations");
var request = InstantiateClassGenerator.Execute<GetRecommendationsRequest>();
var marshaller = new GetRecommendationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetRecommendations", 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 = GetRecommendationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetRecommendations_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetRecommendations");
var request = InstantiateClassGenerator.Execute<GetRecommendationsRequest>();
var marshaller = new GetRecommendationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetRecommendations", 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 = GetRecommendationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void GetRecommendations_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("GetRecommendations");
var request = InstantiateClassGenerator.Execute<GetRecommendationsRequest>();
var marshaller = new GetRecommendationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("GetRecommendations", 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 = GetRecommendationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListFindingsReportsMarshallTest()
{
var operation = service_model.FindOperation("ListFindingsReports");
var request = InstantiateClassGenerator.Execute<ListFindingsReportsRequest>();
var marshaller = new ListFindingsReportsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindingsReports", 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 = ListFindingsReportsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ListFindingsReportsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListFindingsReports_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindingsReports");
var request = InstantiateClassGenerator.Execute<ListFindingsReportsRequest>();
var marshaller = new ListFindingsReportsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindingsReports", 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 = ListFindingsReportsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListFindingsReports_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindingsReports");
var request = InstantiateClassGenerator.Execute<ListFindingsReportsRequest>();
var marshaller = new ListFindingsReportsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindingsReports", 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 = ListFindingsReportsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListFindingsReports_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindingsReports");
var request = InstantiateClassGenerator.Execute<ListFindingsReportsRequest>();
var marshaller = new ListFindingsReportsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindingsReports", 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 = ListFindingsReportsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListFindingsReports_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListFindingsReports");
var request = InstantiateClassGenerator.Execute<ListFindingsReportsRequest>();
var marshaller = new ListFindingsReportsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListFindingsReports", 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 = ListFindingsReportsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfileTimesMarshallTest()
{
var operation = service_model.FindOperation("ListProfileTimes");
var request = InstantiateClassGenerator.Execute<ListProfileTimesRequest>();
var marshaller = new ListProfileTimesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfileTimes", 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 = ListProfileTimesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ListProfileTimesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfileTimes_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListProfileTimes");
var request = InstantiateClassGenerator.Execute<ListProfileTimesRequest>();
var marshaller = new ListProfileTimesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfileTimes", 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 = ListProfileTimesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfileTimes_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListProfileTimes");
var request = InstantiateClassGenerator.Execute<ListProfileTimesRequest>();
var marshaller = new ListProfileTimesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfileTimes", 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 = ListProfileTimesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfileTimes_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListProfileTimes");
var request = InstantiateClassGenerator.Execute<ListProfileTimesRequest>();
var marshaller = new ListProfileTimesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfileTimes", 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 = ListProfileTimesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfileTimes_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListProfileTimes");
var request = InstantiateClassGenerator.Execute<ListProfileTimesRequest>();
var marshaller = new ListProfileTimesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfileTimes", 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 = ListProfileTimesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfilingGroupsMarshallTest()
{
var operation = service_model.FindOperation("ListProfilingGroups");
var request = InstantiateClassGenerator.Execute<ListProfilingGroupsRequest>();
var marshaller = new ListProfilingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfilingGroups", 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 = ListProfilingGroupsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ListProfilingGroupsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfilingGroups_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListProfilingGroups");
var request = InstantiateClassGenerator.Execute<ListProfilingGroupsRequest>();
var marshaller = new ListProfilingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfilingGroups", 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 = ListProfilingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void ListProfilingGroups_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListProfilingGroups");
var request = InstantiateClassGenerator.Execute<ListProfilingGroupsRequest>();
var marshaller = new ListProfilingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListProfilingGroups", 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 = ListProfilingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
public void PostAgentProfileMarshallTest()
{
var operation = service_model.FindOperation("PostAgentProfile");
var request = InstantiateClassGenerator.Execute<PostAgentProfileRequest>();
var marshaller = new PostAgentProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PostAgentProfile", 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 = PostAgentProfileResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as PostAgentProfileResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PostAgentProfile_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("PostAgentProfile");
var request = InstantiateClassGenerator.Execute<PostAgentProfileRequest>();
var marshaller = new PostAgentProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PostAgentProfile", 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 = PostAgentProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PostAgentProfile_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("PostAgentProfile");
var request = InstantiateClassGenerator.Execute<PostAgentProfileRequest>();
var marshaller = new PostAgentProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PostAgentProfile", 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 = PostAgentProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PostAgentProfile_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("PostAgentProfile");
var request = InstantiateClassGenerator.Execute<PostAgentProfileRequest>();
var marshaller = new PostAgentProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PostAgentProfile", 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 = PostAgentProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PostAgentProfile_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("PostAgentProfile");
var request = InstantiateClassGenerator.Execute<PostAgentProfileRequest>();
var marshaller = new PostAgentProfileRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PostAgentProfile", 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 = PostAgentProfileResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PutPermissionMarshallTest()
{
var operation = service_model.FindOperation("PutPermission");
var request = InstantiateClassGenerator.Execute<PutPermissionRequest>();
var marshaller = new PutPermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PutPermission", 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 = PutPermissionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as PutPermissionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PutPermission_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("PutPermission");
var request = InstantiateClassGenerator.Execute<PutPermissionRequest>();
var marshaller = new PutPermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PutPermission", 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 = PutPermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PutPermission_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("PutPermission");
var request = InstantiateClassGenerator.Execute<PutPermissionRequest>();
var marshaller = new PutPermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PutPermission", 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 = PutPermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PutPermission_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("PutPermission");
var request = InstantiateClassGenerator.Execute<PutPermissionRequest>();
var marshaller = new PutPermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PutPermission", 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 = PutPermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PutPermission_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("PutPermission");
var request = InstantiateClassGenerator.Execute<PutPermissionRequest>();
var marshaller = new PutPermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PutPermission", 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 = PutPermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void PutPermission_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("PutPermission");
var request = InstantiateClassGenerator.Execute<PutPermissionRequest>();
var marshaller = new PutPermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("PutPermission", 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 = PutPermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemoveNotificationChannelMarshallTest()
{
var operation = service_model.FindOperation("RemoveNotificationChannel");
var request = InstantiateClassGenerator.Execute<RemoveNotificationChannelRequest>();
var marshaller = new RemoveNotificationChannelRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemoveNotificationChannel", 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 = RemoveNotificationChannelResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as RemoveNotificationChannelResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemoveNotificationChannel_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemoveNotificationChannel");
var request = InstantiateClassGenerator.Execute<RemoveNotificationChannelRequest>();
var marshaller = new RemoveNotificationChannelRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemoveNotificationChannel", 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 = RemoveNotificationChannelResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemoveNotificationChannel_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemoveNotificationChannel");
var request = InstantiateClassGenerator.Execute<RemoveNotificationChannelRequest>();
var marshaller = new RemoveNotificationChannelRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemoveNotificationChannel", 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 = RemoveNotificationChannelResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemoveNotificationChannel_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemoveNotificationChannel");
var request = InstantiateClassGenerator.Execute<RemoveNotificationChannelRequest>();
var marshaller = new RemoveNotificationChannelRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemoveNotificationChannel", 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 = RemoveNotificationChannelResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemoveNotificationChannel_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemoveNotificationChannel");
var request = InstantiateClassGenerator.Execute<RemoveNotificationChannelRequest>();
var marshaller = new RemoveNotificationChannelRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemoveNotificationChannel", 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 = RemoveNotificationChannelResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemovePermissionMarshallTest()
{
var operation = service_model.FindOperation("RemovePermission");
var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>();
var marshaller = new RemovePermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemovePermission", 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 = RemovePermissionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as RemovePermissionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemovePermission_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemovePermission");
var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>();
var marshaller = new RemovePermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemovePermission", 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 = RemovePermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemovePermission_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemovePermission");
var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>();
var marshaller = new RemovePermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemovePermission", 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 = RemovePermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemovePermission_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemovePermission");
var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>();
var marshaller = new RemovePermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemovePermission", 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 = RemovePermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemovePermission_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemovePermission");
var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>();
var marshaller = new RemovePermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemovePermission", 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 = RemovePermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void RemovePermission_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("RemovePermission");
var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>();
var marshaller = new RemovePermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("RemovePermission", 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 = RemovePermissionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void SubmitFeedbackMarshallTest()
{
var operation = service_model.FindOperation("SubmitFeedback");
var request = InstantiateClassGenerator.Execute<SubmitFeedbackRequest>();
var marshaller = new SubmitFeedbackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("SubmitFeedback", 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 = SubmitFeedbackResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as SubmitFeedbackResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void SubmitFeedback_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("SubmitFeedback");
var request = InstantiateClassGenerator.Execute<SubmitFeedbackRequest>();
var marshaller = new SubmitFeedbackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("SubmitFeedback", 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 = SubmitFeedbackResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void SubmitFeedback_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("SubmitFeedback");
var request = InstantiateClassGenerator.Execute<SubmitFeedbackRequest>();
var marshaller = new SubmitFeedbackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("SubmitFeedback", 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 = SubmitFeedbackResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void SubmitFeedback_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("SubmitFeedback");
var request = InstantiateClassGenerator.Execute<SubmitFeedbackRequest>();
var marshaller = new SubmitFeedbackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("SubmitFeedback", 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 = SubmitFeedbackResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void SubmitFeedback_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("SubmitFeedback");
var request = InstantiateClassGenerator.Execute<SubmitFeedbackRequest>();
var marshaller = new SubmitFeedbackRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("SubmitFeedback", 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 = SubmitFeedbackResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
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("CodeGuruProfiler")]
public void UpdateProfilingGroupMarshallTest()
{
var operation = service_model.FindOperation("UpdateProfilingGroup");
var request = InstantiateClassGenerator.Execute<UpdateProfilingGroupRequest>();
var marshaller = new UpdateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateProfilingGroup", 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 = UpdateProfilingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as UpdateProfilingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void UpdateProfilingGroup_ConflictExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateProfilingGroup");
var request = InstantiateClassGenerator.Execute<UpdateProfilingGroupRequest>();
var marshaller = new UpdateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateProfilingGroup", 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 = UpdateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void UpdateProfilingGroup_InternalServerExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateProfilingGroup");
var request = InstantiateClassGenerator.Execute<UpdateProfilingGroupRequest>();
var marshaller = new UpdateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateProfilingGroup", 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 = UpdateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void UpdateProfilingGroup_ResourceNotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateProfilingGroup");
var request = InstantiateClassGenerator.Execute<UpdateProfilingGroupRequest>();
var marshaller = new UpdateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateProfilingGroup", 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 = UpdateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void UpdateProfilingGroup_ThrottlingExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateProfilingGroup");
var request = InstantiateClassGenerator.Execute<UpdateProfilingGroupRequest>();
var marshaller = new UpdateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateProfilingGroup", 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 = UpdateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("CodeGuruProfiler")]
public void UpdateProfilingGroup_ValidationExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdateProfilingGroup");
var request = InstantiateClassGenerator.Execute<UpdateProfilingGroupRequest>();
var marshaller = new UpdateProfilingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdateProfilingGroup", 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 = UpdateProfilingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
} | 50.2218 | 153 | 0.655255 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/test/Services/CodeGuruProfiler/UnitTests/Generated/Marshalling/CodeGuruProfilerMarshallingTests.cs | 185,218 | C# |
using System.ComponentModel.DataAnnotations;
namespace Gicco.Module.Core.ViewModels.Manage
{
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
}
| 21.076923 | 47 | 0.649635 | [
"Apache-2.0"
] | dvbtham/gicco | src/Modules/Gicco.Module.Core/Areas/Core/ViewModels/Manage/AddPhoneNumberViewModel.cs | 276 | C# |
/*
* OpenDoc_API-文档访问
*
* API to access AnyShare 如有任何疑问,可到开发者社区提问:https://developers.aishu.cn # Authentication - 调用需要鉴权的API,必须将token放在HTTP header中:\"Authorization: Bearer ACCESS_TOKEN\" - 对于GET请求,除了将token放在HTTP header中,也可以将token放在URL query string中:\"tokenid=ACCESS_TOKEN\"
*
* The version of the OpenAPI document: 6.0.10
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = AnyShareSDK.Client.OpenAPIDateConverter;
namespace AnyShareSDK.Model
{
/// <summary>
/// ContactorSearchcountRes
/// </summary>
[DataContract]
public partial class ContactorSearchcountRes : IEquatable<ContactorSearchcountRes>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ContactorSearchcountRes" /> class.
/// </summary>
[JsonConstructorAttribute]
protected ContactorSearchcountRes() { }
/// <summary>
/// Initializes a new instance of the <see cref="ContactorSearchcountRes" /> class.
/// </summary>
/// <param name="count">搜索数目 (required).</param>
public ContactorSearchcountRes(long? count = default(long?))
{
this.Count = count;
}
/// <summary>
/// 搜索数目
/// </summary>
/// <value>搜索数目</value>
[DataMember(Name="count", EmitDefaultValue=false)]
public long? Count { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ContactorSearchcountRes {\n");
sb.Append(" Count: ").Append(Count).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ContactorSearchcountRes);
}
/// <summary>
/// Returns true if ContactorSearchcountRes instances are equal
/// </summary>
/// <param name="input">Instance of ContactorSearchcountRes to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ContactorSearchcountRes input)
{
if (input == null)
return false;
return
(
this.Count == input.Count ||
(this.Count != null &&
this.Count.Equals(input.Count))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Count != null)
hashCode = hashCode * 59 + this.Count.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 33.206107 | 257 | 0.588046 | [
"MIT"
] | ArtyDinosaur404/AnyShareSDK | AnyShareSDK/Model/ContactorSearchcountRes.cs | 4,486 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
internal partial class ExpressRouteLinksRestClient
{
private string subscriptionId;
private Uri endpoint;
private ClientDiagnostics _clientDiagnostics;
private HttpPipeline _pipeline;
/// <summary> Initializes a new instance of ExpressRouteLinksRestClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="endpoint"> server parameter. </param>
/// <exception cref="ArgumentNullException"> This occurs when one of the required arguments is null. </exception>
public ExpressRouteLinksRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
endpoint ??= new Uri("https://management.azure.com");
this.subscriptionId = subscriptionId;
this.endpoint = endpoint;
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
internal HttpMessage CreateGetRequest(string resourceGroupName, string expressRoutePortName, string linkName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/ExpressRoutePorts/", false);
uri.AppendPath(expressRoutePortName, true);
uri.AppendPath("/links/", false);
uri.AppendPath(linkName, true);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
return message;
}
/// <summary> Retrieves the specified ExpressRouteLink resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="linkName"> The name of the ExpressRouteLink resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<Response<ExpressRouteLink>> GetAsync(string resourceGroupName, string expressRoutePortName, string linkName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
if (linkName == null)
{
throw new ArgumentNullException(nameof(linkName));
}
using var message = CreateGetRequest(resourceGroupName, expressRoutePortName, linkName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteLink value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
if (document.RootElement.ValueKind == JsonValueKind.Null)
{
value = null;
}
else
{
value = ExpressRouteLink.DeserializeExpressRouteLink(document.RootElement);
}
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Retrieves the specified ExpressRouteLink resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="linkName"> The name of the ExpressRouteLink resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public Response<ExpressRouteLink> Get(string resourceGroupName, string expressRoutePortName, string linkName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
if (linkName == null)
{
throw new ArgumentNullException(nameof(linkName));
}
using var message = CreateGetRequest(resourceGroupName, expressRoutePortName, linkName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteLink value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
if (document.RootElement.ValueKind == JsonValueKind.Null)
{
value = null;
}
else
{
value = ExpressRouteLink.DeserializeExpressRouteLink(document.RootElement);
}
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListRequest(string resourceGroupName, string expressRoutePortName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/ExpressRoutePorts/", false);
uri.AppendPath(expressRoutePortName, true);
uri.AppendPath("/links", false);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
return message;
}
/// <summary> Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<Response<ExpressRouteLinkListResult>> ListAsync(string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
using var message = CreateListRequest(resourceGroupName, expressRoutePortName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteLinkListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
if (document.RootElement.ValueKind == JsonValueKind.Null)
{
value = null;
}
else
{
value = ExpressRouteLinkListResult.DeserializeExpressRouteLinkListResult(document.RootElement);
}
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public Response<ExpressRouteLinkListResult> List(string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
using var message = CreateListRequest(resourceGroupName, expressRoutePortName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteLinkListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
if (document.RootElement.ValueKind == JsonValueKind.Null)
{
value = null;
}
else
{
value = ExpressRouteLinkListResult.DeserializeExpressRouteLinkListResult(document.RootElement);
}
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink, string resourceGroupName, string expressRoutePortName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
return message;
}
/// <summary> Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort resource. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<Response<ExpressRouteLinkListResult>> ListNextPageAsync(string nextLink, string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
using var message = CreateListNextPageRequest(nextLink, resourceGroupName, expressRoutePortName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteLinkListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
if (document.RootElement.ValueKind == JsonValueKind.Null)
{
value = null;
}
else
{
value = ExpressRouteLinkListResult.DeserializeExpressRouteLinkListResult(document.RootElement);
}
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort resource. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public Response<ExpressRouteLinkListResult> ListNextPage(string nextLink, string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
using var message = CreateListNextPageRequest(nextLink, resourceGroupName, expressRoutePortName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteLinkListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
if (document.RootElement.ValueKind == JsonValueKind.Null)
{
value = null;
}
else
{
value = ExpressRouteLinkListResult.DeserializeExpressRouteLinkListResult(document.RootElement);
}
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 48.690751 | 203 | 0.585267 | [
"MIT"
] | Priya91/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/ExpressRouteLinksRestClient.cs | 16,847 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.NetCore.Analyzers.Security.Helpers;
namespace Microsoft.NetCore.Analyzers.Security
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotUseWeakKDFInsufficientIterationCount : DiagnosticAnalyzer
{
internal static DiagnosticDescriptor DefinitelyUseWeakKDFInsufficientIterationCountRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5387",
typeof(SystemSecurityCryptographyResources),
nameof(SystemSecurityCryptographyResources.DefinitelyUseWeakKDFInsufficientIterationCount),
nameof(SystemSecurityCryptographyResources.DefinitelyUseWeakKDFInsufficientIterationCountMessage),
false,
helpLinkUri: null,
descriptionResourceStringName: nameof(SystemSecurityCryptographyResources.DoNotUseWeakKDFInsufficientIterationCountDescription),
customTags: WellKnownDiagnosticTagsExtensions.DataflowAndTelemetry);
internal static DiagnosticDescriptor MaybeUseWeakKDFInsufficientIterationCountRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5388",
typeof(SystemSecurityCryptographyResources),
nameof(SystemSecurityCryptographyResources.MaybeUseWeakKDFInsufficientIterationCount),
nameof(SystemSecurityCryptographyResources.MaybeUseWeakKDFInsufficientIterationCountMessage),
false,
helpLinkUri: null,
descriptionResourceStringName: nameof(SystemSecurityCryptographyResources.DoNotUseWeakKDFInsufficientIterationCountDescription),
customTags: WellKnownDiagnosticTagsExtensions.DataflowAndTelemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
DefinitelyUseWeakKDFInsufficientIterationCountRule,
MaybeUseWeakKDFInsufficientIterationCountRule);
private const int DefaultIterationCount = 1000;
private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue)
{
switch (propertySetAbstractValue[0])
{
case PropertySetAbstractValueKind.Flagged:
return HazardousUsageEvaluationResult.Flagged;
case PropertySetAbstractValueKind.MaybeFlagged:
return HazardousUsageEvaluationResult.MaybeFlagged;
default:
return HazardousUsageEvaluationResult.Unflagged;
}
}
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
HazardousUsageEvaluatorCollection hazardousUsageEvaluators = new HazardousUsageEvaluatorCollection(
new HazardousUsageEvaluator("GetBytes", HazardousUsageCallback));
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationStartAnalysisContext) =>
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationStartAnalysisContext.Compilation);
if (!wellKnownTypeProvider.TryGetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyRfc2898DeriveBytes, out var rfc2898DeriveBytesTypeSymbol))
{
return;
}
var cancellationToken = compilationStartAnalysisContext.CancellationToken;
var sufficientIterationCount = compilationStartAnalysisContext.Options.GetUnsignedIntegralOptionValue(
optionName: EditorConfigOptionNames.SufficientIterationCountForWeakKDFAlgorithm,
rule: DefinitelyUseWeakKDFInsufficientIterationCountRule,
defaultValue: 100000,
cancellationToken: cancellationToken);
var constructorMapper = new ConstructorMapper(
(IMethodSymbol constructorMethod, IReadOnlyList<ValueContentAbstractValue> argumentValueContentAbstractValues,
IReadOnlyList<PointsToAbstractValue> argumentPointsToAbstractValues) =>
{
var kind = DefaultIterationCount >= sufficientIterationCount ? PropertySetAbstractValueKind.Unflagged : PropertySetAbstractValueKind.Flagged;
if (constructorMethod.Parameters.Length >= 3)
{
if (constructorMethod.Parameters[2].Name == "iterations" &&
constructorMethod.Parameters[2].Type.SpecialType == SpecialType.System_Int32)
{
kind = PropertySetCallbacks.EvaluateLiteralValues(argumentValueContentAbstractValues[2], o => Convert.ToInt32(o) < sufficientIterationCount);
}
}
return PropertySetAbstractValue.GetInstance(kind);
});
var propertyMappers = new PropertyMapperCollection(
new PropertyMapper(
"IterationCount",
(ValueContentAbstractValue valueContentAbstractValue) =>
{
return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, o => Convert.ToInt32(o) < sufficientIterationCount);
}));
var rootOperationsNeedingAnalysis = PooledHashSet<(IOperation, ISymbol)>.GetInstance();
compilationStartAnalysisContext.RegisterOperationBlockStartAction(
(OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) =>
{
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation;
if (rfc2898DeriveBytesTypeSymbol.Equals(invocationOperation.Instance?.Type) &&
invocationOperation.TargetMethod.Name == "GetBytes")
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((invocationOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Invocation);
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var argumentOperation = (IArgumentOperation)operationAnalysisContext.Operation;
if (rfc2898DeriveBytesTypeSymbol.Equals(argumentOperation.Parameter.Type))
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((argumentOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Argument);
});
compilationStartAnalysisContext.RegisterCompilationEndAction(
(CompilationAnalysisContext compilationAnalysisContext) =>
{
PooledDictionary<(Location Location, IMethodSymbol Method), HazardousUsageEvaluationResult> allResults = null;
try
{
lock (rootOperationsNeedingAnalysis)
{
if (!rootOperationsNeedingAnalysis.Any())
{
return;
}
allResults = PropertySetAnalysis.BatchGetOrComputeHazardousUsages(
compilationAnalysisContext.Compilation,
rootOperationsNeedingAnalysis,
WellKnownTypeNames.SystemSecurityCryptographyRfc2898DeriveBytes,
constructorMapper,
propertyMappers,
hazardousUsageEvaluators,
InterproceduralAnalysisConfiguration.Create(
compilationAnalysisContext.Options,
SupportedDiagnostics,
defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive,
cancellationToken: cancellationToken));
}
if (allResults == null)
{
return;
}
foreach (KeyValuePair<(Location Location, IMethodSymbol Method), HazardousUsageEvaluationResult> kvp
in allResults)
{
DiagnosticDescriptor descriptor;
switch (kvp.Value)
{
case HazardousUsageEvaluationResult.Flagged:
descriptor = DefinitelyUseWeakKDFInsufficientIterationCountRule;
break;
case HazardousUsageEvaluationResult.MaybeFlagged:
descriptor = MaybeUseWeakKDFInsufficientIterationCountRule;
break;
default:
Debug.Fail($"Unhandled result value {kvp.Value}");
continue;
}
compilationAnalysisContext.ReportDiagnostic(
Diagnostic.Create(
descriptor,
kvp.Key.Location,
sufficientIterationCount));
}
}
finally
{
rootOperationsNeedingAnalysis.Free();
allResults?.Free();
}
});
});
}
}
}
| 57.274775 | 177 | 0.545262 | [
"Apache-2.0"
] | paulomorgado/roslyn-analyzers | src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseWeakKDFInsufficientIterationCount.cs | 12,717 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace SourceGrid.Cells.Views
{
/// <summary>
/// Summary description for a 3D Header.
/// This is a standard header without theme support. Use the ColumnHeaderThemed for theme support.
/// </summary>
[Serializable]
public class ColumnHeader : Header
{
[ThreadStatic] private static ColumnHeader t_Default;
/// <summary>
/// Represents a Column Header with the ability to draw an Image in the right to indicates the sort operation. You must use this model with a cell of type ICellSortableHeader.
/// </summary>
/// <remarks>This default ColumnHeader is shared across the same UI thread, but not between threads. It can be
/// cloned for a unique instance.</remarks>
public new static ColumnHeader Default // Multi-thread safe with [ThreadStatic] backing store
{
get
{
if (t_Default == null)
t_Default = new ColumnHeader();
return t_Default;
}
}
#region Constructors
/// <summary>
/// Use default setting
/// </summary>
public ColumnHeader()
{
Background = new DevAge.Drawing.VisualElements.ColumnHeaderThemed();
}
/// <summary>
/// Copy constructor. This method duplicate all the reference field (Image, Font, StringFormat) creating a new instance.
/// </summary>
/// <param name="p_Source"></param>
public ColumnHeader(ColumnHeader p_Source):base(p_Source)
{
}
#endregion
#region Clone
/// <summary>
/// Clone this object. This method duplicate all the reference field (Image, Font, StringFormat) creating a new instance.
/// </summary>
/// <returns></returns>
public override object Clone()
{
return new ColumnHeader(this);
}
#endregion
#region Visual Elements
public new DevAge.Drawing.VisualElements.IColumnHeader Background
{
get { return (DevAge.Drawing.VisualElements.IColumnHeader)base.Background; }
set { base.Background = value; }
}
protected override void PrepareView(CellContext context)
{
base.PrepareView(context);
PrepareVisualElementSortIndicator(context);
}
protected override IEnumerable<DevAge.Drawing.VisualElements.IVisualElement> GetElements()
{
if (ElementSort != null)
yield return ElementSort;
foreach (DevAge.Drawing.VisualElements.IVisualElement v in GetBaseElements())
yield return v;
}
private IEnumerable<DevAge.Drawing.VisualElements.IVisualElement> GetBaseElements()
{
return base.GetElements();
}
private DevAge.Drawing.VisualElements.ISortIndicator mElementSort = new DevAge.Drawing.VisualElements.SortIndicator();
/// <summary>
/// Gets or sets the visual element used to draw the sort indicator. Default is DevAge.Drawing.VisualElements.SortIndicator
/// </summary>
public DevAge.Drawing.VisualElements.ISortIndicator ElementSort
{
get { return mElementSort; }
set { mElementSort = value; }
}
protected virtual void PrepareVisualElementSortIndicator(CellContext context)
{
Models.ISortableHeader sortModel = (Models.ISortableHeader)context.Cell.Model.FindModel(typeof(Models.ISortableHeader));
if (sortModel != null)
{
Models.SortStatus status = sortModel.GetSortStatus(context);
ElementSort.SortStyle = status.Style;
}
else
ElementSort.SortStyle = DevAge.Drawing.HeaderSortStyle.None;
}
#endregion
}
}
| 32.435897 | 180 | 0.64664 | [
"Unlicense"
] | GibraltarSoftware/SourceGrid | src/SourceGrid/Cells/Views/ColumnHeader.cs | 3,795 | C# |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class MetadataTest
{
[Test]
public void AsciiEntry()
{
var entry = new Metadata.Entry("ABC", "XYZ");
Assert.IsFalse(entry.IsBinary);
Assert.AreEqual("abc", entry.Key); // key is in lowercase.
Assert.AreEqual("XYZ", entry.Value);
CollectionAssert.AreEqual(new[] { (byte)'X', (byte)'Y', (byte)'Z' }, entry.ValueBytes);
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc-bin", "xyz"));
Assert.AreEqual("[Entry: key=abc, value=XYZ]", entry.ToString());
}
[Test]
public void BinaryEntry()
{
var bytes = new byte[] { 1, 2, 3 };
var entry = new Metadata.Entry("ABC-BIN", bytes);
Assert.IsTrue(entry.IsBinary);
Assert.AreEqual("abc-bin", entry.Key); // key is in lowercase.
Assert.Throws(typeof(InvalidOperationException), () => { var v = entry.Value; });
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc", bytes));
Assert.AreEqual("[Entry: key=abc-bin, valueBytes=System.Byte[]]", entry.ToString());
}
[Test]
public void AsciiEntry_KeyValidity()
{
new Metadata.Entry("ABC", "XYZ");
new Metadata.Entry("0123456789abc", "XYZ");
new Metadata.Entry("-abc", "XYZ");
new Metadata.Entry("a_bc_", "XYZ");
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc[", "xyz"));
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc/", "xyz"));
}
[Test]
public void Entry_ConstructionPreconditions()
{
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry(null, "xyz"));
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry("abc", (string)null));
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry("abc-bin", (byte[])null));
}
[Test]
public void Entry_Immutable()
{
var origBytes = new byte[] { 1, 2, 3 };
var bytes = new byte[] { 1, 2, 3 };
var entry = new Metadata.Entry("ABC-BIN", bytes);
bytes[0] = 255; // changing the array passed to constructor should have any effect.
CollectionAssert.AreEqual(origBytes, entry.ValueBytes);
entry.ValueBytes[0] = 255;
CollectionAssert.AreEqual(origBytes, entry.ValueBytes);
}
[Test]
public void Entry_CreateUnsafe_Ascii()
{
var bytes = new byte[] { (byte)'X', (byte)'y' };
var entry = Metadata.Entry.CreateUnsafe("abc", bytes);
Assert.IsFalse(entry.IsBinary);
Assert.AreEqual("abc", entry.Key);
Assert.AreEqual("Xy", entry.Value);
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
}
[Test]
public void Entry_CreateUnsafe_Binary()
{
var bytes = new byte[] { 1, 2, 3 };
var entry = Metadata.Entry.CreateUnsafe("abc-bin", bytes);
Assert.IsTrue(entry.IsBinary);
Assert.AreEqual("abc-bin", entry.Key);
Assert.Throws(typeof(InvalidOperationException), () => { var v = entry.Value; });
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
}
[Test]
public void IndexOf()
{
var metadata = CreateMetadata();
Assert.AreEqual(0, metadata.IndexOf(metadata[0]));
Assert.AreEqual(1, metadata.IndexOf(metadata[1]));
}
[Test]
public void Insert()
{
var metadata = CreateMetadata();
metadata.Insert(0, new Metadata.Entry("new-key", "new-value"));
Assert.AreEqual(3, metadata.Count);
Assert.AreEqual("new-key", metadata[0].Key);
Assert.AreEqual("abc", metadata[1].Key);
}
[Test]
public void RemoveAt()
{
var metadata = CreateMetadata();
metadata.RemoveAt(0);
Assert.AreEqual(1, metadata.Count);
Assert.AreEqual("xyz", metadata[0].Key);
}
[Test]
public void Remove()
{
var metadata = CreateMetadata();
metadata.Remove(metadata[0]);
Assert.AreEqual(1, metadata.Count);
Assert.AreEqual("xyz", metadata[0].Key);
}
[Test]
public void Indexer_Set()
{
var metadata = CreateMetadata();
var entry = new Metadata.Entry("new-key", "new-value");
metadata[1] = entry;
Assert.AreEqual(entry, metadata[1]);
}
[Test]
public void Clear()
{
var metadata = CreateMetadata();
metadata.Clear();
Assert.AreEqual(0, metadata.Count);
}
[Test]
public void Contains()
{
var metadata = CreateMetadata();
Assert.IsTrue(metadata.Contains(metadata[0]));
Assert.IsFalse(metadata.Contains(new Metadata.Entry("new-key", "new-value")));
}
[Test]
public void CopyTo()
{
var metadata = CreateMetadata();
var array = new Metadata.Entry[metadata.Count + 1];
metadata.CopyTo(array, 1);
Assert.AreEqual(default(Metadata.Entry), array[0]);
Assert.AreEqual(metadata[0], array[1]);
}
[Test]
public void IEnumerableGetEnumerator()
{
var metadata = CreateMetadata();
var enumerator = (metadata as System.Collections.IEnumerable).GetEnumerator();
int i = 0;
while (enumerator.MoveNext())
{
Assert.AreEqual(metadata[i], enumerator.Current);
i++;
}
}
[Test]
public void FreezeMakesReadOnly()
{
var entry = new Metadata.Entry("new-key", "new-value");
var metadata = CreateMetadata().Freeze();
Assert.IsTrue(metadata.IsReadOnly);
Assert.Throws<InvalidOperationException>(() => metadata.Insert(0, entry));
Assert.Throws<InvalidOperationException>(() => metadata.RemoveAt(0));
Assert.Throws<InvalidOperationException>(() => metadata[0] = entry);
Assert.Throws<InvalidOperationException>(() => metadata.Add(entry));
Assert.Throws<InvalidOperationException>(() => metadata.Add("new-key", "new-value"));
Assert.Throws<InvalidOperationException>(() => metadata.Add("new-key-bin", new byte[] { 0xaa }));
Assert.Throws<InvalidOperationException>(() => metadata.Clear());
Assert.Throws<InvalidOperationException>(() => metadata.Remove(metadata[0]));
}
private Metadata CreateMetadata()
{
return new Metadata
{
{ "abc", "abc-value" },
{ "xyz", "xyz-value" },
};
}
}
}
| 37 | 109 | 0.587755 | [
"BSD-3-Clause"
] | CharaD7/grpc | src/csharp/Grpc.Core.Tests/MetadataTest.cs | 9,065 | 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 devicefarm-2015-06-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DeviceFarm.Model
{
/// <summary>
/// Container for the parameters to the CreateUpload operation.
/// Uploads an app or test scripts.
/// </summary>
public partial class CreateUploadRequest : AmazonDeviceFarmRequest
{
private string _contentType;
private string _name;
private string _projectArn;
private UploadType _type;
/// <summary>
/// Gets and sets the property ContentType.
/// <para>
/// The upload's content type (for example, "application/octet-stream").
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=64)]
public string ContentType
{
get { return this._contentType; }
set { this._contentType = value; }
}
// Check to see if ContentType property is set
internal bool IsSetContentType()
{
return this._contentType != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The upload's file name. The name should not contain the '/' character. If uploading
/// an iOS app, the file name needs to end with the <code>.ipa</code> extension. If uploading
/// an Android app, the file name needs to end with the <code>.apk</code> extension. For
/// all others, the file name must end with the <code>.zip</code> file extension.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=0, Max=256)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property ProjectArn.
/// <para>
/// The ARN of the project for the upload.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=32, Max=1011)]
public string ProjectArn
{
get { return this._projectArn; }
set { this._projectArn = value; }
}
// Check to see if ProjectArn property is set
internal bool IsSetProjectArn()
{
return this._projectArn != null;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The upload's upload type.
/// </para>
///
/// <para>
/// Must be one of the following values:
/// </para>
/// <ul> <li>
/// <para>
/// ANDROID_APP: An Android upload.
/// </para>
/// </li> <li>
/// <para>
/// IOS_APP: An iOS upload.
/// </para>
/// </li> <li>
/// <para>
/// WEB_APP: A web application upload.
/// </para>
/// </li> <li>
/// <para>
/// EXTERNAL_DATA: An external data upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_PYTHON_TEST_PACKAGE: An Appium Python test package upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_NODE_TEST_PACKAGE: An Appium Node.js test package upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_RUBY_TEST_PACKAGE: An Appium Ruby test package upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package upload for a
/// web app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package upload for
/// a web app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_PYTHON_TEST_PACKAGE: An Appium Python test package upload for a web app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_NODE_TEST_PACKAGE: An Appium Node.js test package upload for a web app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_RUBY_TEST_PACKAGE: An Appium Ruby test package upload for a web app.
/// </para>
/// </li> <li>
/// <para>
/// CALABASH_TEST_PACKAGE: A Calabash test package upload.
/// </para>
/// </li> <li>
/// <para>
/// INSTRUMENTATION_TEST_PACKAGE: An instrumentation upload.
/// </para>
/// </li> <li>
/// <para>
/// UIAUTOMATION_TEST_PACKAGE: A uiautomation test package upload.
/// </para>
/// </li> <li>
/// <para>
/// UIAUTOMATOR_TEST_PACKAGE: A uiautomator test package upload.
/// </para>
/// </li> <li>
/// <para>
/// XCTEST_TEST_PACKAGE: An XCode test package upload.
/// </para>
/// </li> <li>
/// <para>
/// XCTEST_UI_TEST_PACKAGE: An XCode UI test package upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_JAVA_JUNIT_TEST_SPEC: An Appium Java JUnit test spec upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_JAVA_TESTNG_TEST_SPEC: An Appium Java TestNG test spec upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_PYTHON_TEST_SPEC: An Appium Python test spec upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_NODE_TEST_SPEC: An Appium Node.js test spec upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_RUBY_TEST_SPEC: An Appium Ruby test spec upload.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_JAVA_JUNIT_TEST_SPEC: An Appium Java JUnit test spec upload for a web app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_JAVA_TESTNG_TEST_SPEC: An Appium Java TestNG test spec upload for a web
/// app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_PYTHON_TEST_SPEC: An Appium Python test spec upload for a web app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_NODE_TEST_SPEC: An Appium Node.js test spec upload for a web app.
/// </para>
/// </li> <li>
/// <para>
/// APPIUM_WEB_RUBY_TEST_SPEC: An Appium Ruby test spec upload for a web app.
/// </para>
/// </li> <li>
/// <para>
/// INSTRUMENTATION_TEST_SPEC: An instrumentation test spec upload.
/// </para>
/// </li> <li>
/// <para>
/// XCTEST_UI_TEST_SPEC: An XCode UI test spec upload.
/// </para>
/// </li> </ul>
/// <para>
/// <b>Note</b> If you call <code>CreateUpload</code> with <code>WEB_APP</code> specified,
/// AWS Device Farm throws an <code>ArgumentException</code> error.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public UploadType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
}
} | 32.94636 | 108 | 0.518898 | [
"Apache-2.0"
] | icanread/aws-sdk-net | sdk/src/Services/DeviceFarm/Generated/Model/CreateUploadRequest.cs | 8,599 | C# |
/*
* Copyright (c) 2020 Christopher Boustros <github.com/christopher-boustros>
* SPDX-License-Identifier: MIT
*/
// This script is not linked to a game object
using UnityEngine;
/*
* This class defines the constant timestep interval used for the game's physics computations
* The lower the time interval, the faster the game's overall physics motions will appear
* For example, the OperateCannons class is defined to make the cannon move by a particular angle once every INTERVAL amount of time.
* So, by decreasing INTERVAL, the cannon will move faster. This is the same concept for other moving objects, including Balloon and Cannonball
*/
public static class GameTime
{
public const float INTERVAL = 0.02f; // 0.02 seconds
public const float RATE = 1 / INTERVAL; // The framerate equivalent to the interval
/*
* This factor determines by how much an object's position (such as a cannon's angle or a cannonballs height) should be updated for physics computatiosn based on the actual time between frames
* For example, if a cannon is set to move by 0.5 degrees once every GameTime.INTERVAL (so once every 0.02 seconds) but the time between frames was only 0.01 seconds, then the timeFactor()
* will be 0.01/0.02 = 1/2. So for that single frame, the cannon will move by 1/2 of 0.5 degrees in order to keep its motion at 0.5 degrees every 0.02 seconds.
*/
public static float TimeFactor()
{
return Time.deltaTime * RATE;
}
}
| 51.275862 | 196 | 0.736382 | [
"MIT"
] | christopher-boustros/Unity-Cannon-Shooter-Game | Assets/Scripts/GameTime.cs | 1,489 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ServiceDirectory.V1Beta1.Snippets
{
using Google.Api.Gax;
using Google.Cloud.Iam.V1;
using Google.Cloud.ServiceDirectory.V1Beta1;
public sealed partial class GeneratedRegistrationServiceClientStandaloneSnippets
{
/// <summary>Snippet for TestIamPermissions</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void TestIamPermissionsRequestObject()
{
// Create client
RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Permissions = { "", },
};
// Make the request
TestIamPermissionsResponse response = registrationServiceClient.TestIamPermissions(request);
}
}
}
| 39.511111 | 104 | 0.690101 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/servicedirectory/v1beta1/google-cloud-servicedirectory-v1beta1-csharp/Google.Cloud.ServiceDirectory.V1Beta1.StandaloneSnippets/RegistrationServiceClient.TestIamPermissionsRequestObjectSnippet.g.cs | 1,778 | 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.Buffers;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace System.IO.Pipelines.Networking.Libuv.Interop
{
/// <summary>
/// Summary description for UvWriteRequest
/// </summary>
public class UvWriteReq : UvRequest
{
private readonly static Uv.uv_write_cb _uv_write_cb = (IntPtr ptr, int status) => UvWriteCb(ptr, status);
private IntPtr _bufs;
private Action<UvWriteReq, int, object> _callback;
private object _state;
private const int BUFFER_COUNT = 4;
private List<MemoryHandle> _handles = new List<MemoryHandle>();
private List<GCHandle> _pins = new List<GCHandle>(BUFFER_COUNT + 1);
private LibuvAwaitable<UvWriteReq> _awaitable = new LibuvAwaitable<UvWriteReq>();
public UvWriteReq() : base()
{
}
public void Init(UvLoopHandle loop)
{
var requestSize = loop.Libuv.req_size(Uv.RequestType.WRITE);
var bufferSize = Marshal.SizeOf<Uv.uv_buf_t>() * BUFFER_COUNT;
CreateMemory(
loop.Libuv,
loop.ThreadId,
requestSize + bufferSize);
_bufs = handle + requestSize;
}
public unsafe LibuvAwaitable<UvWriteReq> WriteAsync(
UvStreamHandle handle,
ReadableBuffer buffer)
{
Write(handle, buffer, LibuvAwaitable<UvWriteReq>.Callback, _awaitable);
return _awaitable;
}
private unsafe void Write(
UvStreamHandle handle,
ReadableBuffer buffer,
Action<UvWriteReq, int, object> callback,
object state)
{
try
{
int nBuffers = 0;
if (buffer.IsSingleSpan)
{
nBuffers = 1;
}
else
{
foreach (var span in buffer)
{
nBuffers++;
}
}
// add GCHandle to keeps this SafeHandle alive while request processing
_pins.Add(GCHandle.Alloc(this, GCHandleType.Normal));
var pBuffers = (Uv.uv_buf_t*)_bufs;
if (nBuffers > BUFFER_COUNT)
{
// create and pin buffer array when it's larger than the pre-allocated one
var bufArray = new Uv.uv_buf_t[nBuffers];
var gcHandle = GCHandle.Alloc(bufArray, GCHandleType.Pinned);
_pins.Add(gcHandle);
pBuffers = (Uv.uv_buf_t*)gcHandle.AddrOfPinnedObject();
}
if (nBuffers == 1)
{
var memory = buffer.First;
var memoryHandle = memory.Retain(pin: true);
_handles.Add(memoryHandle);
pBuffers[0] = Libuv.buf_init((IntPtr)memoryHandle.PinnedPointer, memory.Length);
}
else
{
int i = 0;
foreach (var memory in buffer)
{
var memoryHandle = memory.Retain(pin: true);
_handles.Add(memoryHandle);
pBuffers[i++] = Libuv.buf_init((IntPtr)memoryHandle.PinnedPointer, memory.Length);
}
}
_callback = callback;
_state = state;
_uv.write(this, handle, pBuffers, nBuffers, _uv_write_cb);
}
catch
{
_callback = null;
_state = null;
Unpin(this);
throw;
}
}
private static void Unpin(UvWriteReq req)
{
foreach (var pin in req._pins)
{
pin.Free();
}
req._pins.Clear();
foreach (var handle in req._handles)
{
handle.Dispose();
}
req._handles.Clear();
}
private static void UvWriteCb(IntPtr ptr, int status)
{
var req = FromIntPtr<UvWriteReq>(ptr);
Unpin(req);
var callback = req._callback;
req._callback = null;
var state = req._state;
req._state = null;
callback(req, status, state);
}
}
}
| 31.828767 | 113 | 0.501829 | [
"MIT"
] | eerhardt/corefxlab | src/System.IO.Pipelines.Networking.Libuv/Interop/UvWriteReq.cs | 4,647 | C# |
namespace Qts.Ultimate.EntityFrameworkCore.Seed.Host
{
public class InitialHostDbBuilder
{
private readonly UltimateDbContext _context;
public InitialHostDbBuilder(UltimateDbContext context)
{
_context = context;
}
public void Create()
{
new DefaultEditionCreator(_context).Create();
new DefaultLanguagesCreator(_context).Create();
new HostRoleAndUserCreator(_context).Create();
new DefaultSettingsCreator(_context).Create();
_context.SaveChanges();
}
}
}
| 26.086957 | 62 | 0.623333 | [
"MIT"
] | nirzaf/Qts.Ultimate | src/Qts.Ultimate.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/InitialHostDbBuilder.cs | 602 | C# |
#pragma warning disable CS0618 // MetadataFileReference to be removed
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class MetadataFileReferenceCompilationTests : CSharpTestBase
{
[Fact]
public void AssemblyFileReferenceNotFound()
{
CSharpCompilation comp = CSharpCompilation.Create(
assemblyName: "Compilation",
options: TestOptions.ReleaseDll,
references: new[] { new MetadataFileReference(@"c:\file_that_does_not_exist.bbb") });
comp.VerifyDiagnostics(
// error CS0006: Metadata file 'c:\file_that_does_not_exist.bbb' could not be found
Diagnostic(ErrorCode.ERR_NoMetadataFile).WithArguments(@"c:\file_that_does_not_exist.bbb"));
}
[Fact]
public void ModuleFileReferenceNotFound()
{
CSharpCompilation comp = CSharpCompilation.Create(
assemblyName: "Compilation",
options: TestOptions.ReleaseDll,
references: new[] { new MetadataFileReference(@"c:\file_that_does_not_exist.bbb", MetadataImageKind.Module) });
comp.VerifyDiagnostics(
// error CS0006: Metadata file 'c:\file_that_does_not_exist.bbb' could not be found
Diagnostic(ErrorCode.ERR_NoMetadataFile).WithArguments(@"c:\file_that_does_not_exist.bbb"));
}
[Fact, WorkItem(545062, "DevDiv")]
public void ExternAliasToSameDll()
{
var systemDllPath = typeof(Uri).Assembly.Location;
var alias1 = new MetadataFileReference(systemDllPath, aliases: ImmutableArray.Create("Alias1"));
var alias2 = new MetadataFileReference(systemDllPath, aliases: ImmutableArray.Create("Alias2"));
var text = @"
extern alias Alias1;
extern alias Alias2;
class A { }
";
var comp = CreateCompilationWithMscorlib(text, references: new MetadataReference[] { alias1, alias2 });
Assert.Equal(3, comp.References.Count());
Assert.Equal("Alias2", comp.References.Last().Properties.Aliases.Single());
comp.VerifyDiagnostics(
// (2,1): info CS8020: Unused extern alias.
// extern alias Alias1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Alias1;"),
// (3,1): info CS8020: Unused extern alias.
// extern alias Alias2;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Alias2;"));
}
[Fact]
public void CS1009FTL_MetadataCantOpenFileModule()
{
//CSC /TARGET:library /addmodule:class1.netmodule text.CS
var text = @"class Test
{
public static int Main()
{
return 1;
}
}";
var refFile = Temp.CreateFile();
var reference = new MetadataFileReference(refFile.Path, MetadataImageKind.Module);
CreateCompilationWithMscorlib(text, new[] { reference }).VerifyDiagnostics(
// error CS0009: Metadata file '...' could not be opened -- Image too small to contain DOS header.
Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(refFile.Path, "Image too small to contain DOS header."));
}
[Fact]
public void CS1009FTL_MetadataCantOpenFileAssembly()
{
//CSC /TARGET:library /reference:class1.netmodule text.CS
var text = @"class Test
{
public static int Main()
{
return 1;
}
}";
var refFile = Temp.CreateFile();
var reference = new MetadataFileReference(refFile.Path);
CreateCompilationWithMscorlib(text, new[] { reference }).VerifyDiagnostics(
// error CS0009: Metadata file '...' could not be opened -- Image too small to contain DOS header.
Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(refFile.Path, "Image too small to contain DOS header."));
}
/// <summary>
/// Compilation A depends on C Version 1.0.0.0, C Version 2.0.0.0, and B. B depends on C Version 2.0.0.0.
/// Checks that the ReferenceManager compares the identities correctly and doesn't throw "Two metadata references found with the same identity" exception.
/// </summary>
[Fact]
public void ReferencesVersioning()
{
using (MetadataCache.LockAndClean())
{
var dir1 = Temp.CreateDirectory();
var dir2 = Temp.CreateDirectory();
var dir3 = Temp.CreateDirectory();
var file1 = dir1.CreateFile("C.dll").WriteAllBytes(TestResources.SymbolsTests.General.C1);
var file2 = dir2.CreateFile("C.dll").WriteAllBytes(TestResources.SymbolsTests.General.C2);
var file3 = dir3.CreateFile("main.dll");
var b = CreateCompilationWithMscorlib(
@"public class B { public static int Main() { return C.Main(); } }",
assemblyName: "b",
references: new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.General.C2) },
options: TestOptions.ReleaseDll);
using (MemoryStream output = new MemoryStream())
{
var emitResult = b.Emit(output);
Assert.True(emitResult.Success);
file3.WriteAllBytes(output.ToArray());
}
var a = CreateCompilationWithMscorlib(
@"class A { public static void Main() { B.Main(); } }",
assemblyName: "a",
references: new[] { new MetadataFileReference(file1.Path), new MetadataFileReference(file2.Path), new MetadataFileReference(file3.Path) },
options: TestOptions.ReleaseDll);
using (var stream = new MemoryStream())
{
a.Emit(stream);
}
}
}
}
} | 42.462585 | 162 | 0.604454 | [
"Apache-2.0"
] | sperling/cskarp | Src/Compilers/CSharp/Test/Symbol/Compilation/MetadataFileReferenceCompilationTests.cs | 6,244 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Controllers;
using BTCPayServer.Events;
using BTCPayServer.Services.Apps;
namespace BTCPayServer.HostedServices
{
public class AppInventoryUpdaterHostedService : EventHostedServiceBase
{
private readonly EventAggregator _eventAggregator;
private readonly AppService _appService;
protected override void SubscribeToEvents()
{
Subscribe<InvoiceEvent>();
Subscribe<UpdateAppInventory>();
}
public AppInventoryUpdaterHostedService(EventAggregator eventAggregator, AppService appService) : base(
eventAggregator)
{
_eventAggregator = eventAggregator;
_appService = appService;
}
protected override async Task ProcessEvent(object evt, CancellationToken cancellationToken)
{
if (evt is UpdateAppInventory updateAppInventory)
{
//get all apps that were tagged that have manageable inventory that has an item that matches the item code in the invoice
var apps = (await _appService.GetApps(updateAppInventory.AppId)).Select(data =>
{
switch (Enum.Parse<AppType>(data.AppType))
{
case AppType.PointOfSale:
var possettings = data.GetSettings<AppsController.PointOfSaleSettings>();
return (Data: data, Settings: (object)possettings,
Items: _appService.Parse(possettings.Template, possettings.Currency));
case AppType.Crowdfund:
var cfsettings = data.GetSettings<CrowdfundSettings>();
return (Data: data, Settings: (object)cfsettings,
Items: _appService.Parse(cfsettings.PerksTemplate, cfsettings.TargetCurrency));
default:
return (null, null, null);
}
}).Where(tuple => tuple.Data != null && tuple.Items.Any(item =>
item.Inventory.HasValue &&
updateAppInventory.Items.ContainsKey(item.Id)));
foreach (var valueTuple in apps)
{
foreach (var item1 in valueTuple.Items.Where(item =>
updateAppInventory.Items.ContainsKey(item.Id)))
{
if (updateAppInventory.Deduct)
{
item1.Inventory -= updateAppInventory.Items[item1.Id];
}
else
{
item1.Inventory += updateAppInventory.Items[item1.Id];
}
}
switch (Enum.Parse<AppType>(valueTuple.Data.AppType))
{
case AppType.PointOfSale:
((AppsController.PointOfSaleSettings)valueTuple.Settings).Template =
_appService.SerializeTemplate(valueTuple.Items);
break;
case AppType.Crowdfund:
((CrowdfundSettings)valueTuple.Settings).PerksTemplate =
_appService.SerializeTemplate(valueTuple.Items);
break;
default:
throw new InvalidOperationException();
}
valueTuple.Data.SetSettings(valueTuple.Settings);
await _appService.UpdateOrCreateApp(valueTuple.Data);
}
}
else if (evt is InvoiceEvent invoiceEvent)
{
Dictionary<string, int> cartItems = null;
bool deduct;
switch (invoiceEvent.Name)
{
case InvoiceEvent.Expired:
case InvoiceEvent.MarkedInvalid:
deduct = false;
break;
case InvoiceEvent.Created:
deduct = true;
break;
default:
return;
}
if ((!string.IsNullOrEmpty(invoiceEvent.Invoice.Metadata.ItemCode) ||
AppService.TryParsePosCartItems(invoiceEvent.Invoice.Metadata.PosData, out cartItems)))
{
var appIds = AppService.GetAppInternalTags(invoiceEvent.Invoice);
if (!appIds.Any())
{
return;
}
var items = cartItems ?? new Dictionary<string, int>();
if (!string.IsNullOrEmpty(invoiceEvent.Invoice.Metadata.ItemCode))
{
items.TryAdd(invoiceEvent.Invoice.Metadata.ItemCode, 1);
}
_eventAggregator.Publish(new UpdateAppInventory()
{
Deduct = deduct,
Items = items,
AppId = appIds
});
}
}
}
public class UpdateAppInventory
{
public string[] AppId { get; set; }
public Dictionary<string, int> Items { get; set; }
public bool Deduct { get; set; }
public override string ToString()
{
return string.Empty;
}
}
}
}
| 39.904762 | 137 | 0.484828 | [
"MIT"
] | 1Blackdiamondsc/btcpayserver | BTCPayServer/HostedServices/AppInventoryUpdaterHostedService.cs | 5,866 | C# |
/*
* Selling Partner API for Messaging
*
* With the Messaging API you can build applications that send messages to buyers. You can get a list of message types that are available for an order that you specify, then call an operation that sends a message to the buyer for that order. The Messaging API returns responses that are formed according to the <a href=https://tools.ietf.org/html/draft-kelly-json-hal-08>JSON Hypertext Application Language</a> (HAL) standard.
*
* OpenAPI spec version: v1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
namespace FikaAmazonAPI.AmazonSpApiSDK.Models.Messaging
{
/// <summary>
/// The response schema for the GetAttributes operation.
/// </summary>
[DataContract]
public partial class GetAttributesResponse : IEquatable<GetAttributesResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAttributesResponse" /> class.
/// </summary>
/// <param name="buyer">The list of attributes related to the buyer..</param>
/// <param name="errors">errors.</param>
public GetAttributesResponse(Buyer buyer = default(Buyer), ErrorList errors = default(ErrorList))
{
this.Buyer = buyer;
this.Errors = errors;
}
public GetAttributesResponse()
{
this.Buyer = default(Buyer);
this.Errors = default(ErrorList);
}
/// <summary>
/// The list of attributes related to the buyer.
/// </summary>
/// <value>The list of attributes related to the buyer.</value>
[DataMember(Name="buyer", EmitDefaultValue=false)]
public Buyer Buyer { get; set; }
/// <summary>
/// Gets or Sets Errors
/// </summary>
[DataMember(Name="errors", EmitDefaultValue=false)]
public ErrorList Errors { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class GetAttributesResponse {\n");
sb.Append(" Buyer: ").Append(Buyer).Append("\n");
sb.Append(" Errors: ").Append(Errors).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GetAttributesResponse);
}
/// <summary>
/// Returns true if GetAttributesResponse instances are equal
/// </summary>
/// <param name="input">Instance of GetAttributesResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GetAttributesResponse input)
{
if (input == null)
return false;
return
(
this.Buyer == input.Buyer ||
(this.Buyer != null &&
this.Buyer.Equals(input.Buyer))
) &&
(
this.Errors == input.Errors ||
(this.Errors != null &&
this.Errors.Equals(input.Errors))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Buyer != null)
hashCode = hashCode * 59 + this.Buyer.GetHashCode();
if (this.Errors != null)
hashCode = hashCode * 59 + this.Errors.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 36.057554 | 426 | 0.571429 | [
"MIT"
] | GuybrushX/Amazon-SP-API-CSharp | Source/FikaAmazonAPI/AmazonSpApiSDK/Models/Messaging/GetAttributesResponse.cs | 5,012 | C# |
namespace MyWebServer.ByTheCakeApp.Services.Contracts
{
using System.Collections.Generic;
using ViewModels.Products;
public interface IProductService
{
void Create(string name, decimal price, string imageUrl);
IEnumerable<ProductListingViewModel> All(string searchTerm = null);
ProductDetailsViewModel Find(int id);
bool Exists(int id);
IEnumerable<ProductInCartViewModel> FindProductsInCart(IEnumerable<int> ids);
}
}
| 24.3 | 85 | 0.718107 | [
"MIT"
] | DannyBerova/CSharp-Web-Development-Basics-May-2018 | 05-HandmadeWebServer-EF-Core/WebServer/ByTheCakeApp/Services/Contracts/IProductService.cs | 488 | C# |
namespace TrafficManager.UI.MainMenu {
using State;
using State.Keybinds;
public class PrioritySignsButton : MenuToolModeButton {
protected override ToolMode ToolMode => ToolMode.AddPrioritySigns;
protected override ButtonFunction Function => ButtonFunction.PrioritySigns;
public override string Tooltip =>
Translation.Menu.Get("Tooltip:Add priority signs") + "\n" +
Translation.Menu.Get("Tooltip.Keybinds:Add priority signs");
public override bool Visible => Options.prioritySignsEnabled;
public override KeybindSetting ShortcutKey => KeybindSettingsBase.PrioritySignsTool;
}
}
| 34.947368 | 92 | 0.718373 | [
"MIT"
] | kianzarrin/Cities-Skylines-Traffic-Manager-President-Edition | TLM/TLM/UI/MainMenu/PrioritySignsButton.cs | 664 | C# |
using EventSourcingOnAzureFunctions.Common.CQRS.CommandHandler.Events;
using EventSourcingOnAzureFunctions.Common.EventSourcing;
using EventSourcingOnAzureFunctions.Common.EventSourcing.Interfaces;
using System;
using System.Collections.Generic;
namespace EventSourcingOnAzureFunctions.Common.CQRS.CommandHandler.Projections
{
/// <summary>
/// A projection to get the execution state (Running, Error, Completed)
/// for a given command instance
/// </summary>
[ProjectionName("Command Execution State") ]
public sealed class ExecutionState
: ProjectionBase,
IHandleEventType<Created>,
IHandleEventType<FatalErrorOccured>,
IHandleEventType<Completed>,
IHandleEventType<CommandStepInitiated>,
IHandleEventType<StepCompleted>
{
// String constants for the different status
public const string STATUS_NEW = @"New";
public const string STATUS_RUNNING = @"Running";
public const string STATUS_ERROR = @"In Error";
public const string STATUS_COMPLETE = @"Complete";
private string _currentStatus = STATUS_NEW;
/// <summary>
/// The command status as at when the projection was executed
/// </summary>
public string CurrentStatus
{
get
{
return _currentStatus;
}
}
private string _message = @"";
public string Message
{
get
{
return _message;
}
}
private string _currentStep = @"";
/// <summary>
/// The name of the step currently being executed
/// </summary>
public string CurrentStep
{
get
{
return _currentStep;
}
}
public void HandleEventInstance(Created eventInstance)
{
if (null != eventInstance)
{
_currentStatus = STATUS_NEW;
_message = $"Created {eventInstance.DateLogged}";
}
}
public void HandleEventInstance(FatalErrorOccured eventInstance)
{
if (null != eventInstance)
{
_currentStatus = STATUS_ERROR;
_message = eventInstance.Message;
}
}
public void HandleEventInstance(Completed eventInstance)
{
if (null != eventInstance)
{
_currentStatus = STATUS_COMPLETE;
_message = eventInstance.Notes;
}
}
public void HandleEventInstance(CommandStepInitiated eventInstance)
{
if (null != eventInstance)
{
_currentStatus = STATUS_RUNNING;
_message = $"Running {eventInstance.StepName}";
_currentStep = eventInstance.StepName;
}
}
public void HandleEventInstance(StepCompleted eventInstance)
{
if (null != eventInstance)
{
_currentStatus = STATUS_RUNNING;
_message = $"Completed {eventInstance.StepName} - {eventInstance.Message} ";
}
}
}
}
| 29.779817 | 92 | 0.56716 | [
"MIT"
] | MerrionComputing/EventsSourcing-on-Azure-Functions | src/EventSourcingOnAzureFunctions.Common/CQRS/CommandHandler/Projections/ExecutionState.cs | 3,248 | 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.
// Original file: https://github.com/IdentityServer/IdentityServer4.Quickstart.UI
// Modified by Jan �koruba
using MicroCommerce.Identity.STS.Identity.ViewModels.Consent;
namespace MicroCommerce.Identity.STS.Identity.ViewModels.Device
{
public class DeviceAuthorizationViewModel : ConsentViewModel
{
public string UserCode { get; set; }
public bool ConfirmUserCode { get; set; }
}
}
| 24.916667 | 107 | 0.742475 | [
"MIT"
] | bao2703/b-shop | src/Services/Identity/MicroCommerce.Identity.Web/ViewModels/Device/DeviceAuthorizationViewModel.cs | 602 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ServiceFabric.Latest.Outputs
{
[OutputType]
public sealed class ArmApplicationHealthPolicyResponse
{
/// <summary>
/// Indicates whether warnings are treated with the same severity as errors.
/// </summary>
public readonly bool? ConsiderWarningAsError;
/// <summary>
/// The health policy used by default to evaluate the health of a service type.
/// </summary>
public readonly Outputs.ArmServiceTypeHealthPolicyResponse? DefaultServiceTypeHealthPolicy;
/// <summary>
/// The maximum allowed percentage of unhealthy deployed applications. Allowed values are Byte values from zero to 100.
/// The percentage represents the maximum tolerated percentage of deployed applications that can be unhealthy before the application is considered in error.
/// This is calculated by dividing the number of unhealthy deployed applications over the number of nodes where the application is currently deployed on in the cluster.
/// The computation rounds up to tolerate one failure on small numbers of nodes. Default percentage is zero.
/// </summary>
public readonly int? MaxPercentUnhealthyDeployedApplications;
/// <summary>
/// The map with service type health policy per service type name. The map is empty by default.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ArmServiceTypeHealthPolicyResponse>? ServiceTypeHealthPolicyMap;
[OutputConstructor]
private ArmApplicationHealthPolicyResponse(
bool? considerWarningAsError,
Outputs.ArmServiceTypeHealthPolicyResponse? defaultServiceTypeHealthPolicy,
int? maxPercentUnhealthyDeployedApplications,
ImmutableDictionary<string, Outputs.ArmServiceTypeHealthPolicyResponse>? serviceTypeHealthPolicyMap)
{
ConsiderWarningAsError = considerWarningAsError;
DefaultServiceTypeHealthPolicy = defaultServiceTypeHealthPolicy;
MaxPercentUnhealthyDeployedApplications = maxPercentUnhealthyDeployedApplications;
ServiceTypeHealthPolicyMap = serviceTypeHealthPolicyMap;
}
}
}
| 48.132075 | 176 | 0.72599 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ServiceFabric/Latest/Outputs/ArmApplicationHealthPolicyResponse.cs | 2,551 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using HoloToolkit.Unity.InputModule;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Controls slicing planes for use in volumetric rendering
/// Planes represent manipulatable viewable regions of the volume
/// </summary>
public class SlicingPlaneController : MonoBehaviour, IManipulationHandler
{
public float KeyboardMovementSpeed = 1.5f;
public float GestureMovementSpeed = 1.0f;
public GameObject PlaneX;
public GameObject PlaneY;
public GameObject PlaneZ;
private bool wasThickSliceEnabled;
public bool ThickSliceEnabled = true;
public Material SliceMaterial;
public Material ThickSliceMaterial;
public void SetMaterial(Material mat)
{
PlaneX.GetComponent<Renderer>().sharedMaterial = mat;
PlaneY.GetComponent<Renderer>().sharedMaterial = mat;
PlaneZ.GetComponent<Renderer>().sharedMaterial = mat;
}
private void OnEnable()
{
//force initial material setting in case user has made strange editor changes
wasThickSliceEnabled = !ThickSliceEnabled;
InputManager.Instance.AddGlobalListener(this.gameObject);
}
private void OnDisable()
{
InputManager.Instance.RemoveGlobalListener(this.gameObject);
}
public void SetThickSliceEnabled(bool on)
{
this.ThickSliceEnabled = on;
}
private void Update()
{
HandleDebugKeys();
Vector4 planeEquation;
var forward = this.transform.forward;
var pos = this.transform.position;
planeEquation.x = forward.x;
planeEquation.y = forward.y;
planeEquation.z = forward.z;
//dot product
planeEquation.w = (planeEquation.x * pos.x +
planeEquation.y * pos.y +
planeEquation.z * pos.z);
Shader.SetGlobalVector("CutPlane", planeEquation);
var cornerPos = this.transform.localPosition;
var slabMin = new Vector4(cornerPos.x - 0.5f, cornerPos.y - 0.5f, cornerPos.z - 0.5f, 0.0f);
var slabMax = new Vector4(cornerPos.x + 0.5f, cornerPos.y + 0.5f, cornerPos.z + 0.5f, 0.0f);
Shader.SetGlobalVector("SlabMin", slabMin);
Shader.SetGlobalVector("SlabMax", slabMax);
if (ThickSliceEnabled != wasThickSliceEnabled)
{
SetMaterial(ThickSliceEnabled ? ThickSliceMaterial : SliceMaterial);
wasThickSliceEnabled = ThickSliceEnabled;
}
Shader.SetGlobalMatrix("_SlicingWorldToLocal", this.transform.worldToLocalMatrix);
}
void HandleDebugKeys()
{
float movementDelta = KeyboardMovementSpeed * Time.deltaTime;
var positionDeltaX = this.transform.localRotation * new Vector3(movementDelta, 0.0f, 0.0f);
var positionDeltaY = this.transform.localRotation * new Vector3(0.0f, movementDelta, 0.0f);
var positionDeltaZ = this.transform.localRotation * new Vector3(0.0f, 0.0f, movementDelta);
if (Input.GetKey(KeyCode.L)) { this.transform.localPosition += positionDeltaX; }
if (Input.GetKey(KeyCode.J)) { this.transform.localPosition -= positionDeltaX; }
if (Input.GetKey(KeyCode.I)) { this.transform.localPosition += positionDeltaY; }
if (Input.GetKey(KeyCode.K)) { this.transform.localPosition -= positionDeltaY; }
if (Input.GetKey(KeyCode.RightBracket)) { this.transform.localPosition += positionDeltaZ; }
if (Input.GetKey(KeyCode.LeftBracket)) { this.transform.localPosition -= positionDeltaZ; }
}
public void OnManipulationStarted(ManipulationEventData eventData)
{
}
public void OnManipulationUpdated(ManipulationEventData eventData)
{
float movementDelta = GestureMovementSpeed * Time.deltaTime;
//TODO: consider tether filter
this.transform.localPosition += this.transform.localRotation * eventData.CumulativeDelta * movementDelta;
}
public void OnManipulationCompleted(ManipulationEventData eventData)
{
}
public void OnManipulationCanceled(ManipulationEventData eventData)
{
}
}
} | 37.283465 | 118 | 0.615628 | [
"MIT"
] | UBCHiveLab/SpectatorBrain | UnityProject/Assets/HoloToolkit-Examples/Medical/Scripts/SlicingPlaneController.cs | 4,737 | C# |
using System;
/*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
namespace com.opengamma.strata.math.impl.statistics.descriptive
{
using ArgChecker = com.opengamma.strata.collect.ArgChecker;
using DoubleArrayMath = com.opengamma.strata.collect.DoubleArrayMath;
using DoubleArray = com.opengamma.strata.collect.array.DoubleArray;
/// <summary>
/// Implementation of a quantile estimator.
/// <para>
/// The quantile is linearly interpolated between two sample values. The probability dimension
/// <i>p<subscript>i</subscript></i> on which the interpolation take place (X axis) varies between actual implementation
/// of the abstract class. For each probability <i>p<subscript>i</subscript></i>, the cumulative distribution value is
/// the sample value with same index. The index used above are the Java index plus 1.
/// </para>
/// <para>
/// Reference: Value-At-Risk, OpenGamma Documentation 31, Version 0.1, April 2015.
/// </para>
/// </summary>
public abstract class InterpolationQuantileMethod : QuantileCalculationMethod
{
protected internal override QuantileResult quantile(double level, DoubleArray sample, bool isExtrapolated)
{
ArgChecker.isTrue(level > 0, "Quantile should be above 0.");
ArgChecker.isTrue(level < 1, "Quantile should be below 1.");
int sampleSize = sampleCorrection(sample.size());
double adjustedLevel = checkIndex(level * sampleSize + indexCorrection(), sample.size(), isExtrapolated);
double[] order = createIndexArray(sample.size());
double[] s = sample.toArray();
DoubleArrayMath.sortPairs(s, order);
int lowerIndex = (int) Math.Floor(adjustedLevel);
int upperIndex = (int) Math.Ceiling(adjustedLevel);
double lowerWeight = upperIndex - adjustedLevel;
double upperWeight = 1d - lowerWeight;
return QuantileResult.of(lowerWeight * s[lowerIndex - 1] + upperWeight * s[upperIndex - 1], new int[]{(int) order[lowerIndex - 1], (int) order[upperIndex - 1]}, DoubleArray.of(lowerWeight, upperWeight));
}
protected internal override QuantileResult expectedShortfall(double level, DoubleArray sample)
{
ArgChecker.isTrue(level > 0, "Quantile should be above 0.");
ArgChecker.isTrue(level < 1, "Quantile should be below 1.");
int sampleSize = sampleCorrection(sample.size());
double fractionalIndex = level * sampleSize + indexCorrection();
double adjustedLevel = checkIndex(fractionalIndex, sample.size(), true);
double[] order = createIndexArray(sample.size());
double[] s = sample.toArray();
DoubleArrayMath.sortPairs(s, order);
int lowerIndex = (int) Math.Floor(adjustedLevel);
int upperIndex = (int) Math.Ceiling(adjustedLevel);
int[] indices = new int[upperIndex];
double[] weights = new double[upperIndex];
double interval = 1d / (double) sampleSize;
weights[0] = interval * (Math.Min(fractionalIndex, 1d) - indexCorrection());
double losses = s[0] * weights[0];
for (int i = 0; i < lowerIndex - 1; i++)
{
losses += 0.5 * (s[i] + s[i + 1]) * interval;
indices[i] = (int) order[i];
weights[i] += 0.5 * interval;
weights[i + 1] += 0.5 * interval;
}
if (lowerIndex != upperIndex)
{
double lowerWeight = upperIndex - adjustedLevel;
double upperWeight = 1d - lowerWeight;
double quantile = lowerWeight * s[lowerIndex - 1] + upperWeight * s[upperIndex - 1];
losses += 0.5 * (s[lowerIndex - 1] + quantile) * interval * upperWeight;
indices[lowerIndex - 1] = (int) order[lowerIndex - 1];
indices[upperIndex - 1] = (int) order[upperIndex - 1];
weights[lowerIndex - 1] += 0.5 * (1d + lowerWeight) * interval * upperWeight;
weights[upperIndex - 1] = 0.5 * upperWeight * interval * upperWeight;
}
if (fractionalIndex > sample.size())
{
losses += s[sample.size() - 1] * (fractionalIndex - sample.size()) * interval;
indices[sample.size() - 1] = (int) order[sample.size() - 1];
weights[sample.size() - 1] += (fractionalIndex - sample.size()) * interval;
}
return QuantileResult.of(losses / level, indices, DoubleArray.ofUnsafe(weights).dividedBy(level));
}
//-------------------------------------------------------------------------
/// <summary>
/// Internal method returning the index correction for the specific implementation.
/// </summary>
/// <returns> the correction </returns>
internal abstract double indexCorrection();
/// <summary>
/// Internal method returning the sample size correction for the specific implementation.
/// </summary>
/// <param name="sampleSize"> the sample size </param>
/// <returns> the correction </returns>
internal abstract int sampleCorrection(int sampleSize);
/// <summary>
/// Generate an index of doubles.
/// <para>
/// Creates an index of doubles from 1.0 to a stipulated number, in increments of 1.
///
/// </para>
/// </summary>
/// <param name="indexArrayLength"> length of index array to be created </param>
/// <returns> array of indices </returns>
private double[] createIndexArray(int indexArrayLength)
{
double[] indexArray = new double[indexArrayLength];
for (int i = 0; i < indexArrayLength; i++)
{
indexArray[i] = i;
}
return indexArray;
}
}
} | 41.857143 | 205 | 0.681077 | [
"Apache-2.0"
] | ckarcz/Strata.ConvertedToCSharp | modules/math/src/main/java/com/opengamma/strata/math/impl/statistics/descriptive/InterpolationQuantileMethod.cs | 5,276 | C# |
// Copyright © 2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Generic callback interface used for asynchronous completion.
/// </summary>
public interface ICompletionCallback : IDisposable
{
/// <summary>
/// Method that will be called once the task is complete.
/// </summary>
void OnComplete();
/// <summary>
/// Gets a value indicating whether the callback has been disposed of.
/// </summary>
bool IsDisposed { get; }
}
}
| 27.08 | 100 | 0.623338 | [
"BSD-3-Clause"
] | 364988343/CefSharp.Net40 | CefSharp/Callback/ICompletionCallback.cs | 678 | C# |
using MessagingClientMVVM.MicroMVVM;
using MessagingClientMVVM.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MessagingClientMVVM.ViewModels
{
public class FriendRequestViewModel : ObservableObject
{
private FriendRequest _fr;
public FriendRequestViewModel(int _senderID, int _receiverID, string _displayName, bool _isSent)
{
_fr = new FriendRequest(_senderID, _receiverID, _displayName, _isSent);
}
public FriendRequest Fr
{
get
{
return _fr;
}
set
{
_fr = value;
RaisePropertyChanged("Fr");
}
}
public string ID
{
get
{
if (_fr.IsSent)
return '#' + _fr.ReceiverID.ToString("D4");
else return '#' + _fr.SenderID.ToString("D4");
}
}
public int IDnumeric
{
get
{
if (_fr.IsSent)
return _fr.ReceiverID;
else return _fr.SenderID;
}
}
public bool IsSent
{
get
{
return _fr.IsSent;
}
set
{
_fr.IsSent = value;
RaisePropertyChanged("IsSent");
RaisePropertyChanged("IsSentStr");
RaisePropertyChanged("IDnumeric");
RaisePropertyChanged("ID");
}
}
public string DisplayName
{
get
{
return _fr.DisplayName;
}
set
{
_fr.DisplayName = value;
RaisePropertyChanged("DisplayName");
}
}
public string IsSentStr
{
get
{
if (_fr.IsSent)
return "Sent";
else return "Received";
}
}
}
}
| 23.932584 | 104 | 0.447887 | [
"Apache-2.0"
] | topham101/MultiUserMessagingApplication | MessagingClientMVVM/ViewModels/FriendRequestViewModel.cs | 2,132 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace BabySmash.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
}
| 19.272727 | 82 | 0.716981 | [
"MIT"
] | rmarinho/babysmash | BabySmash.iOS/Main.cs | 426 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Speck
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Speck());
}
}
} | 23.636364 | 65 | 0.617308 | [
"MIT"
] | GreenPasalacqua/Speck | Speck/Program.cs | 522 | C# |
#region COPYRIGHT© 2009-2014 Phillip Clark. All rights reserved.
// For licensing information see License.txt (MIT style licensing).
#endregion
using System;
using System.Diagnostics.Contracts;
namespace FlitBit.Core.Buffers
{
internal static class CRC
{
internal const int CrcTableLength = 256;
}
/// <summary>
/// Utility class for generating CRC16 checksums.
/// </summary>
public class Crc16
{
static readonly ushort[] Table = new ushort[CRC.CrcTableLength];
static Crc16()
{
const ushort poly = 0xA001;
for (ushort i = 0; i < CRC.CrcTableLength; ++i)
{
ushort value = 0;
var temp = i;
for (byte j = 0; j < 8; ++j)
{
if (((value ^ temp) & 0x0001) != 0)
{
value = (ushort)((value >> 1) ^ poly);
}
else
{
value >>= 1;
}
temp >>= 1;
}
Table[i] = value;
}
}
/// <summary>
/// Computes a checksum over an array of bytes.
/// </summary>
/// <param name="bytes">the bytes</param>
/// <returns>the checksum</returns>
[CLSCompliant(false)]
public ushort ComputeChecksum(byte[] bytes)
{
Contract.Requires<ArgumentNullException>(bytes != null);
ushort crc = 0;
var len = bytes.Length;
for (var i = 0; i < len; ++i)
{
var index = (byte)(crc ^ bytes[i]);
crc = (ushort)((crc >> 8) ^ Table[index]);
}
return crc;
}
}
/// <summary>
/// Utility class for generating CRC16 checksums.
/// </summary>
public class Crc32
{
static readonly uint[] Table = new uint[CRC.CrcTableLength];
static Crc32()
{
const uint poly = 0xedb88320;
for (uint i = 0; i < CRC.CrcTableLength; ++i)
{
var temp = i;
for (var j = 8; j > 0; --j)
{
if ((temp & 1) == 1)
{
temp = (temp >> 1) ^ poly;
}
else
{
temp >>= 1;
}
}
Table[i] = temp;
}
}
/// <summary>
/// Computes a checksum over an array of bytes.
/// </summary>
/// <param name="bytes">the bytes</param>
/// <returns>the checksum</returns>
[CLSCompliant(false)]
public uint ComputeChecksum(byte[] bytes)
{
Contract.Requires<ArgumentNullException>(bytes != null);
var crc = 0xffffffff;
foreach (var b in bytes)
{
var index = (byte)(((crc) & 0xff) ^ b);
crc = (crc >> 8) ^ Table[index];
}
return ~crc;
}
/// <summary>
/// Computes a checksum over an array of bytes beginning with the first and
/// continuing to length.
/// </summary>
/// <param name="bytes"></param>
/// <param name="first"></param>
/// <param name="length"></param>
/// <returns></returns>
[CLSCompliant(false)]
public uint ComputeChecksum(byte[] bytes, int first, int length)
{
var crc = 0xffffffff;
for (var i = first; i < length; ++i)
{
var index = (byte)(((crc) & 0xff) ^ bytes[i]);
crc = (crc >> 8) ^ Table[index];
}
return ~crc;
}
}
/// <summary>
/// A few common initial CRC values
/// </summary>
public enum InitialCrcValue
{
/// <summary>
/// All zero.
/// </summary>
Zeros = 0,
/// <summary>
/// Common initial value of 0x1D0F
/// </summary>
NonZeroX1D0F = 0x1d0f,
/// <summary>
/// Common initial value of 0xFFFF
/// </summary>
NonZeroXFfff = 0xffff,
}
/// <summary>
/// Utility class for generating CRC16CITT checksums.
/// </summary>
public class Crc16Ccitt
{
static readonly ushort[] Table = new ushort[CRC.CrcTableLength];
readonly ushort _initialValue;
static Crc16Ccitt()
{
const ushort poly = 4129;
for (var i = 0; i < CRC.CrcTableLength; ++i)
{
ushort temp = 0;
var a = (ushort)(i << 8);
for (var j = 0; j < 8; ++j)
{
if (((temp ^ a) & 0x8000) != 0)
{
temp = (ushort)((temp << 1) ^ poly);
}
else
{
temp <<= 1;
}
a <<= 1;
}
Table[i] = temp;
}
}
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="initialValue">which initial value the checksum should use</param>
public Crc16Ccitt(InitialCrcValue initialValue) { this._initialValue = (ushort)initialValue; }
/// <summary>
/// Computes a checksum over an array of bytes.
/// </summary>
/// <param name="bytes">the bytes</param>
/// <returns>the checksum</returns>
[CLSCompliant(false)]
public ushort ComputeChecksum(byte[] bytes)
{
Contract.Requires<ArgumentNullException>(bytes != null);
var crc = this._initialValue;
var len = bytes.Length;
for (var i = 0; i < len; ++i)
{
crc = (ushort)((crc << 8) ^ Table[((crc >> 8) ^ (0xff & bytes[i]))]);
}
return crc;
}
}
} | 24.189573 | 98 | 0.514303 | [
"MIT"
] | flitbit-org/fbcore | FlitBit.Core/Buffers/CRC.cs | 5,107 | C# |
using System;
using System.Collections.Generic;
using C5;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuickGraph;
namespace PacePrototype
{
using HashSet = System.Collections.Generic.HashSet<string>;
public class Pair
{
public string X { get; set; }
public string Y { get; set; }
public Pair(string x, string y)
{
X = x;
Y = y;
}
public override string ToString() => $"({X}, {Y})";
}
public class Holder
{
//Should use getter and setters, but no thanks.
public Dictionary<string, List<string>> Graph;
public HashSet A;
public HashSet B;
public int CC;
public bool Stop = false;
public List<Pair> EssentialEdges = new List<Pair>();
public Holder(Dictionary<string, List<string>> graph, HashSet b, HashSet a, int cc)
{
Graph = graph;
A = a;
B = b;
CC = cc;
}
public Holder(Dictionary<string, List<string>> graph, HashSet b, HashSet a) : this(graph, b, a, 0) { }
}
class Kernel
{
// Takes in a .graph file and reads it - if no file is specified reads from System.in
private static Holder Phase1(Holder holder)
{
var tmpGraph = new Dictionary<string, List<string>>(holder.Graph);
while (true)
{
var res = MCS.ExtractChordlessCycle(tmpGraph);
//Our break condition
if (res.Count < 1) break;
holder.CC += (res.Count - 3);
tmpGraph = CleanGraph(tmpGraph, holder, res);
}
return holder;
}
private static Dictionary<string, List<string>> CleanGraph(Dictionary<string, List<string>> graph, Holder holder, List<string> nodes)
{
foreach (var s in nodes)
{
holder.B.Remove(s);
holder.A.Add(s);
graph.Remove(s);
foreach (var key in graph.Keys)
{
graph[key].Remove(s);
}
}
return graph;
}
private static List<string> BFS(string toFind, Holder holder, string startPoint, List<string> listB, List<string> listA)
{
var q = new IntervalHeap<string>();
var distTo = new Dictionary<string, int>();
var edgeTo = new Dictionary<string, string>();
var marked = new Dictionary<string, bool>();
var newGraph = Copy(holder.Graph);
var yEdges = newGraph[toFind];
var xEdges = newGraph[startPoint];
//removing all connections to the a set
for (int i = 0; i < yEdges.Count; i++)
{
var node = yEdges[i];
if (listA.Contains(node))
{
var tmp = newGraph[node];
tmp.Remove(toFind);
newGraph[node] = tmp;
}
else if (xEdges.Contains(node))
{
var tmp = newGraph[node];
tmp.Remove(toFind);
tmp.Remove(startPoint);
newGraph[node] = tmp;
xEdges.Remove(node);
}
}
foreach (var s in listA)
{
yEdges.Remove(s);
}
newGraph[toFind] = yEdges;
newGraph[startPoint] = xEdges;
//We just start at the first node
q.Add(startPoint);
//We now just keep track of occurrences
//Should be two consecutive nodes? This does not do that currently
//Unsure of examples where this would fail
distTo[startPoint] = 0;
marked[startPoint] = true;
while (!q.IsEmpty)
{
var v = q.DeleteMin();
foreach (var w in newGraph[v])
{
if (marked.ContainsKey(w))
{
var mark = marked[w];
if (mark) continue;
}
marked[w] = true;
distTo[w] = distTo[v] + 1;
edgeTo[w] = v;
q.Add(w);
}
}
// Unsure if I need this
// int conBs = 0;
var path = new List<string>();
if (marked.ContainsKey(toFind))
{
string x;
for (x = toFind; distTo[x] != 0; x = edgeTo[x])
{
path.Add(x);
}
path.Add(x);
}
return path;
}
//Missing increasing CC
private static Holder Phase2(Holder holder)
{
var listA = holder.A.ToList();
var listB = holder.B.ToList();
//I could not do this with a set, but can with a list.
//It makes sense, thinking about the structure of Java, that I
//can do this, but not very safe, might be an endless loop!!!
for (var i = 0; i < listA.Count; i++)
{
var x = listA[i];
//Detect if elements are in B, if they are do stuff
var edges = holder.Graph[x];
//Do we want to add things we discover runningly or not?
for (var j = 0; j < edges.Count; j++)
{
var t = edges[j];
if (!listB.Contains(t)) continue;
//shouldBeAdded = true;
//Found our Y
var y = t;
//Need BFS here -- Otherwise it is impossible to locate
//whether or not neighbour to look at is present in a cycle.
//Looking at neighbours of Y, to see if they are connected to
//at least one neighbour of X.
var yNeighbours = new List<string>(holder.Graph[y]);
//Remove all common neighbours
if (yNeighbours.Count <= 0) continue;
foreach (var neighbour in yNeighbours)
{
//for each neighbour
var path = BFS(neighbour, holder, x, listB, listA);
//Found a cycle
if (path.Count > 0)
{
var subpaths = new List<int>();
var currentSubPath = 0;
var foundPath = false;
foreach (var s in path)
{
if (listB.Contains(s))
{
foundPath = true;
currentSubPath++;
listA.Add(s);
listB.Remove(s);
}
else
{
if (foundPath)
{
if (currentSubPath - 1 > 0) subpaths.Add(currentSubPath - 1);
foundPath = false;
currentSubPath = 0;
}
}
}
if (subpaths.Count > 0)
{
if (subpaths.Count == 1)
{
var subpath = subpaths[0];
holder.CC += path.Count - subpath == 1 ? subpath - 2 : subpath - 1;
}
else
{
var addToCC = subpaths.Sum(p => p - 1);
holder.CC += (addToCC / 2);
}
}
}
}
}
}
holder.A = new HashSet(listA);
holder.B = new HashSet(listB);
return holder;
}
private static List<string> BFSPhase3(string toFind, Dictionary<string, List<string>> newGraph, string startPoint)
{
var q = new IntervalHeap<string>();
var distTo = new Dictionary<string, int>();
var edgeTo = new Dictionary<string, string>();
var marked = new Dictionary<string, bool>();
//We just start at the first node
q.Add(startPoint);
//We now just keep track of occurrences
//Should be two consecutive nodes? This does not do that currently
//Unsure of examples where this would fail
distTo.Add(startPoint, 0);
marked.Add(startPoint, true);
var counter = 0;
while (!q.IsEmpty)
{
var v = q.DeleteMin();
foreach (var w in newGraph[v])
{
if (w.Equals(toFind)) counter++;
var mark = false;
if (marked.ContainsKey(w))
mark = marked[w];
if (!mark)
{
marked[w] = true;
distTo[w] = distTo[v] + 1;
edgeTo[w] = v;
q.Add(w);
}
}
}
var path = new List<string>();
var gotThere = marked[toFind];
if (gotThere)
{
string x;
for (x = toFind; distTo[x] != 0; x = edgeTo[x])
{
path.Add(x);
}
path.Add(x);
}
//Now path should contain the shortest possible path;
//Is not part of a cycle
return path;
}
public static Holder Phase3(Holder holder, int k)
{
var startGraph = Copy(holder.Graph);
var listA = new List<string>(holder.A);
var listB = new List<string>(holder.B);
//First generate all nonadjacent pairs from A
var pairs = new List<Pair>();
var resolvedNodes = new List<string>();
foreach (var v in holder.A)
{
var adjacent = holder.Graph[v];
var tmpAs = new HashSet();
tmpAs.UnionWith(holder.A);
tmpAs.UnionWith(adjacent);
foreach (var s in tmpAs)
{
//We can make this check as every pair should have already been made, if
//the given node is found in resolvedNodes.
if (s.Equals(v)) continue;
if (!resolvedNodes.Contains(s))
{
pairs.Add(new Pair(v, s));
}
}
resolvedNodes.Add(v);
}
//First we found all candidates
foreach (var pair in pairs)
{
//To stick with the notation of the paper, y is x, and z is y form the pair.
var yNeighbours = startGraph[pair.X];
//The set we need to check whether is larger than 2k.
var candidates = new List<string>();
foreach (var yNeighbour in yNeighbours)
{
if (listB.Contains(yNeighbour) && startGraph[yNeighbour].Contains(pair.Y))
{
var graph = Copy(startGraph);
var neighbourEdges = graph[yNeighbour];
foreach (var edge in neighbourEdges)
{
if (edge.Equals(pair.X) || edge.Equals(pair.Y)) continue;
var tmp = graph[edge];
tmp.Remove(yNeighbour);
graph[edge] = tmp;
}
var newEdges = new List<string> {pair.X, pair.Y};
graph[yNeighbour] = newEdges;
var neighbourPath = BFSPhase3(pair.Y, graph, yNeighbour);
if (neighbourPath.Count > 0) candidates.Add(yNeighbour);
}
}
if (candidates.Count > 2 * k)
{
holder.EssentialEdges.Add(pair);
}
else
{
foreach (var s in candidates)
{
listB.Remove(s);
listA.Add(s);
}
}
}
holder.A = new HashSet(listA);
holder.B = new HashSet(listB);
return holder;
}
private Dictionary<string, List<string>> graphStart;
private Dictionary<string, List<string>> graph1;
private Dictionary<string, List<string>> graph2;
private Dictionary<string, List<string>> graph3;
private Holder _holder;
public Kernel(Dictionary<string, List<string>> graph)
{
graphStart = Copy(graph);
graph1 = Copy(graph);
graph2 = Copy(graph);
graph3 = Copy(graph);
_holder = new Holder(graph1, new HashSet(graph.Keys), new HashSet());
}
public Holder RunPhase1Then2()
{
RunPhase1();
return RunPhase2();
}
public Holder RunPhase1()
{
_holder = Phase1(_holder);
_holder.Graph = graph2;
return _holder;
}
public Holder RunPhase2()
{
_holder = Phase2(_holder);
_holder.Graph = graph3;
return _holder;
}
public Holder RunPhase3(int k)
{
_holder = Phase3(_holder, k);
_holder.Graph = graphStart;
return _holder;
}
public static Dictionary<string, List<string>> Copy(Dictionary<string, List<string>> original)
{
return original.Keys.ToDictionary(key => key, key => new List<string>(original[key]));
}
public static Holder Init(UndirectedGraph<int, Edge<int>> graph)
{
var graph1 = new Dictionary<string, List<string>>();
foreach (var v in graph.Vertices)
{
graph1.Add(v.ToString(), graph.AdjacentEdges(v).Select(e => e.GetOtherVertex(v).ToString()).ToList());
}
var kernel = new Kernel(graph1);
return kernel.RunPhase1Then2();
}
//public static void main(string[] args)
//{
// InputStream input;
// if (args.length == 0)
// input = System.in;
// else
// input = new FileInputStream(new File(args[0]));
// try (Scanner scanner = new Scanner(input)) {
// Dictionary<string, List<string>> graph = new Dictionary<>();
// Dictionary<string, List<string>> graph2 = new Dictionary<>();
// Dictionary<string, List<string>> graph3 = new Dictionary<>();
// while (scanner.hasNextLine())
// {
// string line = scanner.nextLine();
// string[] split = line.split(" ");
// if (graph.containsKey(split[0]))
// {
// graph[split]0]).Add(split[1]);
// graph2[split]0]).Add(split[1]);
// graph3[split]0]).Add(split[1]);
// }
// else
// {
// List<string> list = new List<>();
// List<string> list2 = new List<>();
// List<string> list3 = new List<>();
// list.Add(split[1]);
// list2.Add(split[1]);
// list3.Add(split[1]);
// graph.Add(split[0], list);
// graph2.Add(split[0], list2);
// graph3.Add(split[0], list3);
// }
// if (graph.containsKey(split[1]))
// {
// graph[split]1]).Add(split[0]);
// graph2[split]1]).Add(split[0]);
// graph3[split]1]).Add(split[0]);
// }
// else
// {
// List<string> list = new List<>();
// List<string> list2 = new List<>();
// List<string> list3 = new List<>();
// list.Add(split[0]);
// list2.Add(split[0]);
// list3.Add(split[0]);
// graph.Add(split[1], list);
// graph2.Add(split[1], list2);
// graph3.Add(split[1], list3);
// }
// }
// Kernel kernel = new Kernel(graph);
// kernel.RunPhase1Then2();
// Holder holder = kernel.RunPhase3(1000);
// //No idea what this value should really be at this time.
// //int k = 100000;
// // Holder holder = new Holder(new Dictionary(graph), graph.keySet(), new HashHashSet(), 0, k);
// //More functional approach, dunno if this is a performance issue
// /*holder = Phase1(holder);
// if(holder.stop) return;
// holder.graph = graph2;//new Dictionary(graph);//graph2;
// holder = Phase2(holder);
// if(holder.stop) return;
// holder.graph = new Dictionary(graph3);//graph3;
// holder = Phase3(holder);
// if(holder.stop) return;*/
// Console.WriteLine(holder.A);
// Console.WriteLine(holder.B);
// Console.WriteLine(holder.cc);
// Console.WriteLine(holder.essentialEdges);
// // Kernel kernel = new Kernel(graph);
// // kernel.runStuff();
// // Console.WriteLine(holder.graph);
// //Console.WriteLine(holder.A.Count);
// /*
// bool hasChanged = true;
// while(hasChanged)
// {
// hasChanged = false;
// for (Dictionary.Entry<string, List<string>> vertexAndEdges : graph.entrySet()) {
// if(vertexAndEdges.getValue().Count==1)
// {
// string other = vertexAndEdges.getValue()[0];
// graph[other].Remove(vertexAndEdges.getKey());
// vertexAndEdges.getValue().Remove(other);
// hasChanged = true;
// }
// }
// }*/
// /*
// HashHashSet outputted = new HashHashSet<>();
// for (Dictionary.Entry<string, List<string>> vertexAndEdges : graph.entrySet()) {
// for (string s : vertexAndEdges.getValue()) {
// if(!outputted.Contains(s)){
// Console.WriteLine(vertexAndEdges.getKey() + " " + s);
// outputted.Add(vertexAndEdges.getKey());
// }
// }
// }*/
// }
}
public class MCS
{
//Returns empty list if no cycle is found.
public static List<string> ExtractChordlessCycle(Dictionary<string, List<string>> graph)
{
var dim = graph.Count;
var ordering = new Dictionary<int, string>();
foreach (var node in graph.Keys)
{
ordering.Add(ordering.Count, node);
}
for (var i = 0; i < dim - 2; i++)
{
for (var j = i + 1; j < dim - 1; j++)
{
if (!AreAdjacent(graph, ordering, i, j))
{
continue;
}
for (int k = i + 1; k < dim; k++)
{
var candidates = new List<List<int>>();
for (int l = i + 1; l < dim; l++)
{
if (l == k || j == k || j == l)
{
continue;
}
if (!AreAdjacent(graph, ordering, k, l))
{
continue;
}
if (!AreAdjacent(graph, ordering, j, l) && !AreAdjacent(graph, ordering, j, k))
{
continue;
}
var nodes = new List<int>();
nodes.Add(i);
nodes.Add(j);
nodes.Add(k);
nodes.Add(l);
if (IsChordless(graph, ordering, nodes))
{
var result = new List<string>();
result.Add(ordering[i]);
result.Add(ordering[j]);
result.Add(ordering[k]);
result.Add(ordering[l]);
return result;
}
candidates.Add(nodes);
}
while (candidates.Count > 0)
{
List<int> v = candidates[0];
candidates.RemoveAt(0);
int l = v[v.Count - 1];
for (int m = i + 1; m < dim; m++)
{
if (v.Contains(m))
{
continue;
}
if (!AreAdjacent(graph, ordering, m, l))
{
continue;
}
bool chord = false;
for (int n = 1; n < v.Count - 1; n++)
{
if (AreAdjacent(graph, ordering, m, v[n]))
{
chord = true;
}
}
if (chord)
{
continue;
}
if (AreAdjacent(graph, ordering, m, k))
{
var result = new List<string>();
for (int n = 0; n < v.Count; n++)
{
result.Add(ordering[v[n]]);
}
result.Add(ordering[m]);
return result;
}
var w = new List<int>(v);
w.Add(m);
candidates.Add(w);
}
}
}
}
}
return new List<string>();
}
private static bool AreAdjacent(Dictionary<string, List<string>> graph, Dictionary<int, string> ordering, int x, int y)
{
return graph[ordering[x]].Contains(ordering[y]);
}
private static bool IsChordless(Dictionary<string, List<string>> graph, Dictionary<int, string> ordering, List<int> nodes)
{
// check if the length of nodes is 4
if (nodes.Count < 4) return false;
// create a set from the nodes and see it the length is 4
var nodeSet = new System.Collections.Generic.HashSet<int>();
foreach (var node in nodes)
{
nodeSet.Add(node);
}
if (nodeSet.Count != nodes.Count) return false;
// for each node count how many adj are there
foreach (int i in nodes)
{
int counter = 0;
foreach (int j in nodes)
{
if (AreAdjacent(graph, ordering, i, j)) counter++;
}
if (counter != 2) return false;
}
// if all of them are 2 return true else false
return true;
}
private static Dictionary<string, List<string>> Clone(Dictionary<string, List<string>> original)
{
var clone = new Dictionary<string, List<string>>();
foreach (var kvPair in original)
{
clone.Add(kvPair.Key, new List<string>(kvPair.Value));
}
return clone;
}
}
}
| 37.087019 | 141 | 0.396761 | [
"MIT"
] | Madsen90/Pace17 | PacePrototype/MinFillKernelizer.cs | 26,000 | C# |
//-----------------------------------------------------------------------------
// FILE: PageBase.razor.cs
// CONTRIBUTOR: Marcus Bowyer
// COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using NeonDashboard.Shared;
using NeonDashboard.Shared.Components;
namespace NeonDashboard.Pages
{
public partial class PageBase : ComponentBase
{
[Parameter]
public string PageTitle { get; set; } = "NeonKUBE Dashboard";
[Parameter]
public string Description { get; set; } = "";
public PageBase()
{
}
public void Dispose()
{
}
}
} | 27.3125 | 80 | 0.695652 | [
"Apache-2.0"
] | codelastnight/neonKUBE | Services/neon-dashboard/Pages/PageBase.razor.cs | 1,313 | C# |
// WARNING
//
// This file has been generated automatically by Visual Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
using System.CodeDom.Compiler;
namespace Stylophone.iOS.ViewControllers
{
[Register ("FilePathCell")]
partial class FilePathCell
{
[Outlet]
UIKit.UIImageView FilePathImage { get; set; }
[Outlet]
UIKit.UILabel FilePathLabel { get; set; }
void ReleaseDesignerOutlets ()
{
if (FilePathImage != null) {
FilePathImage.Dispose ();
FilePathImage = null;
}
if (FilePathLabel != null) {
FilePathLabel.Dispose ();
FilePathLabel = null;
}
}
}
}
| 21.114286 | 83 | 0.694181 | [
"MIT"
] | Difegue/Stylophone | Sources/Stylophone.iOS/ViewControllers/SubViews/FilePathCell.designer.cs | 739 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace EveOpenApi.Api
{
internal interface IApiRequest
{
public Uri RequestUri { get; }
public HttpMethod HttpMethod { get; }
public string User { get; }
public string Scope { get; }
public IDictionary<string, string> Headers { get; }
/// <summary>
/// Add a parameter to the query of this request.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
void SetParameter(string name, string value);
/// <summary>
/// Set a header to a value for this request.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
void SetHeader(string name, string value);
}
} | 22.121212 | 53 | 0.654795 | [
"MIT"
] | henrik9864/EsiNet | Eve-OpenApi/Interfaces/API/IApiRequest.cs | 732 | C# |
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace RedPlus.WebApp.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
| 23.470588 | 83 | 0.734336 | [
"MIT"
] | VisualAcademy/RedPlus.RazorPages | RedPlus.WebApp/Data/ApplicationDbContext.cs | 401 | C# |
using System.Diagnostics.Contracts;
namespace System.Reactive.Linq
{
public static partial class Observable2
{
/// <summary>
/// Creates an observable sequence with two notification channels from the <paramref name="subscribe"/> implementation.
/// </summary>
/// <typeparam name="TLeft">Type of the left notification channel.</typeparam>
/// <typeparam name="TRight">Type of the right notification channel.</typeparam>
/// <param name="subscribe">Subscribes observers to the observable.</param>
/// <returns>An observable with two notification channels that calls the specified <paramref name="subscribe"/> function
/// when an observer subscribes.</returns>
public static IObservable<Either<TLeft, TRight>> CreateEither<TLeft, TRight>(
Func<IObserver<Either<TLeft, TRight>>, Action> subscribe)
{
Contract.Requires(subscribe != null);
Contract.Ensures(Contract.Result<IObservable<Either<TLeft, TRight>>>() != null);
return Observable.Create<Either<TLeft, TRight>>(observer => subscribe(observer));
}
/// <summary>
/// Creates an observable sequence with two notification channels from the <paramref name="subscribe"/> implementation.
/// </summary>
/// <typeparam name="TLeft">Type of the left notification channel.</typeparam>
/// <typeparam name="TRight">Type of the right notification channel.</typeparam>
/// <param name="subscribe">Subscribes observers to the observable.</param>
/// <returns>An observable with two notification channels that calls the specified <paramref name="subscribe"/> function
/// when an observer subscribes.</returns>
public static IObservable<Either<TLeft, TRight>> CreateEither<TLeft, TRight>(
Func<IObserver<Either<TLeft, TRight>>, IDisposable> subscribe)
{
Contract.Requires(subscribe != null);
Contract.Ensures(Contract.Result<IObservable<Either<TLeft, TRight>>>() != null);
return Observable.Create<Either<TLeft, TRight>>(observer => subscribe(observer));
}
}
} | 49.926829 | 125 | 0.708354 | [
"MIT"
] | slorion/multiagent-system-example | DLC.Multiagent/Rxx/System/Reactive/Linq/Observable2 - Either - Create.cs | 2,049 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Csharp Arduino Control 8 LEDs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Csharp Arduino Control 8 LEDs")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("82ce3210-1b60-4749-ab92-2e09e40b5a59")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.540541 | 84 | 0.748247 | [
"MIT"
] | James-chen-ha/C-_control_8_LED_GUI | Properties/AssemblyInfo.cs | 1,429 | C# |
using System.Threading.Tasks;
using Elastic.Xunit.XunitPlumbing;
using Nest;
using Tests.Framework;
using static Tests.Framework.UrlTester;
namespace Tests.XPack.Security.Role.ClearCachedRoles
{
public class ClearCachedRolesUrlTests : UrlTestsBase
{
[U] public override async Task Urls()
{
var role = "some_role";
await POST($"/_xpack/security/role/{role}/_clear_cache")
.Fluent(c => c.ClearCachedRoles(role))
.Request(c => c.ClearCachedRoles(new ClearCachedRolesRequest(role)))
.FluentAsync(c => c.ClearCachedRolesAsync(role))
.RequestAsync(c => c.ClearCachedRolesAsync(new ClearCachedRolesRequest(role)))
;
}
}
}
| 28.521739 | 83 | 0.737805 | [
"Apache-2.0"
] | Henr1k80/elasticsearch-net | src/Tests/Tests/XPack/Security/Role/ClearCachedRoles/ClearCachedRolesUrlTests.cs | 658 | C# |
#region Using
using Emotion.Graphics.Objects;
using Emotion.Primitives;
#endregion
#nullable enable
namespace Emotion.Graphics.ThreeDee
{
/// <summary>
/// Settings description of how to render a 3D object.
/// </summary>
public class MeshMaterial
{
public string Name = null!;
public Color DiffuseColor = Color.White;
public string? DiffuseTextureName = null;
public Texture? DiffuseTexture;
public static MeshMaterial DefaultMaterial = new MeshMaterial();
}
} | 22.125 | 72 | 0.679849 | [
"MIT"
] | simo-andreev/Emotion | Emotion/Graphics/ThreeDee/MeshMaterial.cs | 533 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using SharpVectors.Renderers.Wpf;
using SharpVectors.Converters;
using SharpVectors.Dom.Svg;
using GazoView.Functions;
using System.Windows.Controls;
namespace GazoView
{
class ImageStore
{
private static string[] _imageExtensions = new string[]
{
".jpg", ".jpeg", ".png", ".tif", ".tiff", ".svg", ".bmp", ".gif"
};
private WpfDrawingSettings _drawingSettings = null;
public List<string> Items { get; set; }
private bool _isAllImage = false;
public bool IsAllImage { get { return _isAllImage; } }
private int _currentIndex;
public int CurrentIndex
{
get
{
if (_currentIndex < 0)
{
_currentIndex = Items.Count - 1;
}
else if (_currentIndex >= Items.Count)
{
_currentIndex = 0;
}
return _currentIndex;
}
set { this._currentIndex = value; }
}
public string CurrentExtension
{
get { return (Items != null && Items.Count > 0) ? Path.GetExtension(Items[CurrentIndex]).ToLower() : null; }
}
private BitmapImage _currentBitmapImage = null;
private DrawingImage _currentDrawingImage = null;
public ImageSource CurrentImageSource
{
get
{
if (_currentBitmapImage != null)
{
return _currentBitmapImage;
}
else if (_currentDrawingImage != null)
{
return _currentDrawingImage;
}
return null;
}
}
public string CurrentPath
{
get { return (Items != null && Items.Count > 0) ? Items[CurrentIndex] : null; }
}
private string _currentParentDirectory = null;
public string CurrentParentDirectory
{
get { return _currentParentDirectory; }
}
private double _currentWidth = 0;
public double CurrentWidth
{
get
{
if (_currentBitmapImage != null)
{
_currentWidth = _currentBitmapImage.PixelWidth;
}
else if (_currentDrawingImage != null)
{
_currentWidth = _currentDrawingImage.Width;
}
return _currentWidth;
}
}
private double _currentHeight = 0;
public double CurrentHeight
{
get
{
if (_currentBitmapImage != null)
{
_currentHeight = _currentBitmapImage.PixelHeight;
}
else if (_currentDrawingImage != null)
{
_currentHeight = _currentDrawingImage.Height;
}
return _currentHeight;
}
}
private FileStream _gifStream = null;
public ImageStore() { }
public ImageStore(string[] itemPaths)
{
SetItems(itemPaths);
}
/// <summary>
/// 指定したインデックスの画像をBitmapImageで返す
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private BitmapImage GetBitMapImage(string targetImagePath)
{
_currentDrawingImage = null;
using (FileStream fs = new FileStream(targetImagePath, FileMode.Open, FileAccess.Read))
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.StreamSource = fs;
bmp.EndInit();
bmp.Freeze();
_currentBitmapImage = bmp;
return _currentBitmapImage;
}
}
/// <summary>
/// 指定したインデックスのSVG画像をDrawingImageで返す
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private DrawingImage GetDrawingImage(string targetImagePath)
{
_currentBitmapImage = null;
if (_drawingSettings == null)
{
_drawingSettings = new WpfDrawingSettings();
_drawingSettings.IncludeRuntime = true;
_drawingSettings.TextAsGeometry = false;
}
using (var converter = new StreamSvgConverter(_drawingSettings))
using (MemoryStream ms = new MemoryStream())
{
if (converter.Convert(targetImagePath, ms))
{
_currentDrawingImage = new DrawingImage(converter.Drawing);
return _currentDrawingImage;
}
}
return null;
}
/// <summary>
/// GIFファイル用BitmapImageを取得
/// </summary>
/// <param name="targetImagePath"></param>
/// <returns></returns>
private BitmapImage GetBitMapImageForGif(string targetImagePath)
{
_currentDrawingImage = null;
_gifStream = new FileStream(targetImagePath, FileMode.Open, FileAccess.Read);
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.StreamSource = _gifStream;
bmp.EndInit();
bmp.Freeze();
_currentBitmapImage = bmp;
return _currentBitmapImage;
}
/// <summary>
/// 現在のインデックスの画像をBitmapImageで返す
/// </summary>
/// <returns></returns>
public ImageSource GetCurrentImageSource(Image mainImage)
{
if (CurrentIndex >= 0 && CurrentIndex < Items.Count)
{
string targetImagePath = Items[CurrentIndex];
if (_gifStream != null)
{
WpfAnimatedGif.ImageBehavior.SetAnimatedSource(mainImage, null);
_gifStream.Dispose();
_gifStream = null;
}
if (CurrentExtension == ".svg")
{
return GetDrawingImage(targetImagePath);
}
else if (CurrentExtension == ".gif")
{
BitmapImage bitmapImage = GetBitMapImageForGif(targetImagePath);
WpfAnimatedGif.ImageBehavior.SetAnimatedSource(mainImage, bitmapImage);
return bitmapImage;
}
return GetBitMapImage(targetImagePath);
}
_currentBitmapImage = null;
_currentDrawingImage = null;
return null;
}
/// <summary>
/// ファイルパス(文字列配列)からItemsにセット
/// </summary>
/// <param name="itemPaths"></param>
public void SetItems(string[] itemPaths)
{
if (Items == null) { this.Items = new List<string>(); }
if (Items.Count > 0) { this.Items.Clear(); }
if (itemPaths.Length == 1)
{
// 同フォルダー内の全画像ファイルを対象
this._isAllImage = true;
this._currentParentDirectory = Path.GetDirectoryName(itemPaths[0]);
this.Items = Directory.GetFiles(_currentParentDirectory).
Where(x => _imageExtensions.Contains(Path.GetExtension(x).ToLower())).
OrderBy(x => x, new NaturalStringComparer()).
ToList();
CurrentIndex = Items.IndexOf(itemPaths[0]);
}
else if (itemPaths.Length > 1)
{
// 指定したファイルのみが対象
this._isAllImage = false;
this._currentParentDirectory = null;
this.Items = itemPaths.
OrderBy(x => x, new NaturalStringComparer()).ToList();
CurrentIndex = 0;
}
}
/// <summary>
/// ファイルパス (List<string>)からItemsにセット
/// </summary>
/// <param name="itemPaths"></param>
public void SetItems(List<string> itemPaths)
{
SetItems(itemPaths.ToArray());
}
/// <summary>
/// ファイルパス (1つだけ) からItemsにセット
/// </summary>
/// <param name="itemPath"></param>
public void SetItem(string itemPath)
{
SetItems(new string[] { itemPath });
}
/// <summary>
/// タイトルバーに表示する為の画像ファイルの名前とパスを返す。
/// </summary>
/// <returns></returns>
public string GetCurrentImageTitle()
{
if (Items.Count > 0 && CurrentIndex >= 0)
{
return string.Format("[ {0} ] {1}",
Path.GetFileName(Items[CurrentIndex]), Items[CurrentIndex]);
}
return "";
}
/// <summary>
/// Itemsの更新
/// </summary>
public void UpdateItems()
{
if (Items == null) { return; }
string tempImagePath = Items[CurrentIndex];
List<string> tempItems = Directory.GetFiles(_currentParentDirectory).
Where(x => _imageExtensions.Contains(Path.GetExtension(x).ToLower())).
OrderBy(x => x, new NaturalStringComparer()).
ToList();
if (!Items.SequenceEqual(tempItems))
{
this.Items = tempItems;
CurrentIndex = Items.IndexOf(tempImagePath);
}
}
}
}
| 31.72381 | 120 | 0.505154 | [
"MIT"
] | tgiqfe/GazoView | GazoView/ImageStore.cs | 10,325 | C# |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using PdfSharp.Drawing;
namespace XDrawing.TestLab.Tester
{
/// <summary>
/// Draws a Spirograph.
/// </summary>
public class MiscSpiroGraph : TesterBase
{
/// <summary>
/// Source and more infos: http://www.math.dartmouth.edu/~dlittle/java/SpiroGraph/
/// </summary>
public override void RenderPage(XGraphics gfx)
{
base.RenderPage(gfx);
//int R = 60, r = 60, p = 60, N = 270; // Cardioid
//int R = 60, r = -45, p = -101, N = 270; // Rounded Square
//int R = 75, r = -25, p = 85, N = 270; // Gold fish
//int R = 75, r = -30, p = 60, N = 270; // Star fish
//int R = 100, r = 49, p = 66, N = 7; // String of Pearls
//int R = 90, r = 1, p = 105, N = 105; // Rotating Triangle
//int R = 90, r = 1, p = 105, N = 105;
int R = 60, r = 2, p = 122, N = 490;
int revs = Math.Abs(r) / Gcd(R, Math.Abs(r));
XPoint[] points = new XPoint[revs * N + 1];
for (int i = 0; i <= revs * N; i++)
{
double t = 4 * i * Math.PI / N;
points[i].X = ((R+r)*Math.Cos(t) - p * Math.Cos((R+r)* t / r));
points[i].Y = ((R+r)*Math.Sin(t) - p * Math.Sin((R+r)* t / r));
}
#if true
// Draw as lines
gfx.TranslateTransform(300, 250);
gfx.DrawLines(properties.Pen2.Pen, points);
//gfx.DrawPolygon(properties.Pen2.Pen, properties.Brush2.Brush, points, properties.General.FillMode);
// Draw as closed curve
gfx.TranslateTransform(0, 400);
gfx.DrawClosedCurve(properties.Pen2.Pen, properties.Brush2.Brush, points, properties.General.FillMode,
properties.General.Tension);
#else
gfx.TranslateTransform(300, 400);
XSolidBrush dotBrush = new XSolidBrush(properties.Pen2.Pen.Color);
float width = properties.Pen2.Width;
for (int i = 0; i < revs * N; i++)
gfx.DrawEllipse(dotBrush,points[i].X, points[i].Y, width, width);
#endif
}
public override string Description
{
get {return "Spirograph (DrawLines & DrawClosedCurve)";}
}
/// <summary>
/// Calculates greatest common divisor.
/// </summary>
int Gcd(int x, int y)
{
return x % y == 0 ? y : Gcd(y, x % y);
}
}
}
| 32.205479 | 108 | 0.549128 | [
"MIT"
] | dankennedy/PDFSharp | dev/XGraphicsLab/Tester/Miscellaneous/MiscSpiroGraph.cs | 2,351 | C# |
/*<FILE_LICENSE>
* NFX (.NET Framework Extension) Unistack Library
* Copyright 2003-2018 Agnicore Inc. portions ITAdapter Corp. Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
</FILE_LICENSE>*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using NFX.Web;
using NFX.ApplicationModel;
using NFX.Templatization;
namespace NFX.Wave.Templatization
{
/// <summary>
/// Defines a base class for web-related templates
/// </summary>
public abstract class WaveTemplate : Template<WorkContext, IRenderingTarget, object>
{
/// <summary>
/// Escapes JS literal, see NFX.Web.Utils.EscapeJSLiteral
/// </summary>
public static string EscapeJSLiteral(string value)
{
return value.EscapeJSLiteral();
}
/// <summary>
/// Converts string to HTML-encoded string
/// </summary>
public static string HTMLEncode(string value)
{
return WebUtility.HtmlEncode(value);
}
public WaveTemplate() : base()
{
}
public WaveTemplate(WorkContext context) : base (context)
{
}
public Response Response { get { return Context.Response; } }
/// <summary>
/// Returns session if it is available or null
/// </summary>
public WaveSession Session { get { return Context.Session; } }
/// <summary>
/// Returns CSRF token for session if it is available or null
/// </summary>
public string CSRFToken
{
get
{
var session = this.Session;
if (session==null) return null;
return session.CSRFToken;
}
}
/// <summary>
/// Override to indicate whetner the instance of the template may be reused for processing of other requests
/// (possibly by parallel threads). Override to return false if there is any per-request state shared in instance fields
/// False by default so multiple requests can not reuse the instance
/// </summary>
public override bool CanReuseInstance
{
get { return false; }
}
/// <summary>
/// Override to provides response content type. Default value is HTML
/// </summary>
public virtual string ContentType
{
get { return NFX.Web.ContentType.HTML; }
}
/// <summary>
/// Renders template by generating content into ResponseRenderingTarget
/// </summary>
public void Render(ResponseRenderingTarget target, object model)
{
Context.Response.ContentType = ContentType;
base.Render(target, model);
}
/// <summary>
/// Renders template by generating content into WorkContext
/// </summary>
public void Render(WorkContext work, object model)
{
this.BindGlobalContexts(work);
Render(new ResponseRenderingTarget(work), model);
}
/// <summary>
/// Renders template to string
/// </summary>
public string RenderToString(bool encodeHtml = true, object model = null)
{
var target = new NFX.Templatization.StringRenderingTarget(encodeHtml);
base.Render(target, model);
return target.Value;
}
/// <summary>
/// Renders template to string in a WorkContext
/// </summary>
public string RenderToString(WorkContext work, bool encodeHtml = true, object model = null)
{
this.BindGlobalContexts(work);
var target = new NFX.Templatization.StringRenderingTarget(encodeHtml);
base.Render(target, model);
return target.Value;
}
protected override bool DoPostRender(Exception error)
{
if (error==null) return false;
throw new WaveTemplateRenderingException("{0}.DoPostRender: {1}".Args(GetType().FullName, error.ToMessageWithType()), error);
}
}
/// <summary>
/// Wave template that is scoped to a TModel type for Model (Rendering Context)
/// </summary>
public class WaveTemplate<TModel> : WaveTemplate
{
public WaveTemplate() : base()
{
}
public WaveTemplate(WorkContext context) : base (context)
{
}
/// <summary>
/// Shortcut to TemplateRenderingContext which is set per call to Render(TModel)
/// </summary>
public TModel Model { get { return (TModel)RenderingContext;}}
/// <summary>
/// Renders template by generating content into ResponseRenderingTarget
/// </summary>
/// <param name="target">A ResponseRenderingTarget target to render output into</param>
/// <param name="model">A model object for this rendering call</param>
public void Render(ResponseRenderingTarget target, TModel model)
{
base.Render(target, model);
}
/// <summary>
/// Renders template by generating content into WorkContext
/// </summary>
public void Render(WorkContext work, TModel model)
{
Render(new ResponseRenderingTarget(work), model);
}
}
}
| 30.371134 | 135 | 0.604718 | [
"Apache-2.0"
] | agnicore/nfx | src/NFX.Wave/Templatization/WaveTemplate.cs | 5,892 | 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.
namespace Contoso.GameNetCore.Proto
{
public class GameSocketAcceptContext
{
public virtual string SubProtocol { get; set; }
}
} | 32.5 | 112 | 0.707692 | [
"Apache-2.0"
] | bclnet/GameNetCore | src/Proto/Proto.Features/src/WebSocketAcceptContext.cs | 325 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace HelpingHands.Data.Migrations
{
public partial class addedstatustopurchaseorder : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Status",
table: "PurchaseOrder",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Status",
table: "PurchaseOrder");
}
}
}
| 26.913043 | 71 | 0.594507 | [
"MIT"
] | tmoodley/crispans | content/Data/Migrations/20200410190834_added status to purchase order.cs | 621 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.EntityFrameworkCore.Sqlite.Internal;
namespace Microsoft.EntityFrameworkCore.Query;
public class ComplexNavigationsQuerySqliteTest : ComplexNavigationsQueryRelationalTestBase<ComplexNavigationsQuerySqliteFixture>
{
public ComplexNavigationsQuerySqliteTest(ComplexNavigationsQuerySqliteFixture fixture)
: base(fixture)
{
}
public override async Task Let_let_contains_from_outer_let(bool async)
=> Assert.Equal(
SqliteStrings.ApplyNotSupported,
(await Assert.ThrowsAsync<InvalidOperationException>(
() => base.Let_let_contains_from_outer_let(async))).Message);
public override async Task Prune_does_not_throw_null_ref(bool async)
=> Assert.Equal(
SqliteStrings.ApplyNotSupported,
(await Assert.ThrowsAsync<InvalidOperationException>(
() => base.Prune_does_not_throw_null_ref(async))).Message);
public override async Task Join_with_result_selector_returning_queryable_throws_validation_error(bool async)
=> Assert.Equal(
SqliteStrings.ApplyNotSupported,
(await Assert.ThrowsAsync<InvalidOperationException>(
() => base.Join_with_result_selector_returning_queryable_throws_validation_error(async))).Message);
public override async Task Nested_SelectMany_correlated_with_join_table_correctly_translated_to_apply(bool async)
=> Assert.Equal(
SqliteStrings.ApplyNotSupported,
(await Assert.ThrowsAsync<InvalidOperationException>(
() => base.Nested_SelectMany_correlated_with_join_table_correctly_translated_to_apply(async))).Message);
public override Task GroupJoin_client_method_in_OrderBy(bool async)
=> AssertTranslationFailedWithDetails(
() => base.GroupJoin_client_method_in_OrderBy(async),
CoreStrings.QueryUnableToTranslateMethod(
"Microsoft.EntityFrameworkCore.Query.ComplexNavigationsQueryTestBase<Microsoft.EntityFrameworkCore.Query.ComplexNavigationsQuerySqliteFixture>",
"ClientMethodNullableInt"));
}
| 49.217391 | 160 | 0.746908 | [
"MIT"
] | Applesauce314/efcore | test/EFCore.Sqlite.FunctionalTests/Query/ComplexNavigationsQuerySqliteTest.cs | 2,264 | C# |
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
/// <summary>
/// Creates and maintains a command buffer to set up the textures used in the glowing object image effect.
/// </summary>
public class GlowController : MonoBehaviour
{
private static GlowController _instance;
private CommandBuffer _commandBuffer;
private List<IGlow> _glowableObjects = new List<IGlow>();
private Material _glowMat;
private Material _blurMaterial;
private Vector2 _blurTexelSize;
private int _prePassRenderTexID;
private int _blurPassRenderTexID;
private int _tempRenderTexID;
private int _blurSizeID;
private int _glowColorID;
/// <summary>
/// On Awake, we cache various values and setup our command buffer to be called Before Image Effects.
/// </summary>
private void Awake()
{
_instance = this;
_glowMat = new Material(Shader.Find("Hidden/GlowCmdShader"));
_blurMaterial = new Material(Shader.Find("Hidden/Blur"));
_prePassRenderTexID = Shader.PropertyToID("_GlowPrePassTex");
_blurPassRenderTexID = Shader.PropertyToID("_GlowBlurredTex");
_tempRenderTexID = Shader.PropertyToID("_TempTex0");
_blurSizeID = Shader.PropertyToID("_BlurSize");
_glowColorID = Shader.PropertyToID("_GlowColor");
_commandBuffer = new CommandBuffer();
_commandBuffer.name = "Glowing Objects Buffer"; // This name is visible in the Frame Debugger, so make it a descriptive!
GetComponent<Camera>().AddCommandBuffer(CameraEvent.BeforeImageEffects, _commandBuffer);
}
public static void RegisterObject(IGlow glowObj)
{
if (_instance != null)
{
_instance._glowableObjects.Add(glowObj);
_instance.RebuildCommandBuffer();
}
}
public static void DeregisterObject(IGlow glowObj)
{
if (_instance != null)
{
_instance._glowableObjects.Remove(glowObj);
_instance.RebuildCommandBuffer();
}
}
/// <summary>
/// Adds all the commands, in order, we want our command buffer to execute.
/// Similar to calling sequential rendering methods insde of OnRenderImage().
/// </summary>
private void RebuildCommandBuffer()
{
_commandBuffer.Clear();
_commandBuffer.GetTemporaryRT(_prePassRenderTexID, Screen.width, Screen.height, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default, QualitySettings.antiAliasing);
_commandBuffer.SetRenderTarget(_prePassRenderTexID);
_commandBuffer.ClearRenderTarget(true, true, Color.clear);
// print(string.Format("glowable obj count: {0}", _glowableObjects.Count));
for (int i = 0; i < _glowableObjects.Count; i++)
{
_commandBuffer.SetGlobalColor(_glowColorID, _glowableObjects[i].GlowColor);
for (int j = 0; j < _glowableObjects[i].Renderers.Length; j++)
{
// print(string.Format("{0} length: {1}", _glowableObjects[i].name, _glowableObjects[i].Renderers.Length));
_commandBuffer.DrawRenderer(_glowableObjects[i].Renderers[j], _glowMat);
}
}
_commandBuffer.GetTemporaryRT(_blurPassRenderTexID, Screen.width >> 1, Screen.height >> 1, 0, FilterMode.Bilinear);
_commandBuffer.GetTemporaryRT(_tempRenderTexID, Screen.width >> 1, Screen.height >> 1, 0, FilterMode.Bilinear);
_commandBuffer.Blit(_prePassRenderTexID, _blurPassRenderTexID);
_blurTexelSize = new Vector2(1.5f / (Screen.width >> 1), 1.5f / (Screen.height >> 1));
_commandBuffer.SetGlobalVector(_blurSizeID, _blurTexelSize);
for (int i = 0; i < 4; i++)
{
_commandBuffer.Blit(_blurPassRenderTexID, _tempRenderTexID, _blurMaterial, 0);
_commandBuffer.Blit(_tempRenderTexID, _blurPassRenderTexID, _blurMaterial, 1);
}
}
}
| 34.921569 | 196 | 0.754913 | [
"Apache-2.0"
] | DavidMann10k/Marionette | Assets/_third_party/Outline/GlowController.cs | 3,564 | 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 AWSMigrationHub-2017-05-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MigrationHub.Model
{
/// <summary>
/// This is the response object from the NotifyApplicationState operation.
/// </summary>
public partial class NotifyApplicationStateResponse : AmazonWebServiceResponse
{
}
} | 30.594595 | 113 | 0.739399 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/MigrationHub/Generated/Model/NotifyApplicationStateResponse.cs | 1,132 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
using static Helpers;
/// <summary>
/// Analyzer that looks for several variants of code like `s.Slice(start, end - start)` and
/// offers to update to `s[start..end]` or `s.Slice(start..end)`. In order to convert to the
/// indexer, the type being called on needs a slice-like method that takes two ints, and returns
/// an instance of the same type. It also needs a Length/Count property, as well as an indexer
/// that takes a System.Range instance. In order to convert between methods, there need to be
/// two overloads that are equivalent except that one takes two ints, and the other takes a
/// System.Range.
///
/// It is assumed that if the type follows this shape that it is well behaved and that this
/// transformation will preserve semantics. If this assumption is not good in practice, we
/// could always limit the feature to only work on a whitelist of known safe types.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp), Shared]
internal partial class CSharpUseRangeOperatorDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
// public const string UseIndexer = nameof(UseIndexer);
public const string ComputedRange = nameof(ComputedRange);
public const string ConstantRange = nameof(ConstantRange);
public CSharpUseRangeOperatorDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseRangeOperatorDiagnosticId,
CSharpCodeStyleOptions.PreferRangeOperator,
LanguageNames.CSharp,
new LocalizableResourceString(nameof(FeaturesResources.Use_range_operator), FeaturesResources.ResourceManager, typeof(FeaturesResources)),
new LocalizableResourceString(nameof(FeaturesResources._0_can_be_simplified), FeaturesResources.ResourceManager, typeof(FeaturesResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(compilationContext =>
{
// We're going to be checking every invocation in the compilation. Cache information
// we compute in this object so we don't have to continually recompute it.
var infoCache = new InfoCache(compilationContext.Compilation);
// The System.Range type is always required to offer this fix.
if (infoCache.RangeType != null)
{
compilationContext.RegisterOperationAction(
c => AnalyzeInvocation(c, infoCache),
OperationKind.Invocation);
}
});
}
private void AnalyzeInvocation(
OperationAnalysisContext context, InfoCache infoCache)
{
var resultOpt = AnalyzeInvocation(
(IInvocationOperation)context.Operation, infoCache, context.Options, context.CancellationToken);
if (resultOpt == null)
{
return;
}
context.ReportDiagnostic(CreateDiagnostic(resultOpt.Value));
}
public static Result? AnalyzeInvocation(
IInvocationOperation invocation, InfoCache infoCache,
AnalyzerOptions analyzerOptionsOpt, CancellationToken cancellationToken)
{
// Validate we're on a piece of syntax we expect. While not necessary for analysis, we
// want to make sure we're on something the fixer will know how to actually fix.
if (!(invocation.Syntax is InvocationExpressionSyntax invocationSyntax) ||
invocationSyntax.ArgumentList is null)
{
return default;
}
CodeStyleOption<bool> option = null;
if (analyzerOptionsOpt != null)
{
// Check if we're at least on C# 8, and that the user wants these operators.
var syntaxTree = invocationSyntax.SyntaxTree;
var parseOptions = (CSharpParseOptions)syntaxTree.Options;
if (parseOptions.LanguageVersion < LanguageVersion.CSharp8)
{
return default;
}
option = analyzerOptionsOpt.GetOption(CSharpCodeStyleOptions.PreferRangeOperator, syntaxTree, cancellationToken);
if (!option.Value)
{
return default;
}
}
// look for `s.Slice(e1, end - e2)`
if (invocation.Instance is null ||
invocation.Arguments.Length != 2)
{
return default;
}
// See if the call is to something slice-like.
var targetMethod = invocation.TargetMethod;
// Second arg needs to be a subtraction for: `end - e2`. Once we've seen that we have
// that, try to see if we're calling into some sort of Slice method with a matching
// indexer or overload
if (!IsSubtraction(invocation.Arguments[1].Value, out var subtraction) ||
!infoCache.TryGetMemberInfo(targetMethod, out var memberInfo))
{
return default;
}
// See if we have: (start, end - start). Specifically where the start operation it the
// same as the right side of the subtraction.
var startOperation = invocation.Arguments[0].Value;
if (CSharpSyntaxFacts.Instance.AreEquivalent(startOperation.Syntax, subtraction.RightOperand.Syntax))
{
return new Result(
ResultKind.Computed, option,
invocation, invocationSyntax,
targetMethod, memberInfo,
startOperation, subtraction.LeftOperand);
}
// See if we have: (constant1, s.Length - constant2). The constants don't have to be
// the same value. This will convert over to s[constant1..(constant - constant1)]
if (IsConstantInt32(startOperation) &&
IsConstantInt32(subtraction.RightOperand) &&
IsInstanceLengthCheck(memberInfo.LengthLikeProperty, invocation.Instance, subtraction.LeftOperand))
{
return new Result(
ResultKind.Constant, option,
invocation, invocationSyntax,
targetMethod, memberInfo,
startOperation, subtraction.RightOperand);
}
return default;
}
private Diagnostic CreateDiagnostic(Result result)
{
// Keep track of the invocation node
var invocation = result.Invocation;
var additionalLocations = ImmutableArray.Create(
invocation.GetLocation());
// Mark the span under the two arguments to .Slice(..., ...) as what we will be
// updating.
var arguments = invocation.ArgumentList.Arguments;
var location = Location.Create(invocation.SyntaxTree,
TextSpan.FromBounds(arguments.First().SpanStart, arguments.Last().Span.End));
return DiagnosticHelper.Create(
Descriptor,
location,
result.Option.Notification.Severity,
additionalLocations,
ImmutableDictionary<string, string>.Empty,
result.SliceLikeMethod.Name);
}
private static bool IsConstantInt32(IOperation operation)
=> operation.ConstantValue.HasValue && operation.ConstantValue.Value is int;
}
}
| 45.411765 | 159 | 0.628474 | [
"Apache-2.0"
] | HenrikWM/roslyn | src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs | 8,494 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.1
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NetOffice.DeveloperToolbox.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 42.185185 | 152 | 0.584723 | [
"MIT"
] | NetOffice/NetOffice | Toolbox/Toolbox/Properties/Settings.Designer.cs | 1,143 | C# |
using ColossalFramework.UI;
using ServiceRestrictions.Compatibility;
using ServiceRestrictions.GUI.Districts;
using ServiceRestrictions.Internal;
using UnityEngine;
namespace ServiceRestrictions.GUI
{
public class UiTitleBar : UIPanel
{
public static UiTitleBar Instance;
private UIButton _closeButton;
private UILabel _titleLabel;
public UIDragHandle DragHandle;
public override void Start()
{
base.Start();
Instance = this;
SetupControls();
}
private void SetupControls()
{
name = "ServiceRestrictionTitlebar";
isVisible = false;
canFocus = true;
isInteractive = true;
relativePosition = Vector3.zero;
width = parent.width;
height = 40f;
DragHandle = AddUIComponent<UIDragHandle>();
DragHandle.height = height;
DragHandle.relativePosition = Vector3.zero;
DragHandle.target = parent;
DragHandle.eventMouseUp += (c, e) =>
{
ServiceRestrictionsMod.Settings.PanelX = parent.relativePosition.x;
ServiceRestrictionsMod.Settings.PanelY = parent.relativePosition.y;
ServiceRestrictionsMod.Settings.Save();
};
_titleLabel = AddUIComponent<UILabel>();
_titleLabel.text =
$"{CustomizeItExtendedCompatibility.RetrieveBuildingName()} Restrictions";
_titleLabel.textScale = 0.9f;
_titleLabel.isInteractive = false;
_closeButton = AddUIComponent<UIButton>();
_closeButton.size = new Vector2(20, 20);
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_closeButton.normalBgSprite = "DeleteLineButton";
_closeButton.hoveredBgSprite = "DeleteLineButtonHovered";
_closeButton.pressedBgSprite = "DeleteLineButtonPressed";
_closeButton.eventClick += (component, param) =>
{
if (RestrictedDistrictsPanel.Instance.CampusPanelWrapper != null)
{
RestrictedDistrictsPanel.Instance.CampusPanelWrapper.isVisible = false;
UIUtils.DeepDestroy(RestrictedDistrictsPanel.Instance.CampusPanelWrapper);
}
if (RestrictedDistrictsPanel.Instance.IndustriesPanelWrapper != null)
{
RestrictedDistrictsPanel.Instance.IndustriesPanelWrapper.isVisible = false;
UIUtils.DeepDestroy(RestrictedDistrictsPanel.Instance.IndustriesPanelWrapper);
}
if (RestrictedDistrictsPanel.Instance.ParkPanelWrapper != null)
{
RestrictedDistrictsPanel.Instance.ParkPanelWrapper.isVisible = false;
UIUtils.DeepDestroy(RestrictedDistrictsPanel.Instance.ParkPanelWrapper);
}
ServiceRestrictTool.instance.RestrictedDistrictsPanelWrapper.isVisible = false;
UIUtils.DeepDestroy(ServiceRestrictTool.instance.RestrictedDistrictsPanelWrapper);
};
}
public void RecenterElements()
{
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_titleLabel.relativePosition =
new Vector3((width - _titleLabel.width) / 2f, (height - _titleLabel.height) / 2);
}
}
public class UiIndustriesTitleBar : UIPanel
{
public static UiIndustriesTitleBar Instance;
private UIButton _closeButton;
private UILabel _titleLabel;
public UIDragHandle DragHandle;
public override void Start()
{
base.Start();
Instance = this;
SetupControls();
}
private void SetupControls()
{
name = "ServiceRestrictionIndustriesTitlebar";
isVisible = false;
canFocus = true;
isInteractive = true;
relativePosition = Vector3.zero;
width = parent.width;
height = 40f;
DragHandle = AddUIComponent<UIDragHandle>();
DragHandle.height = height;
DragHandle.relativePosition = Vector3.zero;
DragHandle.target = parent;
_titleLabel = AddUIComponent<UILabel>();
_titleLabel.text = "Industry Restrictions";
_titleLabel.textScale = 0.9f;
_titleLabel.isInteractive = false;
_closeButton = AddUIComponent<UIButton>();
_closeButton.size = new Vector2(20, 20);
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_closeButton.normalBgSprite = "DeleteLineButton";
_closeButton.hoveredBgSprite = "DeleteLineButtonHovered";
_closeButton.pressedBgSprite = "DeleteLineButtonPressed";
_closeButton.eventClick += (component, param) =>
{
RestrictedDistrictsPanel.Instance.IndustriesPanelWrapper.isVisible = false;
UIUtils.DeepDestroy(RestrictedDistrictsPanel.Instance.IndustriesPanelWrapper);
};
}
public void RecenterElements()
{
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_titleLabel.relativePosition =
new Vector3((width - _titleLabel.width) / 2f, (height - _titleLabel.height) / 2);
}
}
public class UiTitleParksBar : UIPanel
{
public static UiTitleParksBar Instance;
private UIButton _closeButton;
private UILabel _titleLabel;
public UIDragHandle DragHandle;
public override void Start()
{
base.Start();
Instance = this;
SetupControls();
}
private void SetupControls()
{
name = "ServiceRestrictionParksTitlebar";
isVisible = false;
canFocus = true;
isInteractive = true;
relativePosition = Vector3.zero;
width = parent.width;
height = 40f;
DragHandle = AddUIComponent<UIDragHandle>();
DragHandle.height = height;
DragHandle.relativePosition = Vector3.zero;
DragHandle.target = parent;
_titleLabel = AddUIComponent<UILabel>();
_titleLabel.text = "Park Restrictions";
_titleLabel.textScale = 0.9f;
_titleLabel.isInteractive = false;
_closeButton = AddUIComponent<UIButton>();
_closeButton.size = new Vector2(20, 20);
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_closeButton.normalBgSprite = "DeleteLineButton";
_closeButton.hoveredBgSprite = "DeleteLineButtonHovered";
_closeButton.pressedBgSprite = "DeleteLineButtonPressed";
_closeButton.eventClick += (component, param) =>
{
RestrictedDistrictsPanel.Instance.ParkPanelWrapper.isVisible = false;
UIUtils.DeepDestroy(RestrictedDistrictsPanel.Instance.ParkPanelWrapper);
};
}
public void RecenterElements()
{
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_titleLabel.relativePosition =
new Vector3((width - _titleLabel.width) / 2f, (height - _titleLabel.height) / 2);
}
}
public class UiCampusTitleBar : UIPanel
{
public static UiCampusTitleBar Instance;
private UIButton _closeButton;
private UILabel _titleLabel;
public UIDragHandle DragHandle;
public override void Start()
{
base.Start();
Instance = this;
SetupControls();
}
private void SetupControls()
{
name = "ServiceRestrictionTitlebar";
isVisible = false;
canFocus = true;
isInteractive = true;
relativePosition = Vector3.zero;
width = parent.width;
height = 40f;
DragHandle = AddUIComponent<UIDragHandle>();
DragHandle.height = height;
DragHandle.relativePosition = Vector3.zero;
DragHandle.target = parent;
_titleLabel = AddUIComponent<UILabel>();
_titleLabel.text = "Campus Restrictions";
_titleLabel.textScale = 0.9f;
_titleLabel.isInteractive = false;
_closeButton = AddUIComponent<UIButton>();
_closeButton.size = new Vector2(20, 20);
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_closeButton.normalBgSprite = "DeleteLineButton";
_closeButton.hoveredBgSprite = "DeleteLineButtonHovered";
_closeButton.pressedBgSprite = "DeleteLineButtonPressed";
_closeButton.eventClick += (component, param) =>
{
RestrictedDistrictsPanel.Instance.CampusPanelWrapper.isVisible = false;
UIUtils.DeepDestroy(RestrictedDistrictsPanel.Instance.CampusPanelWrapper);
};
}
public void RecenterElements()
{
_closeButton.relativePosition = new Vector3(width - _closeButton.width - 10f, 10f);
_titleLabel.relativePosition =
new Vector3((width - _titleLabel.width) / 2f, (height - _titleLabel.height) / 2);
}
}
} | 38.189723 | 98 | 0.602463 | [
"MIT"
] | Celisuis/ServiceRestricter | ServiceRestrictions/GUI/UITitlebar.cs | 9,664 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace Qwiq.Exceptions
{
[DebuggerStepThrough]
internal class InnerExceptionExploder : IExceptionExploder
{
private static readonly ReadOnlyCollection<Exception> Empty = new ReadOnlyCollection<Exception>(new List<Exception>());
public ReadOnlyCollection<Exception> Explode(Exception exception)
{
if (exception?.InnerException == null) return Empty;
// REVIEW: Reference type object allocation is extraneous
var l = new List<Exception>(1)
{
exception.InnerException
};
return l.AsReadOnly();
}
}
} | 30 | 127 | 0.66 | [
"MIT"
] | rjmurillo/Qwiq | src/Qwiq.Core/Exceptions/InnerExceptionExploder.cs | 750 | C# |
namespace MegaBuild
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Menees;
#endregion
[StepDisplay(nameof(MegaBuild), "Opens and builds another MegaBuild project.", "Images.MegaBuildStep.ico")]
[MayRequireAdministrator]
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Called by Reflection.")]
internal sealed class MegaBuildStep : ExecutableStep
{
#region Private Data Members
private bool exit;
private bool minimize;
private bool inProc = true;
private string projectFile = string.Empty;
#endregion
#region Constructors
public MegaBuildStep(Project project, StepCategory category, StepTypeInfo info)
: base(project, category, info)
{
}
#endregion
#region Public Properties
public bool Exit
{
get => this.exit;
set => this.SetValue(ref this.exit, value);
}
public bool InProc
{
get => this.inProc;
set => this.SetValue(ref this.inProc, value);
}
public bool Minimize
{
get => this.minimize;
set => this.SetValue(ref this.minimize, value);
}
public string ProjectFile
{
get => this.projectFile;
set => this.SetValue(ref this.projectFile, value);
}
public override string StepInformation
{
get
{
StringBuilder sb = new();
sb.Append(Path.GetFileName(this.ProjectFile));
if (!this.InProc)
{
sb.Append(", Out-Of-Process");
if (this.Minimize)
{
sb.Append(", Minimize");
}
if (this.Exit)
{
sb.Append(", Exit");
}
}
return sb.ToString();
}
}
#endregion
#region Public Methods
public override bool Execute(StepExecuteArgs args) => this.InProc ? this.ExecuteInProc(args) : this.ExecuteOutOfProc();
public override void ExecuteCustomVerb(string verb)
{
string project = Manager.ExpandVariables(this.ProjectFile);
string quotedProject = TextUtility.EnsureQuotes(project);
switch (verb)
{
case "Open Project":
this.Project.Open(project);
break;
case "Open Project In New Instance":
Process.Start(Application.ExecutablePath, quotedProject);
break;
case "Build Project In New Instance":
Process.Start(Application.ExecutablePath, quotedProject + " /Build");
break;
}
}
public override string[] GetCustomVerbs() => new[] { "Open Project", "Open Project In New Instance", "Build Project In New Instance" };
[SuppressMessage("Usage", "CC0022:Should dispose object", Justification = "Caller disposes new controls.")]
public override void GetStepEditorControls(ICollection<StepEditorControl> controls)
{
base.GetStepEditorControls(controls);
controls.Add(new MegaBuildStepCtrl { Step = this });
}
#endregion
#region Protected Methods
protected internal override void Load(XmlKey key)
{
base.Load(key);
this.ProjectFile = key.GetValue(nameof(this.ProjectFile), this.ProjectFile);
this.Exit = key.GetValue(nameof(this.Exit), this.Exit);
this.Minimize = key.GetValue(nameof(this.Minimize), this.Minimize);
// We have to default InProc to false to keep the same
// behavior for old, loaded steps. (However, it will default
// to true for added/inserted steps.)
this.InProc = key.GetValue(nameof(this.InProc), false);
}
protected internal override void Save(XmlKey key)
{
base.Save(key);
key.SetValue(nameof(this.ProjectFile), this.ProjectFile);
key.SetValue(nameof(this.Exit), this.Exit);
key.SetValue(nameof(this.Minimize), this.Minimize);
key.SetValue(nameof(this.InProc), this.InProc);
}
#endregion
#region Private Methods
private bool ExecuteInProc(StepExecuteArgs args)
{
bool result = false;
using (Project subProject = new(this.Level + 2))
{
// Let the sub-project use the same form, so it can properly
// synchronize messages with the GUI thread.
subProject.Form = this.Project.Form;
string projectFileName = Manager.ExpandVariables(this.ProjectFile);
if (subProject.Open(projectFileName))
{
Step[] steps = new Step[subProject.BuildSteps.Count];
subProject.BuildSteps.CopyTo(steps);
// We have to auto-confirm any confirmable steps to prevent a modal dialog from popping up
// during the build. If they really don't want the confirmable steps to build, then they'll
// need to turn them off (i.e., disable them) in the project.
subProject.Build(steps, BuildOptions.AutoConfirmSteps, args);
while (subProject.Building)
{
// Check the outer project to see if the main build has been stopped/canceled.
// If so, then we need to stop/cancel the inner project too.
if (this.StopBuilding)
{
subProject.StopBuild();
}
Thread.Sleep(TimeSpan.FromSeconds(1));
}
result = subProject.BuildStatus != BuildStatus.Failed;
}
}
return result;
}
private bool ExecuteOutOfProc()
{
StringBuilder sb = new();
sb.Append("/build ");
if (this.Exit)
{
sb.Append("/exit ");
}
sb.Append(TextUtility.EnsureQuotes(this.ProjectFile));
string args = sb.ToString();
// Note: When you're running in the debugger this will NOT minimize the child process. But it does work outside the debugger.
ProcessWindowStyle windowStyle = this.Minimize ? ProcessWindowStyle.Minimized : ProcessWindowStyle.Normal;
ExecuteCommandArgs cmdArgs = new()
{
FileName = Application.ExecutablePath,
Arguments = args,
WindowStyle = windowStyle,
UseShellExecute = true,
};
bool result = this.ExecuteCommand(cmdArgs);
if (this.WaitForCompletion)
{
string message = string.Format(
"Build of MegaBuild project '{0}' {1}.",
Path.GetFileName(this.ProjectFile),
cmdArgs.ExitCode == 0 ? "succeeded" : "failed");
if (cmdArgs.ExitCode == 0)
{
this.Project.OutputLine(message);
}
else
{
this.Project.OutputLine(message, OutputColors.Error, 0, true);
}
}
else
{
this.Project.OutputLine("A new MegaBuild process step was launched asynchronously.");
}
return result;
}
#endregion
}
} | 25.393574 | 137 | 0.687332 | [
"MIT"
] | bmenees/MegaBuild | src/MegaBuildSdk/Classes/MegaBuildStep.cs | 6,323 | C# |
using System;
namespace Szark
{
/// <summary>
/// A struct containing RGBA information.
/// </summary>
public struct Color
{
public byte red, green, blue, alpha;
/// <summary>
/// The Constructor for a color in RGBA form.
/// Alpha is not required and will just render
/// completely opaque.
/// </summary>
/// <param name="red">Red</param>
/// <param name="green">Green</param>
/// <param name="blue">Blue</param>
/// <param name="alpha">Alpha</param>
public Color(byte red, byte green, byte blue, byte alpha = 255)
{
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
}
#region Constants
// Greyscale Colors
public static Color BLANK = new Color(0, 0, 0, 0);
public static Color WHITE = new Color(255, 255, 255);
public static Color GREY = new Color(192, 192, 192);
public static Color BLACK = new Color(0, 0, 0);
public static Color DARK_GREY = new Color(128, 128, 128);
public static Color VERY_DARK_GREY = new Color(64, 64, 64);
// RGB Colors
public static Color RED = new Color(255, 0, 0);
public static Color GREEN = new Color(0, 255, 0);
public static Color BLUE = new Color(0, 0, 255);
public static Color DARK_RED = new Color(128, 0, 0);
public static Color DARK_GREEN = new Color(0, 128, 0);
public static Color DARK_BLUE = new Color(0, 0, 128);
public static Color VERY_DARK_RED = new Color(64, 0, 0);
public static Color VERY_DARK_GREEN = new Color(0, 64, 0);
public static Color VERY_DARK_BLUE = new Color(0, 0, 64);
// CYM Colors
public static Color YELLOW = new Color(255, 255, 0);
public static Color MAGENTA = new Color(255, 0, 255);
public static Color CYAN = new Color(0, 255, 255);
public static Color DARK_YELLOW = new Color(128, 128, 0);
public static Color DARK_MAGENTA = new Color(128, 0, 128);
public static Color DARK_CYAN = new Color(0, 128, 128);
public static Color VERY_DARK_YELLOW = new Color(64, 64, 0);
public static Color VERY_DARK_MAGENTA = new Color(64, 0, 64);
public static Color VERY_DARK_CYAN = new Color(0, 64, 64);
#endregion
/// <summary>
/// Interpolates two colors
/// </summary>
/// <param name="first">First Color</param>
/// <param name="second">Second Color</param>
/// <param name="value">Mix Value (0-1)</param>
/// <returns>The Blended Color</returns>
public static Color Lerp(Color first, Color second, float value)
{
var red = (byte)((1 - value) * first.red + value * second.red);
var green = (byte)((1 - value) * first.green + value * second.green);
var blue = (byte)((1 - value) * first.blue + value * second.blue);
var alpha = (byte)((1 - value) * first.alpha + value * second.alpha);
return new Color(red, green, blue, alpha);
}
/// <summary>
/// Compares this color to another
/// </summary>
/// <returns>If both colors are the same</returns>
public bool Compare(Color other) =>
other.red == red && other.green == green &&
other.blue == blue && other.alpha == alpha;
/// <summary>
/// Creates a instance of Color from HSV color
/// </summary>
/// <param name="h">Hue</param>
/// <param name="S">Saturation</param>
/// <param name="V">Value</param>
/// <param name="alpha">Alpha</param>
/// <returns></returns>
public static Color FromHSV(double h, double S, double V, byte alpha = 255)
{
double H = h;
double R, G, B;
while (H < 0) { H += 360; };
while (H >= 360) { H -= 360; };
if (V <= 0) { R = G = B = 0; }
else if (S <= 0) { R = G = B = V; }
else
{
double hf = H / 60.0;
int i = (int)Math.Floor(hf);
double f = hf - i;
double pv = V * (1 - S);
double qv = V * (1 - S * f);
double tv = V * (1 - S * (1 - f));
switch (i)
{
case 0: R = V; G = tv; B = pv; break;
case 1: R = qv; G = V; B = pv; break;
case 2: R = pv; G = V; B = tv; break;
case 3: R = pv; G = qv; B = V; break;
case 4: R = tv; G = pv; B = V; break;
case 5: R = V; G = pv; B = qv; break;
case 6: R = V; G = tv; B = pv; break;
case -1: R = V; G = pv; B = qv; break;
default: R = G = B = V; break;
}
}
return new Color(
Clamp((byte)(R * 255.0)),
Clamp((byte)(G * 255.0)),
Clamp((byte)(B * 255.0)),
alpha);
}
private static byte Clamp(byte i)
{
if (i < 0) return 0;
if (i > 255) return 255;
return i;
}
// -- Operators --
public static Color operator +(Color f, Color p) =>
new Color((byte)(f.red + p.red), (byte)(f.green + p.green),
(byte)(f.blue + p.blue), (byte)(f.alpha + p.alpha));
public static Color operator -(Color f, Color p) =>
new Color((byte)(f.red - p.red), (byte)(f.green - p.green),
(byte)(f.blue - p.blue), (byte)(f.alpha - p.alpha));
public static Color operator *(Color f, float t) =>
new Color((byte)(f.red * t), (byte)(f.green * t),
(byte)(f.blue * t), (byte)(f.alpha * t));
}
} | 36.432927 | 83 | 0.487364 | [
"MIT"
] | TheOnlyMarv/SzarkEngine | Engine/Color.cs | 5,975 | C# |
using System.Runtime.CompilerServices;
using BepuPhysics;
using BepuUtilities;
namespace Demos.Port
{
public class CustomPositionLastTimestepper : ITimestepper
{
/// <summary>
/// Fires after the sleeper completes and before bodies are integrated.
/// </summary>
public event TimestepperStageHandler Slept;
/// <summary>
/// Fires after bodies have had their velocities and bounding boxes updated, but before collision detection begins.
/// </summary>
public event TimestepperStageHandler BeforeCollisionDetection;
/// <summary>
/// Fires after all collisions have been identified, but before constraints are solved.
/// </summary>
public event TimestepperStageHandler CollisionsDetected;
/// <summary>
/// Fires after the solver executes and before body poses are integrated.
/// </summary>
public event TimestepperStageHandler ConstraintsSolved;
/// <summary>
/// Fires after bodies have their poses integrated and before data structures are incrementally optimized.
/// </summary>
public event TimestepperStageHandler PosesIntegrated;
public void Timestep(Simulation simulation, float dt, IThreadDispatcher threadDispatcher = null)
{
simulation.Sleep(threadDispatcher);
Slept?.Invoke(dt, threadDispatcher);
simulation.IntegrateVelocitiesBoundsAndInertias(dt, threadDispatcher);
BeforeCollisionDetection?.Invoke(dt, threadDispatcher);
simulation.CollisionDetection(dt, threadDispatcher);
CollisionsDetected?.Invoke(dt, threadDispatcher);
int count = simulation.Bodies.ActiveSet.Count;
ref var baseConveyorSettings = ref simulation.Bodies.ActiveSet.ConveyorSettings[0];
ref var baseVelocities = ref simulation.Bodies.ActiveSet.Velocities[0];
ref var basePose = ref simulation.Bodies.ActiveSet.Poses[0];
for (int i = 0; i < count; i++)
{
ref var conveyorSettings = ref Unsafe.Add(ref baseConveyorSettings, i);
ref var velocity = ref Unsafe.Add(ref baseVelocities, i);
if (conveyorSettings.IsLinearConveyor)
{
ref var pose = ref Unsafe.Add(ref basePose, i);
var globalVelocity = System.Numerics.Vector3.Transform(conveyorSettings.ConveyorVelocity, pose.Orientation);
velocity.Linear = conveyorSettings.LinearVelocity + globalVelocity;
}
if (conveyorSettings.IsAngularConveyor)
{
velocity.Angular = conveyorSettings.AngularVelocity + conveyorSettings.ConveyorAngularVelocity;
}
}
simulation.Solve(dt, threadDispatcher);
ConstraintsSolved?.Invoke(dt, threadDispatcher);
for (int i = 0; i < count; i++)
{
ref var conveyorSettings = ref Unsafe.Add(ref baseConveyorSettings, i);
ref var velocity = ref Unsafe.Add(ref baseVelocities, i);
if (conveyorSettings.IsLinearConveyor)
{
velocity.Linear = conveyorSettings.LinearVelocity;
}
if (conveyorSettings.IsAngularConveyor)
{
velocity.Angular = conveyorSettings.AngularVelocity;
}
}
simulation.IntegratePoses(dt, threadDispatcher);
PosesIntegrated?.Invoke(dt, threadDispatcher);
simulation.IncrementallyOptimizeDataStructures(threadDispatcher);
}
}
} | 42.044944 | 128 | 0.622929 | [
"Apache-2.0"
] | FEETB24/bepuphysics2 | Demos/Port/CustomPositionLastTimestepper.cs | 3,744 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Network;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Parameters that define the resource to query the troubleshooting
/// result.
/// </summary>
public partial class QueryTroubleshootingParameters
{
/// <summary>
/// Initializes a new instance of the QueryTroubleshootingParameters
/// class.
/// </summary>
public QueryTroubleshootingParameters()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the QueryTroubleshootingParameters
/// class.
/// </summary>
/// <param name="targetResourceId">The target resource ID to query the
/// troubleshooting result.</param>
public QueryTroubleshootingParameters(string targetResourceId)
{
TargetResourceId = targetResourceId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the target resource ID to query the troubleshooting
/// result.
/// </summary>
[JsonProperty(PropertyName = "targetResourceId")]
public string TargetResourceId { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (TargetResourceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "TargetResourceId");
}
}
}
}
| 31.388889 | 96 | 0.613274 | [
"MIT"
] | azure-keyvault/azure-sdk-for-net | src/SDKs/Network/Management.Network/Generated/Models/QueryTroubleshootingParameters.cs | 2,260 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.