content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice;
namespace NetOffice.MSComctlLibApi
{
#region Delegates
#pragma warning disable
#pragma warning restore
#endregion
///<summary>
/// CoClass ListItems
/// SupportByVersion MSComctlLib, 6
///</summary>
[SupportByVersionAttribute("MSComctlLib", 6)]
[EntityTypeAttribute(EntityType.IsCoClass)]
public class ListItems : IListItems
{
#pragma warning disable
#region Fields
private NetRuntimeSystem.Runtime.InteropServices.ComTypes.IConnectionPoint _connectPoint;
private string _activeSinkId;
private NetRuntimeSystem.Type _thisType;
#endregion
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(ListItems);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public ListItems(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public ListItems(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ListItems(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ListItems(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ListItems(COMObject replacedObject) : base(replacedObject)
{
}
///<summary>
///creates a new instance of ListItems
///</summary>
public ListItems():base("MSComctlLib.ListItems")
{
}
///<summary>
///creates a new instance of ListItems
///</summary>
///<param name="progId">registered ProgID</param>
public ListItems(string progId):base(progId)
{
}
#endregion
#region Static CoClass Methods
/// <summary>
/// returns all running MSComctlLib.ListItems objects from the running object table(ROT)
/// </summary>
/// <returns>an MSComctlLib.ListItems array</returns>
public static NetOffice.MSComctlLibApi.ListItems[] GetActiveInstances()
{
NetRuntimeSystem.Collections.Generic.List<object> proxyList = NetOffice.RunningObjectTable.GetActiveProxiesFromROT("MSComctlLib","ListItems");
NetRuntimeSystem.Collections.Generic.List<NetOffice.MSComctlLibApi.ListItems> resultList = new NetRuntimeSystem.Collections.Generic.List<NetOffice.MSComctlLibApi.ListItems>();
foreach(object proxy in proxyList)
resultList.Add( new NetOffice.MSComctlLibApi.ListItems(null, proxy) );
return resultList.ToArray();
}
/// <summary>
/// returns a running MSComctlLib.ListItems object from the running object table(ROT). the method takes the first element from the table
/// </summary>
/// <returns>an MSComctlLib.ListItems object or null</returns>
public static NetOffice.MSComctlLibApi.ListItems GetActiveInstance()
{
object proxy = NetOffice.RunningObjectTable.GetActiveProxyFromROT("MSComctlLib","ListItems", false);
if(null != proxy)
return new NetOffice.MSComctlLibApi.ListItems(null, proxy);
else
return null;
}
/// <summary>
/// returns a running MSComctlLib.ListItems object from the running object table(ROT). the method takes the first element from the table
/// </summary>
/// <param name="throwOnError">throw an exception if no object was found</param>
/// <returns>an MSComctlLib.ListItems object or null</returns>
public static NetOffice.MSComctlLibApi.ListItems GetActiveInstance(bool throwOnError)
{
object proxy = NetOffice.RunningObjectTable.GetActiveProxyFromROT("MSComctlLib","ListItems", throwOnError);
if(null != proxy)
return new NetOffice.MSComctlLibApi.ListItems(null, proxy);
else
return null;
}
#endregion
#region Events
#endregion
#region IEventBinding Member
/// <summary>
/// creates active sink helper
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void CreateEventBridge()
{
if(false == Factory.Settings.EnableEvents)
return;
if (null != _connectPoint)
return;
if (null == _activeSinkId)
_activeSinkId = SinkHelper.GetConnectionPoint(this, ref _connectPoint, null);
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool EventBridgeInitialized
{
get
{
return (null != _connectPoint);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool HasEventRecipients()
{
if(null == _thisType)
_thisType = this.GetType();
foreach (NetRuntimeSystem.Reflection.EventInfo item in _thisType.GetEvents())
{
MulticastDelegate eventDelegate = (MulticastDelegate) _thisType.GetType().GetField(item.Name,
NetRuntimeSystem.Reflection.BindingFlags.NonPublic |
NetRuntimeSystem.Reflection.BindingFlags.Instance).GetValue(this);
if( (null != eventDelegate) && (eventDelegate.GetInvocationList().Length > 0) )
return false;
}
return false;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Delegate[] GetEventRecipients(string eventName)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
return delegates;
}
else
return new Delegate[0];
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int GetCountOfEventRecipients(string eventName)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
return delegates.Length;
}
else
return 0;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int RaiseCustomEvent(string eventName, ref object[] paramsArray)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
foreach (var item in delegates)
{
try
{
item.Method.Invoke(item.Target, paramsArray);
}
catch (NetRuntimeSystem.Exception exception)
{
Factory.Console.WriteException(exception);
}
}
return delegates.Length;
}
else
return 0;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void DisposeEventBridge()
{
_connectPoint = null;
}
#endregion
#pragma warning restore
}
} | 35.027778 | 179 | 0.607653 | [
"MIT"
] | NetOffice/NetOffice | Source/MSComctlLib/Classes/ListItems.cs | 10,088 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.ExcelApi
{
///<summary>
/// Interface IConnectorFormat
/// SupportByVersion Excel, 9,10,11,12,14,15,16
///</summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsInterface)]
public class IConnectorFormat : COMObject
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IConnectorFormat);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IConnectorFormat(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IConnectorFormat(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IConnectorFormat(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IConnectorFormat(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IConnectorFormat(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IConnectorFormat() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IConnectorFormat(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.OfficeApi.Enums.MsoTriState BeginConnected
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BeginConnected", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.OfficeApi.Enums.MsoTriState)intReturnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Shape BeginConnectedShape
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BeginConnectedShape", paramsArray);
NetOffice.ExcelApi.Shape newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Shape.LateBindingApiWrapperType) as NetOffice.ExcelApi.Shape;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 BeginConnectionSite
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BeginConnectionSite", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.OfficeApi.Enums.MsoTriState EndConnected
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "EndConnected", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.OfficeApi.Enums.MsoTriState)intReturnItem;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.ExcelApi.Shape EndConnectedShape
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "EndConnectedShape", paramsArray);
NetOffice.ExcelApi.Shape newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Shape.LateBindingApiWrapperType) as NetOffice.ExcelApi.Shape;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 EndConnectionSite
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "EndConnectionSite", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public NetOffice.OfficeApi.Enums.MsoConnectorType Type
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Type", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.OfficeApi.Enums.MsoConnectorType)intReturnItem;
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Type", paramsArray);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="connectedShape">NetOffice.ExcelApi.Shape ConnectedShape</param>
/// <param name="connectionSite">Int32 ConnectionSite</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 BeginConnect(NetOffice.ExcelApi.Shape connectedShape, Int32 connectionSite)
{
object[] paramsArray = Invoker.ValidateParamsArray(connectedShape, connectionSite);
object returnItem = Invoker.MethodReturn(this, "BeginConnect", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 BeginDisconnect()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "BeginDisconnect", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
/// <param name="connectedShape">NetOffice.ExcelApi.Shape ConnectedShape</param>
/// <param name="connectionSite">Int32 ConnectionSite</param>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 EndConnect(NetOffice.ExcelApi.Shape connectedShape, Int32 connectionSite)
{
object[] paramsArray = Invoker.ValidateParamsArray(connectedShape, connectionSite);
object returnItem = Invoker.MethodReturn(this, "EndConnect", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)]
public Int32 EndDisconnect()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "EndDisconnect", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
#endregion
#pragma warning restore
}
} | 32.422713 | 193 | 0.698385 | [
"MIT"
] | Engineerumair/NetOffice | Source/Excel/Interfaces/IConnectorFormat.cs | 10,280 | C# |
using Fusee.Base.Core;
using Fusee.Engine.Common;
using Fusee.Engine.Core;
using Fusee.Engine.Core.Effects;
using Fusee.Engine.Core.Primitives;
using Fusee.Engine.Core.Scene;
using Fusee.Engine.Core.ShaderShards;
using Fusee.Math.Core;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Fusee.Engine.Gui
{
/// <summary>
/// Used when positioning UI elements. Each entry corresponds to a commonly used anchor point setup.
/// </summary>
public enum AnchorPos
{
/// <summary>
/// Anchors to the lower left corner of the parent element.
/// </summary>
DownDownLeft, //Min = Max = 0,0
/// <summary>
/// Anchors to the lower right corner of the parent element.
/// </summary>
DownDownRight, //Min = Max = 1,0
/// <summary>
/// Anchors to the upper left corner of the parent element.
/// </summary>
TopTopLeft, //Min = Max = 0,1
/// <summary>
/// Anchors to the upper right corner of the parent element.
/// </summary>
TopTopRight, //Min = Max = 1,1
/// <summary>
/// Stretches across all of the parent element.
/// </summary>
StretchAll, //Min = 0, 0 and Max = 1, 1
/// <summary>
/// Stretches horizontally, but keeps its size vertically.
/// </summary>
StretchHorizontal, //Min = 0,0 and Max = 1,0
/// <summary>
/// Stretches vertically, but keeps its size horizontally.
/// </summary>
StretchVertical, //Min = 0,0 and Max = 0,1
/// <summary>
/// Anchors to the middle of the parent element.
/// </summary>
Middle //Min = Max = 0.5, 0.5
}
/// <summary>
/// Contains convenience functions to position a UI element on its parent element.
/// </summary>
public static class GuiElementPosition
{
/// <summary>
/// Sets the anchor position in percent as a <see cref="MinMaxRect"/> depending on its <see cref="AnchorPos"/>
/// </summary>
/// <param name="anchorPos">The anchor point of the UI element.</param>
/// <returns>The <see cref="MinMaxRect"/> containing the anchor position in percent.</returns>
public static MinMaxRect GetAnchors(AnchorPos anchorPos)
{
return anchorPos switch
{
AnchorPos.DownDownLeft => new MinMaxRect()
{
Min = new float2(0, 0),
Max = new float2(0, 0)
},
AnchorPos.DownDownRight => new MinMaxRect()
{
Min = new float2(1, 0),
Max = new float2(1, 0)
},
AnchorPos.TopTopLeft => new MinMaxRect()
{
Min = new float2(0, 1),
Max = new float2(0, 1)
},
AnchorPos.TopTopRight => new MinMaxRect()
{
Min = new float2(1, 1),
Max = new float2(1, 1)
},
AnchorPos.StretchAll => new MinMaxRect()
{
Min = new float2(0, 0),
Max = new float2(1, 1)
},
AnchorPos.StretchHorizontal => new MinMaxRect()
{
Min = new float2(0, 0),
Max = new float2(1, 0)
},
AnchorPos.StretchVertical => new MinMaxRect()
{
Min = new float2(0, 0),
Max = new float2(0, 1)
},
_ => new MinMaxRect()
{
Min = new float2(0.5f, 0.5f),
Max = new float2(0.5f, 0.5f)
},
};
}
/// <summary>
/// Calculates the offset between an element and their parent element and therefore its size.
/// </summary>
/// <param name="anchorPos">The anchor point of the element.</param>
/// <param name="posOnParent">The position on the parent element.</param>
/// <param name="parentHeight">The height of the parent element.</param>
/// <param name="parentWidth">The width of the parent element.</param>
/// <param name="guiElementDim">The dimensions of the element along the x and y axis.</param>
/// <returns></returns>
public static MinMaxRect CalcOffsets(AnchorPos anchorPos, float2 posOnParent, float parentHeight, float parentWidth, float2 guiElementDim)
{
switch (anchorPos)
{
default:
case AnchorPos.Middle:
var middle = new float2(parentWidth / 2f, parentHeight / 2f);
return new MinMaxRect
{
Min = posOnParent - middle,
Max = posOnParent - middle + guiElementDim
};
case AnchorPos.StretchAll:
return new MinMaxRect
{
Min = new float2(posOnParent.x, posOnParent.y),
Max = new float2(-(parentWidth - posOnParent.x - guiElementDim.x), -(parentHeight - posOnParent.y - guiElementDim.y))
};
case AnchorPos.StretchHorizontal:
return new MinMaxRect
{
Min = new float2(posOnParent.x, posOnParent.y),
Max = new float2(-(parentWidth - (posOnParent.x + guiElementDim.x)), posOnParent.y + guiElementDim.y)
};
case AnchorPos.StretchVertical:
return new MinMaxRect
{
Min = new float2(posOnParent.x, posOnParent.y),
Max = new float2(posOnParent.x + guiElementDim.x, -(parentHeight - (posOnParent.y + guiElementDim.y)))
};
case AnchorPos.DownDownLeft:
return new MinMaxRect
{
Min = new float2(posOnParent.x, posOnParent.y),
Max = new float2(posOnParent.x + guiElementDim.x, posOnParent.y + guiElementDim.y)
};
case AnchorPos.DownDownRight:
return new MinMaxRect
{
Min = new float2(-(parentWidth - posOnParent.x), posOnParent.y),
Max = new float2(-(parentWidth - posOnParent.x - guiElementDim.x), posOnParent.y + guiElementDim.y)
};
case AnchorPos.TopTopLeft:
return new MinMaxRect
{
Min = new float2(posOnParent.x, -(parentHeight - posOnParent.y)),
Max = new float2(posOnParent.x + guiElementDim.x, -(parentHeight - guiElementDim.y - posOnParent.y))
};
case AnchorPos.TopTopRight:
return new MinMaxRect
{
Min = new float2(-(parentWidth - posOnParent.x), -(parentHeight - posOnParent.y)),
Max = new float2(-(parentWidth - guiElementDim.x - posOnParent.x), -(parentHeight - guiElementDim.y - posOnParent.y))
};
}
}
}
/// <summary>
/// Building block to create suitable hierarchies for creating a UI canvas.
/// </summary>
public class CanvasNode : SceneNode
{
/// <summary>
/// Creates a SceneNodeContainer with the proper components and children for rendering a canvas.
/// </summary>
/// <param name="name">The name of the canvas.</param>
/// <param name="canvasRenderMode">Choose in which mode you want to render this canvas.</param>
/// <param name="size">The size of the canvas.</param>
/// By default Scale in SCREEN mode is set to 0.1.
public CanvasNode(string name, CanvasRenderMode canvasRenderMode, MinMaxRect size)
{
Name = name;
Components = new List<SceneComponent>
{
new CanvasTransform(canvasRenderMode)
{
Name = name + "_CanvasTransform",
Size = size
},
new XForm
{
Name = name + "_Canvas_XForm"
}
};
}
}
/// <summary>
/// Building block to create suitable hierarchies for using textures in the UI.
/// </summary>
public class TextureNode : SceneNode
{
/// <summary>
/// Creates a SceneNodeContainer with the proper components and children for rendering a nine sliced texture.
/// By default the border thickness is calculated relative to a unit plane. For a thicker border set the border thickness to the desired value, 2 means a twice as thick border.
/// </summary>
/// <param name="name">Name of the SceneNodeContainer.</param>
/// /<param name="tex">Diffuse texture.</param>
/// <param name="anchors">Anchors for the mesh. Influences the scaling of the object if the enclosing canvas is resized.</param>
/// <param name="offsets">Offsets for the mesh. Defines the position of the object relative to its enclosing UI element.</param>
/// <param name="tiles">Defines the tiling of the inner rectangle of the texture. Use float2.one if you do not desire tiling.</param>
/// <param name="borders">Defines the nine tiles of the texture. Order: left, right, top, bottom. Value is measured in percent from the respective edge of texture.</param>
/// <param name="borderThicknessBottom">Border thickness for the bottom border.</param>
/// <param name="borderScaleFactor">Default value is 1. Set this to scale the border thickness if you use canvas render mode SCREEN.</param>
/// <param name="borderThicknessLeft">Border thickness for the left border.</param>
/// <param name="borderThicknessRight">Border thickness for the right border.</param>
/// <param name="borderThicknessTop">Border thickness for the top border.</param>
/// <returns></returns>
public static TextureNode Create(string name, Texture tex, MinMaxRect anchors,
MinMaxRect offsets, float2 tiles, float4 borders, float borderThicknessLeft = 1, float borderThicknessRight = 1, float borderThicknessTop = 1, float borderThicknessBottom = 1, float borderScaleFactor = 1)
{
return CreateAsync(name, tex, anchors, offsets, tiles, borders, borderThicknessLeft, borderThicknessRight, borderThicknessTop, borderThicknessBottom, borderScaleFactor).Result;
}
/// <summary>
/// Creates a SceneNodeContainer with the proper components and children for rendering a nine sliced texture.
/// By default the border thickness is calculated relative to a unit plane. For a thicker border set the border thickness to the desired value, 2 means a twice as thick border.
/// </summary>
/// <param name="name">Name of the SceneNodeContainer.</param>
/// /<param name="tex">Diffuse texture.</param>
/// <param name="anchors">Anchors for the mesh. Influences the scaling of the object if the enclosing canvas is resized.</param>
/// <param name="offsets">Offsets for the mesh. Defines the position of the object relative to its enclosing UI element.</param>
/// <param name="tiles">Defines the tiling of the inner rectangle of the texture. Use float2.one if you do not desire tiling.</param>
/// <param name="borders">Defines the nine tiles of the texture. Order: left, right, top, bottom. Value is measured in percent from the respective edge of texture.</param>
/// <param name="borderThicknessBottom">Border thickness for the bottom border.</param>
/// <param name="borderScaleFactor">Default value is 1. Set this to scale the border thickness if you use canvas render mode SCREEN.</param>
/// <param name="borderThicknessLeft">Border thickness for the left border.</param>
/// <param name="borderThicknessRight">Border thickness for the right border.</param>
/// <param name="borderThicknessTop">Border thickness for the top border.</param>
/// <returns></returns>
public static async Task<TextureNode> CreateAsync(string name, Texture tex, MinMaxRect anchors,
MinMaxRect offsets, float2 tiles, float4 borders, float borderThicknessLeft = 1, float borderThicknessRight = 1, float borderThicknessTop = 1, float borderThicknessBottom = 1, float borderScaleFactor = 1)
{
var node = new TextureNode();
var borderThickness = new float4(borderThicknessLeft, borderThicknessRight, borderThicknessTop,
borderThicknessBottom);
var vs = await AssetStorage.GetAsync<string>("nineSlice.vert");
var ps = await AssetStorage.GetAsync<string>("nineSliceTile.frag");
node.Name = name;
node.Components = new List<SceneComponent>
{
new RectTransform
{
Name = name + "_RectTransform",
Anchors = anchors,
Offsets = offsets
},
new XForm
{
Name = name + "_XForm",
},
new ShaderEffect(
new FxPassDeclaration
{
VS = vs,
PS = ps,
StateSet = new RenderStateSet
{
AlphaBlendEnable = true,
SourceBlend = Blend.SourceAlpha,
DestinationBlend = Blend.InverseSourceAlpha,
BlendOperation = BlendOperation.Add,
ZEnable = false
}
},
new IFxParamDeclaration[]
{
new FxParamDeclaration<Texture>
{
Name = UniformNameDeclarations.AlbedoTexture,
Value = tex
},
new FxParamDeclaration<float4> {Name = UniformNameDeclarations.Albedo, Value = float4.One},
new FxParamDeclaration<float2> {Name = "Tile", Value = tiles},
new FxParamDeclaration<float> {Name = UniformNameDeclarations.AlbedoMix, Value = 1f},
new FxParamDeclaration<float4>
{
Name = "borders",
Value = borders
},
new FxParamDeclaration<float4> {Name = "borderThickness", Value = borderThickness * borderScaleFactor},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.ITModelView, Value = float4x4.Identity},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.Model, Value = float4x4.Identity},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.View, Value = float4x4.Identity},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.Projection, Value = float4x4.Identity}
}),
new NineSlicePlane()
};
return node;
}
private TextureNode()
{ }
/// <summary>
/// Creates a SceneNodeContainer with the proper components and children for rendering a nine sliced texture.
/// </summary>
/// <param name="name">Name of the SceneNodeContainer.</param>
/// /<param name="tex">Diffuse texture.</param>
/// <param name="anchors">Anchors for the mesh. Influences the scaling of the object if the enclosing canvas is resized.</param>
/// <param name="offsets">Offsets for the mesh. Defines the position of the object relative to its enclosing UI element.</param>
/// <param name="diffuseTexTiles">The tiling of the diffuse texture.</param>
/// <returns></returns>
public static TextureNode Create(string name, Texture tex, MinMaxRect anchors,
MinMaxRect offsets, float2 diffuseTexTiles)
{
return CreateAsync(name, tex, anchors, offsets, diffuseTexTiles).Result;
}
/// <summary>
/// Creates a SceneNodeContainer with the proper components and children for rendering a nine sliced texture.
/// </summary>
/// <param name="name">Name of the SceneNodeContainer.</param>
/// /<param name="tex">Diffuse texture.</param>
/// <param name="anchors">Anchors for the mesh. Influences the scaling of the object if the enclosing canvas is resized.</param>
/// <param name="offsets">Offsets for the mesh. Defines the position of the object relative to its enclosing UI element.</param>
/// <param name="diffuseTexTiles">The tiling of the diffuse texture.</param>
/// <returns></returns>
public static async Task<TextureNode> CreateAsync(string name, Texture tex, MinMaxRect anchors,
MinMaxRect offsets, float2 diffuseTexTiles)
{
var node = new TextureNode();
var vs = await AssetStorage.GetAsync<string>("texture.vert");
var ps = await AssetStorage.GetAsync<string>("texture.frag");
node.Name = name;
node.Components = new List<SceneComponent>
{
new RectTransform
{
Name = name + "_RectTransform",
Anchors = anchors,
Offsets = offsets
},
new XForm
{
Name = name + "_XForm",
},
new ShaderEffect(
new FxPassDeclaration
{
VS = vs,
PS = ps,
StateSet = new RenderStateSet
{
AlphaBlendEnable = true,
SourceBlend = Blend.SourceAlpha,
DestinationBlend = Blend.InverseSourceAlpha,
BlendOperation = BlendOperation.Add,
ZEnable = false
}
},
new IFxParamDeclaration[]
{
new FxParamDeclaration<Texture>
{
Name = UniformNameDeclarations.AlbedoTexture,
Value = tex
},
new FxParamDeclaration<float4> {Name = UniformNameDeclarations.Albedo, Value = float4.One},
new FxParamDeclaration<float> {Name = UniformNameDeclarations.AlbedoMix, Value = 1f},
new FxParamDeclaration<float2> {Name = UniformNameDeclarations.DiffuseTextureTiles, Value = diffuseTexTiles},
new FxParamDeclaration<float4x4> {Name =UniformNameDeclarations.ITModelView, Value = float4x4.Identity},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.ModelViewProjection, Value = float4x4.Identity},
}),
new Plane()
};
return node;
}
}
/// <summary>
/// Creates a SceneNodeContainer with the proper components and children for rendering text in the UI.
/// </summary>
public class TextNode : SceneNode
{
private TextNode()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="TextNode"/> class.
/// </summary>
/// <param name="text">The text you want to display.</param>
/// <param name="name">The name of the SceneNodeContainer.</param>
/// <param name="anchors">Anchors for the mesh. Influences the scaling of the object if the enclosing canvas is resized.</param>
/// <param name="offsets">The offsets.</param>
/// <param name="fontMap">Offsets for the mesh. Defines the position of the object relative to its enclosing UI element.</param>
/// <param name="color">The color.</param>
/// <param name="horizontalAlignment">The <see cref="HorizontalTextAlignment"/> defines the text's placement along the enclosing <see cref="MinMaxRect"/>'s x-axis.</param>
/// <param name="verticalTextAlignment">The <see cref="HorizontalTextAlignment"/> defines the text's placement along the enclosing <see cref="MinMaxRect"/>'s y-axis.</param>
public static TextNode Create(string text, string name, MinMaxRect anchors, MinMaxRect offsets,
FontMap fontMap, float4 color, HorizontalTextAlignment horizontalAlignment = HorizontalTextAlignment.Left, VerticalTextAlignment verticalTextAlignment = VerticalTextAlignment.Top)
{
return CreateAsync(text, name, anchors, offsets, fontMap, color, horizontalAlignment, verticalTextAlignment).Result;
}
/// <summary>
/// Initializes a new instance of the <see cref="TextNode"/> class.
/// </summary>
/// <param name="text">The text you want to display.</param>
/// <param name="name">The name of the SceneNodeContainer.</param>
/// <param name="anchors">Anchors for the mesh. Influences the scaling of the object if the enclosing canvas is resized.</param>
/// <param name="offsets">The offsets.</param>
/// <param name="fontMap">Offsets for the mesh. Defines the position of the object relative to its enclosing UI element.</param>
/// <param name="color">The color.</param>
/// <param name="horizontalAlignment">The <see cref="HorizontalTextAlignment"/> defines the text's placement along the enclosing <see cref="MinMaxRect"/>'s x-axis.</param>
/// <param name="verticalTextAlignment">The <see cref="HorizontalTextAlignment"/> defines the text's placement along the enclosing <see cref="MinMaxRect"/>'s y-axis.</param>
public static async Task<TextNode> CreateAsync(string text, string name, MinMaxRect anchors, MinMaxRect offsets,
FontMap fontMap, float4 color, HorizontalTextAlignment horizontalAlignment = HorizontalTextAlignment.Left, VerticalTextAlignment verticalTextAlignment = VerticalTextAlignment.Top)
{
var node = new TextNode();
string vs = await AssetStorage.GetAsync<string>("texture.vert");
string ps = await AssetStorage.GetAsync<string>("text.frag");
var textMesh = new GuiText(fontMap, text, horizontalAlignment)
{
Name = name + "textMesh"
};
var xFormText = new XFormText
{
Width = textMesh.Width,
Height = textMesh.Height,
HorizontalAlignment = textMesh.HorizontalAlignment,
VerticalAlignment = verticalTextAlignment
};
node.Name = name;
node.Components = new List<SceneComponent>
{
new RectTransform
{
Name = name + "_RectTransform",
Anchors = anchors,
Offsets = offsets
},
new XForm
{
Name = name + "_XForm",
}
};
node.Children = new ChildList()
{
new SceneNode()
{
Components = new List<SceneComponent>()
{
xFormText,
new ShaderEffect(
new FxPassDeclaration
{
VS = vs,
PS = ps,
StateSet = new RenderStateSet
{
AlphaBlendEnable = true,
SourceBlend = Blend.SourceAlpha,
DestinationBlend = Blend.InverseSourceAlpha,
BlendOperation = BlendOperation.Add,
ZEnable = false
}
},
new IFxParamDeclaration[]
{
new FxParamDeclaration<Texture>
{
Name = UniformNameDeclarations.AlbedoTexture,
Value = new Texture(fontMap.Image)
},
new FxParamDeclaration<float4>
{
Name = UniformNameDeclarations.Albedo, Value = color
},
new FxParamDeclaration<float> {Name = UniformNameDeclarations.AlbedoMix, Value = 0.0f},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.ITModelView, Value = float4x4.Identity},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.ModelView, Value = float4x4.Identity},
new FxParamDeclaration<float4x4> {Name = UniformNameDeclarations.ModelViewProjection, Value = float4x4.Identity},
new FxParamDeclaration<float2> {Name = UniformNameDeclarations.DiffuseTextureTiles, Value = float2.One},
new FxParamDeclaration<int> {Name= UniformNameDeclarations.FuseePlatformId, Value = 0}
}),
textMesh,
}
}
};
return node;
}
}
} | 51.391137 | 216 | 0.536405 | [
"BSD-2-Clause",
"MIT"
] | ASPePeX/Fusee | src/Engine/GUI/GuiNode.cs | 26,674 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.Razor
{
internal static class CustomMvcRazorLoggerExtensions
{
private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
private static readonly Action<ILogger, string, Exception> _generatedCodeToAssemblyCompilationStart;
private static readonly Action<ILogger, string, double, Exception> _generatedCodeToAssemblyCompilationEnd;
private static readonly Action<ILogger, string, Exception> _viewCompilerStartCodeGeneration;
private static readonly Action<ILogger, string, double, Exception> _viewCompilerEndCodeGeneration;
private static readonly Action<ILogger, string, Exception> _viewCompilerLocatedCompiledView;
private static readonly Action<ILogger, Exception> _viewCompilerNoCompiledViewsFound;
private static readonly Action<ILogger, string, Exception> _viewCompilerLocatedCompiledViewForPath;
private static readonly Action<ILogger, string, Exception> _viewCompilerRecompilingCompiledView;
private static readonly Action<ILogger, string, Exception> _viewCompilerCouldNotFindFileToCompileForPath;
private static readonly Action<ILogger, string, Exception> _viewCompilerFoundFileToCompileForPath;
private static readonly Action<ILogger, string, Exception> _viewCompilerInvalidatingCompiledFile;
private static readonly Action<ILogger, string, string, Exception> _viewLookupCacheMiss;
private static readonly Action<ILogger, string, string, Exception> _viewLookupCacheHit;
private static readonly Action<ILogger, string, Exception> _precompiledViewFound;
private static readonly Action<ILogger, string, Exception> _tagHelperComponentInitialized;
private static readonly Action<ILogger, string, Exception> _tagHelperComponentProcessed;
static CustomMvcRazorLoggerExtensions()
{
_viewCompilerStartCodeGeneration = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(1, "ViewCompilerStartCodeGeneration"),
"Code generation for the Razor file at '{FilePath}' started.");
_viewCompilerEndCodeGeneration = LoggerMessage.Define<string, double>(
LogLevel.Debug,
new EventId(2, "ViewCompilerEndCodeGeneration"),
"Code generation for the Razor file at '{FilePath}' completed in {ElapsedMilliseconds}ms.");
_viewCompilerLocatedCompiledView = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(3, "ViewCompilerLocatedCompiledView"),
"Initializing Razor view compiler with compiled view: '{ViewName}'.");
_viewCompilerNoCompiledViewsFound = LoggerMessage.Define(
LogLevel.Debug,
new EventId(4, "ViewCompilerNoCompiledViewsFound"),
"Initializing Razor view compiler with no compiled views.");
_viewCompilerLocatedCompiledViewForPath = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(5, "ViewCompilerLocatedCompiledViewForPath"),
"Located compiled view for view at path '{Path}'.");
_viewCompilerRecompilingCompiledView = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(6, "ViewCompilerRecompilingCompiledView"),
"Invalidating compiled view for view at path '{Path}'.");
_viewCompilerCouldNotFindFileToCompileForPath = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(7, "ViewCompilerCouldNotFindFileAtPath"),
"Could not find a file for view at path '{Path}'.");
_viewCompilerFoundFileToCompileForPath = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(8, "ViewCompilerFoundFileToCompile"),
"Found file at path '{Path}'.");
_viewCompilerInvalidatingCompiledFile = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(9, "ViewCompilerInvalidingCompiledFile"),
"Invalidating compiled view at path '{Path}' with a file since the checksum did not match.");
_viewLookupCacheMiss = LoggerMessage.Define<string, string>(
LogLevel.Debug,
new EventId(1, "ViewLookupCacheMiss"),
"View lookup cache miss for view '{ViewName}' in controller '{ControllerName}'.");
_viewLookupCacheHit = LoggerMessage.Define<string, string>(
LogLevel.Debug,
new EventId(2, "ViewLookupCacheHit"),
"View lookup cache hit for view '{ViewName}' in controller '{ControllerName}'.");
_precompiledViewFound = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(3, "PrecompiledViewFound"),
"Using precompiled view for '{RelativePath}'.");
_generatedCodeToAssemblyCompilationStart = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(1, "GeneratedCodeToAssemblyCompilationStart"),
"Compilation of the generated code for the Razor file at '{FilePath}' started.");
_generatedCodeToAssemblyCompilationEnd = LoggerMessage.Define<string, double>(
LogLevel.Debug,
new EventId(2, "GeneratedCodeToAssemblyCompilationEnd"),
"Compilation of the generated code for the Razor file at '{FilePath}' completed in {ElapsedMilliseconds}ms.");
_tagHelperComponentInitialized = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(2, "TagHelperComponentInitialized"),
"Tag helper component '{ComponentName}' initialized.");
_tagHelperComponentProcessed = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(3, "TagHelperComponentProcessed"),
"Tag helper component '{ComponentName}' processed.");
}
public static void ViewCompilerStartCodeGeneration(this ILogger logger, string filePath)
{
_viewCompilerStartCodeGeneration(logger, filePath, null);
}
public static void ViewCompilerEndCodeGeneration(this ILogger logger, string filePath, long startTimestamp)
{
// Don't log if logging wasn't enabled at start of request as time will be wildly wrong.
if (startTimestamp != 0)
{
var currentTimestamp = Stopwatch.GetTimestamp();
var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp)));
_viewCompilerEndCodeGeneration(logger, filePath, elapsed.TotalMilliseconds, null);
}
}
public static void ViewCompilerLocatedCompiledView(this ILogger logger, string view)
{
_viewCompilerLocatedCompiledView(logger, view, null);
}
public static void ViewCompilerNoCompiledViewsFound(this ILogger logger)
{
_viewCompilerNoCompiledViewsFound(logger, null);
}
public static void ViewCompilerLocatedCompiledViewForPath(this ILogger logger, string path)
{
_viewCompilerLocatedCompiledViewForPath(logger, path, null);
}
public static void ViewCompilerCouldNotFindFileAtPath(this ILogger logger, string path)
{
_viewCompilerCouldNotFindFileToCompileForPath(logger, path, null);
}
public static void ViewCompilerFoundFileToCompile(this ILogger logger, string path)
{
_viewCompilerFoundFileToCompileForPath(logger, path, null);
}
public static void ViewCompilerInvalidingCompiledFile(this ILogger logger, string path)
{
_viewCompilerInvalidatingCompiledFile(logger, path, null);
}
public static void ViewLookupCacheMiss(this ILogger logger, string viewName, string controllerName)
{
_viewLookupCacheMiss(logger, viewName, controllerName, null);
}
public static void ViewLookupCacheHit(this ILogger logger, string viewName, string controllerName)
{
_viewLookupCacheHit(logger, viewName, controllerName, null);
}
public static void PrecompiledViewFound(this ILogger logger, string relativePath)
{
_precompiledViewFound(logger, relativePath, null);
}
public static void GeneratedCodeToAssemblyCompilationStart(this ILogger logger, string filePath)
{
_generatedCodeToAssemblyCompilationStart(logger, filePath, null);
}
public static void TagHelperComponentInitialized(this ILogger logger, string componentName)
{
_tagHelperComponentInitialized(logger, componentName, null);
}
public static void TagHelperComponentProcessed(this ILogger logger, string componentName)
{
_tagHelperComponentProcessed(logger, componentName, null);
}
public static void GeneratedCodeToAssemblyCompilationEnd(this ILogger logger, string filePath, long startTimestamp)
{
// Don't log if logging wasn't enabled at start of request as time will be wildly wrong.
if (startTimestamp != 0)
{
var currentTimestamp = Stopwatch.GetTimestamp();
var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp)));
_generatedCodeToAssemblyCompilationEnd(logger, filePath, elapsed.TotalMilliseconds, null);
}
}
}
} | 48.873171 | 126 | 0.672622 | [
"MIT"
] | magicyqy/QStack.Framework | QStack.Framework.AspNetCore.Plugin/Compiler/CustomMvcRazorLoggerExtensions.cs | 10,021 | C# |
using System.Windows.Forms;
namespace StringKingUI
{
public partial class TextBoxControl : UserControl
{
public TextBoxControl()
{
InitializeComponent();
textBoxMain.MaxLength = int.MaxValue;
}
public new string Text
{
get
{
return textBoxMain.Text;
}
set
{
textBoxMain.Text = value;
}
}
public new string[] Lines
{
get
{
return textBoxMain.Lines;
}
}
private void textBoxMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
textBoxMain.SelectAll();
}
}
private void textBoxMain_Enter(object sender, System.EventArgs e)
{
textBoxMain.SelectAll();
}
}
}
| 21.166667 | 74 | 0.435039 | [
"MIT"
] | freaxnx01/StringKing | StringKingUI/Controls/TextBoxControl.cs | 1,018 | C# |
using Anabi.Common.Utils;
using Anabi.DataAccess.Ef;
using Anabi.Validators.Extensions;
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
namespace Anabi.Domain.Person.Commands
{
public class DeleteDefendant : IRequest
{
public int AssetId { get; set; }
public int DefendantId { get; set; }
}
public class DeleteDefendantValidator: AbstractValidator<DeleteDefendant>
{
private readonly AnabiContext context;
public DeleteDefendantValidator(AnabiContext ctx)
{
this.context = ctx;
RuleFor(m => m.AssetId).MustBeInDbSet(context.Assets).WithMessage(Constants.ASSET_INVALID_ID);
RuleFor(m => m.DefendantId).MustBeInDbSet(context.Persons).WithMessage(Constants.DEFENDANT_INVALID_ID);
RuleFor(m => m).MustAsync(AssetDefendantExist).WithMessage(Constants.ASSET_DEFENDANT_INVALID_IDS);
}
private async Task<bool> AssetDefendantExist(DeleteDefendant command, CancellationToken cancellationToken)
{
var assetDefendantExists = await context.AssetDefendants
.AnyAsync(x => x.AssetId == command.AssetId && x.PersonId == command.DefendantId);
return assetDefendantExists;
}
}
}
| 35.184211 | 115 | 0.701571 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | code4romania/anabi-gestiune-api | Anabi.Domain.Core/Person/Commands/DeleteDefendant.cs | 1,339 | C# |
using System;
namespace app
{
class Program
{
static void Main(string[] args)
{
int i = 1;
TestM(ref i);
}
static void TestM(ref int i)
{
i = 3;
Console.WriteLine(i);
}
}
}
| 11.5 | 35 | 0.495652 | [
"MIT"
] | ABaboshin/DotNetCoreProfiler | tests/integration/param-ref/app/Program.cs | 232 | C# |
using System.Management;
namespace PoleStat.StatisticsPages
{
internal abstract class BaseGpuPage : IStatisticsPage
{
private readonly ManagementObjectSearcher _managementObjectSearcher;
protected ManagementObject ManagementObject { get; private set; }
protected BaseGpuPage()
{
_managementObjectSearcher = new ManagementObjectSearcher("select * from Win32_VideoController");
}
public virtual DisplayMessage GetMessage()
{
foreach (var o in _managementObjectSearcher.Get())
{
ManagementObject = (ManagementObject)o;
}
return null;
}
protected string GetGpuName()
{
string name = ManagementObject["Name"].ToString();
name = name.Replace("NVIDIA ", string.Empty);
return name;
}
}
}
| 20.638889 | 99 | 0.736205 | [
"MIT"
] | anarchysteven/polestat | PoleStat/StatisticsPages/BaseGpuPage.cs | 745 | C# |
/**
* Copyright 2015 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $
* Revision: $LastChangedRevision: 2623 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2007_v02_r02.Claims.Coct_mt300000ca {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Datatype;
using Ca.Infoway.Messagebuilder.Datatype.Impl;
using Ca.Infoway.Messagebuilder.Datatype.Lang;
using Ca.Infoway.Messagebuilder.Model;
using System.Collections.Generic;
/**
* <summary>Business Name: Person Prescribing</summary>
*
* <p>Person Prescribing</p>
*/
[Hl7PartTypeMappingAttribute(new string[] {"COCT_MT300000CA.PrescriberPerson"})]
public class PersonPrescribing : MessagePartBean {
private PN name;
private LIST<TEL, TelecommunicationAddress> telecom;
public PersonPrescribing() {
this.name = new PNImpl();
this.telecom = new LISTImpl<TEL, TelecommunicationAddress>(typeof(TELImpl));
}
/**
* <summary>Business Name: Prescriber Name</summary>
*
* <remarks>Relationship: COCT_MT300000CA.PrescriberPerson.name
* Conformance/Cardinality: REQUIRED (1) <p>Name of person
* prescribing</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"name"})]
public PersonName Name {
get { return this.name.Value; }
set { this.name.Value = value; }
}
/**
* <summary>Business Name: Prescriber Telephone Number</summary>
*
* <remarks>Relationship:
* COCT_MT300000CA.PrescriberPerson.telecom
* Conformance/Cardinality: REQUIRED (0-3) <p>used for Coverage
* Extension to contact prescriber</p> <p>Telephone no. of the
* prescriber</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"telecom"})]
public IList<TelecommunicationAddress> Telecom {
get { return this.telecom.RawList(); }
}
}
} | 38.567568 | 89 | 0.641205 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-v02_r02/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2007_v02_r02/Claims/Coct_mt300000ca/PersonPrescribing.cs | 2,854 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace StoicGoose.DataStorage
{
public abstract class ConfigurationBase<T> where T : class, new()
{
public static readonly Dictionary<string, object> Defaults = default;
static ConfigurationBase()
{
Defaults = GetDefaultValues();
}
private static Dictionary<string, object> GetDefaultValues()
{
var dict = new Dictionary<string, object>();
var instance = new T();
foreach (var property in typeof(T).GetProperties().Where(x => x.CanWrite))
{
var value = property.GetValue(instance);
if (value == null || (property.PropertyType == typeof(string) && string.IsNullOrEmpty(value as string))) continue;
dict.Add(property.Name, value);
}
return dict;
}
public void ResetToDefault(string name)
{
var property = GetType().GetProperty(name);
if (property == null) throw new ArgumentException($"Setting '{name}' not found in {GetType().Name}", nameof(name));
property.SetValue(this, Defaults[name]);
}
}
public static class ConfigurationBase
{
public static void CopyConfiguration(object source, object destination)
{
if (source == null) throw new ArgumentNullException(nameof(source), "Source cannot be null");
if (destination == null) throw new ArgumentNullException(nameof(destination), "Destination cannot be null");
var sourceType = source.GetType();
var destType = destination.GetType();
foreach (var sourceProperty in sourceType.GetProperties().Where(x => x.CanRead))
{
var destProperty = destType.GetProperty(sourceProperty.Name);
if (destProperty == null || !destProperty.CanWrite || destProperty.GetSetMethod(true) == null || destProperty.GetSetMethod(true).IsPrivate ||
destProperty.GetSetMethod(true).Attributes.HasFlag(System.Reflection.MethodAttributes.Static) ||
!destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
continue;
var sourceValue = sourceProperty.GetValue(source, null);
var destValue = destProperty.GetValue(destination, null);
if ((sourceProperty.PropertyType.BaseType.IsGenericType ? sourceProperty.PropertyType.BaseType.GetGenericTypeDefinition() : sourceProperty.PropertyType.BaseType) == typeof(ConfigurationBase<>))
CopyConfiguration(sourceValue, destValue);
else
destProperty.SetValue(destination, sourceValue);
}
}
}
}
| 35.161765 | 197 | 0.731493 | [
"MIT"
] | xdanieldzd/StoicGoose | StoicGoose/DataStorage/ConfigurationBase.cs | 2,393 | 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 XLuaCSObjectWrapMongoDBBsonSerializationAttributesBsonDefaultValueAttributeWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.MongoDBBsonSerializationAttributesBsonDefaultValueAttributeWrap);
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.MongoDBBsonSerializationAttributesBsonDefaultValueAttributeWrap gen_ret = new XLua.CSObjectWrap.MongoDBBsonSerializationAttributesBsonDefaultValueAttributeWrap();
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.MongoDBBsonSerializationAttributesBsonDefaultValueAttributeWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.MongoDBBsonSerializationAttributesBsonDefaultValueAttributeWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 25.754545 | 185 | 0.593717 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapMongoDBBsonSerializationAttributesBsonDefaultValueAttributeWrapWrap.cs | 2,835 | C# |
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.EntityFrameworkCore;
using SimpleIdServer.Scim.Domains;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SimpleIdServer.Scim.Persistence.EF
{
public class EFSCIMSchemaQueryRepository : ISCIMSchemaQueryRepository
{
private readonly SCIMDbContext _context;
public EFSCIMSchemaQueryRepository(SCIMDbContext context)
{
_context = context;
}
public Task<SCIMSchema> FindSCIMSchemaById(string schemaId)
{
return _context.SCIMSchemaLst.Include(s => s.SchemaExtensions).Include(s => s.Attributes)
.FirstOrDefaultAsync(s => s.Id == schemaId);
}
public async Task<IEnumerable<SCIMSchema>> FindSCIMSchemaByIdentifiers(IEnumerable<string> schemaIdentifiers)
{
var result = await _context.SCIMSchemaLst.Include(s => s.SchemaExtensions).Include(s => s.Attributes)
.Where(s => schemaIdentifiers.Contains(s.Id))
.ToListAsync();
return result;
}
public async Task<SCIMSchema> FindRootSCIMSchemaByResourceType(string resourceType)
{
return await _context.SCIMSchemaLst.Include(s => s.SchemaExtensions).Include(s => s.Attributes)
.FirstOrDefaultAsync(s => s.ResourceType == resourceType && s.IsRootSchema == true);
}
public async Task<IEnumerable<SCIMSchema>> GetAll()
{
var result = await _context.SCIMSchemaLst.Include(s => s.SchemaExtensions).Include(s => s.Attributes)
.ToListAsync();
return result;
}
public async Task<IEnumerable<SCIMSchema>> GetAllRoot()
{
var result = await _context.SCIMSchemaLst
.Include(s => s.SchemaExtensions)
.Include(s => s.Attributes)
.Where(s => s.IsRootSchema == true).ToListAsync();
return result;
}
public Task<SCIMSchema> FindRootSCIMSchemaByName(string name)
{
return _context.SCIMSchemaLst.Include(s => s.SchemaExtensions).Include(s => s.Attributes)
.FirstOrDefaultAsync(s => s.Name == name && s.IsRootSchema == true);
}
}
}
| 37.96875 | 117 | 0.638683 | [
"Apache-2.0"
] | xinxin-sympli/SimpleIdServer | src/Scim/SimpleIdServer.Scim.Persistence.EF/EFSCIMSchemaQueryRepository.cs | 2,432 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Csrs.Interfaces.Dynamics.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Microsoft.Dynamics.CRM.sitemap
/// </summary>
public partial class MicrosoftDynamicsCRMsitemap
{
/// <summary>
/// Initializes a new instance of the MicrosoftDynamicsCRMsitemap
/// class.
/// </summary>
public MicrosoftDynamicsCRMsitemap()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the MicrosoftDynamicsCRMsitemap
/// class.
/// </summary>
public MicrosoftDynamicsCRMsitemap(System.DateTimeOffset? overwritetime = default(System.DateTimeOffset?), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), string sitemapxml = default(string), string sitemapnameunique = default(string), string _createdbyValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), string _modifiedonbehalfbyValue = default(string), string versionnumber = default(string), string _createdonbehalfbyValue = default(string), string sitemapidunique = default(string), string _modifiedbyValue = default(string), int? componentstate = default(int?), bool? isappaware = default(bool?), string sitemapname = default(string), string _organizationidValue = default(string), string solutionid = default(string), string sitemapid = default(string), bool? ismanaged = default(bool?), MicrosoftDynamicsCRMsystemuser siteMapModifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser siteMapModifiedby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser siteMapCreatedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMorganization organizationid = default(MicrosoftDynamicsCRMorganization), MicrosoftDynamicsCRMsystemuser siteMapCreatedby = default(MicrosoftDynamicsCRMsystemuser))
{
Overwritetime = overwritetime;
Modifiedon = modifiedon;
Sitemapxml = sitemapxml;
Sitemapnameunique = sitemapnameunique;
this._createdbyValue = _createdbyValue;
Createdon = createdon;
this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue;
Versionnumber = versionnumber;
this._createdonbehalfbyValue = _createdonbehalfbyValue;
Sitemapidunique = sitemapidunique;
this._modifiedbyValue = _modifiedbyValue;
Componentstate = componentstate;
Isappaware = isappaware;
Sitemapname = sitemapname;
this._organizationidValue = _organizationidValue;
Solutionid = solutionid;
Sitemapid = sitemapid;
Ismanaged = ismanaged;
SiteMapModifiedonbehalfby = siteMapModifiedonbehalfby;
SiteMapModifiedby = siteMapModifiedby;
SiteMapCreatedonbehalfby = siteMapCreatedonbehalfby;
Organizationid = organizationid;
SiteMapCreatedby = siteMapCreatedby;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "overwritetime")]
public System.DateTimeOffset? Overwritetime { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedon")]
public System.DateTimeOffset? Modifiedon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "sitemapxml")]
public string Sitemapxml { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "sitemapnameunique")]
public string Sitemapnameunique { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdby_value")]
public string _createdbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdon")]
public System.DateTimeOffset? Createdon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedonbehalfby_value")]
public string _modifiedonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public string Versionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdonbehalfby_value")]
public string _createdonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "sitemapidunique")]
public string Sitemapidunique { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedby_value")]
public string _modifiedbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "componentstate")]
public int? Componentstate { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "isappaware")]
public bool? Isappaware { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "sitemapname")]
public string Sitemapname { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_organizationid_value")]
public string _organizationidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "solutionid")]
public string Solutionid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "sitemapid")]
public string Sitemapid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "ismanaged")]
public bool? Ismanaged { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "SiteMap_modifiedonbehalfby")]
public MicrosoftDynamicsCRMsystemuser SiteMapModifiedonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "SiteMap_modifiedby")]
public MicrosoftDynamicsCRMsystemuser SiteMapModifiedby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "SiteMap_createdonbehalfby")]
public MicrosoftDynamicsCRMsystemuser SiteMapCreatedonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "organizationid")]
public MicrosoftDynamicsCRMorganization Organizationid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "SiteMap_createdby")]
public MicrosoftDynamicsCRMsystemuser SiteMapCreatedby { get; set; }
}
}
| 39.983333 | 1,339 | 0.636237 | [
"Apache-2.0"
] | KyleKayfish/jag-csrs-portal-public | src/backend/Csrs.Interfaces.Dynamics/Models/MicrosoftDynamicsCRMsitemap.cs | 7,197 | C# |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinearAlgebraLibrary.Tests
{
[TestClass]
public class VectorTests
{
private Vector R1_origin, R2_origin, R3_origin, R100_origin;
private Vector R1_1, R2_1, R3_1, R100_1;
[TestInitialize]
public void TestInitializer()
{
R1_origin = new Vector(new double[1]);
R2_origin = new Vector(new double[2]);
R3_origin = new Vector(new double[3]);
R100_origin = new Vector(new double[100]);
R1_1 = new Vector(new double[] {1});
R2_1 = new Vector(1, 1);
R3_1 = new Vector(1, 1, 1);
R100_1 = new Vector(Enumerable.Repeat(1.0, 100).ToArray());
}
[TestCategory("Vector Summation"), TestMethod]
public void SummationWithZeroVectorIsTheSameVector()
{
Assert.AreEqual(R1_1, R1_1 + R1_origin);
}
[TestCategory("Defaults"), TestCategory("Normalization"), TestMethod]
public void NormalizedZeroVectorIsStillZeroVector()
{
R1_origin.Normalize();
R2_origin.Normalize();
R3_origin.Normalize();
R100_origin.Normalize();
Assert.IsTrue(R1_origin.IsNull());
Assert.IsTrue(R2_origin.IsNull());
Assert.IsTrue(R3_origin.IsNull());
Assert.IsTrue(R100_origin.IsNull());
}
[TestCategory("Defaults"), TestMethod]
public void DefaultVectorIsAScalarZero()
{
var v = new Vector();
Assert.AreEqual(1, v.Coordinates.Length);
Assert.AreEqual(0, v.Coordinates[0]);
}
[TestCategory("Defaults"), TestMethod]
public void OriginIsAlwaysNullVector()
{
Assert.IsTrue(R1_origin.IsNull());
Assert.IsTrue(R2_origin.IsNull());
Assert.IsTrue(R3_origin.IsNull());
Assert.IsTrue(R100_origin.IsNull());
}
[TestCategory("Vector Length"), TestMethod]
public void LengthOfZeroVectorIsZero()
{
Assert.AreEqual(0, R1_origin.GetLength());
Assert.AreEqual(0, R2_origin.GetLength());
Assert.AreEqual(0, R3_origin.GetLength());
Assert.AreEqual(0, R100_origin.GetLength());
}
[TestCategory("Vector Length"), TestMethod]
public void LengthOf1VectorIsSqrtN()
{
Assert.AreEqual(Math.Sqrt(R1_1.Coordinates.Length), R1_1.GetLength());
Assert.AreEqual(Math.Sqrt(R2_1.Coordinates.Length), R2_1.GetLength());
Assert.AreEqual(Math.Sqrt(R3_1.Coordinates.Length), R3_1.GetLength());
Assert.AreEqual(Math.Sqrt(R100_1.Coordinates.Length), R100_1.GetLength());
}
[TestCategory("Vector Length"), TestMethod]
public void LengthOfNormalizedNonZeroVectorIsOne()
{
R1_1.Normalize();
R2_1.Normalize();
R3_1.Normalize();
R100_1.Normalize();
Assert.AreEqual(1, R1_1.GetLength(), General.Eps);
Assert.AreEqual(1, R2_1.GetLength(), General.Eps);
Assert.AreEqual(1, R3_1.GetLength(), General.Eps);
Assert.AreEqual(1, R100_1.GetLength(), General.Eps);
}
}
} | 33.949495 | 86 | 0.586433 | [
"MIT"
] | karhu-san/mathematics-library | LinearAlgebraLibrary.Tests/VectorTests/VectorTest.cs | 3,363 | C# |
using NuGet.Test.Mocks;
using NuGet.VisualStudio;
namespace NuGet.Dialog.Test
{
internal class MockVsProjectSystem : MockProjectSystem, IVsProjectSystem
{
public string UniqueName
{
get { return "Unique Name"; }
}
}
}
| 19.142857 | 76 | 0.63806 | [
"ECL-2.0",
"Apache-2.0"
] | bobstrickland03/nuget2 | test/Dialog.Test/Mocks/MockVsProjectSystem.cs | 270 | C# |
using System;
namespace NetEaseController
{
[Serializable]
public struct Points
{
public ushort x;
public ushort y;
}
}
| 12.833333 | 27 | 0.603896 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | mingl0280/NetEase-WebController.Net | NetEaseController/Points.cs | 156 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Security.Cryptography.Encryption.Aes.Tests
{
using Aes = System.Security.Cryptography.Aes;
[SkipOnMono("Not supported on Browser", TestPlatforms.Browser)]
public class AesContractTests
{
[Fact]
public static void VerifyDefaults()
{
using (Aes aes = AesFactory.Create())
{
Assert.Equal(128, aes.BlockSize);
Assert.Equal(256, aes.KeySize);
Assert.Equal(CipherMode.CBC, aes.Mode);
Assert.Equal(PaddingMode.PKCS7, aes.Padding);
}
}
[Fact]
public static void LegalBlockSizes()
{
using (Aes aes = AesFactory.Create())
{
KeySizes[] blockSizes = aes.LegalBlockSizes;
Assert.NotNull(blockSizes);
Assert.Equal(1, blockSizes.Length);
KeySizes blockSizeLimits = blockSizes[0];
Assert.Equal(128, blockSizeLimits.MinSize);
Assert.Equal(128, blockSizeLimits.MaxSize);
Assert.Equal(0, blockSizeLimits.SkipSize);
}
}
[Fact]
public static void LegalKeySizes()
{
using (Aes aes = AesFactory.Create())
{
KeySizes[] keySizes = aes.LegalKeySizes;
Assert.NotNull(keySizes);
Assert.Equal(1, keySizes.Length);
KeySizes keySizeLimits = keySizes[0];
Assert.Equal(128, keySizeLimits.MinSize);
Assert.Equal(256, keySizeLimits.MaxSize);
Assert.Equal(64, keySizeLimits.SkipSize);
}
}
[Theory]
[InlineData(64, false)] // too small
[InlineData(129, false)] // in valid range but not valid increment
[InlineData(384, false)] // too large
// Skip on .NET Framework because change is not ported https://github.com/dotnet/runtime/issues/21236
[InlineData(536870928, true)] // number of bits overflows and wraps around to a valid size
public static void InvalidKeySizes(int invalidKeySize, bool skipOnNetfx)
{
if (skipOnNetfx && PlatformDetection.IsNetFramework)
return;
using (Aes aes = AesFactory.Create())
{
// Test KeySize property
Assert.Throws<CryptographicException>(() => aes.KeySize = invalidKeySize);
// Test passing a key to CreateEncryptor and CreateDecryptor
aes.GenerateIV();
byte[] iv = aes.IV;
byte[] key;
try
{
key = new byte[invalidKeySize];
}
catch (OutOfMemoryException) // in case there isn't enough memory at test-time to allocate the large array
{
return;
}
Exception e = Record.Exception(() => aes.CreateEncryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}");
e = Record.Exception(() => aes.CreateDecryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}");
}
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindows7))]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(7, true)]
[InlineData(9, true)]
[InlineData(-1, true)]
[InlineData(int.MaxValue, true)]
[InlineData(int.MinValue, true)]
[InlineData(64, false)]
[InlineData(256, true)]
[InlineData(127, true)]
public static void InvalidCFBFeedbackSizes(int feedbackSize, bool discoverableInSetter)
{
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
aes.Mode = CipherMode.CFB;
if (discoverableInSetter)
{
// there are some key sizes that are invalid for any of the modes,
// so the exception is thrown in the setter
Assert.Throws<CryptographicException>(() =>
{
aes.FeedbackSize = feedbackSize;
});
}
else
{
aes.FeedbackSize = feedbackSize;
// however, for CFB only few sizes are valid. Those should throw in the
// actual AES instantiation.
Assert.Throws<CryptographicException>(() => aes.CreateDecryptor());
Assert.Throws<CryptographicException>(() => aes.CreateEncryptor());
}
}
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindows7))]
[InlineData(8)]
[InlineData(128)]
public static void ValidCFBFeedbackSizes(int feedbackSize)
{
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
aes.Mode = CipherMode.CFB;
aes.FeedbackSize = feedbackSize;
using var decryptor = aes.CreateDecryptor();
using var encryptor = aes.CreateEncryptor();
Assert.NotNull(decryptor);
Assert.NotNull(encryptor);
}
}
[Theory]
[InlineData(64, false)] // smaller than default BlockSize
[InlineData(129, false)] // larger than default BlockSize
// Skip on .NET Framework because change is not ported https://github.com/dotnet/runtime/issues/21236
[InlineData(536870928, true)] // number of bits overflows and wraps around to default BlockSize
public static void InvalidIVSizes(int invalidIvSize, bool skipOnNetfx)
{
if (skipOnNetfx && PlatformDetection.IsNetFramework)
return;
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
byte[] key = aes.Key;
byte[] iv;
try
{
iv = new byte[invalidIvSize];
}
catch (OutOfMemoryException) // in case there isn't enough memory at test-time to allocate the large array
{
return;
}
Exception e = Record.Exception(() => aes.CreateEncryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}");
e = Record.Exception(() => aes.CreateDecryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {(e?.ToString() ?? "null")}");
}
}
[Fact]
public static void VerifyKeyGeneration_Default()
{
using (Aes aes = AesFactory.Create())
{
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyKeyGeneration_128()
{
using (Aes aes = AesFactory.Create())
{
aes.KeySize = 128;
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyKeyGeneration_192()
{
using (Aes aes = AesFactory.Create())
{
aes.KeySize = 192;
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyKeyGeneration_256()
{
using (Aes aes = AesFactory.Create())
{
aes.KeySize = 256;
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyIVGeneration()
{
using (Aes aes = AesFactory.Create())
{
int blockSize = aes.BlockSize;
aes.GenerateIV();
byte[] iv = aes.IV;
Assert.NotNull(iv);
Assert.Equal(blockSize, aes.BlockSize);
Assert.Equal(blockSize, iv.Length * 8);
// Standard randomness caveat: There's a very low chance that the generated IV -is-
// all zeroes. This works out to 1/2^128, which is more unlikely than 1/10^38.
Assert.NotEqual(new byte[iv.Length], iv);
}
}
[Fact]
public static void ValidateEncryptorProperties()
{
using (Aes aes = AesFactory.Create())
{
ValidateTransformProperties(aes, aes.CreateEncryptor());
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In .NET Framework AesCryptoServiceProvider requires a set key and throws otherwise. See https://github.com/dotnet/runtime/issues/21393.")]
public static void ValidateDecryptorProperties()
{
using (Aes aes = AesFactory.Create())
{
ValidateTransformProperties(aes, aes.CreateDecryptor());
}
}
[Fact]
public static void CreateTransformExceptions()
{
byte[] key;
byte[] iv;
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
aes.GenerateIV();
key = aes.Key;
iv = aes.IV;
}
using (Aes aes = AesFactory.Create())
{
aes.Mode = CipherMode.CBC;
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, null));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, null));
// CBC requires an IV.
Assert.Throws<CryptographicException>(() => aes.CreateEncryptor(key, null));
Assert.Throws<CryptographicException>(() => aes.CreateDecryptor(key, null));
}
using (Aes aes = AesFactory.Create())
{
aes.Mode = CipherMode.ECB;
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, null));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, null));
// ECB will accept an IV (but ignore it), and doesn't require it.
using (ICryptoTransform didNotThrow = aes.CreateEncryptor(key, null))
{
Assert.NotNull(didNotThrow);
}
using (ICryptoTransform didNotThrow = aes.CreateDecryptor(key, null))
{
Assert.NotNull(didNotThrow);
}
}
}
[Fact]
public static void ValidateOffsetAndCount()
{
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
aes.GenerateIV();
// aes.BlockSize is in bits, new byte[] is in bytes, so we have 8 blocks.
byte[] full = new byte[aes.BlockSize];
int blockByteCount = aes.BlockSize / 8;
for (int i = 0; i < full.Length; i++)
{
full[i] = unchecked((byte)i);
}
byte[] firstBlock = new byte[blockByteCount];
byte[] middleHalf = new byte[4 * blockByteCount];
// Copy the first blockBytes of full into firstBlock.
Buffer.BlockCopy(full, 0, firstBlock, 0, blockByteCount);
// [Skip][Skip][Take][Take][Take][Take][Skip][Skip] => "middle half"
Buffer.BlockCopy(full, 2 * blockByteCount, middleHalf, 0, middleHalf.Length);
byte[] firstBlockEncrypted;
byte[] firstBlockEncryptedFromCount;
byte[] middleHalfEncrypted;
byte[] middleHalfEncryptedFromOffsetAndCount;
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
firstBlockEncrypted = encryptor.TransformFinalBlock(firstBlock, 0, firstBlock.Length);
}
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
firstBlockEncryptedFromCount = encryptor.TransformFinalBlock(full, 0, firstBlock.Length);
}
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
middleHalfEncrypted = encryptor.TransformFinalBlock(middleHalf, 0, middleHalf.Length);
}
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
middleHalfEncryptedFromOffsetAndCount = encryptor.TransformFinalBlock(full, 2 * blockByteCount, middleHalf.Length);
}
Assert.Equal(firstBlockEncrypted, firstBlockEncryptedFromCount);
Assert.Equal(middleHalfEncrypted, middleHalfEncryptedFromOffsetAndCount);
}
}
private static void ValidateTransformProperties(Aes aes, ICryptoTransform transform)
{
Assert.NotNull(transform);
Assert.Equal(aes.BlockSize, transform.InputBlockSize * 8);
Assert.Equal(aes.BlockSize, transform.OutputBlockSize * 8);
Assert.True(transform.CanTransformMultipleBlocks);
}
private static void VerifyKeyGeneration(Aes aes)
{
int keySize = aes.KeySize;
aes.GenerateKey();
byte[] key = aes.Key;
Assert.NotNull(key);
Assert.Equal(keySize, aes.KeySize);
Assert.Equal(keySize, key.Length * 8);
// Standard randomness caveat: There's a very low chance that the generated key -is-
// all zeroes. For a 128-bit key this is 1/2^128, which is more unlikely than 1/10^38.
Assert.NotEqual(new byte[key.Length], key);
}
}
}
| 36.625935 | 208 | 0.532239 | [
"MIT"
] | 2m0nd/runtime | src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/AES/AesContractTests.cs | 14,687 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.BLOCKCHAIN.Models
{
public class DeleteDataauthorizationParticipantResponse : TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
[NameInMap("req_msg_id")]
[Validation(Required=false)]
public string ReqMsgId { get; set; }
// 结果码,一般OK表示调用成功
[NameInMap("result_code")]
[Validation(Required=false)]
public string ResultCode { get; set; }
// 异常信息的文本描述
[NameInMap("result_msg")]
[Validation(Required=false)]
public string ResultMsg { get; set; }
}
}
| 23.033333 | 72 | 0.642547 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | blockchain/csharp/core/Models/DeleteDataauthorizationParticipantResponse.cs | 765 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Ibmcloud.V1Alpha1
{
public class AccessPolicyStatusSubjectArgs : Pulumi.ResourceArgs
{
[Input("accessGroupDef")]
public Input<Pulumi.Kubernetes.Types.Inputs.Ibmcloud.V1Alpha1.AccessPolicyStatusSubjectAccessGroupDefArgs>? AccessGroupDef { get; set; }
[Input("accessGroupID")]
public Input<string>? AccessGroupID { get; set; }
[Input("serviceID")]
public Input<string>? ServiceID { get; set; }
[Input("userEmail")]
public Input<string>? UserEmail { get; set; }
public AccessPolicyStatusSubjectArgs()
{
}
}
}
| 29.28125 | 144 | 0.684098 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/ibmcloud-iam-operator/dotnet/Kubernetes/Crds/Operators/IbmcloudIamOperator/Ibmcloud/V1Alpha1/Inputs/AccessPolicyStatusSubjectArgs.cs | 937 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using Unity.Lifetime;
using UnityWcfPerrequestLifetimeManager.Extensions;
namespace UnityWcfPerrequestLifetimeManager.Managers
{
public abstract class WcfLifetimeManager<T> : LifetimeManager
where T : IExtensibleObject<T>
{
private Guid key = Guid.NewGuid();
protected WcfLifetimeManager()
: base()
{
}
private UnityWcfExtension<T> Extension
{
get
{
UnityWcfExtension<T> extension = this.FindExtension();
if (extension == null)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, "UnityWcfExtension<{0}> must be registered in WCF.", typeof(T).Name));
}
return extension;
}
}
public override object GetValue(ILifetimeContainer container = null)
{
return this.Extension.FindInstance(this.key);
}
public override void SetValue(object newValue, ILifetimeContainer container = null)
{
this.Extension.RegisterInstance(this.key, newValue);
}
public override void RemoveValue(ILifetimeContainer container = null)
{
this.Extension.RemoveInstance(this.key);
}
protected override LifetimeManager OnCreateLifetimeManager()
{
throw new NotImplementedException();
}
protected abstract UnityWcfExtension<T> FindExtension();
}
} | 28.7 | 136 | 0.616725 | [
"MIT"
] | pragashonlink/Unity.Wcf.PerrequestLifetimeManager | UnityWcfPerrequestLifetimeManager/Managers/WcfLifetimeManager.cs | 1,724 | C# |
using UnityEngine;
using System.Collections;
public class Add10ItemsNormal : MonoBehaviour
{
static int index;
GameObject item;
void Start()
{
item = Resources.Load("Item") as GameObject;
index = 0;
}
void OnClick()
{
UIGridDyn grid = GameObject.Find("UI Root/Camera/New/Panel/Grid").gameObject.GetComponent<UIGridDyn>();
int i = Random.Range(1, 20);
grid.RemoveItem(i.ToString());
//UIGrid grid = GameObject.Find("UI Root/Camera/Normal/Panel/Grid").GetComponent<UIGrid>();
//for (int i = 0; i < 10; i++)
//{
// GameObject myItem = GameObject.Instantiate(item) as GameObject;
// myItem.transform.parent = grid.transform;
// myItem.transform.localScale = new Vector3(1, 1, 1);
// UILabel label = myItem.transform.FindChild("Label1").GetComponent<UILabel>();
// label.text = "Item " + index;
// label = myItem.transform.FindChild("Label2").GetComponent<UILabel>();
// label.text = "Test " + index;
// index++;
//}
//grid.Reposition();
grid.Resort();
}
}
| 27.857143 | 111 | 0.576068 | [
"MIT"
] | android-crack/joework | UnityWorkspace/listmore/nguiListTest/Assets/Scripts/Add10ItemsNormal.cs | 1,172 | 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!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.ContactCenterInsights.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedContactCenterInsightsClientTest
{
[xunit::FactAttribute]
public void CreateConversationRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationRequest request = new CreateConversationRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Conversation = new Conversation(),
ConversationId = "conversation_id32c22ad5",
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.CreateConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.CreateConversation(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConversationRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationRequest request = new CreateConversationRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Conversation = new Conversation(),
ConversationId = "conversation_id32c22ad5",
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.CreateConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.CreateConversationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.CreateConversationAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConversation()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationRequest request = new CreateConversationRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Conversation = new Conversation(),
ConversationId = "conversation_id32c22ad5",
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.CreateConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.CreateConversation(request.Parent, request.Conversation, request.ConversationId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConversationAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationRequest request = new CreateConversationRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Conversation = new Conversation(),
ConversationId = "conversation_id32c22ad5",
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.CreateConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.CreateConversationAsync(request.Parent, request.Conversation, request.ConversationId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.CreateConversationAsync(request.Parent, request.Conversation, request.ConversationId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConversationResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationRequest request = new CreateConversationRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Conversation = new Conversation(),
ConversationId = "conversation_id32c22ad5",
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.CreateConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.CreateConversation(request.ParentAsLocationName, request.Conversation, request.ConversationId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConversationResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationRequest request = new CreateConversationRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Conversation = new Conversation(),
ConversationId = "conversation_id32c22ad5",
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.CreateConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.CreateConversationAsync(request.ParentAsLocationName, request.Conversation, request.ConversationId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.CreateConversationAsync(request.ParentAsLocationName, request.Conversation, request.ConversationId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConversationRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationRequest request = new UpdateConversationRequest
{
Conversation = new Conversation(),
UpdateMask = new wkt::FieldMask(),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.UpdateConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.UpdateConversation(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConversationRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationRequest request = new UpdateConversationRequest
{
Conversation = new Conversation(),
UpdateMask = new wkt::FieldMask(),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.UpdateConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.UpdateConversationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.UpdateConversationAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConversation()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationRequest request = new UpdateConversationRequest
{
Conversation = new Conversation(),
UpdateMask = new wkt::FieldMask(),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.UpdateConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.UpdateConversation(request.Conversation, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConversationAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationRequest request = new UpdateConversationRequest
{
Conversation = new Conversation(),
UpdateMask = new wkt::FieldMask(),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.UpdateConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.UpdateConversationAsync(request.Conversation, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.UpdateConversationAsync(request.Conversation, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConversationRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationRequest request = new GetConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
View = ConversationView.Basic,
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.GetConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.GetConversation(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConversationRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationRequest request = new GetConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
View = ConversationView.Basic,
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.GetConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.GetConversationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.GetConversationAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConversation()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationRequest request = new GetConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.GetConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.GetConversation(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConversationAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationRequest request = new GetConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.GetConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.GetConversationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.GetConversationAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConversationResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationRequest request = new GetConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.GetConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation response = client.GetConversation(request.ConversationName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConversationResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationRequest request = new GetConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
Conversation expectedResponse = new Conversation
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
DataSource = new ConversationDataSource(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
AgentId = "agent_id5ff0189b",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CallMetadata = new Conversation.Types.CallMetadata(),
Transcript = new Conversation.Types.Transcript(),
Medium = Conversation.Types.Medium.Unspecified,
Duration = new wkt::Duration(),
TurnCount = -1286028205,
LatestAnalysis = new Analysis(),
RuntimeAnnotations =
{
new RuntimeAnnotation(),
},
LanguageCode = "language_code2f6c7160",
ExpireTime = new wkt::Timestamp(),
Ttl = new wkt::Duration(),
StartTime = new wkt::Timestamp(),
DialogflowIntents =
{
{
"key8a0b6e3c",
new DialogflowIntent()
},
},
};
mockGrpcClient.Setup(x => x.GetConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Conversation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Conversation responseCallSettings = await client.GetConversationAsync(request.ConversationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Conversation responseCancellationToken = await client.GetConversationAsync(request.ConversationName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConversationRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationRequest request = new DeleteConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
Force = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeleteConversation(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConversationRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationRequest request = new DeleteConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
Force = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeleteConversationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConversationAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConversation()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationRequest request = new DeleteConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeleteConversation(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConversationAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationRequest request = new DeleteConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeleteConversationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConversationAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConversationResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationRequest request = new DeleteConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeleteConversation(request.ConversationName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConversationResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationRequest request = new DeleteConversationRequest
{
ConversationName = ConversationName.FromProjectLocationConversation("[PROJECT]", "[LOCATION]", "[CONVERSATION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeleteConversationAsync(request.ConversationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConversationAsync(request.ConversationName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAnalysisRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAnalysisRequest request = new GetAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
Analysis expectedResponse = new Analysis
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
RequestTime = new wkt::Timestamp(),
CreateTime = new wkt::Timestamp(),
AnalysisResult = new AnalysisResult(),
};
mockGrpcClient.Setup(x => x.GetAnalysis(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Analysis response = client.GetAnalysis(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAnalysisRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAnalysisRequest request = new GetAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
Analysis expectedResponse = new Analysis
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
RequestTime = new wkt::Timestamp(),
CreateTime = new wkt::Timestamp(),
AnalysisResult = new AnalysisResult(),
};
mockGrpcClient.Setup(x => x.GetAnalysisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Analysis>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Analysis responseCallSettings = await client.GetAnalysisAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Analysis responseCancellationToken = await client.GetAnalysisAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAnalysis()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAnalysisRequest request = new GetAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
Analysis expectedResponse = new Analysis
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
RequestTime = new wkt::Timestamp(),
CreateTime = new wkt::Timestamp(),
AnalysisResult = new AnalysisResult(),
};
mockGrpcClient.Setup(x => x.GetAnalysis(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Analysis response = client.GetAnalysis(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAnalysisAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAnalysisRequest request = new GetAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
Analysis expectedResponse = new Analysis
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
RequestTime = new wkt::Timestamp(),
CreateTime = new wkt::Timestamp(),
AnalysisResult = new AnalysisResult(),
};
mockGrpcClient.Setup(x => x.GetAnalysisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Analysis>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Analysis responseCallSettings = await client.GetAnalysisAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Analysis responseCancellationToken = await client.GetAnalysisAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAnalysisResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAnalysisRequest request = new GetAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
Analysis expectedResponse = new Analysis
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
RequestTime = new wkt::Timestamp(),
CreateTime = new wkt::Timestamp(),
AnalysisResult = new AnalysisResult(),
};
mockGrpcClient.Setup(x => x.GetAnalysis(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Analysis response = client.GetAnalysis(request.AnalysisName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAnalysisResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAnalysisRequest request = new GetAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
Analysis expectedResponse = new Analysis
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
RequestTime = new wkt::Timestamp(),
CreateTime = new wkt::Timestamp(),
AnalysisResult = new AnalysisResult(),
};
mockGrpcClient.Setup(x => x.GetAnalysisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Analysis>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Analysis responseCallSettings = await client.GetAnalysisAsync(request.AnalysisName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Analysis responseCancellationToken = await client.GetAnalysisAsync(request.AnalysisName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAnalysisRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteAnalysisRequest request = new DeleteAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAnalysis(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeleteAnalysis(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAnalysisRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteAnalysisRequest request = new DeleteAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAnalysisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeleteAnalysisAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAnalysisAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAnalysis()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteAnalysisRequest request = new DeleteAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAnalysis(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeleteAnalysis(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAnalysisAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteAnalysisRequest request = new DeleteAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAnalysisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeleteAnalysisAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAnalysisAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAnalysisResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteAnalysisRequest request = new DeleteAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAnalysis(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeleteAnalysis(request.AnalysisName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAnalysisResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteAnalysisRequest request = new DeleteAnalysisRequest
{
AnalysisName = AnalysisName.FromProjectLocationConversationAnalysis("[PROJECT]", "[LOCATION]", "[CONVERSATION]", "[ANALYSIS]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAnalysisAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeleteAnalysisAsync(request.AnalysisName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAnalysisAsync(request.AnalysisName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateIssueModelRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueModelRequest request = new UpdateIssueModelRequest
{
IssueModel = new IssueModel(),
UpdateMask = new wkt::FieldMask(),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.UpdateIssueModel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel response = client.UpdateIssueModel(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateIssueModelRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueModelRequest request = new UpdateIssueModelRequest
{
IssueModel = new IssueModel(),
UpdateMask = new wkt::FieldMask(),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.UpdateIssueModelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IssueModel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel responseCallSettings = await client.UpdateIssueModelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IssueModel responseCancellationToken = await client.UpdateIssueModelAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateIssueModel()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueModelRequest request = new UpdateIssueModelRequest
{
IssueModel = new IssueModel(),
UpdateMask = new wkt::FieldMask(),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.UpdateIssueModel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel response = client.UpdateIssueModel(request.IssueModel, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateIssueModelAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueModelRequest request = new UpdateIssueModelRequest
{
IssueModel = new IssueModel(),
UpdateMask = new wkt::FieldMask(),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.UpdateIssueModelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IssueModel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel responseCallSettings = await client.UpdateIssueModelAsync(request.IssueModel, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IssueModel responseCancellationToken = await client.UpdateIssueModelAsync(request.IssueModel, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIssueModelRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueModelRequest request = new GetIssueModelRequest
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.GetIssueModel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel response = client.GetIssueModel(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIssueModelRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueModelRequest request = new GetIssueModelRequest
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.GetIssueModelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IssueModel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel responseCallSettings = await client.GetIssueModelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IssueModel responseCancellationToken = await client.GetIssueModelAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIssueModel()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueModelRequest request = new GetIssueModelRequest
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.GetIssueModel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel response = client.GetIssueModel(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIssueModelAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueModelRequest request = new GetIssueModelRequest
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.GetIssueModelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IssueModel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel responseCallSettings = await client.GetIssueModelAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IssueModel responseCancellationToken = await client.GetIssueModelAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIssueModelResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueModelRequest request = new GetIssueModelRequest
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.GetIssueModel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel response = client.GetIssueModel(request.IssueModelName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIssueModelResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueModelRequest request = new GetIssueModelRequest
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
IssueModel expectedResponse = new IssueModel
{
IssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
State = IssueModel.Types.State.Unspecified,
InputDataConfig = new IssueModel.Types.InputDataConfig(),
TrainingStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.GetIssueModelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IssueModel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
IssueModel responseCallSettings = await client.GetIssueModelAsync(request.IssueModelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IssueModel responseCancellationToken = await client.GetIssueModelAsync(request.IssueModelName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListIssueModelsRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssueModelsRequest request = new ListIssueModelsRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
ListIssueModelsResponse expectedResponse = new ListIssueModelsResponse
{
IssueModels = { new IssueModel(), },
};
mockGrpcClient.Setup(x => x.ListIssueModels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssueModelsResponse response = client.ListIssueModels(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListIssueModelsRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssueModelsRequest request = new ListIssueModelsRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
ListIssueModelsResponse expectedResponse = new ListIssueModelsResponse
{
IssueModels = { new IssueModel(), },
};
mockGrpcClient.Setup(x => x.ListIssueModelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListIssueModelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssueModelsResponse responseCallSettings = await client.ListIssueModelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ListIssueModelsResponse responseCancellationToken = await client.ListIssueModelsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListIssueModels()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssueModelsRequest request = new ListIssueModelsRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
ListIssueModelsResponse expectedResponse = new ListIssueModelsResponse
{
IssueModels = { new IssueModel(), },
};
mockGrpcClient.Setup(x => x.ListIssueModels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssueModelsResponse response = client.ListIssueModels(request.Parent);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListIssueModelsAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssueModelsRequest request = new ListIssueModelsRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
ListIssueModelsResponse expectedResponse = new ListIssueModelsResponse
{
IssueModels = { new IssueModel(), },
};
mockGrpcClient.Setup(x => x.ListIssueModelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListIssueModelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssueModelsResponse responseCallSettings = await client.ListIssueModelsAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ListIssueModelsResponse responseCancellationToken = await client.ListIssueModelsAsync(request.Parent, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListIssueModelsResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssueModelsRequest request = new ListIssueModelsRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
ListIssueModelsResponse expectedResponse = new ListIssueModelsResponse
{
IssueModels = { new IssueModel(), },
};
mockGrpcClient.Setup(x => x.ListIssueModels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssueModelsResponse response = client.ListIssueModels(request.ParentAsLocationName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListIssueModelsResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssueModelsRequest request = new ListIssueModelsRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
ListIssueModelsResponse expectedResponse = new ListIssueModelsResponse
{
IssueModels = { new IssueModel(), },
};
mockGrpcClient.Setup(x => x.ListIssueModelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListIssueModelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssueModelsResponse responseCallSettings = await client.ListIssueModelsAsync(request.ParentAsLocationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ListIssueModelsResponse responseCancellationToken = await client.ListIssueModelsAsync(request.ParentAsLocationName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIssueRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueRequest request = new GetIssueRequest
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIssue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue response = client.GetIssue(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIssueRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueRequest request = new GetIssueRequest
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIssueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Issue>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue responseCallSettings = await client.GetIssueAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Issue responseCancellationToken = await client.GetIssueAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIssue()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueRequest request = new GetIssueRequest
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIssue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue response = client.GetIssue(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIssueAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueRequest request = new GetIssueRequest
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIssueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Issue>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue responseCallSettings = await client.GetIssueAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Issue responseCancellationToken = await client.GetIssueAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIssueResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueRequest request = new GetIssueRequest
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIssue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue response = client.GetIssue(request.IssueName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIssueResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIssueRequest request = new GetIssueRequest
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIssueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Issue>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue responseCallSettings = await client.GetIssueAsync(request.IssueName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Issue responseCancellationToken = await client.GetIssueAsync(request.IssueName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListIssuesRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssuesRequest request = new ListIssuesRequest
{
ParentAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
ListIssuesResponse expectedResponse = new ListIssuesResponse
{
Issues = { new Issue(), },
};
mockGrpcClient.Setup(x => x.ListIssues(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssuesResponse response = client.ListIssues(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListIssuesRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssuesRequest request = new ListIssuesRequest
{
ParentAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
ListIssuesResponse expectedResponse = new ListIssuesResponse
{
Issues = { new Issue(), },
};
mockGrpcClient.Setup(x => x.ListIssuesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListIssuesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssuesResponse responseCallSettings = await client.ListIssuesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ListIssuesResponse responseCancellationToken = await client.ListIssuesAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListIssues()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssuesRequest request = new ListIssuesRequest
{
ParentAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
ListIssuesResponse expectedResponse = new ListIssuesResponse
{
Issues = { new Issue(), },
};
mockGrpcClient.Setup(x => x.ListIssues(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssuesResponse response = client.ListIssues(request.Parent);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListIssuesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssuesRequest request = new ListIssuesRequest
{
ParentAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
ListIssuesResponse expectedResponse = new ListIssuesResponse
{
Issues = { new Issue(), },
};
mockGrpcClient.Setup(x => x.ListIssuesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListIssuesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssuesResponse responseCallSettings = await client.ListIssuesAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ListIssuesResponse responseCancellationToken = await client.ListIssuesAsync(request.Parent, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListIssuesResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssuesRequest request = new ListIssuesRequest
{
ParentAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
ListIssuesResponse expectedResponse = new ListIssuesResponse
{
Issues = { new Issue(), },
};
mockGrpcClient.Setup(x => x.ListIssues(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssuesResponse response = client.ListIssues(request.ParentAsIssueModelName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListIssuesResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ListIssuesRequest request = new ListIssuesRequest
{
ParentAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
ListIssuesResponse expectedResponse = new ListIssuesResponse
{
Issues = { new Issue(), },
};
mockGrpcClient.Setup(x => x.ListIssuesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListIssuesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
ListIssuesResponse responseCallSettings = await client.ListIssuesAsync(request.ParentAsIssueModelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ListIssuesResponse responseCancellationToken = await client.ListIssuesAsync(request.ParentAsIssueModelName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateIssueRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueRequest request = new UpdateIssueRequest
{
Issue = new Issue(),
UpdateMask = new wkt::FieldMask(),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateIssue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue response = client.UpdateIssue(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateIssueRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueRequest request = new UpdateIssueRequest
{
Issue = new Issue(),
UpdateMask = new wkt::FieldMask(),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateIssueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Issue>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue responseCallSettings = await client.UpdateIssueAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Issue responseCancellationToken = await client.UpdateIssueAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateIssue()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueRequest request = new UpdateIssueRequest
{
Issue = new Issue(),
UpdateMask = new wkt::FieldMask(),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateIssue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue response = client.UpdateIssue(request.Issue, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateIssueAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIssueRequest request = new UpdateIssueRequest
{
Issue = new Issue(),
UpdateMask = new wkt::FieldMask(),
};
Issue expectedResponse = new Issue
{
IssueName = IssueName.FromProjectLocationIssueModelIssue("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]", "[ISSUE]"),
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateIssueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Issue>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Issue responseCallSettings = await client.UpdateIssueAsync(request.Issue, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Issue responseCancellationToken = await client.UpdateIssueAsync(request.Issue, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateIssueModelStatsRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateIssueModelStatsRequest request = new CalculateIssueModelStatsRequest
{
IssueModelAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
CalculateIssueModelStatsResponse expectedResponse = new CalculateIssueModelStatsResponse
{
CurrentStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.CalculateIssueModelStats(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateIssueModelStatsResponse response = client.CalculateIssueModelStats(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateIssueModelStatsRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateIssueModelStatsRequest request = new CalculateIssueModelStatsRequest
{
IssueModelAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
CalculateIssueModelStatsResponse expectedResponse = new CalculateIssueModelStatsResponse
{
CurrentStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.CalculateIssueModelStatsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateIssueModelStatsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateIssueModelStatsResponse responseCallSettings = await client.CalculateIssueModelStatsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CalculateIssueModelStatsResponse responseCancellationToken = await client.CalculateIssueModelStatsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateIssueModelStats()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateIssueModelStatsRequest request = new CalculateIssueModelStatsRequest
{
IssueModelAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
CalculateIssueModelStatsResponse expectedResponse = new CalculateIssueModelStatsResponse
{
CurrentStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.CalculateIssueModelStats(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateIssueModelStatsResponse response = client.CalculateIssueModelStats(request.IssueModel);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateIssueModelStatsAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateIssueModelStatsRequest request = new CalculateIssueModelStatsRequest
{
IssueModelAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
CalculateIssueModelStatsResponse expectedResponse = new CalculateIssueModelStatsResponse
{
CurrentStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.CalculateIssueModelStatsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateIssueModelStatsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateIssueModelStatsResponse responseCallSettings = await client.CalculateIssueModelStatsAsync(request.IssueModel, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CalculateIssueModelStatsResponse responseCancellationToken = await client.CalculateIssueModelStatsAsync(request.IssueModel, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateIssueModelStatsResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateIssueModelStatsRequest request = new CalculateIssueModelStatsRequest
{
IssueModelAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
CalculateIssueModelStatsResponse expectedResponse = new CalculateIssueModelStatsResponse
{
CurrentStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.CalculateIssueModelStats(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateIssueModelStatsResponse response = client.CalculateIssueModelStats(request.IssueModelAsIssueModelName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateIssueModelStatsResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateIssueModelStatsRequest request = new CalculateIssueModelStatsRequest
{
IssueModelAsIssueModelName = IssueModelName.FromProjectLocationIssueModel("[PROJECT]", "[LOCATION]", "[ISSUE_MODEL]"),
};
CalculateIssueModelStatsResponse expectedResponse = new CalculateIssueModelStatsResponse
{
CurrentStats = new IssueModelLabelStats(),
};
mockGrpcClient.Setup(x => x.CalculateIssueModelStatsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateIssueModelStatsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateIssueModelStatsResponse responseCallSettings = await client.CalculateIssueModelStatsAsync(request.IssueModelAsIssueModelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CalculateIssueModelStatsResponse responseCancellationToken = await client.CalculateIssueModelStatsAsync(request.IssueModelAsIssueModelName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreatePhraseMatcherRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePhraseMatcherRequest request = new CreatePhraseMatcherRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseMatcher = new PhraseMatcher(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CreatePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.CreatePhraseMatcher(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreatePhraseMatcherRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePhraseMatcherRequest request = new CreatePhraseMatcherRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseMatcher = new PhraseMatcher(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CreatePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.CreatePhraseMatcherAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.CreatePhraseMatcherAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreatePhraseMatcher()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePhraseMatcherRequest request = new CreatePhraseMatcherRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseMatcher = new PhraseMatcher(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CreatePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.CreatePhraseMatcher(request.Parent, request.PhraseMatcher);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreatePhraseMatcherAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePhraseMatcherRequest request = new CreatePhraseMatcherRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseMatcher = new PhraseMatcher(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CreatePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.CreatePhraseMatcherAsync(request.Parent, request.PhraseMatcher, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.CreatePhraseMatcherAsync(request.Parent, request.PhraseMatcher, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreatePhraseMatcherResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePhraseMatcherRequest request = new CreatePhraseMatcherRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseMatcher = new PhraseMatcher(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CreatePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.CreatePhraseMatcher(request.ParentAsLocationName, request.PhraseMatcher);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreatePhraseMatcherResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreatePhraseMatcherRequest request = new CreatePhraseMatcherRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseMatcher = new PhraseMatcher(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CreatePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.CreatePhraseMatcherAsync(request.ParentAsLocationName, request.PhraseMatcher, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.CreatePhraseMatcherAsync(request.ParentAsLocationName, request.PhraseMatcher, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPhraseMatcherRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPhraseMatcherRequest request = new GetPhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.GetPhraseMatcher(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPhraseMatcherRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPhraseMatcherRequest request = new GetPhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.GetPhraseMatcherAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.GetPhraseMatcherAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPhraseMatcher()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPhraseMatcherRequest request = new GetPhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.GetPhraseMatcher(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPhraseMatcherAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPhraseMatcherRequest request = new GetPhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.GetPhraseMatcherAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.GetPhraseMatcherAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPhraseMatcherResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPhraseMatcherRequest request = new GetPhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.GetPhraseMatcher(request.PhraseMatcherName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPhraseMatcherResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPhraseMatcherRequest request = new GetPhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.GetPhraseMatcherAsync(request.PhraseMatcherName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.GetPhraseMatcherAsync(request.PhraseMatcherName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeletePhraseMatcherRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeletePhraseMatcherRequest request = new DeletePhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeletePhraseMatcher(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePhraseMatcherRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeletePhraseMatcherRequest request = new DeletePhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeletePhraseMatcherAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePhraseMatcherAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeletePhraseMatcher()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeletePhraseMatcherRequest request = new DeletePhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeletePhraseMatcher(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePhraseMatcherAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeletePhraseMatcherRequest request = new DeletePhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeletePhraseMatcherAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePhraseMatcherAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeletePhraseMatcherResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeletePhraseMatcherRequest request = new DeletePhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
client.DeletePhraseMatcher(request.PhraseMatcherName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePhraseMatcherResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeletePhraseMatcherRequest request = new DeletePhraseMatcherRequest
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
await client.DeletePhraseMatcherAsync(request.PhraseMatcherName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePhraseMatcherAsync(request.PhraseMatcherName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdatePhraseMatcherRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdatePhraseMatcherRequest request = new UpdatePhraseMatcherRequest
{
PhraseMatcher = new PhraseMatcher(),
UpdateMask = new wkt::FieldMask(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdatePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.UpdatePhraseMatcher(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdatePhraseMatcherRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdatePhraseMatcherRequest request = new UpdatePhraseMatcherRequest
{
PhraseMatcher = new PhraseMatcher(),
UpdateMask = new wkt::FieldMask(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdatePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.UpdatePhraseMatcherAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.UpdatePhraseMatcherAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdatePhraseMatcher()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdatePhraseMatcherRequest request = new UpdatePhraseMatcherRequest
{
PhraseMatcher = new PhraseMatcher(),
UpdateMask = new wkt::FieldMask(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdatePhraseMatcher(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher response = client.UpdatePhraseMatcher(request.PhraseMatcher, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdatePhraseMatcherAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdatePhraseMatcherRequest request = new UpdatePhraseMatcherRequest
{
PhraseMatcher = new PhraseMatcher(),
UpdateMask = new wkt::FieldMask(),
};
PhraseMatcher expectedResponse = new PhraseMatcher
{
PhraseMatcherName = PhraseMatcherName.FromProjectLocationPhraseMatcher("[PROJECT]", "[LOCATION]", "[PHRASE_MATCHER]"),
RevisionId = "revision_id8d9ae05d",
VersionTag = "version_tage7ed110f",
RevisionCreateTime = new wkt::Timestamp(),
DisplayName = "display_name137f65c2",
Type = PhraseMatcher.Types.PhraseMatcherType.Unspecified,
Active = false,
PhraseMatchRuleGroups =
{
new PhraseMatchRuleGroup(),
},
ActivationUpdateTime = new wkt::Timestamp(),
RoleMatch = ConversationParticipant.Types.Role.HumanAgent,
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdatePhraseMatcherAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PhraseMatcher>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
PhraseMatcher responseCallSettings = await client.UpdatePhraseMatcherAsync(request.PhraseMatcher, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PhraseMatcher responseCancellationToken = await client.UpdatePhraseMatcherAsync(request.PhraseMatcher, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateStatsRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateStatsRequest request = new CalculateStatsRequest
{
LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "filtere47ac9b2",
};
CalculateStatsResponse expectedResponse = new CalculateStatsResponse
{
AverageDuration = new wkt::Duration(),
AverageTurnCount = 239030703,
ConversationCount = 1758685422,
SmartHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
CustomHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
#pragma warning disable CS0612
IssueMatches =
#pragma warning restore CS0612
{
{
"key8a0b6e3c",
1623286560
},
},
ConversationCountTimeSeries = new CalculateStatsResponse.Types.TimeSeries(),
IssueMatchesStats =
{
{
"key8a0b6e3c",
new IssueModelLabelStats.Types.IssueStats()
},
},
};
mockGrpcClient.Setup(x => x.CalculateStats(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateStatsResponse response = client.CalculateStats(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateStatsRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateStatsRequest request = new CalculateStatsRequest
{
LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "filtere47ac9b2",
};
CalculateStatsResponse expectedResponse = new CalculateStatsResponse
{
AverageDuration = new wkt::Duration(),
AverageTurnCount = 239030703,
ConversationCount = 1758685422,
SmartHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
CustomHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
#pragma warning disable CS0612
IssueMatches =
#pragma warning restore CS0612
{
{
"key8a0b6e3c",
1623286560
},
},
ConversationCountTimeSeries = new CalculateStatsResponse.Types.TimeSeries(),
IssueMatchesStats =
{
{
"key8a0b6e3c",
new IssueModelLabelStats.Types.IssueStats()
},
},
};
mockGrpcClient.Setup(x => x.CalculateStatsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateStatsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateStatsResponse responseCallSettings = await client.CalculateStatsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CalculateStatsResponse responseCancellationToken = await client.CalculateStatsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateStats()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateStatsRequest request = new CalculateStatsRequest
{
LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
CalculateStatsResponse expectedResponse = new CalculateStatsResponse
{
AverageDuration = new wkt::Duration(),
AverageTurnCount = 239030703,
ConversationCount = 1758685422,
SmartHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
CustomHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
#pragma warning disable CS0612
IssueMatches =
#pragma warning restore CS0612
{
{
"key8a0b6e3c",
1623286560
},
},
ConversationCountTimeSeries = new CalculateStatsResponse.Types.TimeSeries(),
IssueMatchesStats =
{
{
"key8a0b6e3c",
new IssueModelLabelStats.Types.IssueStats()
},
},
};
mockGrpcClient.Setup(x => x.CalculateStats(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateStatsResponse response = client.CalculateStats(request.Location);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateStatsAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateStatsRequest request = new CalculateStatsRequest
{
LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
CalculateStatsResponse expectedResponse = new CalculateStatsResponse
{
AverageDuration = new wkt::Duration(),
AverageTurnCount = 239030703,
ConversationCount = 1758685422,
SmartHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
CustomHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
#pragma warning disable CS0612
IssueMatches =
#pragma warning restore CS0612
{
{
"key8a0b6e3c",
1623286560
},
},
ConversationCountTimeSeries = new CalculateStatsResponse.Types.TimeSeries(),
IssueMatchesStats =
{
{
"key8a0b6e3c",
new IssueModelLabelStats.Types.IssueStats()
},
},
};
mockGrpcClient.Setup(x => x.CalculateStatsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateStatsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateStatsResponse responseCallSettings = await client.CalculateStatsAsync(request.Location, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CalculateStatsResponse responseCancellationToken = await client.CalculateStatsAsync(request.Location, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateStatsResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateStatsRequest request = new CalculateStatsRequest
{
LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
CalculateStatsResponse expectedResponse = new CalculateStatsResponse
{
AverageDuration = new wkt::Duration(),
AverageTurnCount = 239030703,
ConversationCount = 1758685422,
SmartHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
CustomHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
#pragma warning disable CS0612
IssueMatches =
#pragma warning restore CS0612
{
{
"key8a0b6e3c",
1623286560
},
},
ConversationCountTimeSeries = new CalculateStatsResponse.Types.TimeSeries(),
IssueMatchesStats =
{
{
"key8a0b6e3c",
new IssueModelLabelStats.Types.IssueStats()
},
},
};
mockGrpcClient.Setup(x => x.CalculateStats(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateStatsResponse response = client.CalculateStats(request.LocationAsLocationName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateStatsResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateStatsRequest request = new CalculateStatsRequest
{
LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
CalculateStatsResponse expectedResponse = new CalculateStatsResponse
{
AverageDuration = new wkt::Duration(),
AverageTurnCount = 239030703,
ConversationCount = 1758685422,
SmartHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
CustomHighlighterMatches =
{
{
"key8a0b6e3c",
1623286560
},
},
#pragma warning disable CS0612
IssueMatches =
#pragma warning restore CS0612
{
{
"key8a0b6e3c",
1623286560
},
},
ConversationCountTimeSeries = new CalculateStatsResponse.Types.TimeSeries(),
IssueMatchesStats =
{
{
"key8a0b6e3c",
new IssueModelLabelStats.Types.IssueStats()
},
},
};
mockGrpcClient.Setup(x => x.CalculateStatsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateStatsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
CalculateStatsResponse responseCallSettings = await client.CalculateStatsAsync(request.LocationAsLocationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CalculateStatsResponse responseCancellationToken = await client.CalculateStatsAsync(request.LocationAsLocationName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSettingsRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.GetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings response = client.GetSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSettingsRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.GetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.GetSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.GetSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSettings()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.GetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings response = client.GetSettings(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSettingsAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.GetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.GetSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.GetSettingsAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSettingsResourceNames()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.GetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings response = client.GetSettings(request.SettingsName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSettingsResourceNamesAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.GetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.GetSettingsAsync(request.SettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.GetSettingsAsync(request.SettingsName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSettingsRequestObject()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.UpdateSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings response = client.UpdateSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSettingsRequestObjectAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.UpdateSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.UpdateSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.UpdateSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSettings()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.UpdateSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings response = client.UpdateSettings(request.Settings, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSettingsAsync()
{
moq::Mock<ContactCenterInsights.ContactCenterInsightsClient> mockGrpcClient = new moq::Mock<ContactCenterInsights.ContactCenterInsightsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
LanguageCode = "language_code2f6c7160",
ConversationTtl = new wkt::Duration(),
PubsubNotificationSettings =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
AnalysisConfig = new Settings.Types.AnalysisConfig(),
};
mockGrpcClient.Setup(x => x.UpdateSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ContactCenterInsightsClient client = new ContactCenterInsightsClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.UpdateSettingsAsync(request.Settings, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.UpdateSettingsAsync(request.Settings, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| 60.094438 | 256 | 0.635597 | [
"Apache-2.0"
] | amanda-tarafa/google-cloud-dotnet | apis/Google.Cloud.ContactCenterInsights.V1/Google.Cloud.ContactCenterInsights.V1.Tests/ContactCenterInsightsClientTest.g.cs | 207,446 | C# |
using Microsoft.AspNetCore.Builder;
#if NETSTANDARD2_0
using Microsoft.AspNetCore.Hosting;
#endif
using Microsoft.Extensions.DependencyInjection;
#if NETCOREAPP3_1
using Microsoft.Extensions.Hosting;
#endif
using NetModular.Lib.Utils.Core.Helpers;
using HostOptions = NetModular.Lib.Host.Web.Options.HostOptions;
namespace NetModular.Lib.Host.Web
{
public abstract class StartupAbstract
{
protected readonly HostOptions HostOptions;
#if NETSTANDARD2_0
protected readonly IHostingEnvironment Env;
protected StartupAbstract(IHostingEnvironment env)
#elif NETCOREAPP3_1
protected readonly IHostEnvironment Env;
protected StartupAbstract(IHostEnvironment env)
#endif
{
Env = env;
var cfgHelper = new ConfigurationHelper();
//加载主机配置项
HostOptions = cfgHelper.Get<HostOptions>("Host", env.EnvironmentName) ?? new HostOptions();
}
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddWebHost(HostOptions, Env);
}
public virtual void Configure(IApplicationBuilder app)
{
app.UseWebHost(HostOptions, Env);
app.UseShutdownHandler();
}
}
}
| 26.893617 | 103 | 0.691456 | [
"MIT"
] | ZedrealLin/NetModular | src/Framework/Host/Host.Web/StartupAbstract.cs | 1,280 | C# |
using ElRaccoone.Tweens.Core;
using UnityEngine;
namespace ElRaccoone.Tweens {
public static class EulerAnglesYTween {
public static Tween<float> TweenRotationY (this Component self, float to, float duration) =>
Tween<float>.Add<Driver> (self).Finalize (duration, to);
public static Tween<float> TweenRotationY (this GameObject self, float to, float duration) =>
Tween<float>.Add<Driver> (self).Finalize (duration, to);
private class Driver : Tween<float> {
private Quaternion quaternionValueFrom;
private Quaternion quaternionValueTo;
public override bool OnInitialize () {
return true;
}
public override float OnGetFrom () {
return this.transform.eulerAngles.y;
}
public override void OnUpdate (float easedTime) {
this.quaternionValueFrom = Quaternion.Euler (this.transform.eulerAngles.x, this.valueFrom, this.transform.eulerAngles.z);
this.quaternionValueTo = Quaternion.Euler (this.transform.eulerAngles.x, this.valueTo, this.transform.eulerAngles.z);
this.transform.rotation = Quaternion.Lerp (this.quaternionValueFrom, this.quaternionValueTo, easedTime);
}
}
}
} | 38.516129 | 129 | 0.713568 | [
"MIT"
] | stefankohl-dev/unity-tweens | Runtime/EulerAnglesYTween.cs | 1,194 | C# |
using System;
using System.Linq;
using Iviz.Controllers;
using Iviz.Core;
using Iviz.Displays;
using Iviz.Resources;
using Iviz.XmlRpc;
using UnityEngine;
namespace Iviz.App.ARDialogs
{
public class ARLineConnector : MonoBehaviour
{
GameObject node;
readonly MeshMarkerResource[] spheres = new MeshMarkerResource[3];
LineResource lines;
int layer;
Color32 color;
readonly NativeList<LineWithColor> lineSegments = new NativeList<LineWithColor>();
public Func<Vector3> Start { get; set; }
public Func<Vector3> End { get; set; }
void Awake()
{
node = new GameObject("AR LineConnector Node");
lines = ResourcePool.RentDisplay<LineResource>(node.transform);
lines.ElementScale = 0.005f;
foreach (ref var sphere in spheres.Ref())
{
sphere = ResourcePool.Rent<MeshMarkerResource>(Resource.Displays.Sphere, node.transform);
sphere.Transform.localScale = 0.05f * Vector3.one;
sphere.CastsShadows = false;
}
Color = Color.cyan;
Layer = LayerType.IgnoreRaycast;
}
public int Layer
{
get => layer;
set
{
layer = value;
lines.Layer = value;
foreach (var sphere in spheres)
{
sphere.Layer = value;
}
}
}
public bool Visible
{
get => gameObject.activeSelf;
set
{
gameObject.SetActive(value);
node.SetActive(value);
}
}
public Color Color
{
get => color;
set
{
color = value;
Color32 colorMid = color.WithAlpha(130);
Color32 colorB = color.WithAlpha(10);
spheres[0].Color = color;
spheres[1].Color = colorMid;
spheres[2].Color = colorB;
spheres[0].EmissiveColor = color;
spheres[1].EmissiveColor = colorMid;
spheres[2].EmissiveColor = colorB;
}
}
public void SplitForRecycle()
{
lines.Suspend();
ResourcePool.ReturnDisplay(lines);
foreach (var sphere in spheres)
{
sphere.Suspend();
ResourcePool.Return(Resource.Displays.Sphere, sphere.gameObject);
}
}
public void Update()
{
if (Start == null || End == null)
{
return;
}
Vector3 a = Start();
Vector3 b = End();
Vector3 mid = new Vector3((a.x + b.x) / 2, b.y, (a.z + b.z) / 2);
spheres[0].Transform.position = a;
spheres[1].Transform.position = mid;
spheres[2].Transform.position = b;
Color32 colorMid = color.WithAlpha(130);
Color32 colorB = color.WithAlpha(10);
lineSegments.Clear();
lineSegments.Add(new LineWithColor(a, color, mid, colorMid));
lineSegments.Add(new LineWithColor(mid, colorMid, b, colorB));
lines.Set(lineSegments);
}
void OnDestroy()
{
lineSegments.Dispose();
Destroy(node);
}
}
} | 27.273438 | 105 | 0.497279 | [
"MIT"
] | KIT-ISAS/iviz | iviz/Assets/Application/ARDialogs/ARLineConnector.cs | 3,491 | C# |
using AutomaticTypeMapper;
using EOLib.Domain.Character;
namespace EOLib.Domain.Chat.Commands
{
[AutoMappedType]
public class NoWallCommand : IPlayerCommand
{
private readonly ICharacterRepository _characterRepository;
public string CommandText => "nowall";
public NoWallCommand(ICharacterRepository characterRepository)
{
_characterRepository = characterRepository;
}
public bool Execute(string parameter)
{
if (_characterRepository.MainCharacter.AdminLevel == AdminLevel.Player)
return false;
var newNoWall = !_characterRepository.MainCharacter.NoWall;
var newCharacter = _characterRepository.MainCharacter.WithNoWall(newNoWall);
_characterRepository.MainCharacter = newCharacter;
return true;
}
}
}
| 28.290323 | 88 | 0.673888 | [
"MIT"
] | Septharoth/EndlessClient | EOLib/Domain/Chat/Commands/NoWallCommand.cs | 879 | C# |
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V22.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V22.Segment{
///<summary>
/// Represents an HL7 ODS message segment.
/// This segment has the following fields:<ol>
///<li>ODS-1: Type (ID)</li>
///<li>ODS-2: Service Period (CE)</li>
///<li>ODS-3: Diet, Supplement, or Preference Code (CE)</li>
///<li>ODS-4: Text Instruction (ST)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class ODS : AbstractSegment {
/**
* Creates a ODS (DIETARY ORDERS, SUPPLEMENTS, and PREFERENCES) segment object that belongs to the given
* message.
*/
public ODS(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(ID), true, 1, 1, new System.Object[]{message, 159}, "Type");
this.add(typeof(CE), false, 10, 60, new System.Object[]{message}, "Service Period");
this.add(typeof(CE), true, 20, 60, new System.Object[]{message}, "Diet, Supplement, or Preference Code");
this.add(typeof(ST), false, 2, 80, new System.Object[]{message}, "Text Instruction");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns Type(ODS-1).
///</summary>
public ID Type
{
get{
ID ret = null;
try
{
IType t = this.GetField(1, 0);
ret = (ID)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Service Period(ODS-2).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CE GetServicePeriod(int rep)
{
CE ret = null;
try
{
IType t = this.GetField(2, rep);
ret = (CE)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Service Period (ODS-2).
///</summary>
public CE[] GetServicePeriod() {
CE[] ret = null;
try {
IType[] t = this.GetField(2);
ret = new CE[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CE)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Service Period (ODS-2).
///</summary>
public int ServicePeriodRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(2);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Diet, Supplement, or Preference Code(ODS-3).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CE GetDietSupplementOrPreferenceCode(int rep)
{
CE ret = null;
try
{
IType t = this.GetField(3, rep);
ret = (CE)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Diet, Supplement, or Preference Code (ODS-3).
///</summary>
public CE[] GetDietSupplementOrPreferenceCode() {
CE[] ret = null;
try {
IType[] t = this.GetField(3);
ret = new CE[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CE)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Diet, Supplement, or Preference Code (ODS-3).
///</summary>
public int DietSupplementOrPreferenceCodeRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(3);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Text Instruction(ODS-4).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public ST GetTextInstruction(int rep)
{
ST ret = null;
try
{
IType t = this.GetField(4, rep);
ret = (ST)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Text Instruction (ODS-4).
///</summary>
public ST[] GetTextInstruction() {
ST[] ret = null;
try {
IType[] t = this.GetField(4);
ret = new ST[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (ST)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Text Instruction (ODS-4).
///</summary>
public int TextInstructionRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(4);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
}} | 35.406639 | 121 | 0.660377 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V22/Segment/ODS.cs | 8,533 | C# |
using Lucene.Net.Analysis.Util;
using NUnit.Framework;
namespace Lucene.Net.Analysis.Ckb
{
/*
* 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>
/// Test the Sorani analyzer
/// </summary>
public class TestSoraniAnalyzer : BaseTokenStreamTestCase
{
/// <summary>
/// This test fails with NPE when the stopwords file is missing in classpath
/// </summary>
[Test]
public virtual void TestResourcesAvailable()
{
new SoraniAnalyzer(TEST_VERSION_CURRENT);
}
[Test]
public virtual void TestStopwords()
{
Analyzer a = new SoraniAnalyzer(TEST_VERSION_CURRENT);
AssertAnalyzesTo(a, "ئەم پیاوە", new string[] { "پیاو" });
}
[Test]
public virtual void TestCustomStopwords()
{
Analyzer a = new SoraniAnalyzer(TEST_VERSION_CURRENT, CharArraySet.EMPTY_SET);
AssertAnalyzesTo(a, "ئەم پیاوە", new string[] { "ئەم", "پیاو" });
}
[Test]
public virtual void TestReusableTokenStream()
{
Analyzer a = new SoraniAnalyzer(TEST_VERSION_CURRENT);
AssertAnalyzesTo(a, "پیاوە", new string[] { "پیاو" });
AssertAnalyzesTo(a, "پیاو", new string[] { "پیاو" });
}
[Test]
public virtual void TestWithStemExclusionSet()
{
CharArraySet set = new CharArraySet(TEST_VERSION_CURRENT, 1, true);
set.add("پیاوە");
Analyzer a = new SoraniAnalyzer(TEST_VERSION_CURRENT, CharArraySet.EMPTY_SET, set);
AssertAnalyzesTo(a, "پیاوە", new string[] { "پیاوە" });
}
/// <summary>
/// blast some random strings through the analyzer </summary>
[Test]
public virtual void TestRandomStrings()
{
CheckRandomData(Random, new SoraniAnalyzer(TEST_VERSION_CURRENT), 1000 * RandomMultiplier);
}
}
} | 36.181818 | 103 | 0.622398 | [
"Apache-2.0"
] | Ref12/lucenenet | src/Lucene.Net.Tests.Analysis.Common/Analysis/Ckb/TestSoraniAnalyzer.cs | 2,847 | C# |
//-----------------------------------------------------------------------
// <copyright file="SolutionFile_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Tests for the parts of SolutionFile that are surfaced as
// public API</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Build.Construction;
using Microsoft.Build.Shared;
using Microsoft.Build.Exceptions;
namespace Microsoft.Build.UnitTests.Construction
{
/// <summary>
/// Tests for the parts of SolutionFile that are surfaced as public API
/// </summary>
[TestClass]
public class SolutionFile_Tests
{
/// <summary>
/// Test that a project with the C++ project guid and an extension of vcproj is seen as invalid.
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ParseSolution_VC()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'Project name.vcproj', 'Relative path\to\Project name.vcproj', '{0ABED153-9451-483C-8140-9E8D7306B216}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|AnyCPU = Debug|AnyCPU
Release|AnyCPU = Release|AnyCPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.Build.0 = Release|AnyCPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.Fail("Should not get here");
}
/// <summary>
/// Test that a project with the C++ project guid and an arbitrary extension is seen as valid --
/// we assume that all C++ projects except .vcproj are MSBuild format.
/// </summary>
[TestMethod]
public void ParseSolution_VC2()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'Project name.myvctype', 'Relative path\to\Project name.myvctype', '{0ABED153-9451-483C-8140-9E8D7306B216}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|AnyCPU = Debug|AnyCPU
Release|AnyCPU = Release|AnyCPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.Build.0 = Release|AnyCPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual("Project name.myvctype", solution.ProjectsInOrder[0].ProjectName);
Assert.AreEqual("Relative path\\to\\Project name.myvctype", solution.ProjectsInOrder[0].RelativePath);
Assert.AreEqual("{0ABED153-9451-483C-8140-9E8D7306B216}", solution.ProjectsInOrder[0].ProjectGuid);
}
/// <summary>
/// A slightly more complicated test where there is some different whitespace.
/// </summary>
[TestMethod]
public void ParseSolutionWithDifferentSpacing()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project(' { Project GUID} ') = ' Project name ', ' Relative path to project file ' , ' {0ABED153-9451-483C-8140-9E8D7306B216} '
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|AnyCPU = Debug|AnyCPU
Release|AnyCPU = Release|AnyCPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.Build.0 = Release|AnyCPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual("Project name", solution.ProjectsInOrder[0].ProjectName);
Assert.AreEqual("Relative path to project file", solution.ProjectsInOrder[0].RelativePath);
Assert.AreEqual("{0ABED153-9451-483C-8140-9E8D7306B216}", solution.ProjectsInOrder[0].ProjectGuid);
}
/// <summary>
/// Solution with an empty project name. This is somewhat malformed, but we should
/// still behave reasonably instead of crashing.
/// </summary>
[TestMethod]
public void ParseSolution_EmptyProjectName()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{Project GUID}') = '', 'src\.proj', '{0ABED153-9451-483C-8140-9E8D7306B216}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|AnyCPU = Debug|AnyCPU
Release|AnyCPU = Release|AnyCPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.Build.0 = Release|AnyCPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.IsTrue(solution.ProjectsInOrder[0].ProjectName.StartsWith("EmptyProjectName"));
Assert.AreEqual("src\\.proj", solution.ProjectsInOrder[0].RelativePath);
Assert.AreEqual("{0ABED153-9451-483C-8140-9E8D7306B216}", solution.ProjectsInOrder[0].ProjectGuid);
}
/// <summary>
/// Test some characters that are valid in a file name but that also could be
/// considered a delimiter by a parser. Does quoting work for special characters?
/// </summary>
[TestMethod]
public void ParseSolutionWhereProjectNameHasSpecialCharacters()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{Project GUID}') = 'MyProject,(=IsGreat)', 'Relative path to project file' , '{0ABED153-9451-483C-8140-9E8D7306B216}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|AnyCPU = Debug|AnyCPU
Release|AnyCPU = Release|AnyCPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{0ABED153-9451-483C-8140-9E8D7306B216}.Release|AnyCPU.Build.0 = Release|AnyCPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual("MyProject,(=IsGreat)", solution.ProjectsInOrder[0].ProjectName);
Assert.AreEqual("Relative path to project file", solution.ProjectsInOrder[0].RelativePath);
Assert.AreEqual("{0ABED153-9451-483C-8140-9E8D7306B216}", solution.ProjectsInOrder[0].ProjectGuid);
}
/// <summary>
/// Ensure that a bogus version stamp in the .SLN file results in an
/// InvalidProjectFileException.
/// </summary>
[ExpectedException(typeof(InvalidProjectFileException))]
[TestMethod]
public void BadVersionStamp()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version a.b
# Visual Studio 2005
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
}
/// <summary>
/// Expected version numbers less than 7 to cause an invalid project file exception.
/// </summary>
[ExpectedException(typeof(InvalidProjectFileException))]
[TestMethod]
public void VersionTooLow()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 6.0
# Visual Studio 2005
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
}
/// <summary>
/// Test to parse a very basic .sln file to validate that description property in a solution file
/// is properly handled.
/// </summary>
[TestMethod]
public void ParseSolutionFileWithDescriptionInformation()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'AnyProject', 'AnyProject\AnyProject.csproj', '{2CAB0FBD-15D8-458B-8E63-1B5B840E9798}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
Description = Some description of this solution
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2CAB0FBD-15D8-458B-8E63-1B5B840E9798}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2CAB0FBD-15D8-458B-8E63-1B5B840E9798}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2CAB0FBD-15D8-458B-8E63-1B5B840E9798}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2CAB0FBD-15D8-458B-8E63-1B5B840E9798}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
try
{
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
}
catch (Exception ex)
{
Assert.Fail("Failed to parse solution containing description information. Error: " + ex.Message);
}
}
/// <summary>
/// Tests the parsing of a very basic .SLN file with three independent projects.
/// </summary>
[TestMethod]
public void BasicSolution()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{F184B08F-C81C-45F6-A57F-5ABD9991F28F}') = 'ConsoleApplication1', 'ConsoleApplication1\ConsoleApplication1.vbproj', '{AB3413A6-D689-486D-B7F0-A095371B3F13}'
EndProject
Project('{F184B08F-C81C-45F6-A57F-5ABD9991F28F}') = 'vbClassLibrary', 'vbClassLibrary\vbClassLibrary.vbproj', '{BA333A76-4511-47B8-8DF4-CA51C303AD0B}'
EndProject
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{DEBCE986-61B9-435E-8018-44B9EF751655}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|AnyCPU = Debug|AnyCPU
Release|AnyCPU = Release|AnyCPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{AB3413A6-D689-486D-B7F0-A095371B3F13}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{AB3413A6-D689-486D-B7F0-A095371B3F13}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{AB3413A6-D689-486D-B7F0-A095371B3F13}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{AB3413A6-D689-486D-B7F0-A095371B3F13}.Release|AnyCPU.Build.0 = Release|AnyCPU
{BA333A76-4511-47B8-8DF4-CA51C303AD0B}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{BA333A76-4511-47B8-8DF4-CA51C303AD0B}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{BA333A76-4511-47B8-8DF4-CA51C303AD0B}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{BA333A76-4511-47B8-8DF4-CA51C303AD0B}.Release|AnyCPU.Build.0 = Release|AnyCPU
{DEBCE986-61B9-435E-8018-44B9EF751655}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU
{DEBCE986-61B9-435E-8018-44B9EF751655}.Debug|AnyCPU.Build.0 = Debug|AnyCPU
{DEBCE986-61B9-435E-8018-44B9EF751655}.Release|AnyCPU.ActiveCfg = Release|AnyCPU
{DEBCE986-61B9-435E-8018-44B9EF751655}.Release|AnyCPU.Build.0 = Release|AnyCPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual(3, solution.ProjectsInOrder.Count);
Assert.AreEqual("ConsoleApplication1", solution.ProjectsInOrder[0].ProjectName);
Assert.AreEqual(@"ConsoleApplication1\ConsoleApplication1.vbproj", solution.ProjectsInOrder[0].RelativePath);
Assert.AreEqual("{AB3413A6-D689-486D-B7F0-A095371B3F13}", solution.ProjectsInOrder[0].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[0].Dependencies.Count);
Assert.AreEqual(null, solution.ProjectsInOrder[0].ParentProjectGuid);
Assert.AreEqual("vbClassLibrary", solution.ProjectsInOrder[1].ProjectName);
Assert.AreEqual(@"vbClassLibrary\vbClassLibrary.vbproj", solution.ProjectsInOrder[1].RelativePath);
Assert.AreEqual("{BA333A76-4511-47B8-8DF4-CA51C303AD0B}", solution.ProjectsInOrder[1].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[1].Dependencies.Count);
Assert.AreEqual(null, solution.ProjectsInOrder[1].ParentProjectGuid);
Assert.AreEqual("ClassLibrary1", solution.ProjectsInOrder[2].ProjectName);
Assert.AreEqual(@"ClassLibrary1\ClassLibrary1.csproj", solution.ProjectsInOrder[2].RelativePath);
Assert.AreEqual("{DEBCE986-61B9-435E-8018-44B9EF751655}", solution.ProjectsInOrder[2].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[2].Dependencies.Count);
Assert.AreEqual(null, solution.ProjectsInOrder[2].ParentProjectGuid);
}
/// <summary>
/// Exercises solution folders, and makes sure that samely named projects in different
/// solution folders will get correctly uniquified.
/// </summary>
[TestMethod]
public void SolutionFolders()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{34E0D07D-CF8F-459D-9449-C4188D8C5564}'
EndProject
Project('{2150E333-8FDC-42A3-9474-1A3956D46DE8}') = 'MySlnFolder', 'MySlnFolder', '{E0F97730-25D2-418A-A7BD-02CAFDC6E470}'
EndProject
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'MyPhysicalFolder\ClassLibrary1\ClassLibrary1.csproj', '{A5EE8128-B08E-4533-86C5-E46714981680}'
EndProject
Project('{2150E333-8FDC-42A3-9474-1A3956D46DE8}') = 'MySubSlnFolder', 'MySubSlnFolder', '{2AE8D6C4-FB43-430C-8AEB-15E5EEDAAE4B}'
EndProject
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary2', 'ClassLibrary2\ClassLibrary2.csproj', '{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Release|Any CPU.ActiveCfg = Release|Any CPU
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Release|Any CPU.Build.0 = Release|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Release|Any CPU.Build.0 = Release|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{A5EE8128-B08E-4533-86C5-E46714981680} = {E0F97730-25D2-418A-A7BD-02CAFDC6E470}
{2AE8D6C4-FB43-430C-8AEB-15E5EEDAAE4B} = {E0F97730-25D2-418A-A7BD-02CAFDC6E470}
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4} = {2AE8D6C4-FB43-430C-8AEB-15E5EEDAAE4B}
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual(5, solution.ProjectsInOrder.Count);
Assert.AreEqual(@"ClassLibrary1\ClassLibrary1.csproj", solution.ProjectsInOrder[0].RelativePath);
Assert.AreEqual("{34E0D07D-CF8F-459D-9449-C4188D8C5564}", solution.ProjectsInOrder[0].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[0].Dependencies.Count);
Assert.AreEqual(null, solution.ProjectsInOrder[0].ParentProjectGuid);
Assert.AreEqual("{E0F97730-25D2-418A-A7BD-02CAFDC6E470}", solution.ProjectsInOrder[1].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[1].Dependencies.Count);
Assert.AreEqual(null, solution.ProjectsInOrder[1].ParentProjectGuid);
Assert.AreEqual(@"MyPhysicalFolder\ClassLibrary1\ClassLibrary1.csproj", solution.ProjectsInOrder[2].RelativePath);
Assert.AreEqual("{A5EE8128-B08E-4533-86C5-E46714981680}", solution.ProjectsInOrder[2].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[2].Dependencies.Count);
Assert.AreEqual("{E0F97730-25D2-418A-A7BD-02CAFDC6E470}", solution.ProjectsInOrder[2].ParentProjectGuid);
Assert.AreEqual("{2AE8D6C4-FB43-430C-8AEB-15E5EEDAAE4B}", solution.ProjectsInOrder[3].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[3].Dependencies.Count);
Assert.AreEqual("{E0F97730-25D2-418A-A7BD-02CAFDC6E470}", solution.ProjectsInOrder[3].ParentProjectGuid);
Assert.AreEqual(@"ClassLibrary2\ClassLibrary2.csproj", solution.ProjectsInOrder[4].RelativePath);
Assert.AreEqual("{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}", solution.ProjectsInOrder[4].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[4].Dependencies.Count);
Assert.AreEqual("{2AE8D6C4-FB43-430C-8AEB-15E5EEDAAE4B}", solution.ProjectsInOrder[4].ParentProjectGuid);
}
/// <summary>
/// Tests situation where there's a nonexistent project listed in the solution folders. We should
/// error with a useful message.
/// </summary>
[TestMethod]
public void MissingNestedProject()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{2150E333-8FDC-42A3-9474-1A3956D46DE8}') = 'MySlnFolder', 'MySlnFolder', '{E0F97730-25D2-418A-A7BD-02CAFDC6E470}'
EndProject
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'MyPhysicalFolder\ClassLibrary1\ClassLibrary1.csproj', '{A5EE8128-B08E-4533-86C5-E46714981680}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Release|Any CPU.ActiveCfg = Release|Any CPU
{34E0D07D-CF8F-459D-9449-C4188D8C5564}.Release|Any CPU.Build.0 = Release|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A5EE8128-B08E-4533-86C5-E46714981680}.Release|Any CPU.Build.0 = Release|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6DB98C35-FDCC-4818-B5D4-1F0A385FDFD4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{A5EE8128-B08E-4533-86C5-E46714981680} = {E0F97730-25D2-418A-A7BD-02CAFDC6E470}
{2AE8D6C4-FB43-430C-8AEB-15E5EEDAAE4B} = {E0F97730-25D2-418A-A7BD-02CAFDC6E470}
EndGlobalSection
EndGlobal
";
try
{
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
}
catch (InvalidProjectFileException e)
{
Assert.AreEqual("MSB5023", e.ErrorCode);
Assert.IsTrue(e.Message.Contains("{2AE8D6C4-FB43-430C-8AEB-15E5EEDAAE4B}"));
return;
}
// Should not get here
Assert.Fail();
}
/// <summary>
/// Verifies that hand-coded project-to-project dependencies listed in the .SLN file
/// are correctly recognized by our solution parser.
/// </summary>
[TestMethod]
public void SolutionDependencies()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{05A5AD00-71B5-4612-AF2F-9EA9121C4111}'
ProjectSection(ProjectDependencies) = postProject
{FAB4EE06-6E01-495A-8926-5514599E3DD9} = {FAB4EE06-6E01-495A-8926-5514599E3DD9}
EndProjectSection
EndProject
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary2', 'ClassLibrary2\ClassLibrary2.csproj', '{7F316407-AE3E-4F26-BE61-2C50D30DA158}'
ProjectSection(ProjectDependencies) = postProject
{FAB4EE06-6E01-495A-8926-5514599E3DD9} = {FAB4EE06-6E01-495A-8926-5514599E3DD9}
{05A5AD00-71B5-4612-AF2F-9EA9121C4111} = {05A5AD00-71B5-4612-AF2F-9EA9121C4111}
EndProjectSection
EndProject
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary3', 'ClassLibrary3\ClassLibrary3.csproj', '{FAB4EE06-6E01-495A-8926-5514599E3DD9}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{05A5AD00-71B5-4612-AF2F-9EA9121C4111}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{05A5AD00-71B5-4612-AF2F-9EA9121C4111}.Debug|Any CPU.Build.0 = Debug|Any CPU
{05A5AD00-71B5-4612-AF2F-9EA9121C4111}.Release|Any CPU.ActiveCfg = Release|Any CPU
{05A5AD00-71B5-4612-AF2F-9EA9121C4111}.Release|Any CPU.Build.0 = Release|Any CPU
{7F316407-AE3E-4F26-BE61-2C50D30DA158}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F316407-AE3E-4F26-BE61-2C50D30DA158}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F316407-AE3E-4F26-BE61-2C50D30DA158}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F316407-AE3E-4F26-BE61-2C50D30DA158}.Release|Any CPU.Build.0 = Release|Any CPU
{FAB4EE06-6E01-495A-8926-5514599E3DD9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAB4EE06-6E01-495A-8926-5514599E3DD9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAB4EE06-6E01-495A-8926-5514599E3DD9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAB4EE06-6E01-495A-8926-5514599E3DD9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual(3, solution.ProjectsInOrder.Count);
Assert.AreEqual(@"ClassLibrary1\ClassLibrary1.csproj", solution.ProjectsInOrder[0].RelativePath);
Assert.AreEqual("{05A5AD00-71B5-4612-AF2F-9EA9121C4111}", solution.ProjectsInOrder[0].ProjectGuid);
Assert.AreEqual(1, solution.ProjectsInOrder[0].Dependencies.Count);
Assert.AreEqual("{FAB4EE06-6E01-495A-8926-5514599E3DD9}", (string) solution.ProjectsInOrder[0].Dependencies[0]);
Assert.AreEqual(null, solution.ProjectsInOrder[0].ParentProjectGuid);
Assert.AreEqual(@"ClassLibrary2\ClassLibrary2.csproj", solution.ProjectsInOrder[1].RelativePath);
Assert.AreEqual("{7F316407-AE3E-4F26-BE61-2C50D30DA158}", solution.ProjectsInOrder[1].ProjectGuid);
Assert.AreEqual(2, solution.ProjectsInOrder[1].Dependencies.Count);
Assert.AreEqual("{FAB4EE06-6E01-495A-8926-5514599E3DD9}", (string) solution.ProjectsInOrder[1].Dependencies[0]);
Assert.AreEqual("{05A5AD00-71B5-4612-AF2F-9EA9121C4111}", (string) solution.ProjectsInOrder[1].Dependencies[1]);
Assert.AreEqual(null, solution.ProjectsInOrder[1].ParentProjectGuid);
Assert.AreEqual(@"ClassLibrary3\ClassLibrary3.csproj", solution.ProjectsInOrder[2].RelativePath);
Assert.AreEqual("{FAB4EE06-6E01-495A-8926-5514599E3DD9}", solution.ProjectsInOrder[2].ProjectGuid);
Assert.AreEqual(0, solution.ProjectsInOrder[2].Dependencies.Count);
Assert.AreEqual(null, solution.ProjectsInOrder[2].ParentProjectGuid);
}
/// <summary>
/// Make sure the solution configurations get parsed correctly for a simple mixed C#/VC solution
/// </summary>
[TestMethod]
public void ParseSolutionConfigurations()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
EndProject
Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'MainApp', 'MainApp\MainApp.vcxproj', '{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|Win32 = Debug|Win32
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|ARM.ActiveCfg = Debug|ARM
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|ARM.Build.0 = Debug|ARM
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Win32.ActiveCfg = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Win32.ActiveCfg = Release|Any CPU
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Any CPU.ActiveCfg = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.Build.0 = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Win32.ActiveCfg = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Win32.Build.0 = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Any CPU.ActiveCfg = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Mixed Platforms.ActiveCfg = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Mixed Platforms.Build.0 = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Win32.ActiveCfg = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual(7, solution.SolutionConfigurations.Count);
List<string> configurationNames = new List<string>(6);
foreach (SolutionConfigurationInSolution configuration in solution.SolutionConfigurations)
{
configurationNames.Add(configuration.FullName);
}
Assert.IsTrue(configurationNames.Contains("Debug|Any CPU"));
Assert.IsTrue(configurationNames.Contains("Debug|Mixed Platforms"));
Assert.IsTrue(configurationNames.Contains("Debug|Win32"));
Assert.IsTrue(configurationNames.Contains("Release|Any CPU"));
Assert.IsTrue(configurationNames.Contains("Release|Mixed Platforms"));
Assert.IsTrue(configurationNames.Contains("Release|Win32"));
Assert.AreEqual("Debug", solution.GetDefaultConfigurationName(), "Default solution configuration");
Assert.AreEqual("Mixed Platforms", solution.GetDefaultPlatformName(), "Default solution platform");
}
/// <summary>
/// Make sure the solution configurations get parsed correctly for a simple C# application
/// </summary>
[TestMethod]
public void ParseSolutionConfigurationsNoMixedPlatform()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|Any CPU = Debug|Any CPU
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|Any CPU = Release|Any CPU
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|ARM.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|ARM.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|x86.ActiveCfg = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|ARM.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|ARM.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
Assert.AreEqual(6, solution.SolutionConfigurations.Count);
List<string> configurationNames = new List<string>(6);
foreach (SolutionConfigurationInSolution configuration in solution.SolutionConfigurations)
{
configurationNames.Add(configuration.FullName);
}
Assert.IsTrue(configurationNames.Contains("Debug|Any CPU"));
Assert.IsTrue(configurationNames.Contains("Debug|ARM"));
Assert.IsTrue(configurationNames.Contains("Debug|x86"));
Assert.IsTrue(configurationNames.Contains("Release|Any CPU"));
Assert.IsTrue(configurationNames.Contains("Release|ARM"));
Assert.IsTrue(configurationNames.Contains("Release|x86"));
Assert.AreEqual("Debug", solution.GetDefaultConfigurationName(), "Default solution configuration");
Assert.AreEqual("Any CPU", solution.GetDefaultPlatformName(), "Default solution platform");
}
/// <summary>
/// Test some invalid cases for solution configuration parsing.
/// There can be only one '=' character in a sln cfg entry, separating two identical names
/// </summary>
[ExpectedException(typeof(InvalidProjectFileException))]
[TestMethod]
public void ParseInvalidSolutionConfigurations1()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any=CPU = Debug|Any=CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
}
/// <summary>
/// Test some invalid cases for solution configuration parsing
/// There can be only one '=' character in a sln cfg entry, separating two identical names
/// </summary>
[ExpectedException(typeof(InvalidProjectFileException))]
[TestMethod]
public void ParseInvalidSolutionConfigurations2()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Something|Else
Release|Any CPU = Release|Any CPU
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
}
/// <summary>
/// Test some invalid cases for solution configuration parsing
/// Solution configurations must include the platform part
/// </summary>
[ExpectedException(typeof(InvalidProjectFileException))]
[TestMethod]
public void ParseInvalidSolutionConfigurations3()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug = Debug
Release|Any CPU = Release|Any CPU
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
}
/// <summary>
/// Make sure the project configurations in solution configurations get parsed correctly
/// for a simple mixed C#/VC solution
/// </summary>
[TestMethod]
public void ParseProjectConfigurationsInSolutionConfigurations1()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
EndProject
Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'MainApp', 'MainApp\MainApp.vcxproj', '{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|Win32 = Debug|Win32
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Win32.ActiveCfg = Debug|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Win32.ActiveCfg = Release|Any CPU
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Any CPU.ActiveCfg = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.Build.0 = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Win32.ActiveCfg = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Win32.Build.0 = Debug|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Any CPU.ActiveCfg = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Mixed Platforms.ActiveCfg = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Mixed Platforms.Build.0 = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Win32.ActiveCfg = Release|Win32
{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
ProjectInSolution csharpProject = (ProjectInSolution) solution.ProjectsByGuid["{6185CC21-BE89-448A-B3C0-D1C27112E595}"];
ProjectInSolution vcProject = (ProjectInSolution) solution.ProjectsByGuid["{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}"];
Assert.AreEqual(6, csharpProject.ProjectConfigurations.Count);
Assert.AreEqual("Debug|AnyCPU", csharpProject.ProjectConfigurations["Debug|Any CPU"].FullName);
Assert.AreEqual(true, csharpProject.ProjectConfigurations["Debug|Any CPU"].IncludeInBuild);
Assert.AreEqual("Release|AnyCPU", csharpProject.ProjectConfigurations["Debug|Mixed Platforms"].FullName);
Assert.AreEqual(true, csharpProject.ProjectConfigurations["Debug|Mixed Platforms"].IncludeInBuild);
Assert.AreEqual("Debug|AnyCPU", csharpProject.ProjectConfigurations["Debug|Win32"].FullName);
Assert.AreEqual(false, csharpProject.ProjectConfigurations["Debug|Win32"].IncludeInBuild);
Assert.AreEqual("Release|AnyCPU", csharpProject.ProjectConfigurations["Release|Any CPU"].FullName);
Assert.AreEqual(true, csharpProject.ProjectConfigurations["Release|Any CPU"].IncludeInBuild);
Assert.AreEqual("Release|AnyCPU", csharpProject.ProjectConfigurations["Release|Mixed Platforms"].FullName);
Assert.AreEqual(true, csharpProject.ProjectConfigurations["Release|Mixed Platforms"].IncludeInBuild);
Assert.AreEqual("Release|AnyCPU", csharpProject.ProjectConfigurations["Release|Win32"].FullName);
Assert.AreEqual(false, csharpProject.ProjectConfigurations["Release|Win32"].IncludeInBuild);
Assert.AreEqual(6, vcProject.ProjectConfigurations.Count);
Assert.AreEqual("Debug|Win32", vcProject.ProjectConfigurations["Debug|Any CPU"].FullName);
Assert.AreEqual(false, vcProject.ProjectConfigurations["Debug|Any CPU"].IncludeInBuild);
Assert.AreEqual("Debug|Win32", vcProject.ProjectConfigurations["Debug|Mixed Platforms"].FullName);
Assert.AreEqual(true, vcProject.ProjectConfigurations["Debug|Mixed Platforms"].IncludeInBuild);
Assert.AreEqual("Debug|Win32", vcProject.ProjectConfigurations["Debug|Win32"].FullName);
Assert.AreEqual(true, vcProject.ProjectConfigurations["Debug|Win32"].IncludeInBuild);
Assert.AreEqual("Release|Win32", vcProject.ProjectConfigurations["Release|Any CPU"].FullName);
Assert.AreEqual(false, vcProject.ProjectConfigurations["Release|Any CPU"].IncludeInBuild);
Assert.AreEqual("Release|Win32", vcProject.ProjectConfigurations["Release|Mixed Platforms"].FullName);
Assert.AreEqual(true, vcProject.ProjectConfigurations["Release|Mixed Platforms"].IncludeInBuild);
Assert.AreEqual("Release|Win32", vcProject.ProjectConfigurations["Release|Win32"].FullName);
Assert.AreEqual(true, vcProject.ProjectConfigurations["Release|Win32"].IncludeInBuild);
}
/// <summary>
/// Make sure the project configurations in solution configurations get parsed correctly
/// for a more tricky solution
/// </summary>
[TestMethod]
public void ParseProjectConfigurationsInSolutionConfigurations2()
{
string solutionFileContents =
@"
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'C:\solutions\WebSite1\', '..\WebSite1\', '{E8E75132-67E4-4D6F-9CAE-8DA4C883F418}'
EndProject
Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'C:\solutions\WebSite2\', '..\WebSite2\', '{E8E75132-67E4-4D6F-9CAE-8DA4C883F419}'
EndProject
Project('{2150E333-8FDC-42A3-9474-1A3956D46DE8}') = 'NewFolder1', 'NewFolder1', '{54D20FFE-84BE-4066-A51E-B25D040A4235}'
EndProject
Project('{2150E333-8FDC-42A3-9474-1A3956D46DE8}') = 'NewFolder2', 'NewFolder2', '{D2633E4D-46FF-4C4E-8340-4BC7CDF78615}'
EndProject
Project('{8BC9CEB9-8B4A-11D0-8D11-00A0C91BC942}') = 'MSBuild.exe', '..\..\dd\binaries.x86dbg\bin\i386\MSBuild.exe', '{25FD9E7C-F37E-48E0-9A7C-607FE4AACCC0}'
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|.NET = Debug|.NET
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E8E75132-67E4-4D6F-9CAE-8DA4C883F418}.Debug|.NET.ActiveCfg = Debug|.NET
{E8E75132-67E4-4D6F-9CAE-8DA4C883F418}.Debug|.NET.Build.0 = Debug|.NET
{25FD9E7C-F37E-48E0-9A7C-607FE4AACCC0}.Debug|.NET.ActiveCfg = Debug
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{25FD9E7C-F37E-48E0-9A7C-607FE4AACCC0} = {D2633E4D-46FF-4C4E-8340-4BC7CDF78615}
EndGlobalSection
EndGlobal
";
SolutionFile solution = ParseSolutionHelper(solutionFileContents);
ProjectInSolution webProject = (ProjectInSolution)solution.ProjectsByGuid["{E8E75132-67E4-4D6F-9CAE-8DA4C883F418}"];
ProjectInSolution exeProject = (ProjectInSolution)solution.ProjectsByGuid["{25FD9E7C-F37E-48E0-9A7C-607FE4AACCC0}"];
ProjectInSolution missingWebProject = (ProjectInSolution)solution.ProjectsByGuid["{E8E75132-67E4-4D6F-9CAE-8DA4C883F419}"];
Assert.AreEqual(1, webProject.ProjectConfigurations.Count);
Assert.AreEqual("Debug|.NET", webProject.ProjectConfigurations["Debug|.NET"].FullName);
Assert.AreEqual(true, webProject.ProjectConfigurations["Debug|.NET"].IncludeInBuild);
Assert.AreEqual(1, exeProject.ProjectConfigurations.Count);
Assert.AreEqual("Debug", exeProject.ProjectConfigurations["Debug|.NET"].FullName);
Assert.AreEqual(false, exeProject.ProjectConfigurations["Debug|.NET"].IncludeInBuild);
Assert.AreEqual(0, missingWebProject.ProjectConfigurations.Count);
Assert.AreEqual("Debug", solution.GetDefaultConfigurationName(), "Default solution configuration");
Assert.AreEqual(".NET", solution.GetDefaultPlatformName(), "Default solution platform");
}
/// <summary>
/// Helper method to create a SolutionFile object, and call it to parse the SLN file
/// represented by the string contents passed in.
/// </summary>
private static SolutionFile ParseSolutionHelper(string solutionFileContents)
{
solutionFileContents = solutionFileContents.Replace('\'', '"');
string solutionPath = FileUtilities.GetTemporaryFile(".sln");
try
{
File.WriteAllText(solutionPath, solutionFileContents);
SolutionFile sp = SolutionFile.Parse(solutionPath);
return sp;
}
finally
{
File.Delete(solutionPath);
}
}
}
}
| 60.356614 | 182 | 0.591318 | [
"MIT"
] | ZZHGit/msbuild | src/XMakeBuildEngine/UnitTestsPublicOM/Construction/SolutionFile_Tests.cs | 56,095 | C# |
namespace MyLeasing.Api.Core.Application
{
using AutoMapper;
using MyLeasing.Api.Core.Helper;
using MyLeasing.Api.Infrastructure.Data.Entities;
using MyLeasing.Api.Infrastructure.Repository.Interface;
using MyLeasing.Common.Rest;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class LesseeApplication : GenericApplication<LesseeRest, LesseeDto>
{
private readonly IUserHelper _userHelper;
public LesseeApplication(ILesseeRepository repository, IMapper mapper, IUserHelper userHelper)
: base(repository, mapper)
{
this._userHelper = userHelper;
}
public async override Task<LesseeRest> Save(LesseeRest entity)
{
var user = await this.CreateUser(entity.User, entity.Password);
if (user != null)
{
entity.User = user;
entity.Contracts = new List<ContractRest>();
return await base.Save(entity);
}
throw new Exception("User With this email already exists");
}
private async Task<UserRest> CreateUser(UserRest user, string password)
{
var result = await _userHelper.AddUserAsync(Mapper.Map<UserDto>(user), password);
if (result.Succeeded)
{
var userDto = await _userHelper.GetUserByEmailAsync(user.Email);
await _userHelper.AddUserToRoleAsync(userDto, Constans.ROLE_LESSEE);
return Mapper.Map<UserRest>(userDto);
}
return null;
}
}
}
| 34.808511 | 102 | 0.623472 | [
"MIT"
] | JuanchoAnime/MyLeasing | MyLeasing.Api/Core/Application/LesseeApplication.cs | 1,638 | C# |
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Z.Test.EntityFramework.Plus
{
[TestClass]
public partial class QueryCache_UseTagsAsCacheKey
{
}
} | 45.3125 | 191 | 0.769655 | [
"MIT"
] | Ahmed-Abdelhameed/EntityFramework-Plus | src/Z.Test.EntityFramework.Plus.EFCore.Shared/QueryCache/QueryCache_UseTagsAsCacheKey.cs | 728 | C# |
using System;
namespace ChallengeUbistart.Business.Models
{
public class Item : Entity
{
public Guid ClientId { get; set; }
public string Description { get; set; }
public ItemStatus ItemStatus { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime DueDate { get; set; }
public DateTime FinishedAt { get; set; }
/* EF Relations */
public Client Client { get; set; }
}
} | 24.761905 | 50 | 0.590385 | [
"MIT"
] | jadson-medeiros/challengeubistart | src/ChallengeUbistart.Business/Models/Item.cs | 520 | C# |
using System.Collections.Generic;
namespace RestfulApiBestPracticesAspNetCore.Services
{
public class PropertyMappingValue
{
public IEnumerable<string> DestinationProperties { get; private set; }
public bool Revert { get; private set; }
public PropertyMappingValue(IEnumerable<string> destinationProperties,
bool revert = false)
{
DestinationProperties = destinationProperties;
Revert = revert;
}
}
}
| 27.333333 | 78 | 0.668699 | [
"MIT"
] | BionStt/RestfulApiBestPracticesAspNetCore | RestfulApiBestPracticesAspNetCore/Services/PropertyMappingValue.cs | 494 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using VideoApi.Domain.Ddd;
using VideoApi.Domain.Enums;
namespace VideoApi.Domain
{
public class Participant : Entity<Guid>
{
private Participant()
{
Id = Guid.NewGuid();
ParticipantStatuses = new List<ParticipantStatus>();
}
public Participant(Guid participantRefId, string name, string displayName, string username, UserRole userRole,
string caseTypeGroup) : this()
{
ParticipantRefId = participantRefId;
DisplayName = displayName;
Username = username;
UserRole = userRole;
CaseTypeGroup = caseTypeGroup;
Name = name;
}
public Guid ParticipantRefId { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public string Username { get; set; }
public UserRole UserRole { get; set; }
public string CaseTypeGroup { get; set; }
public string Representee { get; set; }
public RoomType? CurrentRoom { get; set; }
public long? TestCallResultId { get; set; }
public virtual TestCallResult TestCallResult { get; private set; }
protected virtual IList<ParticipantStatus> ParticipantStatuses { get; set; }
public IList<ParticipantStatus> GetParticipantStatuses()
{
return ParticipantStatuses;
}
public ParticipantStatus GetCurrentStatus()
{
return ParticipantStatuses.OrderByDescending(x => x.TimeStamp).FirstOrDefault();
}
public void UpdateParticipantStatus(ParticipantState status)
{
ParticipantStatuses.Add(new ParticipantStatus(status));
}
public void UpdateTestCallResult(bool passed, TestScore score)
{
TestCallResult = new TestCallResult(passed, score);
}
public TestCallResult GetTestCallResult()
{
return TestCallResult;
}
public void UpdateCurrentRoom(RoomType? currentRoom)
{
CurrentRoom = currentRoom;
}
public bool IsJudge()
{
return UserRole == UserRole.Judge;
}
public bool IsVideoHearingOfficer()
{
return UserRole == UserRole.VideoHearingsOfficer;
}
}
} | 30.64557 | 118 | 0.605535 | [
"MIT"
] | ryantestgmail/vh-video-api | VideoAPI/VideoApi.Domain/Participant.cs | 2,421 | 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 resource-groups-2017-11-27.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.ResourceGroups.Model
{
/// <summary>
/// This is the response object from the SearchResources operation.
/// </summary>
public partial class SearchResourcesResponse : AmazonWebServiceResponse
{
private string _nextToken;
private List<ResourceIdentifier> _resourceIdentifiers = new List<ResourceIdentifier>();
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The NextToken value to include in a subsequent <code>SearchResources</code> request,
/// to get more results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property ResourceIdentifiers.
/// <para>
/// The ARNs and resource types of resources that are members of the group that you specified.
/// </para>
/// </summary>
public List<ResourceIdentifier> ResourceIdentifiers
{
get { return this._resourceIdentifiers; }
set { this._resourceIdentifiers = value; }
}
// Check to see if ResourceIdentifiers property is set
internal bool IsSetResourceIdentifiers()
{
return this._resourceIdentifiers != null && this._resourceIdentifiers.Count > 0;
}
}
} | 32.631579 | 113 | 0.645968 | [
"Apache-2.0"
] | GitGaby/aws-sdk-net | sdk/src/Services/ResourceGroups/Generated/Model/SearchResourcesResponse.cs | 2,480 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Orchard.Environment.Configuration;
using Orchard.FileSystems.AppData;
using System.IO;
namespace Orchard.Reports.Services {
public class ReportsPersister : IReportsPersister {
private readonly IAppDataFolder _appDataFolder;
private readonly ShellSettings _shellSettings;
private readonly string _reportsFileName;
private readonly DataContractSerializer _dataContractSerializer;
private readonly object _synLock = new object();
public ReportsPersister(IAppDataFolder appDataFolder, ShellSettings shellSettings) {
_appDataFolder = appDataFolder;
_shellSettings = shellSettings;
_dataContractSerializer = new DataContractSerializer(typeof(Report), new [] { typeof(ReportEntry) });
_reportsFileName = Path.Combine(Path.Combine("Sites", _shellSettings.Name), "reports.dat");
}
public IEnumerable<Report> Fetch() {
lock ( _synLock ) {
if ( !_appDataFolder.FileExists(_reportsFileName) ) {
yield break;
}
var text = _appDataFolder.ReadFile(_reportsFileName);
var xmlDocument = XDocument.Parse(text);
var rootNode = xmlDocument.Root;
if (rootNode == null) {
yield break;
}
foreach (var reportNode in rootNode.Elements()) {
var reader = new StringReader(reportNode.Value);
using (var xmlReader = XmlReader.Create(reader)) {
yield return (Report) _dataContractSerializer.ReadObject(xmlReader, true);
}
}
}
}
public void Save(IEnumerable<Report> reports) {
lock ( _synLock ) {
var xmlDocument = new XDocument();
xmlDocument.Add(new XElement("Reports"));
foreach (var report in reports) {
var reportNode = new XElement("Report");
var writer = new StringWriter();
using (var xmlWriter = XmlWriter.Create(writer)) {
_dataContractSerializer.WriteObject(xmlWriter, report);
}
reportNode.Value = writer.ToString();
xmlDocument.Root.Add(reportNode);
}
var saveWriter = new StringWriter();
xmlDocument.Save(saveWriter);
_appDataFolder.CreateFile(_reportsFileName, saveWriter.ToString());
}
}
}
}
| 40.970588 | 114 | 0.568916 | [
"MIT"
] | AccentureRapid/OrchardCollaboration | src/Orchard/Reports/Services/ReportsPersister.cs | 2,788 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
internal class Utils
{
public static string RunProcess(
string path,
string args = "",
IDictionary<string, string>? envVars = null,
string? workingDir = null,
bool ignoreErrors = false)
{
LogInfo($"Running: {path} {args}");
var outputBuilder = new StringBuilder();
var errorBuilder = new StringBuilder();
var processStartInfo = new ProcessStartInfo
{
FileName = path,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
};
if (workingDir != null)
{
processStartInfo.WorkingDirectory = workingDir;
}
if (envVars != null)
{
foreach (KeyValuePair<string, string> envVar in envVars)
{
processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
}
}
Process process = Process.Start(processStartInfo)!;
process.ErrorDataReceived += (sender, e) =>
{
LogError(e.Data);
outputBuilder.AppendLine(e.Data);
errorBuilder.AppendLine(e.Data);
};
process.OutputDataReceived += (sender, e) =>
{
LogInfo(e.Data);
outputBuilder.AppendLine(e.Data);
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("Error: " + errorBuilder);
}
return outputBuilder.ToString().Trim('\r','\n');
}
public static TaskLoggingHelper? Logger { get; set; }
public static void LogInfo(string? msg)
{
if (msg != null)
{
Logger?.LogMessage(MessageImportance.High, msg);
}
}
public static void LogError(string? msg)
{
if (msg != null)
{
Logger?.LogError(msg);
}
}
}
| 26.988636 | 81 | 0.568421 | [
"MIT"
] | 2m0nd/runtime | tools-local/tasks/mobile.tasks/AotCompilerTask/Utils.cs | 2,375 | C# |
/*
* Copyright (c) 2009, 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 names of copyright holders, nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Diagnostics;
using DIaLOGIKa.b2xtranslator.StructuredStorage.Reader;
using DIaLOGIKa.b2xtranslator.Tools;
namespace DIaLOGIKa.b2xtranslator.OfficeGraph
{
/// <summary>
/// This record specifies the beginning of a collection of records as defined by
/// the Chart Sheet Substream ABNF. The collection of records specifies the options
/// of the data table which can be displayed within a chart area.
/// </summary>
[OfficeGraphBiffRecordAttribute(GraphRecordNumber.Dat)]
public class Dat : OfficeGraphBiffRecord
{
public const GraphRecordNumber ID = GraphRecordNumber.Dat;
/// <summary>
/// A bit that specifies whether horizontal cell borders are displayed within the data table.
/// </summary>
public bool fHasBordHorz;
/// <summary>
/// A bit that specifies whether vertical cell borders are displayed within the data table.
/// </summary>
public bool fHasBordVert;
/// <summary>
/// A bit that specifies whether an outside outline is displayed around the data table.
/// </summary>
public bool fHasBordOutline;
/// <summary>
/// A bit that specifies whether the legend key is displayed next to the name of the series.
/// If the value is 1, the legend key symbols are displayed next to the name of the series.
/// </summary>
public bool fShowSeriesKey;
public Dat(IStreamReader reader, GraphRecordNumber id, UInt16 length)
: base(reader, id, length)
{
// assert that the correct record type is instantiated
Debug.Assert(this.Id == ID);
// initialize class members from stream
UInt16 flags = reader.ReadUInt16();
this.fHasBordHorz = Utils.BitmaskToBool(flags, 0x0001);
this.fHasBordVert = Utils.BitmaskToBool(flags, 0x0002);
this.fHasBordOutline = Utils.BitmaskToBool(flags, 0x0004);
this.fShowSeriesKey = Utils.BitmaskToBool(flags, 0x0008);
// assert that the correct number of bytes has been read from the stream
Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position);
}
}
}
| 45.724138 | 102 | 0.677728 | [
"BSD-3-Clause"
] | datadiode/B2XTranslator | src/Common/OfficeGraph/BiffRecords/Dat.cs | 3,980 | C# |
using UnityEngine;
using System.Collections;
public class ColorBlindnessDropdownHandler : MonoBehaviour {
public ColorBlindnessController ctrlr;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnValueChanged(int index) {
print ("Picked: " + index);
if (ctrlr != null) {
print ("setting ctrlr");
ctrlr.setEffect (index);
}
}
}
| 14.3 | 60 | 0.675991 | [
"MIT"
] | imtc-gatech/UnityVisionLossTools | Assets/UnityColorBlindness/Scripts/ColorBlindnessDropdownHandler.cs | 431 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.ResourceManager.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
/// <summary>
/// Provides operations for working with resources and resource groups.
/// </summary>
public partial interface IResourceManagementClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// The ID of the target subscription.
/// </summary>
string SubscriptionId { get; set; }
/// <summary>
/// The API version to use for this operation.
/// </summary>
string ApiVersion { get; }
/// <summary>
/// The preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default
/// value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When
/// set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
IOperations Operations { get; }
/// <summary>
/// Gets the IDeploymentsOperations.
/// </summary>
IDeploymentsOperations Deployments { get; }
/// <summary>
/// Gets the IProvidersOperations.
/// </summary>
IProvidersOperations Providers { get; }
/// <summary>
/// Gets the IResourcesOperations.
/// </summary>
IResourcesOperations Resources { get; }
/// <summary>
/// Gets the IResourceGroupsOperations.
/// </summary>
IResourceGroupsOperations ResourceGroups { get; }
/// <summary>
/// Gets the ITagsOperations.
/// </summary>
ITagsOperations Tags { get; }
/// <summary>
/// Gets the IDeploymentOperations.
/// </summary>
IDeploymentOperations DeploymentOperations { get; }
}
}
| 29.476636 | 78 | 0.581167 | [
"MIT"
] | HarveyLink/azure-libraries-for-net | src/ResourceManagement/ResourceManager/Generated/IResourceManagementClient.cs | 3,154 | C# |
//
// Copyright (c) 2017-2019 the rbfx project.
//
// 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.
//
namespace Urho3DNet
{
public partial class Node
{
public T CreateComponent<T>(CreateMode mode = CreateMode.Replicated, uint id = 0) where T: Component
{
return (T)CreateComponent(typeof(T).Name, mode, id);
}
public T GetComponent<T>(bool recursive) where T: Component
{
return (T)GetComponent(typeof(T).Name, recursive);
}
/// <summary>
/// Get first occurrence of a component type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetComponent<T>() where T: Component
{
return (T)GetComponent(typeof(T).Name);
}
/// <summary>
/// get all components of a type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public ComponentList GetComponents<T>(bool recursive = false) where T: Component
{
ComponentList componentList = new ComponentList();
GetComponents(componentList, typeof(T).Name, recursive);
return componentList;
}
}
}
| 38 | 108 | 0.657895 | [
"MIT"
] | mostafa901/rbfx | Source/Urho3D/CSharp/Managed/Scene/Node.cs | 2,280 | C# |
// NOTE: to match Mesen timings, set idleSynch to true at power on, and set start_up_offset to -3
using System;
using System.Linq;
using BizHawk.Common;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Components.M6502;
#pragma warning disable 162
namespace BizHawk.Emulation.Cores.Nintendo.NES
{
public partial class NES : IEmulator, ISoundProvider, ICycleTiming
{
//hardware/state
public MOS6502X<CpuLink> cpu;
public PPU ppu;
public APU apu;
public byte[] ram;
public byte[] CIRAM; //AKA nametables
string game_name = ""; //friendly name exposed to user and used as filename base
internal CartInfo cart; //the current cart prototype. should be moved into the board, perhaps
internal INesBoard Board; //the board hardware that is currently driving things
EDetectionOrigin origin = EDetectionOrigin.None;
int sprdma_countdown;
public bool _irq_apu; //various irq signals that get merged to the cpu irq pin
/// <summary>clock speed of the main cpu in hz</summary>
public int cpuclockrate { get; private set; }
//user configuration
public int[] palette_compiled = new int[64 * 8];
//variable set when VS system games are running
internal bool _isVS = false;
//some VS games have a ppu that switches 2000 and 2001, so keep trcak of that
public byte _isVS2c05 = 0;
//since prg reg for VS System is set in the controller regs, it is convenient to have it here
//instead of in the board
public byte VS_chr_reg;
public byte VS_prg_reg;
//various VS controls
public byte[] VS_dips = new byte[8];
public byte VS_service = 0;
public byte VS_coin_inserted=0;
public byte VS_ROM_control;
// cheat addr index tracker
// disables all cheats each frame
public int[] cheat_addresses = new int[0x1000];
public byte[] cheat_value = new byte[0x1000];
public int[] cheat_compare_val = new int[0x1000];
public int[] cheat_compare_type = new int[0x1000];
public int num_cheats;
// new input system
NESControlSettings ControllerSettings; // this is stored internally so that a new change of settings won't replace
IControllerDeck ControllerDeck;
byte latched4016;
private DisplayType _display_type = DisplayType.NTSC;
//Sound config
public void SetVol1(int v) { apu.m_vol = v; }
BlipBuffer blip = new BlipBuffer(4096);
const int blipbuffsize = 4096;
public int old_s = 0;
public bool CanProvideAsync => false;
public void SetSyncMode(SyncSoundMode mode)
{
if (mode != SyncSoundMode.Sync)
{
throw new NotSupportedException("Only sync mode is supported");
}
}
public void GetSamplesAsync(short[] samples)
{
throw new NotSupportedException("Async not supported");
}
public SyncSoundMode SyncMode => SyncSoundMode.Sync;
public void Dispose()
{
if (blip != null)
{
blip.Dispose();
blip = null;
}
}
public void GetSamplesSync(out short[] samples, out int nsamp)
{
blip.EndFrame(apu.sampleclock);
apu.sampleclock = 0;
nsamp = blip.SamplesAvailable();
samples = new short[nsamp * 2];
blip.ReadSamples(samples, nsamp, true);
// duplicate to stereo
for (int i = 0; i < nsamp * 2; i += 2)
samples[i + 1] = samples[i];
Board.ApplyCustomAudio(samples);
}
public void DiscardSamples()
{
blip.Clear();
apu.sampleclock = 0;
}
public void HardReset()
{
cpu = new MOS6502X<CpuLink>(new CpuLink(this))
{
BCD_Enabled = false
};
ppu = new PPU(this);
ram = new byte[0x800];
CIRAM = new byte[0x800];
// wire controllers
// todo: allow changing this
ControllerDeck = ControllerSettings.Instantiate(ppu.LightGunCallback);
// set controller definition first time only
if (ControllerDefinition == null)
{
ControllerDefinition = new ControllerDefinition(ControllerDeck.GetDefinition())
{
Name = "NES Controller"
};
// controls other than the deck
ControllerDefinition.BoolButtons.Add("Power");
ControllerDefinition.BoolButtons.Add("Reset");
if (Board is FDS b)
{
ControllerDefinition.BoolButtons.Add("FDS Eject");
for (int i = 0; i < b.NumSides; i++)
{
ControllerDefinition.BoolButtons.Add("FDS Insert " + i);
}
}
if (_isVS)
{
ControllerDefinition.BoolButtons.Add("Insert Coin P1");
ControllerDefinition.BoolButtons.Add("Insert Coin P2");
ControllerDefinition.BoolButtons.Add("Service Switch");
}
}
// Add in the reset timing axis for subneshawk
if (using_reset_timing && ControllerDefinition.Axes.Count == 0)
{
ControllerDefinition.AddAxis("Reset Cycle", 0.RangeTo(500000), 0);
}
// don't replace the magicSoundProvider on reset, as it's not needed
// if (magicSoundProvider != null) magicSoundProvider.Dispose();
// set up region
switch (_display_type)
{
case DisplayType.PAL:
apu = new APU(this, apu, true);
ppu.region = PPU.Region.PAL;
VsyncNum = 50;
VsyncDen = 1;
cpuclockrate = 1662607;
cpu_sequence = cpu_sequence_PAL;
_display_type = DisplayType.PAL;
ClockRate = 5320342.5;
break;
case DisplayType.NTSC:
apu = new APU(this, apu, false);
ppu.region = PPU.Region.NTSC;
VsyncNum = 39375000;
VsyncDen = 655171;
cpuclockrate = 1789773;
cpu_sequence = cpu_sequence_NTSC;
ClockRate = 5369318.1818181818181818181818182;
break;
// this is in bootgod, but not used at all
case DisplayType.Dendy:
apu = new APU(this, apu, false);
ppu.region = PPU.Region.Dendy;
VsyncNum = 50;
VsyncDen = 1;
cpuclockrate = 1773448;
cpu_sequence = cpu_sequence_NTSC;
_display_type = DisplayType.Dendy;
ClockRate = 5320342.5;
break;
default:
throw new Exception("Unknown displaytype!");
}
blip.SetRates((uint)cpuclockrate, 44100);
BoardSystemHardReset();
// apu has some specific power up bahaviour that we will emulate here
apu.NESHardReset();
if (SyncSettings.InitialWRamStatePattern != null && SyncSettings.InitialWRamStatePattern.Any())
{
for (int i = 0; i < 0x800; i++)
{
ram[i] = SyncSettings.InitialWRamStatePattern[i % SyncSettings.InitialWRamStatePattern.Count];
}
}
else
{
// check fceux's PowerNES and FCEU_MemoryRand function for more information:
// relevant games: Cybernoid; Minna no Taabou no Nakayoshi Daisakusen; Huang Di; and maybe mechanized attack
for (int i = 0; i < 0x800; i++)
{
if ((i & 4) != 0)
{
ram[i] = 0xFF;
}
else
{
ram[i] = 0x00;
}
}
}
SetupMemoryDomains();
// some boards cannot have specific values in RAM upon initialization
// Let's hard code those cases here
// these will be defined through the gameDB exclusively for now.
if (cart.GameInfo!=null)
{
if (cart.GameInfo.Hash == "60FC5FA5B5ACCAF3AEFEBA73FC8BFFD3C4DAE558" // Camerica Golden 5
|| cart.GameInfo.Hash == "BAD382331C30B22A908DA4BFF2759C25113CC26A" // Camerica Golden 5
|| cart.GameInfo.Hash == "40409FEC8249EFDB772E6FFB2DCD41860C6CCA23" // Camerica Pegasus 4-in-1
)
{
ram[0x701] = 0xFF;
}
if (cart.GameInfo.Hash == "68ABE1E49C9E9CCEA978A48232432C252E5912C0") // Dancing Blocks
{
ram[0xEC] = 0;
ram[0xED] = 0;
}
if (cart.GameInfo.Hash == "00C50062A2DECE99580063777590F26A253AAB6B") // Silva Saga
{
for (int i = 0; i < Board.Wram.Length; i++)
{
Board.Wram[i] = 0xFF;
}
}
}
}
public long CycleCount => ppu.TotalCycles;
public double ClockRate { get; private set; }
private int VsyncNum { get; set; }
private int VsyncDen { get; set; }
private IController _controller = NullController.Instance;
bool resetSignal;
bool hardResetSignal;
public bool FrameAdvance(IController controller, bool render, bool rendersound)
{
_controller = controller;
if (Tracer.Enabled)
cpu.TraceCallback = s => Tracer.Put(s);
else
cpu.TraceCallback = null;
lagged = true;
if (resetSignal)
{
Board.NesSoftReset();
cpu.NESSoftReset();
apu.NESSoftReset();
ppu.NESSoftReset();
}
else if (hardResetSignal)
{
HardReset();
}
Frame++;
//if (resetSignal)
//Controller.UnpressButton("Reset"); TODO fix this
resetSignal = controller.IsPressed("Reset");
hardResetSignal = controller.IsPressed("Power");
if (Board is FDS)
{
var b = Board as FDS;
if (controller.IsPressed("FDS Eject"))
b.Eject();
for (int i = 0; i < b.NumSides; i++)
if (controller.IsPressed("FDS Insert " + i))
b.InsertSide(i);
}
if (_isVS)
{
if (controller.IsPressed("Service Switch"))
VS_service = 1;
else
VS_service = 0;
if (controller.IsPressed("Insert Coin P1"))
VS_coin_inserted |= 1;
else
VS_coin_inserted &= 2;
if (controller.IsPressed("Insert Coin P2"))
VS_coin_inserted |= 2;
else
VS_coin_inserted &= 1;
}
if (ppu.ppudead > 0)
{
while (ppu.ppudead > 0)
{
ppu.NewDeadPPU();
}
}
else
{
// do the vbl ticks seperate, that will save us a few checks that don't happen in active region
while (ppu.do_vbl)
{
ppu.TickPPU_VBL();
}
// now do the rest of the frame
while (ppu.do_active_sl)
{
ppu.TickPPU_active();
}
// now do the pre-NMI lines
while (ppu.do_pre_vbl)
{
ppu.TickPPU_preVBL();
}
}
if (lagged)
{
_lagcount++;
islag = true;
}
else
islag = false;
videoProvider.FillFrameBuffer();
// turn off all cheats
// any cheats still active will be re-applied by the buspoke at the start of the next frame
num_cheats = 0;
return true;
}
// these variables are for subframe input control
public bool controller_was_latched;
public bool frame_is_done;
public bool current_strobe;
public bool new_strobe;
public bool alt_lag;
// variable used with subneshawk to trigger reset at specific cycle after reset
public bool using_reset_timing = false;
// this function will run one step of the ppu
// it will return whether the controller is read or not.
public void do_single_step(IController controller, out bool cont_read, out bool frame_done)
{
_controller = controller;
controller_was_latched = false;
frame_is_done = false;
current_strobe = new_strobe;
if (ppu.ppudead > 0)
{
ppu.NewDeadPPU();
}
else if (ppu.do_vbl)
{
ppu.TickPPU_VBL();
}
else if (ppu.do_active_sl)
{
ppu.TickPPU_active();
}
else if (ppu.do_pre_vbl)
{
ppu.TickPPU_preVBL();
}
cont_read = controller_was_latched;
frame_done = frame_is_done;
}
//PAL:
//sequence of ppu clocks per cpu clock: 3,3,3,3,4
//at least it should be, but something is off with that (start up time?) so it is 3,3,3,4,3 for now
//NTSC:
//sequence of ppu clocks per cpu clock: 3
public byte[] cpu_sequence;
static byte[] cpu_sequence_NTSC = { 3, 3, 3, 3, 3 };
static byte[] cpu_sequence_PAL = { 3, 3, 3, 4, 3 };
public int cpu_deadcounter;
public int oam_dma_index;
public bool oam_dma_exec = false;
public ushort oam_dma_addr;
public byte oam_dma_byte;
public bool dmc_dma_exec = false;
public bool dmc_realign;
public bool IRQ_delay;
public bool special_case_delay; // very ugly but the only option
public bool do_the_reread;
public byte DB; //old data bus values from previous reads
internal void RunCpuOne()
{
///////////////////////////
// OAM DMA start
///////////////////////////
if (oam_dma_exec && apu.dmc_dma_countdown != 1 && !dmc_realign)
{
if (cpu_deadcounter == 0)
{
if (oam_dma_index % 2 == 0)
{
oam_dma_byte = ReadMemory(oam_dma_addr);
oam_dma_addr++;
}
else
{
WriteMemory(0x2004, oam_dma_byte);
}
oam_dma_index++;
if (oam_dma_index == 512) oam_dma_exec = false;
}
else
{
cpu_deadcounter--;
}
}
dmc_realign = false;
/////////////////////////////
// OAM DMA end
/////////////////////////////
/////////////////////////////
// dmc dma start
/////////////////////////////
if (apu.dmc_dma_countdown > 0)
{
if (apu.dmc_dma_countdown == 1)
{
dmc_realign = true;
}
cpu.RDY = false;
dmc_dma_exec = true;
apu.dmc_dma_countdown--;
if (apu.dmc_dma_countdown == 0)
{
apu.RunDMCFetch();
dmc_dma_exec = false;
apu.dmc_dma_countdown = -1;
do_the_reread = true;
}
}
/////////////////////////////
// dmc dma end
/////////////////////////////
apu.RunOneFirst();
if (cpu.RDY && !IRQ_delay)
{
cpu.IRQ = _irq_apu || Board.IrqSignal;
}
else if (special_case_delay || apu.dmc_dma_countdown == 3)
{
cpu.IRQ = _irq_apu || Board.IrqSignal;
special_case_delay = false;
}
cpu.ExecuteOne();
Board.ClockCpu();
int s = apu.EmitSample();
if (s != old_s)
{
blip.AddDelta(apu.sampleclock, s - old_s);
old_s = s;
}
apu.sampleclock++;
apu.RunOneLast();
if (do_the_reread && cpu.RDY)
do_the_reread = false;
IRQ_delay = false;
if (!dmc_dma_exec && !oam_dma_exec && !cpu.RDY)
{
cpu.RDY = true;
IRQ_delay = true;
}
}
public byte ReadReg(int addr)
{
byte ret_spec;
switch (addr)
{
case 0x4000:
case 0x4001:
case 0x4002:
case 0x4003:
case 0x4004:
case 0x4005:
case 0x4006:
case 0x4007:
case 0x4008:
case 0x4009:
case 0x400A:
case 0x400B:
case 0x400C:
case 0x400D:
case 0x400E:
case 0x400F:
case 0x4010:
case 0x4011:
case 0x4012:
case 0x4013:
return DB;
//return apu.ReadReg(addr);
case 0x4014: /*OAM DMA*/ break;
case 0x4015: return (byte)((byte)(apu.ReadReg(addr) & 0xDF) + (byte)(DB & 0x20));
case 0x4016:
if (_isVS)
{
byte ret = 0;
ret = read_joyport(0x4016);
ret &= 1;
ret = (byte)(ret | (VS_service << 2) | (VS_dips[0] << 3) | (VS_dips[1] << 4) | (VS_coin_inserted << 5) | (VS_ROM_control<<7));
return ret;
}
else
{
// special hardware glitch case
ret_spec = read_joyport(addr);
if (do_the_reread && ppu.region==PPU.Region.NTSC)
{
ret_spec = read_joyport(addr);
do_the_reread = false;
}
return ret_spec;
}
case 0x4017:
if (_isVS)
{
byte ret = 0;
ret = read_joyport(0x4017);
ret &= 1;
ret = (byte)(ret | (VS_dips[2] << 2) | (VS_dips[3] << 3) | (VS_dips[4] << 4) | (VS_dips[5] << 5) | (VS_dips[6] << 6) | (VS_dips[7] << 7));
return ret;
}
else
{
// special hardware glitch case
ret_spec = read_joyport(addr);
if (do_the_reread && ppu.region == PPU.Region.NTSC)
{
ret_spec = read_joyport(addr);
do_the_reread = false;
}
return ret_spec;
}
default:
//Console.WriteLine("read register: {0:x4}", addr);
break;
}
return DB;
}
public byte PeekReg(int addr)
{
switch (addr)
{
case 0x4000:
case 0x4001:
case 0x4002:
case 0x4003:
case 0x4004:
case 0x4005:
case 0x4006:
case 0x4007:
case 0x4008:
case 0x4009:
case 0x400A:
case 0x400B:
case 0x400C:
case 0x400D:
case 0x400E:
case 0x400F:
case 0x4010:
case 0x4011:
case 0x4012:
case 0x4013:
return apu.PeekReg(addr);
case 0x4014: /*OAM DMA*/ break;
case 0x4015: return apu.PeekReg(addr);
case 0x4016:
case 0x4017:
return peek_joyport(addr);
default:
//Console.WriteLine("read register: {0:x4}", addr);
break;
}
return 0xFF;
}
void WriteReg(int addr, byte val)
{
switch (addr)
{
case 0x4000:
case 0x4001:
case 0x4002:
case 0x4003:
case 0x4004:
case 0x4005:
case 0x4006:
case 0x4007:
case 0x4008:
case 0x4009:
case 0x400A:
case 0x400B:
case 0x400C:
case 0x400D:
case 0x400E:
case 0x400F:
case 0x4010:
case 0x4011:
case 0x4012:
case 0x4013:
apu.WriteReg(addr, val);
break;
case 0x4014:
//schedule a sprite dma event for beginning 1 cycle in the future.
//this receives 2 because that's just the way it works out.
oam_dma_addr = (ushort)(val << 8);
sprdma_countdown = 1;
if (sprdma_countdown > 0)
{
sprdma_countdown--;
if (sprdma_countdown == 0)
{
if (cpu.TotalExecutedCycles % 2 == 0)
{
cpu_deadcounter = 2;
}
else
{
cpu_deadcounter = 1;
}
oam_dma_exec = true;
cpu.RDY = false;
oam_dma_index = 0;
special_case_delay = true;
}
}
break;
case 0x4015: apu.WriteReg(addr, val); break;
case 0x4016:
if (_isVS)
{
write_joyport(val);
VS_chr_reg = (byte)((val & 0x4)>>2);
//TODO: does other stuff for dual system
//this is actually different then assignment
VS_prg_reg = (byte)((val & 0x4)>>2);
}
else
{
write_joyport(val);
}
break;
case 0x4017: apu.WriteReg(addr, val); break;
default:
//Console.WriteLine("wrote register: {0:x4} = {1:x2}", addr, val);
break;
}
}
void write_joyport(byte value)
{
var si = new StrobeInfo(latched4016, value);
ControllerDeck.Strobe(si, _controller);
latched4016 = value;
new_strobe = (value & 1) > 0;
if (current_strobe && !new_strobe)
{
controller_was_latched = true;
alt_lag = false;
}
}
byte read_joyport(int addr)
{
InputCallbacks.Call();
lagged = false;
byte ret;
if (_isVS)
{
// for whatever reason, in VS left and right controller have swapped regs
ret = addr == 0x4017 ? ControllerDeck.ReadA(_controller) : ControllerDeck.ReadB(_controller);
}
else
{
ret = addr == 0x4016 ? ControllerDeck.ReadA(_controller) : ControllerDeck.ReadB(_controller);
}
ret &= 0x1f;
ret |= (byte)(0xe0 & DB);
return ret;
}
byte peek_joyport(int addr)
{
// at the moment, the new system doesn't support peeks
return 0;
}
/// <summary>
/// Sets the provided palette as current.
/// Applies the current deemph settings if needed to expand a 64-entry palette to 512
/// </summary>
public void SetPalette(byte[,] pal)
{
int nColors = pal.GetLength(0);
int nElems = pal.GetLength(1);
if (nColors == 512)
{
//just copy the palette directly
for (int c = 0; c < 64 * 8; c++)
{
int r = pal[c, 0];
int g = pal[c, 1];
int b = pal[c, 2];
palette_compiled[c] = (int)unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
}
}
else
{
//expand using deemph
for (int i = 0; i < 64 * 8; i++)
{
int d = i >> 6;
int c = i & 63;
int r = pal[c, 0];
int g = pal[c, 1];
int b = pal[c, 2];
Palettes.ApplyDeemphasis(ref r, ref g, ref b, d);
palette_compiled[i] = (int)unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
}
}
}
/// <summary>
/// looks up an internal NES pixel value to an rgb int (applying the core's current palette and assuming no deemph)
/// </summary>
public int LookupColor(int pixel)
{
return palette_compiled[pixel];
}
public byte DummyReadMemory(ushort addr) { return 0; }
public void ApplySystemBusPoke(int addr, byte value)
{
if (addr < 0x2000)
{
ram[(addr & 0x7FF)] = value;
}
else if (addr < 0x4000)
{
ppu.WriteReg(addr, value);
}
else if (addr < 0x4020)
{
WriteReg(addr, value);
}
else if (addr < 0x6000)
{
//let's ignore pokes to EXP until someone asks for it. there's really almost no way that could ever be done without the board having a PokeEXP method
}
else if (addr < 0x8000)
{
Board.WriteWram(addr - 0x6000, value);
}
else
{
// apply a cheat to non-writable memory
ApplyCheat(addr, value);
}
}
public byte PeekMemory(ushort addr)
{
byte ret;
if (addr >= 0x4020)
{
//easy optimization, since rom reads are so common, move this up (reordering the rest of these elseifs is not easy)
ret = Board.PeekCart(addr);
}
else if (addr < 0x0800)
{
ret = ram[addr];
}
else if (addr < 0x2000)
{
ret = ram[addr & 0x7FF];
}
else if (addr < 0x4000)
{
ret = Board.PeekReg2xxx(addr);
}
else if (addr < 0x4020)
{
ret = PeekReg(addr); //we're not rebasing the register just to keep register names canonical
}
else
{
throw new Exception("Woopsie-doodle!");
ret = 0xFF;
}
return ret;
}
public void ExecFetch(ushort addr)
{
if (MemoryCallbacks.HasExecutes)
{
uint flags = (uint)(MemoryCallbackFlags.CPUZero | MemoryCallbackFlags.AccessExecute);
MemoryCallbacks.CallMemoryCallbacks(addr, 0, flags, "System Bus");
}
}
public byte ReadMemory(ushort addr)
{
byte ret;
if (addr >= 0x8000)
{
// easy optimization, since rom reads are so common, move this up (reordering the rest of these else ifs is not easy)
ret = Board.ReadPrg(addr - 0x8000);
// handle cheats, currently all cheats are of game genie style only
if (num_cheats != 0)
{
for (int i = 0; i < num_cheats; i++)
{
if (cheat_addresses[i] == addr)
{
if (cheat_compare_type[i] == 0)
{
ret = cheat_value[i];
}
else if ((cheat_compare_type[i] == 1) && ((int)ret == cheat_compare_val[i]))
{
ret = cheat_value[i];
}
}
}
}
}
else if (addr < 0x0800)
{
ret = ram[addr];
}
else if (addr < 0x2000)
{
ret = ram[addr & 0x7FF];
}
else if (addr < 0x4000)
{
ret = Board.ReadReg2xxx(addr);
}
else if (addr < 0x4020)
{
ret = ReadReg(addr); // we're not rebasing the register just to keep register names canonical
}
else if (addr < 0x6000)
{
ret = Board.ReadExp(addr - 0x4000);
}
else
{
ret = Board.ReadWram(addr - 0x6000);
}
if (MemoryCallbacks.HasReads)
{
uint flags = (uint)(MemoryCallbackFlags.CPUZero | MemoryCallbackFlags.AccessRead);
MemoryCallbacks.CallMemoryCallbacks(addr, ret, flags, "System Bus");
}
DB = ret;
return ret;
}
public void ApplyCheat(int addr, byte value)
{
if (addr <= 0xFFFF)
{
cheat_addresses[num_cheats] = addr;
cheat_value[num_cheats] = value;
// there is no compare here
cheat_compare_val[num_cheats] = -1;
cheat_compare_type[num_cheats] = 0;
if (num_cheats < 0x1000) { num_cheats++; }
}
}
public void ApplyCompareCheat(int addr, byte value, int compare, int comparetype)
{
if (addr <= 0xFFFF)
{
cheat_addresses[num_cheats] = addr;
cheat_value[num_cheats] = value;
cheat_compare_val[num_cheats] = compare;
cheat_compare_type[num_cheats] = comparetype;
if (num_cheats < 0x1000) { num_cheats++; }
}
}
public void WriteMemory(ushort addr, byte value)
{
if (addr < 0x0800)
{
ram[addr] = value;
}
else if (addr < 0x2000)
{
ram[addr & 0x7FF] = value;
}
else if (addr < 0x4000)
{
Board.WriteReg2xxx(addr, value);
}
else if (addr < 0x4020)
{
WriteReg(addr, value); //we're not rebasing the register just to keep register names canonical
}
else if (addr < 0x6000)
{
Board.WriteExp(addr - 0x4000, value);
}
else if (addr < 0x8000)
{
Board.WriteWram(addr - 0x6000, value);
}
else
{
Board.WritePrg(addr - 0x8000, value);
}
if (MemoryCallbacks.HasWrites)
{
uint flags = (uint)(MemoryCallbackFlags.CPUZero | MemoryCallbackFlags.AccessWrite | MemoryCallbackFlags.SizeByte);
MemoryCallbacks.CallMemoryCallbacks(addr, value, flags, "System Bus");
}
}
// the palette for each VS game needs to be chosen explicitly since there are 6 different ones.
public void PickVSPalette(CartInfo cart)
{
switch (cart.Palette)
{
case "2C05": SetPalette(Palettes.palette_2c03_2c05); ppu.CurrentLuma = PPU.PaletteLuma2C03; break;
case "2C04-1": SetPalette(Palettes.palette_2c04_001); ppu.CurrentLuma = PPU.PaletteLuma2C04_1; break;
case "2C04-2": SetPalette(Palettes.palette_2c04_002); ppu.CurrentLuma = PPU.PaletteLuma2C04_2; break;
case "2C04-3": SetPalette(Palettes.palette_2c04_003); ppu.CurrentLuma = PPU.PaletteLuma2C04_3; break;
case "2C04-4": SetPalette(Palettes.palette_2c04_004); ppu.CurrentLuma = PPU.PaletteLuma2C04_4; break;
}
//since this will run for every VS game, let's get security setting too
//values below 16 are for the 2c05 PPU
//values 16,32,48 are for Namco games and dealt with in mapper 206
_isVS2c05 = (byte)(cart.VsSecurity & 15);
}
}
}
| 24.672381 | 154 | 0.594959 | [
"MIT"
] | Qapples/BizHawk | src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.Core.cs | 25,906 | C# |
using System.Collections.Generic;
using ActionsOnGoogle.Core.v2.Response;
namespace WebApplicationAPI.Helpers
{
} | 17.142857 | 39 | 0.8 | [
"Apache-2.0"
] | LindaLawton/actions-on-google-dotnet | src/WebApplicationAPI/Helpers/Responsebuilder.cs | 122 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
namespace Platinum.Resolver
{
/// <summary />
public class UrlResolver : XmlUrlResolver
{
private bool _collect;
private List<Uri> _uri;
/// <summary>
/// Initializes a new instance of the UrlResolver class, defaulting
/// to not collecting URI which are resolved by the instance.
/// </summary>
public UrlResolver()
{
_collect = false;
}
/// <summary>
/// Initializes a new instance of the UrlResolver class.
/// </summary>
/// <param name="collect">Whether to collect URI which are resolved by
/// this instance.</param>
public UrlResolver( bool collect )
{
_collect = collect;
if ( collect == true )
_uri = new List<Uri>();
}
/// <summary>
/// Returns a list of all collected URI which use the file scheme.
/// </summary>
/// <returns>List of file URI which were collected by resolver. If the
/// resolver was configured with collection off, then returns null.</returns>
public List<string> GetFileUri()
{
if ( _collect == false )
return null;
return _uri
.FindAll( i => i.Scheme == "file" )
.Select( i => i.PathAndQuery )
.ToList();
}
/// <summary>
/// Maps a URI to an object containing the actual resource.
/// </summary>
/// <param name="absoluteUri">The URI returned from <see cref="ResolveUri"/>.</param>
/// <param name="role">The current implementation does not use this parameter when resolving URIs.
/// This is provided for future extensibility purposes. For example, this can
/// be mapped to the xlink: role and used as an implementation specific argument
/// in other scenarios.</param>
/// <param name="ofObjectToReturn">The type of object to return. The current implementation
/// only returns <see cref="Stream"/> objects.</param>
/// <returns>A <see cref="Stream"/> object or null if a type other than stream is specified.</returns>
public override object GetEntity( Uri absoluteUri, string role, Type ofObjectToReturn )
{
if ( absoluteUri == null )
return base.GetEntity( absoluteUri, role, ofObjectToReturn );
if ( absoluteUri.Scheme == "assembly" )
{
string assemblyName = absoluteUri.Segments[ 1 ].TrimEnd( '/' );
string resourceName;
if ( absoluteUri.Segments[ 2 ] == "~/" )
resourceName = assemblyName;
else
resourceName = absoluteUri.Segments[ 2 ].TrimEnd( '/' );
for ( int i=3; i< absoluteUri.Segments.Length; i++ )
resourceName = resourceName + "." + absoluteUri.Segments[ i ].TrimEnd( '/' );
Assembly assembly = Assembly.Load( assemblyName );
Stream stream = assembly.GetManifestResourceStream( resourceName );
if ( stream == null )
throw new ResolverException( ER.UrlResolver_Assembly_ResourceNotFound, assemblyName, resourceName );
return stream;
}
else
{
return base.GetEntity( absoluteUri, role, ofObjectToReturn );
}
}
/// <summary>
/// Maps a URI to an object containing the actual resource.
/// </summary>
/// <param name="absoluteUri">The URI returned from <see cref="ResolveUri"/>.</param>
/// <returns>A <see cref="Stream"/> object.</returns>
public Stream GetEntity( Uri absoluteUri )
{
return (Stream) GetEntity( absoluteUri, null, typeof( Stream ) );
}
/// <summary>
/// Resolves the absolute URI from the base and relative URIs.
/// </summary>
/// <param name="baseUri">The base URI used to resolve the relative URI.</param>
/// <param name="relativeUri">The URI to resolve. The URI can be absolute or relative.
/// If absolute, this value effectively replaces the baseUri value. If relative, it
/// combines with the baseUri to make an absolute URI.</param>
/// <returns>A <see cref="Uri"/> representing the absolute URI, or null if the relative
/// URI cannot be resolved.</returns>
public override Uri ResolveUri( Uri baseUri, string relativeUri )
{
IUrlResolver resolver = GetResolver( baseUri, relativeUri );
Uri uri;
if ( resolver == null )
uri = base.ResolveUri( baseUri, relativeUri );
else
uri = resolver.ResolveUri( baseUri, relativeUri );
if ( _collect == true )
{
lock ( this )
{
if ( _uri.Contains( uri ) == false )
_uri.Add( uri );
}
}
return uri;
}
private static IUrlResolver GetResolver( Uri baseUri, string relativeUri )
{
Uri theUri = baseUri;
if ( baseUri == null )
theUri = new Uri( relativeUri );
/*
*
*/
ResolverDefinition rc = ResolverConfiguration.Current.CustomResolvers
.SingleOrDefault( i => i.Scheme == theUri.Scheme );
if ( rc == null )
return null;
if ( rc.ResolverInstance != null )
return rc.ResolverInstance;
/*
*
*/
IUrlResolver resolver;
try
{
resolver = Activator.Create<IUrlResolver>( rc.Moniker );
}
catch ( ActorException ex )
{
throw new ResolverException( ER.UrlResolver_InvalidCustomResolver, ex, rc.Scheme, rc.Moniker );
}
/*
*
*/
if ( rc.ResolverInstance != null )
{
lock ( rc.ResolverInstance )
{
if ( rc.ResolverInstance != null )
{
rc.ResolverInstance = resolver;
}
}
}
return resolver;
}
}
}
/* eof */ | 33.11 | 120 | 0.523558 | [
"BSD-3-Clause"
] | filipetoscano/Platinum | src/Platinum.Core/Resolver/UrlResolver.cs | 6,624 | C# |
using UnityEngine;
public abstract class AStateModifier : ScriptableObject
{
public float time = 10f;
public float cooldown = 20f;
[Range(0, 1)] public float cost = 0.5f;
[TextArea] public string description;
public abstract void Apply(State state);
} | 23.545455 | 55 | 0.749035 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Aggrathon/Ludum-Dare-43 | Assets/Scripts/AStateModifier.cs | 261 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215
{
using static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Extensions;
/// <summary>The Kusto SKU description of given resource type</summary>
public partial class SkuDescription
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ISkuDescription.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ISkuDescription.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ISkuDescription FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json ? new SkuDescription(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject into a new instance of <see cref="SkuDescription" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject instance to deserialize from.</param>
internal SkuDescription(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_locationInfo = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonArray>("locationInfo"), out var __jsonLocationInfo) ? If( __jsonLocationInfo as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonArray, out var __v) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ISkuLocationInfoItem[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ISkuLocationInfoItem) (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.SkuLocationInfoItem.FromJson(__u) )) ))() : null : LocationInfo;}
{_location = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonArray>("locations"), out var __jsonLocations) ? If( __jsonLocations as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonArray, out var __q) ? new global::System.Func<string[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__q, (__p)=>(string) (__p is Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString __o ? (string)(__o.ToString()) : null)) ))() : null : Location;}
{_resourceType = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString>("resourceType"), out var __jsonResourceType) ? (string)__jsonResourceType : (string)ResourceType;}
{_restriction = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonArray>("restrictions"), out var __jsonRestrictions) ? If( __jsonRestrictions as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonArray, out var __l) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ISkuDescriptionRestrictionsItem[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ISkuDescriptionRestrictionsItem) (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.SkuDescriptionRestrictionsItem.FromJson(__k) )) ))() : null : Restriction;}
{_tier = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString>("tier"), out var __jsonTier) ? (string)__jsonTier : (string)Tier;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="SkuDescription" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="SkuDescription" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeReadOnly))
{
if (null != this._locationInfo)
{
var __w = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.XNodeArray();
foreach( var __x in this._locationInfo )
{
AddIf(__x?.ToJson(null, serializationMode) ,__w.Add);
}
container.Add("locationInfo",__w);
}
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeReadOnly))
{
if (null != this._location)
{
var __r = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.XNodeArray();
foreach( var __s in this._location )
{
AddIf(null != (((object)__s)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString(__s.ToString()) : null ,__r.Add);
}
container.Add("locations",__r);
}
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._resourceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString(this._resourceType.ToString()) : null, "resourceType" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeReadOnly))
{
if (null != this._restriction)
{
var __m = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.XNodeArray();
foreach( var __n in this._restriction )
{
AddIf(__n?.ToJson(null, serializationMode) ,__m.Add);
}
container.Add("restrictions",__m);
}
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._tier)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString(this._tier.ToString()) : null, "tier" ,container.Add );
}
AfterToJson(ref container);
return container;
}
}
} | 77.130719 | 710 | 0.668164 | [
"MIT"
] | Arsasana/azure-powershell | src/Kusto/generated/api/Models/Api20200215/SkuDescription.json.cs | 11,649 | C# |
namespace Com.Zoho.Crm.API.Notes
{
public interface ActionHandler
{
}
} | 10.714286 | 32 | 0.733333 | [
"Apache-2.0"
] | AppifySheets/zohocrm-csharp-sdk-2.1 | ZohoCRM/Com/Zoho/Crm/API/Notes/ActionHandler.cs | 75 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PuppeteerSharp.Helpers;
using PuppeteerSharp.Helpers.Json;
using PuppeteerSharp.Input;
using PuppeteerSharp.Media;
using PuppeteerSharp.Messaging;
using PuppeteerSharp.Mobile;
using PuppeteerSharp.PageAccessibility;
using PuppeteerSharp.PageCoverage;
namespace PuppeteerSharp
{
/// <summary>
/// Provides methods to interact with a single tab in Chromium. One <see cref="Browser"/> instance might have multiple <see cref="Page"/> instances.
/// </summary>
/// <example>
/// This example creates a page, navigates it to a URL, and then saves a screenshot:
/// <code>
/// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
/// var page = await browser.NewPageAsync();
/// await page.GoToAsync("https://example.com");
/// await page.ScreenshotAsync("screenshot.png");
/// await browser.CloseAsync();
/// </code>
/// </example>
[DebuggerDisplay("Page {Url}")]
public class Page : IDisposable, IAsyncDisposable
{
private readonly TaskQueue _screenshotTaskQueue;
private readonly EmulationManager _emulationManager;
private readonly Dictionary<string, Delegate> _pageBindings;
private readonly Dictionary<string, Worker> _workers;
private readonly ILogger _logger;
private PageGetLayoutMetricsResponse _burstModeMetrics;
private bool _screenshotBurstModeOn;
private ScreenshotOptions _screenshotBurstModeOptions;
private readonly TaskCompletionSource<bool> _closeCompletedTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
private TaskCompletionSource<bool> _sessionClosedTcs;
private readonly TimeoutSettings _timeoutSettings;
private bool _fileChooserInterceptionIsDisabled;
private readonly ConcurrentDictionary<Guid, TaskCompletionSource<FileChooser>> _fileChooserInterceptors;
private static readonly Dictionary<string, decimal> _unitToPixels = new Dictionary<string, decimal> {
{"px", 1},
{"in", 96},
{"cm", 37.8m},
{"mm", 3.78m}
};
private Page(
CDPSession client,
Target target,
TaskQueue screenshotTaskQueue)
{
Client = client;
Target = target;
Keyboard = new Keyboard(client);
Mouse = new Mouse(client, Keyboard);
Touchscreen = new Touchscreen(client, Keyboard);
Tracing = new Tracing(client);
Coverage = new Coverage(client);
_fileChooserInterceptors = new ConcurrentDictionary<Guid, TaskCompletionSource<FileChooser>>();
_timeoutSettings = new TimeoutSettings();
_emulationManager = new EmulationManager(client);
_pageBindings = new Dictionary<string, Delegate>();
_workers = new Dictionary<string, Worker>();
_logger = Client.Connection.LoggerFactory.CreateLogger<Page>();
Accessibility = new Accessibility(client);
_screenshotTaskQueue = screenshotTaskQueue;
_ = target.CloseTask.ContinueWith(_ =>
{
try
{
Close?.Invoke(this, EventArgs.Empty);
}
finally
{
IsClosed = true;
_closeCompletedTcs.TrySetResult(true);
}
});
}
#region Public Properties
/// <summary>
/// Chrome DevTools Protocol session.
/// </summary>
public CDPSession Client { get; }
/// <summary>
/// Raised when the JavaScript <c>load</c> <see href="https://developer.mozilla.org/en-US/docs/Web/Events/load"/> event is dispatched.
/// </summary>
public event EventHandler Load;
/// <summary>
/// Raised when the page crashes
/// </summary>
public event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Raised when the JavaScript code makes a call to <c>console.timeStamp</c>. For the list of metrics see <see cref="MetricsAsync"/>.
/// </summary>
public event EventHandler<MetricEventArgs> Metrics;
/// <summary>
/// Raised when a JavaScript dialog appears, such as <c>alert</c>, <c>prompt</c>, <c>confirm</c> or <c>beforeunload</c>. Puppeteer can respond to the dialog via <see cref="Dialog"/>'s <see cref="PuppeteerSharp.Dialog.Accept(string)"/> or <see cref="PuppeteerSharp.Dialog.Dismiss"/> methods.
/// </summary>
public event EventHandler<DialogEventArgs> Dialog;
/// <summary>
/// Raised when the JavaScript <c>DOMContentLoaded</c> <see href="https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded"/> event is dispatched.
/// </summary>
public event EventHandler DOMContentLoaded;
/// <summary>
/// Raised when JavaScript within the page calls one of console API methods, e.g. <c>console.log</c> or <c>console.dir</c>. Also emitted if the page throws an error or a warning.
/// The arguments passed into <c>console.log</c> appear as arguments on the event handler.
/// </summary>
/// <example>
/// An example of handling <see cref="Console"/> event:
/// <code>
/// <![CDATA[
/// page.Console += (sender, e) =>
/// {
/// for (var i = 0; i < e.Message.Args.Count; ++i)
/// {
/// System.Console.WriteLine($"{i}: {e.Message.Args[i]}");
/// }
/// }
/// ]]>
/// </code>
/// </example>
public event EventHandler<ConsoleEventArgs> Console;
/// <summary>
/// Raised when a frame is attached.
/// </summary>
public event EventHandler<FrameEventArgs> FrameAttached;
/// <summary>
/// Raised when a frame is detached.
/// </summary>
public event EventHandler<FrameEventArgs> FrameDetached;
/// <summary>
/// Raised when a frame is navigated to a new url.
/// </summary>
public event EventHandler<FrameEventArgs> FrameNavigated;
/// <summary>
/// Raised when a <see cref="Response"/> is received.
/// </summary>
/// <example>
/// An example of handling <see cref="Response"/> event:
/// <code>
/// <![CDATA[
/// var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
/// page.Response += async(sender, e) =>
/// {
/// if (e.Response.Url.Contains("script.js"))
/// {
/// tcs.TrySetResult(await e.Response.TextAsync());
/// }
/// };
///
/// await Task.WhenAll(
/// page.GoToAsync(TestConstants.ServerUrl + "/grid.html"),
/// tcs.Task);
/// Console.WriteLine(await tcs.Task);
/// ]]>
/// </code>
/// </example>
public event EventHandler<ResponseCreatedEventArgs> Response;
/// <summary>
/// Raised when a page issues a request. The <see cref="Request"/> object is read-only.
/// In order to intercept and mutate requests, see <see cref="SetRequestInterceptionAsync(bool)"/>
/// </summary>
public event EventHandler<RequestEventArgs> Request;
/// <summary>
/// Raised when a request finishes successfully.
/// </summary>
public event EventHandler<RequestEventArgs> RequestFinished;
/// <summary>
/// Raised when a request fails, for example by timing out.
/// </summary>
public event EventHandler<RequestEventArgs> RequestFailed;
/// <summary>
/// Raised when an uncaught exception happens within the page.
/// </summary>
public event EventHandler<PageErrorEventArgs> PageError;
/// <summary>
/// Emitted when a dedicated WebWorker (<see href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"/>) is spawned by the page.
/// </summary>
public event EventHandler<WorkerEventArgs> WorkerCreated;
/// <summary>
/// Emitted when a dedicated WebWorker (<see href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"/>) is terminated.
/// </summary>
public event EventHandler<WorkerEventArgs> WorkerDestroyed;
/// <summary>
/// Raised when the page closes.
/// </summary>
public event EventHandler Close;
/// <summary>
/// Raised when the page opens a new tab or window.
/// </summary>
public event EventHandler<PopupEventArgs> Popup;
/// <summary>
/// This setting will change the default maximum time for the following methods:
/// - <see cref="GoToAsync(string, NavigationOptions)"/>
/// - <see cref="GoBackAsync(NavigationOptions)"/>
/// - <see cref="GoForwardAsync(NavigationOptions)"/>
/// - <see cref="ReloadAsync(NavigationOptions)"/>
/// - <see cref="SetContentAsync(string, NavigationOptions)"/>
/// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>
/// **NOTE** <see cref="DefaultNavigationTimeout"/> takes priority over <seealso cref="DefaultTimeout"/>
/// </summary>
public int DefaultNavigationTimeout
{
get => _timeoutSettings.NavigationTimeout;
set => _timeoutSettings.NavigationTimeout = value;
}
/// <summary>
/// This setting will change the default maximum times for the following methods:
/// - <see cref="GoBackAsync(NavigationOptions)"/>
/// - <see cref="GoForwardAsync(NavigationOptions)"/>
/// - <see cref="GoToAsync(string, NavigationOptions)"/>
/// - <see cref="ReloadAsync(NavigationOptions)"/>
/// - <see cref="SetContentAsync(string, NavigationOptions)"/>
/// - <see cref="WaitForFunctionAsync(string, object[])"/>
/// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>
/// - <see cref="WaitForRequestAsync(string, WaitForOptions)"/>
/// - <see cref="WaitForResponseAsync(string, WaitForOptions)"/>
/// - <see cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>
/// - <see cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>
/// - <see cref="WaitForExpressionAsync(string, WaitForFunctionOptions)"/>
/// </summary>
public int DefaultTimeout
{
get => _timeoutSettings.Timeout;
set => _timeoutSettings.Timeout = value;
}
/// <summary>
/// Gets page's main frame
/// </summary>
/// <remarks>
/// Page is guaranteed to have a main frame which persists during navigations.
/// </remarks>
public Frame MainFrame => FrameManager.MainFrame;
/// <summary>
/// Gets all frames attached to the page.
/// </summary>
/// <value>An array of all frames attached to the page.</value>
public Frame[] Frames => FrameManager.GetFrames();
/// <summary>
/// Gets all workers in the page.
/// </summary>
public Worker[] Workers => _workers.Values.ToArray();
/// <summary>
/// Shortcut for <c>page.MainFrame.Url</c>
/// </summary>
public string Url => MainFrame.Url;
/// <summary>
/// Gets that target this page was created from.
/// </summary>
public Target Target { get; }
/// <summary>
/// Gets this page's keyboard
/// </summary>
public Keyboard Keyboard { get; }
/// <summary>
/// Gets this page's touchscreen
/// </summary>
public Touchscreen Touchscreen { get; }
/// <summary>
/// Gets this page's coverage
/// </summary>
public Coverage Coverage { get; }
/// <summary>
/// Gets this page's tracing
/// </summary>
public Tracing Tracing { get; }
/// <summary>
/// Gets this page's mouse
/// </summary>
public Mouse Mouse { get; }
/// <summary>
/// Gets this page's viewport
/// </summary>
public ViewPortOptions Viewport { get; private set; }
/// <summary>
/// List of supported metrics provided by the <see cref="Metrics"/> event.
/// </summary>
public static readonly IEnumerable<string> SupportedMetrics = new List<string>
{
"Timestamp",
"Documents",
"Frames",
"JSEventListeners",
"Nodes",
"LayoutCount",
"RecalcStyleCount",
"LayoutDuration",
"RecalcStyleDuration",
"ScriptDuration",
"TaskDuration",
"JSHeapUsedSize",
"JSHeapTotalSize"
};
/// <summary>
/// Get the browser the page belongs to.
/// </summary>
public Browser Browser => Target.Browser;
/// <summary>
/// Get the browser context that the page belongs to.
/// </summary>
public BrowserContext BrowserContext => Target.BrowserContext;
/// <summary>
/// Get an indication that the page has been closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets the accessibility.
/// </summary>
public Accessibility Accessibility { get; }
internal bool JavascriptEnabled { get; set; } = true;
internal bool HasPopupEventListeners => Popup?.GetInvocationList().Any() == true;
internal FrameManager FrameManager { get; private set; }
private Task SessionClosedTask
{
get
{
if (_sessionClosedTcs == null)
{
_sessionClosedTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Client.Disconnected += clientDisconnected;
void clientDisconnected(object sender, EventArgs e)
{
_sessionClosedTcs.TrySetException(new TargetClosedException("Target closed", "Session closed"));
Client.Disconnected -= clientDisconnected;
}
}
return _sessionClosedTcs.Task;
}
}
#endregion
#region Public Methods
/// <summary>
/// Sets the page's geolocation.
/// </summary>
/// <returns>The task.</returns>
/// <param name="options">Geolocation options.</param>
/// <remarks>
/// Consider using <seealso cref="PuppeteerSharp.BrowserContext.OverridePermissionsAsync(string, IEnumerable{OverridePermission})"/> to grant permissions for the page to read its geolocation.
/// </remarks>
public Task SetGeolocationAsync(GeolocationOption options)
{
if (options.Longitude < -180 || options.Longitude > 180)
{
throw new ArgumentException($"Invalid longitude '{ options.Longitude }': precondition - 180 <= LONGITUDE <= 180 failed.");
}
if (options.Latitude < -90 || options.Latitude > 90)
{
throw new ArgumentException($"Invalid latitude '{ options.Latitude }': precondition - 90 <= LATITUDE <= 90 failed.");
}
if (options.Accuracy < 0)
{
throw new ArgumentException($"Invalid accuracy '{options.Accuracy}': precondition 0 <= ACCURACY failed.");
}
return Client.SendAsync("Emulation.setGeolocationOverride", options);
}
/// <summary>
/// Returns metrics
/// </summary>
/// <returns>Task which resolves into a list of metrics</returns>
/// <remarks>
/// All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
/// </remarks>
public async Task<Dictionary<string, decimal>> MetricsAsync()
{
var response = await Client.SendAsync<PerformanceGetMetricsResponse>("Performance.getMetrics").ConfigureAwait(false);
return BuildMetricsObject(response.Metrics);
}
/// <summary>
/// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Touchscreen"/> to tap in the center of the element.
/// </summary>
/// <param name="selector">A selector to search for element to tap. If there are multiple elements satisfying the selector, the first will be clicked.</param>
/// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
/// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully tapped</returns>
public async Task TapAsync(string selector)
{
var handle = await QuerySelectorAsync(selector).ConfigureAwait(false);
if (handle == null)
{
throw new SelectorException($"No node found for selector: {selector}", selector);
}
await handle.TapAsync().ConfigureAwait(false);
await handle.DisposeAsync().ConfigureAwait(false);
}
/// <summary>
/// The method runs <c>document.querySelector</c> within the page. If no element matches the selector, the return value resolve to <c>null</c>.
/// </summary>
/// <param name="selector">A selector to query page for</param>
/// <returns>Task which resolves to <see cref="ElementHandle"/> pointing to the frame element</returns>
/// <remarks>
/// Shortcut for <c>page.MainFrame.QuerySelectorAsync(selector)</c>
/// </remarks>
/// <seealso cref="Frame.QuerySelectorAsync(string)"/>
public Task<ElementHandle> QuerySelectorAsync(string selector)
=> MainFrame.QuerySelectorAsync(selector);
/// <summary>
/// Runs <c>document.querySelectorAll</c> within the page. If no elements match the selector, the return value resolve to <see cref="Array.Empty{T}"/>.
/// </summary>
/// <param name="selector">A selector to query page for</param>
/// <returns>Task which resolves to ElementHandles pointing to the frame elements</returns>
/// <seealso cref="Frame.QuerySelectorAllAsync(string)"/>
public Task<ElementHandle[]> QuerySelectorAllAsync(string selector)
=> MainFrame.QuerySelectorAllAsync(selector);
/// <summary>
/// A utility function to be used with <see cref="Extensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>
/// </summary>
/// <param name="selector">A selector to query page for</param>
/// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>
public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)
=> EvaluateFunctionHandleAsync("selector => Array.from(document.querySelectorAll(selector))", selector);
/// <summary>
/// Evaluates the XPath expression
/// </summary>
/// <param name="expression">Expression to evaluate <see href="https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate"/></param>
/// <returns>Task which resolves to an array of <see cref="ElementHandle"/></returns>
/// <remarks>
/// Shortcut for <c>page.MainFrame.XPathAsync(expression)</c>
/// </remarks>
/// <seealso cref="Frame.XPathAsync(string)"/>
public Task<ElementHandle[]> XPathAsync(string expression) => MainFrame.XPathAsync(expression);
/// <summary>
/// Executes a script in browser context
/// </summary>
/// <param name="script">Script to be evaluated in browser context</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// </remarks>
/// <returns>Task which resolves to script return value</returns>
public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)
{
var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);
return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);
}
/// <summary>
/// Executes a script in browser context
/// </summary>
/// <param name="pageFunction">Script to be evaluated in browser context</param>
/// <param name="args">Function arguments</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// <see cref="JSHandle"/> instances can be passed as arguments
/// </remarks>
/// <returns>Task which resolves to script return value</returns>
public async Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)
{
var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);
return await context.EvaluateFunctionHandleAsync(pageFunction, args).ConfigureAwait(false);
}
/// <summary>
/// Adds a function which would be invoked in one of the following scenarios:
/// - whenever the page is navigated
/// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame
/// </summary>
/// <param name="pageFunction">Function to be evaluated in browser context</param>
/// <param name="args">Arguments to pass to <c>pageFunction</c></param>
/// <remarks>
/// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.
/// </remarks>
/// <example>
/// An example of overriding the navigator.languages property before the page loads:
/// <code>
/// await page.EvaluateOnNewDocumentAsync("() => window.__example = true");
/// </code>
/// </example>
/// <returns>Task</returns>
[Obsolete("User EvaluateFunctionOnNewDocumentAsync instead")]
public Task EvaluateOnNewDocumentAsync(string pageFunction, params object[] args)
=> EvaluateFunctionOnNewDocumentAsync(pageFunction, args);
/// <summary>
/// Adds a function which would be invoked in one of the following scenarios:
/// - whenever the page is navigated
/// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame
/// </summary>
/// <param name="pageFunction">Function to be evaluated in browser context</param>
/// <param name="args">Arguments to pass to <c>pageFunction</c></param>
/// <remarks>
/// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.
/// </remarks>
/// <example>
/// An example of overriding the navigator.languages property before the page loads:
/// <code>
/// await page.EvaluateFunctionOnNewDocumentAsync("() => window.__example = true");
/// </code>
/// </example>
/// <returns>Task</returns>
public Task EvaluateFunctionOnNewDocumentAsync(string pageFunction, params object[] args)
{
var source = EvaluationString(pageFunction, args);
return Client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new PageAddScriptToEvaluateOnNewDocumentRequest
{
Source = source
});
}
/// <summary>
/// Adds a function which would be invoked in one of the following scenarios:
/// - whenever the page is navigated
/// - whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame
/// </summary>
/// <param name="expression">Javascript expression to be evaluated in browser context</param>
/// <remarks>
/// The function is invoked after the document was created but before any of its scripts were run. This is useful to amend JavaScript environment, e.g. to seed <c>Math.random</c>.
/// </remarks>
/// <example>
/// An example of overriding the navigator.languages property before the page loads:
/// <code>
/// await page.EvaluateExpressionOnNewDocumentAsync("window.__example = true;");
/// </code>
/// </example>
/// <returns>Task</returns>
public Task EvaluateExpressionOnNewDocumentAsync(string expression)
=> Client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new PageAddScriptToEvaluateOnNewDocumentRequest
{
Source = expression
});
/// <summary>
/// The method iterates JavaScript heap and finds all the objects with the given prototype.
/// Shortcut for <c>page.MainFrame.GetExecutionContextAsync().QueryObjectsAsync(prototypeHandle)</c>.
/// </summary>
/// <returns>A task which resolves to a handle to an array of objects with this prototype.</returns>
/// <param name="prototypeHandle">A handle to the object prototype.</param>
public async Task<JSHandle> QueryObjectsAsync(JSHandle prototypeHandle)
{
var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);
return await context.QueryObjectsAsync(prototypeHandle).ConfigureAwait(false);
}
/// <summary>
/// Activating request interception enables <see cref="PuppeteerSharp.Request.AbortAsync(RequestAbortErrorCode)">request.AbortAsync</see>,
/// <see cref="PuppeteerSharp.Request.ContinueAsync(Payload)">request.ContinueAsync</see> and <see cref="PuppeteerSharp.Request.RespondAsync(ResponseData)">request.RespondAsync</see> methods.
/// </summary>
/// <returns>The request interception task.</returns>
/// <param name="value">Whether to enable request interception..</param>
public Task SetRequestInterceptionAsync(bool value)
=> FrameManager.NetworkManager.SetRequestInterceptionAsync(value);
/// <summary>
/// Set offline mode for the page.
/// </summary>
/// <returns>Result task</returns>
/// <param name="value">When <c>true</c> enables offline mode for the page.</param>
public Task SetOfflineModeAsync(bool value) => FrameManager.NetworkManager.SetOfflineModeAsync(value);
/// <summary>
/// Emulates network conditions
/// </summary>
/// <param name="networkConditions">Passing <c>null</c> disables network condition emulation.</param>
/// <returns>Result task</returns>
/// <remarks>
/// **NOTE** This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644)
/// </remarks>
public Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions) => FrameManager.NetworkManager.EmulateNetworkConditionsAsync(networkConditions);
/// <summary>
/// Returns the page's cookies
/// </summary>
/// <param name="urls">Url's to return cookies for</param>
/// <returns>Array of cookies</returns>
/// <remarks>
/// If no URLs are specified, this method returns cookies for the current page URL.
/// If URLs are specified, only cookies for those URLs are returned.
/// </remarks>
public async Task<CookieParam[]> GetCookiesAsync(params string[] urls)
=> (await Client.SendAsync<NetworkGetCookiesResponse>("Network.getCookies", new NetworkGetCookiesRequest
{
Urls = urls.Length > 0 ? urls : new string[] { Url }
}).ConfigureAwait(false)).Cookies;
/// <summary>
/// Clears all of the current cookies and then sets the cookies for the page
/// </summary>
/// <param name="cookies">Cookies to set</param>
/// <returns>Task</returns>
public async Task SetCookieAsync(params CookieParam[] cookies)
{
foreach (var cookie in cookies)
{
if (string.IsNullOrEmpty(cookie.Url) && Url.StartsWith("http", StringComparison.Ordinal))
{
cookie.Url = Url;
}
if (cookie.Url == "about:blank")
{
throw new PuppeteerException($"Blank page can not have cookie \"{cookie.Name}\"");
}
}
await DeleteCookieAsync(cookies).ConfigureAwait(false);
if (cookies.Length > 0)
{
await Client.SendAsync("Network.setCookies", new NetworkSetCookiesRequest
{
Cookies = cookies
}).ConfigureAwait(false);
}
}
/// <summary>
/// Deletes cookies from the page
/// </summary>
/// <param name="cookies">Cookies to delete</param>
/// <returns>Task</returns>
public async Task DeleteCookieAsync(params CookieParam[] cookies)
{
var pageURL = Url;
foreach (var cookie in cookies)
{
if (string.IsNullOrEmpty(cookie.Url) && pageURL.StartsWith("http", StringComparison.Ordinal))
{
cookie.Url = pageURL;
}
await Client.SendAsync("Network.deleteCookies", cookie).ConfigureAwait(false);
}
}
/// <summary>
/// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content
/// </summary>
/// <param name="options">add script tag options</param>
/// <remarks>
/// Shortcut for <c>page.MainFrame.AddScriptTagAsync(options)</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>
/// <seealso cref="Frame.AddScriptTagAsync(AddTagOptions)"/>
public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainFrame.AddScriptTagAsync(options);
/// <summary>
/// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content
/// </summary>
/// <param name="url">script url</param>
/// <remarks>
/// Shortcut for <c>page.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url })</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>
public Task<ElementHandle> AddScriptTagAsync(string url) => AddScriptTagAsync(new AddTagOptions { Url = url });
/// <summary>
/// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content
/// </summary>
/// <param name="options">add style tag options</param>
/// <remarks>
/// Shortcut for <c>page.MainFrame.AddStyleTagAsync(options)</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>
/// <seealso cref="Frame.AddStyleTag(AddTagOptions)"/>
public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainFrame.AddStyleTagAsync(options);
/// <summary>
/// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content
/// </summary>
/// <param name="url">stylesheel url</param>
/// <remarks>
/// Shortcut for <c>page.MainFrame.AddStyleTagAsync(new AddTagOptions { Url = url })</c>
/// </remarks>
/// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>
public Task<ElementHandle> AddStyleTagAsync(string url) => AddStyleTagAsync(new AddTagOptions { Url = url });
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves when <paramref name="puppeteerFunction"/> completes.
/// </summary>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync(string, Action)"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync(string name, Action puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{TResult}(string, Func{TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<TResult>(string name, Func<TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T">The parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T, TResult}(string, Func{T, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T, TResult>(string name, Func<T, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, TResult}(string, Func{T1, T2, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T1, T2, TResult>(string name, Func<T1, T2, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, TResult}(string, Func{T1, T2, T3, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Adds a function called <c>name</c> on the page's <c>window</c> object.
/// When called, the function executes <paramref name="puppeteerFunction"/> in C# and returns a <see cref="Task"/> which resolves to the return value of <paramref name="puppeteerFunction"/>.
/// </summary>
/// <typeparam name="T1">The first parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T2">The second parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T3">The third parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="T4">The fourth parameter of <paramref name="puppeteerFunction"/></typeparam>
/// <typeparam name="TResult">The result of <paramref name="puppeteerFunction"/></typeparam>
/// <param name="name">Name of the function on the window object</param>
/// <param name="puppeteerFunction">Callback function which will be called in Puppeteer's context.</param>
/// <remarks>
/// If the <paramref name="puppeteerFunction"/> returns a <see cref="Task"/>, it will be awaited.
/// Functions installed via <see cref="ExposeFunctionAsync{T1, T2, T3, T4, TResult}(string, Func{T1, T2, T3, T4, TResult})"/> survive navigations
/// </remarks>
/// <returns>Task</returns>
public Task ExposeFunctionAsync<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult> puppeteerFunction)
=> ExposeFunctionAsync(name, (Delegate)puppeteerFunction);
/// <summary>
/// Gets the full HTML contents of the page, including the doctype.
/// </summary>
/// <returns>Task which resolves to the HTML content.</returns>
/// <seealso cref="Frame.GetContentAsync"/>
public Task<string> GetContentAsync() => FrameManager.MainFrame.GetContentAsync();
/// <summary>
/// Sets the HTML markup to the page
/// </summary>
/// <param name="html">HTML markup to assign to the page.</param>
/// <param name="options">The navigations options</param>
/// <returns>Task.</returns>
/// <seealso cref="Frame.SetContentAsync(string, NavigationOptions)"/>
public Task SetContentAsync(string html, NavigationOptions options = null) => FrameManager.MainFrame.SetContentAsync(html, options);
/// <summary>
/// Navigates to an url
/// </summary>
/// <remarks>
/// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will throw an error if:
/// - there's an SSL error (e.g. in case of self-signed certificates).
/// - target URL is invalid.
/// - the `timeout` is exceeded during navigation.
/// - the remote server does not respond or is unreachable.
/// - the main resource failed to load.
///
/// <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> will not throw an error when any valid HTTP status code is returned by the remote server,
/// including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling <see cref="PuppeteerSharp.Response.Status"/>
///
/// > **NOTE** <see cref="GoToAsync(string, int?, WaitUntilNavigation[])"/> either throws an error or returns a main resource response.
/// The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
///
/// > **NOTE** Headless mode doesn't support navigation to a PDF document. See the <see fref="https://bugs.chromium.org/p/chromium/issues/detail?id=761295">upstream issue</see>.
///
/// Shortcut for <seealso cref="Frame.GoToAsync(string, int?, WaitUntilNavigation[])"/>
/// </remarks>
/// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
/// <param name="options">Navigation parameters.</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.</returns>
/// <seealso cref="GoToAsync(string, int?, WaitUntilNavigation[])"/>
public Task<Response> GoToAsync(string url, NavigationOptions options) => FrameManager.MainFrame.GoToAsync(url, options);
/// <summary>
/// Navigates to an url
/// </summary>
/// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
/// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>
/// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>
/// <seealso cref="GoToAsync(string, NavigationOptions)"/>
public Task<Response> GoToAsync(string url, int? timeout = null, WaitUntilNavigation[] waitUntil = null)
=> GoToAsync(url, new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });
/// <summary>
/// Navigates to an url
/// </summary>
/// <param name="url">URL to navigate page to. The url should include scheme, e.g. https://.</param>
/// <param name="waitUntil">When to consider navigation succeeded.</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>
/// <seealso cref="GoToAsync(string, NavigationOptions)"/>
public Task<Response> GoToAsync(string url, WaitUntilNavigation waitUntil)
=> GoToAsync(url, new NavigationOptions { WaitUntil = new[] { waitUntil } });
/// <summary>
/// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>
/// <returns></returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task PdfAsync(string file) => PdfAsync(file, new PdfOptions());
/// <summary>
/// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="file">The file path to save the PDF to. paths are resolved using <see cref="Path.GetFullPath(string)"/></param>
/// <param name="options">pdf options</param>
/// <returns></returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public async Task PdfAsync(string file, PdfOptions options)
=> await PdfInternalAsync(file, options).ConfigureAwait(false);
/// <summary>
/// generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task<Stream> PdfStreamAsync() => PdfStreamAsync(new PdfOptions());
/// <summary>
/// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="options">pdf options</param>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public async Task<Stream> PdfStreamAsync(PdfOptions options)
=> new MemoryStream(await PdfDataAsync(options).ConfigureAwait(false));
/// <summary>
/// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task<byte[]> PdfDataAsync() => PdfDataAsync(new PdfOptions());
/// <summary>
/// Generates a pdf of the page with <see cref="MediaType.Print"/> css media. To generate a pdf with <see cref="MediaType.Screen"/> media call <see cref="EmulateMediaAsync(MediaType)"/> with <see cref="MediaType.Screen"/>
/// </summary>
/// <param name="options">pdf options</param>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the PDF data.</returns>
/// <remarks>
/// Generating a pdf is currently only supported in Chrome headless
/// </remarks>
public Task<byte[]> PdfDataAsync(PdfOptions options) => PdfInternalAsync(null, options);
internal async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)
{
var paperWidth = PaperFormat.Letter.Width;
var paperHeight = PaperFormat.Letter.Height;
if (options.Format != null)
{
paperWidth = options.Format.Width;
paperHeight = options.Format.Height;
}
else
{
if (options.Width != null)
{
paperWidth = ConvertPrintParameterToInches(options.Width);
}
if (options.Height != null)
{
paperHeight = ConvertPrintParameterToInches(options.Height);
}
}
var marginTop = ConvertPrintParameterToInches(options.MarginOptions.Top);
var marginLeft = ConvertPrintParameterToInches(options.MarginOptions.Left);
var marginBottom = ConvertPrintParameterToInches(options.MarginOptions.Bottom);
var marginRight = ConvertPrintParameterToInches(options.MarginOptions.Right);
var result = await Client.SendAsync<PagePrintToPDFResponse>("Page.printToPDF", new PagePrintToPDFRequest
{
TransferMode = "ReturnAsStream",
Landscape = options.Landscape,
DisplayHeaderFooter = options.DisplayHeaderFooter,
HeaderTemplate = options.HeaderTemplate,
FooterTemplate = options.FooterTemplate,
PrintBackground = options.PrintBackground,
Scale = options.Scale,
PaperWidth = paperWidth,
PaperHeight = paperHeight,
MarginTop = marginTop,
MarginBottom = marginBottom,
MarginLeft = marginLeft,
MarginRight = marginRight,
PageRanges = options.PageRanges,
PreferCSSPageSize = options.PreferCSSPageSize
}).ConfigureAwait(false);
return await ProtocolStreamReader.ReadProtocolStreamByteAsync(Client, result.Stream, file).ConfigureAwait(false);
}
/// <summary>
/// Enables/Disables Javascript on the page
/// </summary>
/// <returns>Task.</returns>
/// <param name="enabled">Whether or not to enable JavaScript on the page.</param>
public Task SetJavaScriptEnabledAsync(bool enabled)
{
if (enabled == JavascriptEnabled)
{
return Task.CompletedTask;
}
JavascriptEnabled = enabled;
return Client.SendAsync("Emulation.setScriptExecutionDisabled", new EmulationSetScriptExecutionDisabledRequest
{
Value = !enabled
});
}
/// <summary>
/// Toggles bypassing page's Content-Security-Policy.
/// </summary>
/// <param name="enabled">sets bypassing of page's Content-Security-Policy.</param>
/// <returns></returns>
/// <remarks>
/// CSP bypassing happens at the moment of CSP initialization rather then evaluation.
/// Usually this means that <see cref="SetBypassCSPAsync(bool)"/> should be called before navigating to the domain.
/// </remarks>
public Task SetBypassCSPAsync(bool enabled) => Client.SendAsync("Page.setBypassCSP", new PageSetBypassCSPRequest
{
Enabled = enabled
});
/// <summary>
/// Emulates a media such as screen or print.
/// </summary>
/// <returns>Task.</returns>
/// <param name="media">Media to set.</param>
[Obsolete("User EmulateMediaTypeAsync instead")]
public Task EmulateMediaAsync(MediaType media) => EmulateMediaTypeAsync(media);
/// <summary>
/// Emulates a media such as screen or print.
/// </summary>
/// <param name="type">Media to set.</param>
/// <example>
/// <code>
/// <![CDATA[
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");
/// // → true
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");
/// // → true
/// await page.EmulateMediaTypeAsync(MediaType.Print);
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");
/// // → false
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");
/// // → true
/// await page.EmulateMediaTypeAsync(MediaType.None);
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('screen').matches)");
/// // → true
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('print').matches)");
/// // → true
/// ]]>
/// </code>
/// </example>
/// <returns>Emulate media type task.</returns>
public Task EmulateMediaTypeAsync(MediaType type)
=> Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaTypeRequest { Media = type });
/// <summary>
/// Given an array of media feature objects, emulates CSS media features on the page.
/// </summary>
/// <param name="features">Features to apply</param>
/// <example>
/// <code>
/// <![CDATA[
/// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" }});
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");
/// // → true
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");
/// // → false
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
/// // → false
/// await page.EmulateMediaFeaturesAsync(new MediaFeature[]{ new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" }});
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");
/// // → true
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
/// // → false
/// await page.EmulateMediaFeaturesAsync(new MediaFeature[]
/// {
/// new MediaFeature { MediaFeature = MediaFeature.PrefersColorScheme, Value = "dark" },
/// new MediaFeature { MediaFeature = MediaFeature.PrefersReducedMotion, Value = "reduce" },
/// });
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: dark)').matches)");
/// // → true
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: light)').matches)");
/// // → false
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
/// // → false
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-reduced-motion: reduce)').matches)");
/// // → true
/// await page.EvaluateFunctionAsync<bool>("() => matchMedia('(prefers-color-scheme: no-preference)').matches)");
/// // → false
/// ]]>
/// </code>
/// </example>
/// <returns>Emulate features task</returns>
public Task EmulateMediaFeaturesAsync(IEnumerable<MediaFeatureValue> features)
=> Client.SendAsync("Emulation.setEmulatedMedia", new EmulationSetEmulatedMediaFeatureRequest { Features = features });
/// <summary>
/// Sets the viewport.
/// In the case of multiple pages in a single browser, each page can have its own viewport size.
/// <see cref="SetViewportAsync(ViewPortOptions)"/> will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.
/// </summary>
/// <example>
///<![CDATA[
/// using(var page = await browser.NewPageAsync())
/// {
/// await page.SetViewPortAsync(new ViewPortOptions
/// {
/// Width = 640,
/// Height = 480,
/// DeviceScaleFactor = 1
/// });
/// await page.goto('https://www.example.com');
/// }
/// ]]>
/// </example>
/// <returns>The viewport task.</returns>
/// <param name="viewport">Viewport options.</param>
public async Task SetViewportAsync(ViewPortOptions viewport)
{
var needsReload = await _emulationManager.EmulateViewport(viewport).ConfigureAwait(false);
Viewport = viewport;
if (needsReload)
{
await ReloadAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Emulates given device metrics and user agent.
/// </summary>
/// <remarks>
/// This method is a shortcut for calling two methods:
/// <see cref="SetViewportAsync(ViewPortOptions)"/>
/// <see cref="SetUserAgentAsync(string)"/>
/// To aid emulation, puppeteer provides a list of device descriptors which can be obtained via the <see cref="Puppeteer.Devices"/>.
/// <see cref="EmulateAsync(DeviceDescriptor)"/> will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.
/// </remarks>
/// <example>
///<![CDATA[
/// var iPhone = Puppeteer.Devices[DeviceDescriptorName.IPhone6];
/// using(var page = await browser.NewPageAsync())
/// {
/// await page.EmulateAsync(iPhone);
/// await page.goto('https://www.google.com');
/// }
/// ]]>
/// </example>
/// <returns>Task.</returns>
/// <param name="options">Emulation options.</param>
public Task EmulateAsync(DeviceDescriptor options) => Task.WhenAll(
SetViewportAsync(options.ViewPort),
SetUserAgentAsync(options.UserAgent));
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>The screenshot task.</returns>
/// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension.
/// If path is a relative path, then it is resolved relative to current working directory. If no path is provided,
/// the image won't be saved to the disk.</param>
public Task ScreenshotAsync(string file) => ScreenshotAsync(file, new ScreenshotOptions());
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>The screenshot task.</returns>
/// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension.
/// If path is a relative path, then it is resolved relative to current working directory. If no path is provided,
/// the image won't be saved to the disk.</param>
/// <param name="options">Screenshot options.</param>
public async Task ScreenshotAsync(string file, ScreenshotOptions options)
{
if (!options.Type.HasValue)
{
options.Type = ScreenshotOptions.GetScreenshotTypeFromFile(file);
if (options.Type == ScreenshotType.Jpeg && !options.Quality.HasValue)
{
options.Quality = 90;
}
}
var data = await ScreenshotDataAsync(options).ConfigureAwait(false);
using (var fs = AsyncFileHelper.CreateStream(file, FileMode.Create))
{
await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
}
}
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the image data.</returns>
public Task<Stream> ScreenshotStreamAsync() => ScreenshotStreamAsync(new ScreenshotOptions());
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="Stream"/> containing the image data.</returns>
/// <param name="options">Screenshot options.</param>
public async Task<Stream> ScreenshotStreamAsync(ScreenshotOptions options)
=> new MemoryStream(await ScreenshotDataAsync(options).ConfigureAwait(false));
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="string"/> containing the image data as base64.</returns>
public Task<string> ScreenshotBase64Async() => ScreenshotBase64Async(new ScreenshotOptions());
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="string"/> containing the image data as base64.</returns>
/// <param name="options">Screenshot options.</param>
public Task<string> ScreenshotBase64Async(ScreenshotOptions options)
{
var screenshotType = options.Type;
if (!screenshotType.HasValue)
{
screenshotType = ScreenshotType.Png;
}
if (options.Quality.HasValue)
{
if (screenshotType != ScreenshotType.Jpeg)
{
throw new ArgumentException($"options.Quality is unsupported for the {screenshotType} screenshots");
}
if (options.Quality < 0 || options.Quality > 100)
{
throw new ArgumentException($"Expected options.quality to be between 0 and 100 (inclusive), got {options.Quality}");
}
}
if (options?.Clip?.Width == 0)
{
throw new PuppeteerException("Expected options.Clip.Width not to be 0.");
}
if (options?.Clip?.Height == 0)
{
throw new PuppeteerException("Expected options.Clip.Height not to be 0.");
}
if (options.Clip != null && options.FullPage)
{
throw new ArgumentException("options.clip and options.fullPage are exclusive");
}
return _screenshotTaskQueue.Enqueue(() => PerformScreenshot(screenshotType.Value, options));
}
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the image data.</returns>
public Task<byte[]> ScreenshotDataAsync() => ScreenshotDataAsync(new ScreenshotOptions());
/// <summary>
/// Takes a screenshot of the page
/// </summary>
/// <returns>Task which resolves to a <see cref="byte"/>[] containing the image data.</returns>
/// <param name="options">Screenshot options.</param>
public async Task<byte[]> ScreenshotDataAsync(ScreenshotOptions options)
=> Convert.FromBase64String(await ScreenshotBase64Async(options).ConfigureAwait(false));
/// <summary>
/// Returns page's title
/// </summary>
/// <returns>page's title</returns>
/// <see cref="Frame.GetTitleAsync"/>
public Task<string> GetTitleAsync() => MainFrame.GetTitleAsync();
/// <summary>
/// Closes the page.
/// </summary>
/// <param name="options">Close options.</param>
/// <returns>Task.</returns>
public Task CloseAsync(PageCloseOptions options = null)
{
if (!(Client?.Connection?.IsClosed ?? true))
{
var runBeforeUnload = options?.RunBeforeUnload ?? false;
if (runBeforeUnload)
{
return Client.SendAsync("Page.close");
}
return Client.Connection.SendAsync("Target.closeTarget", new TargetCloseTargetRequest
{
TargetId = Target.TargetId
}).ContinueWith(task => Target.CloseTask);
}
_logger.LogWarning("Protocol error: Connection closed. Most likely the page has been closed.");
return _closeCompletedTcs.Task;
}
/// <summary>
/// Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.
/// </summary>
/// <param name="enabled">sets the <c>enabled</c> state of the cache</param>
/// <returns>Task</returns>
public Task SetCacheEnabledAsync(bool enabled = true)
=> FrameManager.NetworkManager.SetCacheEnabledAsync(enabled);
/// <summary>
/// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Mouse"/> to click in the center of the element.
/// </summary>
/// <param name="selector">A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.</param>
/// <param name="options">click options</param>
/// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
/// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully clicked</returns>
public Task ClickAsync(string selector, ClickOptions options = null) => FrameManager.MainFrame.ClickAsync(selector, options);
/// <summary>
/// Fetches an element with <paramref name="selector"/>, scrolls it into view if needed, and then uses <see cref="Mouse"/> to hover over the center of the element.
/// </summary>
/// <param name="selector">A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.</param>
/// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
/// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully hovered</returns>
public Task HoverAsync(string selector) => FrameManager.MainFrame.HoverAsync(selector);
/// <summary>
/// Fetches an element with <paramref name="selector"/> and focuses it
/// </summary>
/// <param name="selector">A selector to search for element to focus. If there are multiple elements satisfying the selector, the first will be focused.</param>
/// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
/// <returns>Task which resolves when the element matching <paramref name="selector"/> is successfully focused</returns>
public Task FocusAsync(string selector) => FrameManager.MainFrame.FocusAsync(selector);
/// <summary>
/// Sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.
/// </summary>
/// <param name="selector">A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="text">A text to type into a focused element</param>
/// <param name="options"></param>
/// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
/// <remarks>
/// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="PuppeteerSharp.Input.Keyboard.PressAsync(string, PressOptions)"/>
/// </remarks>
/// <example>
/// <code>
/// await page.TypeAsync("#mytextarea", "Hello"); // Types instantly
/// await page.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user
/// </code>
/// </example>
/// <returns>Task</returns>
public Task TypeAsync(string selector, string text, TypeOptions options = null)
=> FrameManager.MainFrame.TypeAsync(selector, text, options);
/// <summary>
/// Executes a script in browser context
/// </summary>
/// <param name="script">Script to be evaluated in browser context</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// </remarks>
/// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>
/// <returns>Task which resolves to script return value</returns>
public Task<JToken> EvaluateExpressionAsync(string script)
=> FrameManager.MainFrame.EvaluateExpressionAsync<JToken>(script);
/// <summary>
/// Executes a script in browser context
/// </summary>
/// <typeparam name="T">The type to deserialize the result to</typeparam>
/// <param name="script">Script to be evaluated in browser context</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// </remarks>
/// <seealso cref="EvaluateFunctionAsync{T}(string, object[])"/>
/// <returns>Task which resolves to script return value</returns>
public Task<T> EvaluateExpressionAsync<T>(string script)
=> FrameManager.MainFrame.EvaluateExpressionAsync<T>(script);
/// <summary>
/// Executes a function in browser context
/// </summary>
/// <param name="script">Script to be evaluated in browser context</param>
/// <param name="args">Arguments to pass to script</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// <see cref="JSHandle"/> instances can be passed as arguments
/// </remarks>
/// <seealso cref="EvaluateExpressionAsync{T}(string)"/>
/// <returns>Task which resolves to script return value</returns>
public Task<JToken> EvaluateFunctionAsync(string script, params object[] args)
=> FrameManager.MainFrame.EvaluateFunctionAsync<JToken>(script, args);
/// <summary>
/// Executes a function in browser context
/// </summary>
/// <typeparam name="T">The type to deserialize the result to</typeparam>
/// <param name="script">Script to be evaluated in browser context</param>
/// <param name="args">Arguments to pass to script</param>
/// <remarks>
/// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.
/// <see cref="JSHandle"/> instances can be passed as arguments
/// </remarks>
/// <seealso cref="EvaluateExpressionAsync{T}(string)"/>
/// <returns>Task which resolves to script return value</returns>
public Task<T> EvaluateFunctionAsync<T>(string script, params object[] args)
=> FrameManager.MainFrame.EvaluateFunctionAsync<T>(script, args);
/// <summary>
/// Sets the user agent to be used in this page
/// </summary>
/// <param name="userAgent">Specific user agent to use in this page</param>
/// <returns>Task</returns>
public Task SetUserAgentAsync(string userAgent)
=> FrameManager.NetworkManager.SetUserAgentAsync(userAgent);
/// <summary>
/// Sets extra HTTP headers that will be sent with every request the page initiates
/// </summary>
/// <param name="headers">Additional http headers to be sent with every request</param>
/// <returns>Task</returns>
public Task SetExtraHttpHeadersAsync(Dictionary<string, string> headers)
=> FrameManager.NetworkManager.SetExtraHTTPHeadersAsync(headers);
/// <summary>
/// Provide credentials for http authentication <see href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication"/>
/// </summary>
/// <param name="credentials">The credentials</param>
/// <returns></returns>
/// <remarks>
/// To disable authentication, pass <c>null</c>
/// </remarks>
public Task AuthenticateAsync(Credentials credentials) => FrameManager.NetworkManager.AuthenticateAsync(credentials);
/// <summary>
/// Reloads the page
/// </summary>
/// <param name="options">Navigation options</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>
/// <seealso cref="ReloadAsync(int?, WaitUntilNavigation[])"/>
public async Task<Response> ReloadAsync(NavigationOptions options)
{
var navigationTask = WaitForNavigationAsync(options);
await Task.WhenAll(
navigationTask,
Client.SendAsync("Page.reload", new PageReloadRequest { FrameId = MainFrame.Id })).ConfigureAwait(false);
return navigationTask.Result;
}
/// <summary>
/// Reloads the page
/// </summary>
/// <param name="timeout">Maximum navigation time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout. </param>
/// <param name="waitUntil">When to consider navigation succeeded, defaults to <see cref="WaitUntilNavigation.Load"/>. Given an array of <see cref="WaitUntilNavigation"/>, navigation is considered to be successful after all events have been fired</param>
/// <returns>Task which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect</returns>
/// <seealso cref="ReloadAsync(NavigationOptions)"/>
public Task<Response> ReloadAsync(int? timeout = null, WaitUntilNavigation[] waitUntil = null)
=> ReloadAsync(new NavigationOptions { Timeout = timeout, WaitUntil = waitUntil });
/// <summary>
/// Triggers a change and input event once all the provided options have been selected.
/// If there's no <![CDATA[<select>]]> element matching selector, the method throws an error.
/// </summary>
/// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
/// <param name="selector">A selector to query page for</param>
/// <param name="values">Values of options to select. If the <![CDATA[<select>]]> has the multiple attribute,
/// all values are considered, otherwise only the first one is taken into account.</param>
/// <returns>Returns an array of option values that have been successfully selected.</returns>
/// <seealso cref="Frame.SelectAsync(string, string[])"/>
public Task<string[]> SelectAsync(string selector, params string[] values)
=> MainFrame.SelectAsync(selector, values);
/// <summary>
/// Waits for a timeout
/// </summary>
/// <param name="milliseconds"></param>
/// <returns>A task that resolves when after the timeout</returns>
/// <seealso cref="Frame.WaitForTimeoutAsync(int)"/>
public Task WaitForTimeoutAsync(int milliseconds)
=> MainFrame.WaitForTimeoutAsync(milliseconds);
/// <summary>
/// Waits for a function to be evaluated to a truthy value
/// </summary>
/// <param name="script">Function to be evaluated in browser context</param>
/// <param name="options">Optional waiting parameters</param>
/// <param name="args">Arguments to pass to <c>script</c></param>
/// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>
/// <seealso cref="Frame.WaitForFunctionAsync(string, WaitForFunctionOptions, object[])"/>
public Task<JSHandle> WaitForFunctionAsync(string script, WaitForFunctionOptions options = null, params object[] args)
=> MainFrame.WaitForFunctionAsync(script, options ?? new WaitForFunctionOptions(), args);
/// <summary>
/// Waits for a function to be evaluated to a truthy value
/// </summary>
/// <param name="script">Function to be evaluated in browser context</param>
/// <param name="args">Arguments to pass to <c>script</c></param>
/// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>
public Task<JSHandle> WaitForFunctionAsync(string script, params object[] args) => WaitForFunctionAsync(script, null, args);
/// <summary>
/// Waits for an expression to be evaluated to a truthy value
/// </summary>
/// <param name="script">Expression to be evaluated in browser context</param>
/// <param name="options">Optional waiting parameters</param>
/// <returns>A task that resolves when the <c>script</c> returns a truthy value</returns>
/// <seealso cref="Frame.WaitForExpressionAsync(string, WaitForFunctionOptions)"/>
public Task<JSHandle> WaitForExpressionAsync(string script, WaitForFunctionOptions options = null)
=> MainFrame.WaitForExpressionAsync(script, options ?? new WaitForFunctionOptions());
/// <summary>
/// Waits for a selector to be added to the DOM
/// </summary>
/// <param name="selector">A selector of an element to wait for</param>
/// <param name="options">Optional waiting parameters</param>
/// <returns>A task that resolves when element specified by selector string is added to DOM.
/// Resolves to `null` if waiting for `hidden: true` and selector is not found in DOM.</returns>
/// <seealso cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>
/// <seealso cref="Frame.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>
public Task<ElementHandle> WaitForSelectorAsync(string selector, WaitForSelectorOptions options = null)
=> MainFrame.WaitForSelectorAsync(selector, options ?? new WaitForSelectorOptions());
/// <summary>
/// Waits for a xpath selector to be added to the DOM
/// </summary>
/// <param name="xpath">A xpath selector of an element to wait for</param>
/// <param name="options">Optional waiting parameters</param>
/// <returns>A task which resolves when element specified by xpath string is added to DOM.
/// Resolves to `null` if waiting for `hidden: true` and xpath is not found in DOM.</returns>
/// <example>
/// <code>
/// <![CDATA[
/// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
/// var page = await browser.NewPageAsync();
/// string currentURL = null;
/// page
/// .WaitForXPathAsync("//img")
/// .ContinueWith(_ => Console.WriteLine("First URL with image: " + currentURL));
/// foreach (var current in new[] { "https://example.com", "https://google.com", "https://bbc.com" })
/// {
/// currentURL = current;
/// await page.GoToAsync(currentURL);
/// }
/// await browser.CloseAsync();
/// ]]>
/// </code>
/// </example>
/// <seealso cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>
/// <seealso cref="Frame.WaitForXPathAsync(string, WaitForSelectorOptions)"/>
public Task<ElementHandle> WaitForXPathAsync(string xpath, WaitForSelectorOptions options = null)
=> MainFrame.WaitForXPathAsync(xpath, options ?? new WaitForSelectorOptions());
/// <summary>
/// This resolves when the page navigates to a new URL or reloads.
/// It is useful for when you run code which will indirectly cause the page to navigate.
/// </summary>
/// <param name="options">navigation options</param>
/// <returns>Task which resolves to the main resource response.
/// In case of multiple redirects, the navigation will resolve with the response of the last redirect.
/// In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
/// </returns>
/// <remarks>
/// Usage of the <c>History API</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/History_API"/> to change the URL is considered a navigation
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// var navigationTask = page.WaitForNavigationAsync();
/// await page.ClickAsync("a.my-link");
/// await navigationTask;
/// ]]>
/// </code>
/// </example>
public Task<Response> WaitForNavigationAsync(NavigationOptions options = null) => FrameManager.WaitForFrameNavigationAsync(FrameManager.MainFrame, options);
/// <summary>
/// Waits for a request.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var firstRequest = await page.WaitForRequestAsync("http://example.com/resource");
/// return firstRequest.Url;
/// ]]>
/// </code>
/// </example>
/// <returns>A task which resolves when a matching request was made.</returns>
/// <param name="url">URL to wait for.</param>
/// <param name="options">Options.</param>
public Task<Request> WaitForRequestAsync(string url, WaitForOptions options = null)
=> WaitForRequestAsync(request => request.Url == url, options);
/// <summary>
/// Waits for a request.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var request = await page.WaitForRequestAsync(request => request.Url === "http://example.com" && request.Method === HttpMethod.Get;
/// return request.Url;
/// ]]>
/// </code>
/// </example>
/// <returns>A task which resolves when a matching request was made.</returns>
/// <param name="predicate">Function which looks for a matching request.</param>
/// <param name="options">Options.</param>
public async Task<Request> WaitForRequestAsync(Func<Request, bool> predicate, WaitForOptions options = null)
{
var timeout = options?.Timeout ?? DefaultTimeout;
var requestTcs = new TaskCompletionSource<Request>(TaskCreationOptions.RunContinuationsAsynchronously);
void requestEventListener(object sender, RequestEventArgs e)
{
if (predicate(e.Request))
{
requestTcs.TrySetResult(e.Request);
FrameManager.NetworkManager.Request -= requestEventListener;
}
}
FrameManager.NetworkManager.Request += requestEventListener;
await Task.WhenAny(requestTcs.Task, SessionClosedTask).WithTimeout(timeout, t =>
{
FrameManager.NetworkManager.Request -= requestEventListener;
return new TimeoutException($"Timeout of {t.TotalMilliseconds} ms exceeded");
}).ConfigureAwait(false);
if (SessionClosedTask.IsFaulted)
{
await SessionClosedTask.ConfigureAwait(false);
}
return await requestTcs.Task.ConfigureAwait(false);
}
/// <summary>
/// Waits for a response.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var firstResponse = await page.WaitForResponseAsync("http://example.com/resource");
/// return firstResponse.Url;
/// ]]>
/// </code>
/// </example>
/// <returns>A task which resolves when a matching response is received.</returns>
/// <param name="url">URL to wait for.</param>
/// <param name="options">Options.</param>
public Task<Response> WaitForResponseAsync(string url, WaitForOptions options = null)
=> WaitForResponseAsync(response => response.Url == url, options);
/// <summary>
/// Waits for a response.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var response = await page.WaitForResponseAsync(response => response.Url === "http://example.com" && response.Status === HttpStatus.Ok;
/// return response.Url;
/// ]]>
/// </code>
/// </example>
/// <returns>A task which resolves when a matching response is received.</returns>
/// <param name="predicate">Function which looks for a matching response.</param>
/// <param name="options">Options.</param>
public async Task<Response> WaitForResponseAsync(Func<Response, bool> predicate, WaitForOptions options = null)
{
var timeout = options?.Timeout ?? DefaultTimeout;
var responseTcs = new TaskCompletionSource<Response>(TaskCreationOptions.RunContinuationsAsynchronously);
void responseEventListener(object sender, ResponseCreatedEventArgs e)
{
if (predicate(e.Response))
{
responseTcs.TrySetResult(e.Response);
FrameManager.NetworkManager.Response -= responseEventListener;
}
}
FrameManager.NetworkManager.Response += responseEventListener;
await Task.WhenAny(responseTcs.Task, SessionClosedTask).WithTimeout(timeout).ConfigureAwait(false);
if (SessionClosedTask.IsFaulted)
{
await SessionClosedTask.ConfigureAwait(false);
}
return await responseTcs.Task.ConfigureAwait(false);
}
/// <summary>
/// Waits for a page to open a file picker
/// </summary>
/// <remarks>
/// In non-headless Chromium, this method results in the native file picker dialog **not showing up** for the user.
/// </remarks>
/// <example>
/// This method is typically coupled with an action that triggers file choosing.
/// The following example clicks a button that issues a file chooser, and then
/// responds with `/tmp/myfile.pdf` as if a user has selected this file.
/// <code>
/// <![CDATA[
/// var waitTask = page.WaitForFileChooserAsync();
/// await Task.WhenAll(
/// waitTask,
/// page.ClickAsync("#upload-file-button")); // some button that triggers file selection
///
/// await waitTask.Result.AcceptAsync('/tmp/myfile.pdf');
/// ]]>
/// </code>
///
/// This must be called *before* the file chooser is launched. It will not return a currently active file chooser.
/// </example>
/// <param name="options">Optional waiting parameters.</param>
/// <returns>A task that resolves after a page requests a file picker.</returns>
public async Task<FileChooser> WaitForFileChooserAsync(WaitForFileChooserOptions options = null)
{
if (_fileChooserInterceptionIsDisabled)
{
throw new PuppeteerException("File chooser handling does not work with multiple connections to the same page");
}
var timeout = options?.Timeout ?? _timeoutSettings.Timeout;
var tcs = new TaskCompletionSource<FileChooser>(TaskCreationOptions.RunContinuationsAsynchronously);
var guid = Guid.NewGuid();
_fileChooserInterceptors.TryAdd(guid, tcs);
try
{
return await tcs.Task.WithTimeout(timeout).ConfigureAwait(false);
}
catch (Exception)
{
_fileChooserInterceptors.TryRemove(guid, out _);
throw;
}
}
/// <summary>
/// Navigate to the previous page in history.
/// </summary>
/// <returns>Task that resolves to the main resource response. In case of multiple redirects,
/// the navigation will resolve with the response of the last redirect. If can not go back, resolves to null.</returns>
/// <param name="options">Navigation parameters.</param>
public Task<Response> GoBackAsync(NavigationOptions options = null) => GoAsync(-1, options);
/// <summary>
/// Navigate to the next page in history.
/// </summary>
/// <returns>Task that resolves to the main resource response. In case of multiple redirects,
/// the navigation will resolve with the response of the last redirect. If can not go forward, resolves to null.</returns>
/// <param name="options">Navigation parameters.</param>
public Task<Response> GoForwardAsync(NavigationOptions options = null) => GoAsync(1, options);
/// <summary>
/// Resets the background color and Viewport after taking Screenshots using BurstMode.
/// </summary>
/// <returns>The burst mode off.</returns>
public Task SetBurstModeOffAsync()
{
_screenshotBurstModeOn = false;
if (_screenshotBurstModeOptions != null)
{
ResetBackgroundColorAndViewportAsync(_screenshotBurstModeOptions);
}
return Task.CompletedTask;
}
/// <summary>
/// Brings page to front (activates tab).
/// </summary>
/// <returns>A task that resolves when the message has been sent to Chromium.</returns>
public Task BringToFrontAsync() => Client.SendAsync("Page.bringToFront");
/// <summary>
/// Changes the timezone of the page.
/// </summary>
/// <param name="timezoneId">Timezone to set. See <seealso href="https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1" >ICU’s `metaZones.txt`</seealso>
/// for a list of supported timezone IDs. Passing `null` disables timezone emulation.</param>
/// <returns>The viewport task.</returns>
public async Task EmulateTimezoneAsync(string timezoneId)
{
try
{
await Client.SendAsync("Emulation.setTimezoneOverride", new EmulateTimezoneRequest
{
TimezoneId = timezoneId ?? string.Empty
}).ConfigureAwait(false);
}
catch (Exception ex) when (ex.Message.Contains("Invalid timezone"))
{
throw new PuppeteerException($"Invalid timezone ID: { timezoneId }");
}
}
#endregion
internal void OnPopup(Page popupPage) => Popup?.Invoke(this, new PopupEventArgs { PopupPage = popupPage });
#region Private Method
internal static async Task<Page> CreateAsync(
CDPSession client,
Target target,
bool ignoreHTTPSErrors,
ViewPortOptions defaultViewPort,
TaskQueue screenshotTaskQueue)
{
var page = new Page(client, target, screenshotTaskQueue);
await page.InitializeAsync(ignoreHTTPSErrors).ConfigureAwait(false);
if (defaultViewPort != null)
{
await page.SetViewportAsync(defaultViewPort).ConfigureAwait(false);
}
return page;
}
private async Task InitializeAsync(bool ignoreHTTPSErrors)
{
FrameManager = await FrameManager.CreateFrameManagerAsync(Client, this, ignoreHTTPSErrors, _timeoutSettings).ConfigureAwait(false);
var networkManager = FrameManager.NetworkManager;
Client.MessageReceived += Client_MessageReceived;
FrameManager.FrameAttached += (_, e) => FrameAttached?.Invoke(this, e);
FrameManager.FrameDetached += (_, e) => FrameDetached?.Invoke(this, e);
FrameManager.FrameNavigated += (_, e) => FrameNavigated?.Invoke(this, e);
networkManager.Request += (_, e) => Request?.Invoke(this, e);
networkManager.RequestFailed += (_, e) => RequestFailed?.Invoke(this, e);
networkManager.Response += (_, e) => Response?.Invoke(this, e);
networkManager.RequestFinished += (_, e) => RequestFinished?.Invoke(this, e);
await Task.WhenAll(
Client.SendAsync("Target.setAutoAttach", new TargetSetAutoAttachRequest
{
AutoAttach = true,
WaitForDebuggerOnStart = false,
Flatten = true
}),
Client.SendAsync("Performance.enable", null),
Client.SendAsync("Log.enable", null)).ConfigureAwait(false);
try
{
await Client.SendAsync("Page.setInterceptFileChooserDialog", new PageSetInterceptFileChooserDialog
{
Enabled = true
}).ConfigureAwait(false);
}
catch
{
_fileChooserInterceptionIsDisabled = true;
}
}
private async Task<Response> GoAsync(int delta, NavigationOptions options)
{
var history = await Client.SendAsync<PageGetNavigationHistoryResponse>("Page.getNavigationHistory").ConfigureAwait(false);
if (history.Entries.Count <= history.CurrentIndex + delta || history.CurrentIndex + delta < 0)
{
return null;
}
var entry = history.Entries[history.CurrentIndex + delta];
var waitTask = WaitForNavigationAsync(options);
await Task.WhenAll(
waitTask,
Client.SendAsync("Page.navigateToHistoryEntry", new PageNavigateToHistoryEntryRequest
{
EntryId = entry.Id
})).ConfigureAwait(false);
return waitTask.Result;
}
private Dictionary<string, decimal> BuildMetricsObject(List<Metric> metrics)
{
var result = new Dictionary<string, decimal>();
foreach (var item in metrics)
{
if (SupportedMetrics.Contains(item.Name))
{
result.Add(item.Name, item.Value);
}
}
return result;
}
private async Task<string> PerformScreenshot(ScreenshotType type, ScreenshotOptions options)
{
if (!_screenshotBurstModeOn)
{
await Client.SendAsync("Target.activateTarget", new TargetActivateTargetRequest
{
TargetId = Target.TargetId
}).ConfigureAwait(false);
}
var clip = options.Clip != null ? ProcessClip(options.Clip) : null;
if (!_screenshotBurstModeOn)
{
if (options != null && options.FullPage)
{
var metrics = _screenshotBurstModeOn
? _burstModeMetrics :
await Client.SendAsync<PageGetLayoutMetricsResponse>("Page.getLayoutMetrics").ConfigureAwait(false);
if (options.BurstMode)
{
_burstModeMetrics = metrics;
}
var contentSize = metrics.ContentSize;
var width = Convert.ToInt32(Math.Ceiling(contentSize.Width));
var height = Convert.ToInt32(Math.Ceiling(contentSize.Height));
// Overwrite clip for full page at all times.
clip = new Clip
{
X = 0,
Y = 0,
Width = width,
Height = height,
Scale = 1
};
var isMobile = Viewport?.IsMobile ?? false;
var deviceScaleFactor = Viewport?.DeviceScaleFactor ?? 1;
var isLandscape = Viewport?.IsLandscape ?? false;
var screenOrientation = isLandscape ?
new ScreenOrientation
{
Angle = 90,
Type = ScreenOrientationType.LandscapePrimary
} :
new ScreenOrientation
{
Angle = 0,
Type = ScreenOrientationType.PortraitPrimary
};
await Client.SendAsync("Emulation.setDeviceMetricsOverride", new EmulationSetDeviceMetricsOverrideRequest
{
Mobile = isMobile,
Width = width,
Height = height,
DeviceScaleFactor = deviceScaleFactor,
ScreenOrientation = screenOrientation
}).ConfigureAwait(false);
}
if (options?.OmitBackground == true && type == ScreenshotType.Png)
{
await Client.SendAsync("Emulation.setDefaultBackgroundColorOverride", new EmulationSetDefaultBackgroundColorOverrideRequest
{
Color = new EmulationSetDefaultBackgroundColorOverrideColor
{
R = 0,
G = 0,
B = 0,
A = 0
}
}).ConfigureAwait(false);
}
}
var screenMessage = new PageCaptureScreenshotRequest
{
Format = type.ToString().ToLower(CultureInfo.CurrentCulture)
};
if (options.Quality.HasValue)
{
screenMessage.Quality = options.Quality.Value;
}
if (clip != null)
{
screenMessage.Clip = clip;
}
var result = await Client.SendAsync<PageCaptureScreenshotResponse>("Page.captureScreenshot", screenMessage).ConfigureAwait(false);
if (options.BurstMode)
{
_screenshotBurstModeOptions = options;
_screenshotBurstModeOn = true;
}
else
{
await ResetBackgroundColorAndViewportAsync(options).ConfigureAwait(false);
}
return result.Data;
}
private Clip ProcessClip(Clip clip)
{
var x = Math.Round(clip.X);
var y = Math.Round(clip.Y);
return new Clip
{
X = x,
Y = y,
Width = Math.Round(clip.Width + clip.X - x, MidpointRounding.AwayFromZero),
Height = Math.Round(clip.Height + clip.Y - y, MidpointRounding.AwayFromZero),
Scale = 1
};
}
private Task ResetBackgroundColorAndViewportAsync(ScreenshotOptions options)
{
var omitBackgroundTask = options?.OmitBackground == true && options.Type == ScreenshotType.Png ?
Client.SendAsync("Emulation.setDefaultBackgroundColorOverride") : Task.CompletedTask;
var setViewPortTask = (options?.FullPage == true && Viewport != null) ?
SetViewportAsync(Viewport) : Task.CompletedTask;
return Task.WhenAll(omitBackgroundTask, setViewPortTask);
}
private decimal ConvertPrintParameterToInches(object parameter)
{
if (parameter == null)
{
return 0;
}
decimal pixels;
if (parameter is decimal || parameter is int)
{
pixels = Convert.ToDecimal(parameter, CultureInfo.CurrentCulture);
}
else
{
var text = parameter.ToString();
var unit = text.Substring(text.Length - 2).ToLower(CultureInfo.CurrentCulture);
string valueText;
if (_unitToPixels.ContainsKey(unit))
{
valueText = text.Substring(0, text.Length - 2);
}
else
{
// In case of unknown unit try to parse the whole parameter as number of pixels.
// This is consistent with phantom's paperSize behavior.
unit = "px";
valueText = text;
}
if (decimal.TryParse(valueText, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var number))
{
pixels = number * _unitToPixels[unit];
}
else
{
throw new ArgumentException($"Failed to parse parameter value: '{text}'", nameof(parameter));
}
}
return pixels / 96;
}
private async void Client_MessageReceived(object sender, MessageEventArgs e)
{
try
{
switch (e.MessageID)
{
case "Page.domContentEventFired":
DOMContentLoaded?.Invoke(this, EventArgs.Empty);
break;
case "Page.loadEventFired":
Load?.Invoke(this, EventArgs.Empty);
break;
case "Runtime.consoleAPICalled":
await OnConsoleAPIAsync(e.MessageData.ToObject<PageConsoleResponse>(true)).ConfigureAwait(false);
break;
case "Page.javascriptDialogOpening":
OnDialog(e.MessageData.ToObject<PageJavascriptDialogOpeningResponse>(true));
break;
case "Runtime.exceptionThrown":
HandleException(e.MessageData.ToObject<RuntimeExceptionThrownResponse>(true).ExceptionDetails);
break;
case "Inspector.targetCrashed":
OnTargetCrashed();
break;
case "Performance.metrics":
EmitMetrics(e.MessageData.ToObject<PerformanceMetricsResponse>(true));
break;
case "Target.attachedToTarget":
await OnAttachedToTargetAsync(e.MessageData.ToObject<TargetAttachedToTargetResponse>(true)).ConfigureAwait(false);
break;
case "Target.detachedFromTarget":
OnDetachedFromTarget(e.MessageData.ToObject<TargetDetachedFromTargetResponse>(true));
break;
case "Log.entryAdded":
await OnLogEntryAddedAsync(e.MessageData.ToObject<LogEntryAddedResponse>(true)).ConfigureAwait(false);
break;
case "Runtime.bindingCalled":
await OnBindingCalled(e.MessageData.ToObject<BindingCalledResponse>(true)).ConfigureAwait(false);
break;
case "Page.fileChooserOpened":
await OnFileChooserAsync(e.MessageData.ToObject<PageFileChooserOpenedResponse>(true)).ConfigureAwait(false);
break;
}
}
catch (Exception ex)
{
var message = $"Page failed to process {e.MessageID}. {ex.Message}. {ex.StackTrace}";
_logger.LogError(ex, message);
Client.Close(message);
}
}
private async Task OnFileChooserAsync(PageFileChooserOpenedResponse e)
{
if (_fileChooserInterceptors.Count == 0)
{
try
{
await Client.SendAsync("Page.handleFileChooser", new PageHandleFileChooserRequest
{
Action = FileChooserAction.Fallback
}).ConfigureAwait(false);
return;
}
catch (Exception ex)
{
_logger.LogError(ex, ex.ToString());
}
}
var frame = await FrameManager.GetFrameAsync(e.FrameId).ConfigureAwait(false);
var context = await frame.GetExecutionContextAsync().ConfigureAwait(false);
var element = await context.AdoptBackendNodeAsync(e.BackendNodeId).ConfigureAwait(false);
var fileChooser = new FileChooser(element, e);
while (_fileChooserInterceptors.Count > 0)
{
var key = _fileChooserInterceptors.FirstOrDefault().Key;
if (_fileChooserInterceptors.TryRemove(key, out var tcs))
{
tcs.TrySetResult(fileChooser);
}
}
}
private async Task OnBindingCalled(BindingCalledResponse e)
{
string expression;
try
{
var result = await ExecuteBinding(e).ConfigureAwait(false);
expression = EvaluationString(
@"function deliverResult(name, seq, result) {
window[name]['callbacks'].get(seq).resolve(result);
window[name]['callbacks'].delete(seq);
}",
e.BindingPayload.Name,
e.BindingPayload.Seq,
result);
}
catch (Exception ex)
{
if (ex is TargetInvocationException)
{
ex = ex.InnerException;
}
expression = EvaluationString(
@"function deliverError(name, seq, message, stack) {
const error = new Error(message);
error.stack = stack;
window[name]['callbacks'].get(seq).reject(error);
window[name]['callbacks'].delete(seq);
}",
e.BindingPayload.Name,
e.BindingPayload.Seq,
ex.Message,
ex.StackTrace);
}
Client.Send("Runtime.evaluate", new
{
expression,
contextId = e.ExecutionContextId
});
}
private async Task<object> ExecuteBinding(BindingCalledResponse e)
{
const string taskResultPropertyName = "Result";
object result;
var binding = _pageBindings[e.BindingPayload.Name];
var methodParams = binding.Method.GetParameters().Select(parameter => parameter.ParameterType).ToArray();
var args = e.BindingPayload.Args.Select((token, i) => token.ToObject(methodParams[i])).ToArray();
result = binding.DynamicInvoke(args);
if (result is Task taskResult)
{
await taskResult.ConfigureAwait(false);
if (taskResult.GetType().IsGenericType)
{
// the task is already awaited and therefore the call to property Result will not deadlock
result = taskResult.GetType().GetProperty(taskResultPropertyName).GetValue(taskResult);
}
}
return result;
}
private void OnDetachedFromTarget(TargetDetachedFromTargetResponse e)
{
var sessionId = e.SessionId;
if (_workers.TryGetValue(sessionId, out var worker))
{
WorkerDestroyed?.Invoke(this, new WorkerEventArgs(worker));
_workers.Remove(sessionId);
}
}
private async Task OnAttachedToTargetAsync(TargetAttachedToTargetResponse e)
{
var targetInfo = e.TargetInfo;
var sessionId = e.SessionId;
if (targetInfo.Type != TargetType.Worker)
{
try
{
await Client.SendAsync("Target.detachFromTarget", new TargetDetachFromTargetRequest
{
SessionId = sessionId
}).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
}
return;
}
var session = Connection.FromSession(Client).GetSession(sessionId);
var worker = new Worker(session, targetInfo.Url, AddConsoleMessageAsync, HandleException);
_workers[sessionId] = worker;
WorkerCreated?.Invoke(this, new WorkerEventArgs(worker));
}
private async Task OnLogEntryAddedAsync(LogEntryAddedResponse e)
{
if (e.Entry.Args != null)
{
foreach (var arg in e.Entry?.Args)
{
await RemoteObjectHelper.ReleaseObjectAsync(Client, arg, _logger).ConfigureAwait(false);
}
}
if (e.Entry.Source != TargetType.Worker)
{
Console?.Invoke(this, new ConsoleEventArgs(new ConsoleMessage(
e.Entry.Level,
e.Entry.Text,
null,
new ConsoleMessageLocation
{
URL = e.Entry.URL,
LineNumber = e.Entry.LineNumber
})));
}
}
private void OnTargetCrashed()
{
if (Error == null)
{
throw new TargetCrashedException();
}
Error.Invoke(this, new ErrorEventArgs("Page crashed!"));
}
private void EmitMetrics(PerformanceMetricsResponse metrics)
=> Metrics?.Invoke(this, new MetricEventArgs(metrics.Title, BuildMetricsObject(metrics.Metrics)));
private void HandleException(EvaluateExceptionResponseDetails exceptionDetails)
=> PageError?.Invoke(this, new PageErrorEventArgs(GetExceptionMessage(exceptionDetails)));
private string GetExceptionMessage(EvaluateExceptionResponseDetails exceptionDetails)
{
if (exceptionDetails.Exception != null)
{
return exceptionDetails.Exception.Description;
}
var message = exceptionDetails.Text;
if (exceptionDetails.StackTrace != null)
{
foreach (var callframe in exceptionDetails.StackTrace.CallFrames)
{
var location = $"{callframe.Url}:{callframe.LineNumber}:{callframe.ColumnNumber}";
var functionName = callframe.FunctionName ?? "<anonymous>";
message += $"\n at {functionName} ({location})";
}
}
return message;
}
private void OnDialog(PageJavascriptDialogOpeningResponse message)
{
var dialog = new Dialog(Client, message.Type, message.Message, message.DefaultPrompt);
Dialog?.Invoke(this, new DialogEventArgs(dialog));
}
private Task OnConsoleAPIAsync(PageConsoleResponse message)
{
if (message.ExecutionContextId == 0)
{
return Task.CompletedTask;
}
var ctx = FrameManager.ExecutionContextById(message.ExecutionContextId);
var values = message.Args.Select(ctx.CreateJSHandle).ToArray();
return AddConsoleMessageAsync(message.Type, values, message.StackTrace);
}
private async Task AddConsoleMessageAsync(ConsoleType type, JSHandle[] values, Messaging.StackTrace stackTrace)
{
if (Console?.GetInvocationList().Length == 0)
{
await Task.WhenAll(values.Select(v => RemoteObjectHelper.ReleaseObjectAsync(Client, v.RemoteObject, _logger))).ConfigureAwait(false);
return;
}
var tokens = values.Select(i => i.RemoteObject.ObjectId != null
? i.ToString()
: RemoteObjectHelper.ValueFromRemoteObject<string>(i.RemoteObject));
var location = new ConsoleMessageLocation();
if (stackTrace?.CallFrames?.Length > 0)
{
var callFrame = stackTrace.CallFrames[0];
location.URL = callFrame.URL;
location.LineNumber = callFrame.LineNumber;
location.ColumnNumber = callFrame.ColumnNumber;
}
var consoleMessage = new ConsoleMessage(type, string.Join(" ", tokens), values, location);
Console?.Invoke(this, new ConsoleEventArgs(consoleMessage));
}
private async Task ExposeFunctionAsync(string name, Delegate puppeteerFunction)
{
if (_pageBindings.ContainsKey(name))
{
throw new PuppeteerException($"Failed to add page binding with name {name}: window['{name}'] already exists!");
}
_pageBindings.Add(name, puppeteerFunction);
const string addPageBinding = @"function addPageBinding(bindingName) {
const binding = window[bindingName];
window[bindingName] = (...args) => {
const me = window[bindingName];
let callbacks = me['callbacks'];
if (!callbacks) {
callbacks = new Map();
me['callbacks'] = callbacks;
}
const seq = (me['lastSeq'] || 0) + 1;
me['lastSeq'] = seq;
const promise = new Promise((resolve, reject) => callbacks.set(seq, {resolve, reject}));
binding(JSON.stringify({name: bindingName, seq, args}));
return promise;
};
}";
var expression = EvaluationString(addPageBinding, name);
await Client.SendAsync("Runtime.addBinding", new RuntimeAddBindingRequest { Name = name }).ConfigureAwait(false);
await Client.SendAsync("Page.addScriptToEvaluateOnNewDocument", new PageAddScriptToEvaluateOnNewDocumentRequest
{
Source = expression
}).ConfigureAwait(false);
await Task.WhenAll(Frames.Select(frame => frame.EvaluateExpressionAsync(expression)
.ContinueWith(task =>
{
if (task.IsFaulted)
{
_logger.LogError(task.Exception.ToString());
}
}))).ConfigureAwait(false);
}
private static string EvaluationString(string fun, params object[] args)
{
return $"({fun})({string.Join(",", args.Select(SerializeArgument))})";
string SerializeArgument(object arg)
{
return arg == null
? "undefined"
: JsonConvert.SerializeObject(arg, JsonHelper.DefaultJsonSerializerSettings);
}
}
#endregion
#region IDisposable
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases all resource used by the <see cref="Page"/> object by calling the <see cref="CloseAsync"/> method.
/// </summary>
/// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="Page"/>. The
/// <see cref="Dispose()"/> method leaves the <see cref="Page"/> in an unusable state. After
/// calling <see cref="Dispose()"/>, you must release all references to the <see cref="Page"/> so
/// the garbage collector can reclaim the memory that the <see cref="Page"/> was occupying.</remarks>
/// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>
protected virtual void Dispose(bool disposing) => _ = CloseAsync();
#endregion
#region IAsyncDisposable
/// <summary>
/// Releases all resource used by the <see cref="Page"/> object by calling the <see cref="CloseAsync"/> method.
/// </summary>
/// <remarks>Call <see cref="DisposeAsync"/> when you are finished using the <see cref="Page"/>. The
/// <see cref="DisposeAsync"/> method leaves the <see cref="Page"/> in an unusable state. After
/// calling <see cref="DisposeAsync"/>, you must release all references to the <see cref="Page"/> so
/// the garbage collector can reclaim the memory that the <see cref="Page"/> was occupying.</remarks>
/// <returns>ValueTask</returns>
public ValueTask DisposeAsync() => new ValueTask(CloseAsync());
#endregion
}
}
| 48.244426 | 298 | 0.594149 | [
"MIT"
] | GeekQuants/puppeteer-sharp | lib/PuppeteerSharp/Page.cs | 119,053 | C# |
/*
© Siemens AG, 2017-2018
Author: Dr. Martin Bischoff (martin.bischoff@siemens.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<http://www.apache.org/licenses/LICENSE-2.0>.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using UnityEngine;
using Object = UnityEngine.Object;
namespace RosSharp
{
public static class TransformExtensions
{
private const int RoundDigits = 6;
public static void DestroyImmediateIfExists<T>(this Transform transform) where T : Component
{
T component = transform.GetComponent<T>();
if (component != null)
Object.DestroyImmediate(component);
}
public static T AddComponentIfNotExists<T>(this Transform transform) where T : Component
{
T component = transform.GetComponent<T>();
if (component == null)
component = transform.gameObject.AddComponent<T>();
return component;
}
public static void SetParentAndAlign(this Transform transform, Transform parent, bool keepLocalTransform = true)
{
Vector3 localPosition = transform.localPosition;
Quaternion localRotation = transform.localRotation;
transform.parent = parent;
if (keepLocalTransform)
{
transform.position = transform.parent.position + localPosition;
transform.rotation = transform.parent.rotation * localRotation;
}
else
{
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
}
}
public static bool HasExactlyOneChild(this Transform transform)
{
return transform.childCount == 1;
}
public static void MoveChildTransformToParent(this Transform parent, bool transferRotation = true)
{
//Detach child in order to get a transform indenpendent from parent
Transform childTransform = parent.GetChild(0);
parent.DetachChildren();
//Copy transform from child to parent
parent.position = childTransform.position;
parent.localScale = childTransform.localScale;
if (transferRotation)
{
parent.rotation = childTransform.rotation;
childTransform.localRotation = Quaternion.identity;
}
childTransform.parent = parent;
childTransform.localPosition = Vector3.zero;
childTransform.localScale = Vector3.one;
}
public static double[] ToRosRPY(this Vector3 transform)
{
Vector3 rpyVector = new Vector3(
-transform.z * Mathf.Deg2Rad,
transform.x * Mathf.Deg2Rad,
-transform.y * Mathf.Deg2Rad);
return rpyVector == Vector3.zero ? null : rpyVector.ToRoundedDoubleArray();
}
public static Vector3 Ros2Unity(this Vector3 vector3)
{
return new Vector3(-vector3.y, vector3.z, vector3.x);
}
public static Vector3 Unity2Ros(this Vector3 vector3)
{
return new Vector3(vector3.z, -vector3.x, vector3.y);
}
public static Vector3 Ros2UnityScale(this Vector3 vector3)
{
return new Vector3(vector3.y, vector3.z, vector3.x);
}
public static Vector3 Unity2RosScale(this Vector3 vector3)
{
return new Vector3(vector3.z, vector3.x, vector3.y);
}
public static Quaternion Ros2Unity(this Quaternion quaternion)
{
return new Quaternion(quaternion.y, -quaternion.z, -quaternion.x, quaternion.w);
}
public static Quaternion Unity2Ros(this Quaternion quaternion)
{
return new Quaternion(-quaternion.z, quaternion.x, -quaternion.y, quaternion.w);
}
public static double[] ToRoundedDoubleArray(this Vector3 vector3)
{
double[] arr = new double[3];
for (int i = 0; i < 3; i++)
arr[i] = Math.Round(vector3[i], RoundDigits);
return arr;
}
public static Vector3 ToVector3(this double[] array)
{
return new Vector3((float)array[0], (float)array[1], (float)array[2]);
}
public static string SetSeparatorChar(this string path)
{
return path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
/// <summary>
/// This function is written to compare two double arrays.
/// It returns true if each number respective number in the array is equal to within a delta amount to each other.
/// Vector3 == Vector3 only allows for a difference of 1e-5
/// </summary>
/// <param name="array">First double array</param>
/// <param name="array2">Second Double array</param>
/// <param name="delta">Allowed delta between numbers allowed</param>
/// <returns></returns>
public static bool DoubleDeltaCompare(this double[] array, double[] array2, double delta)
{
if (array.Length != array2.Length)
return false;
for (int i = 0; i < array.Length ; i++)
{
if ((array[i] >= array2[i] - delta) && (array[i] <= array2[i] + delta))
continue;
else
return false;
}
return true;
}
/// <summary>
/// This function is written to compare two Vector3.
/// It returns true if each number respective number in the array is equal to within a delta amount to each other.
/// </summary>
/// <param name="array">First Vector3</param>
/// <param name="array2">Second Vector3</param>
/// <param name="delta">Allowed delta between numbers allowed</param>
/// <returns></returns>
public static bool VectorEqualDelta(this Vector3 source, Vector3 exported, double delta)
{
return Vector3.SqrMagnitude(source - exported) < delta;
}
public static bool EqualsDelta(this double first, double second, double delta)
{
if (Math.Abs(first - second) <= Math.Abs(delta * first))
return true;
else
return false;
}
/// <summary>
/// Implments element-wise subtraction between two matrices
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Matrix4x4 Subtract(this Matrix4x4 first, Matrix4x4 second)
{
Matrix4x4 result = new Matrix4x4();
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
result[i, j] = first[i, j] - second[i, j];
}
}
return result;
}
/// <summary>
/// Divides each float number of a Matrix4x4 type with a float scalar.
/// The function is added as it does not support element-wise division by float
/// https://docs.unity3d.com/ScriptReference/Matrix4x4.html
/// </summary>
/// <param name="first">Matrix divisor</param>
/// <param name="second">Float dividend</param>
/// <returns></returns>
public static Matrix4x4 FloatDivide(this Matrix4x4 first, float second)
{
Matrix4x4 result = new Matrix4x4();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i, j] = first[i, j] / second;
}
}
return result;
}
/// <summary>
/// Function overload of ToString method of Matrix3x3 to achieve unrounded print of the matrix
/// </summary>
/// <param name="first">Matrix to be printed</param>
/// <returns></returns>
public static string ToString(this Matrix4x4 first)
{
return ("Matrix : " + first[0, 0] + " " + first[0, 1] + " " + first[0, 2] + " " + first[0, 3] + " " +
first[1, 0] + " " + first[1, 1] + " " + first[1, 2] + " " + first[1, 3] + " " +
first[2, 0] + " " + first[2, 1] + " " + first[2, 2] + " " + first[2, 3] + " " +
first[3, 0] + " " + first[3, 1] + " " + first[3, 2] + " " + first[3, 3]);
}
}
}
| 37.272727 | 122 | 0.564745 | [
"Apache-2.0"
] | JGroxz/URDF-Importer | com.unity.robotics.urdf-importer/Runtime/Extensions/TransformExtensions.cs | 9,023 | C# |
namespace Signum.Engine;
public static class LinqHintsExpand
{
public static IQueryable<T> ExpandLite<T, L>(this IQueryable<T> source, Expression<Func<T, Lite<L>?>> liteSelector, ExpandLite expandLite)
where L : class, IEntity
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return source.Provider.CreateQuery<T>(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()!).MakeGenericMethod(new Type[] { typeof(T), typeof(L) }), new Expression[] { source.Expression, Expression.Quote(liteSelector), Expression.Constant(expandLite) }));
}
public static IQueryable<T> ExpandEntity<T, L>(this IQueryable<T> source, Expression<Func<T, L?>> entitySelector, ExpandEntity expandEntity)
where L : class, IEntity
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return source.Provider.CreateQuery<T>(Expression.Call(null, ((MethodInfo)MethodBase.GetCurrentMethod()!).MakeGenericMethod(new Type[] { typeof(T), typeof(L) }), new Expression[] { source.Expression, Expression.Quote(entitySelector), Expression.Constant(expandEntity) }));
}
}
public enum ExpandLite
{
EntityEager,
//Default,
ToStringEager,
ToStringLazy,
ToStringNull,
}
public enum ExpandEntity
{
EagerEntity,
LazyEntity,
}
| 35.846154 | 280 | 0.681688 | [
"MIT"
] | Faridmehr/framework | Signum.Engine/LinqExpandHints.cs | 1,398 | C# |
/*
* Copyright (c) 2016-2018 Håkan Edling
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Collections.Generic;
namespace Piranha.Models
{
/// <summary>
/// Region list for dynamic models.
/// </summary>
/// <typeparam name="T">The item type</typeparam>
public class RegionList<T> : List<T>, IRegionList
{
/// <summary>
/// Gets/sets the page type id.
/// </summary>
public string TypeId { get; set; }
/// <summary>
/// Gets/sets the region id.
/// </summary>
public string RegionId { get; set; }
/// <summary>
/// Gets/sets the parent model.
/// </summary>
public IDynamicModel Model { get; set; }
/// <summary>
/// Adds a new item to the region list
/// </summary>
/// <param name="item">The item</param>
public void Add(object item)
{
if (item.GetType() == typeof(T))
{
base.Add((T)item);
}
else throw new ArgumentException("Item type does not match the list");
}
}
}
| 25.176471 | 82 | 0.53972 | [
"MIT"
] | Lewis-Bass/SafeHaven | core/Piranha/Models/RegionList.cs | 1,287 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BubbleSortCinematic : Cinematic
{
}
| 16.125 | 44 | 0.821705 | [
"MIT"
] | JohnSongNow/youtube-tutorials | bubble-sort/BubbleSortCinematic.cs | 129 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Zoltu.Nethermind.Plugin.Multicall
{
public abstract class DisposeAsyncOnce : IAsyncDisposable
{
private UInt32 _disposed;
protected abstract ValueTask DisposeOnce();
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
await DisposeOnce();
}
}
}
| 20.473684 | 59 | 0.755784 | [
"Unlicense"
] | Zoltu/nethermind-plugin-multi-call | source/DisposeAsyncOnce.cs | 389 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.SignalR.Infrastructure;
namespace Microsoft.AspNet.SignalR.Hubs
{
public class HubConnectionContextBase : IHubConnectionContext
{
public HubConnectionContextBase()
{
}
public HubConnectionContextBase(IConnection connection, IHubPipelineInvoker invoker, string hubName)
{
Connection = connection;
Invoker = invoker;
HubName = hubName;
All = AllExcept();
}
protected IHubPipelineInvoker Invoker { get; private set; }
protected IConnection Connection { get; private set; }
protected string HubName { get; private set; }
public dynamic All
{
get;
set;
}
/// <summary>
/// Returns a dynamic representation of all clients except the calling client ones specified.
/// </summary>
/// <param name="excludeConnectionIds">The list of connection ids to exclude</param>
/// <returns>A dynamic representation of all clients except the calling client ones specified.</returns>
public dynamic AllExcept(params string[] excludeConnectionIds)
{
return new ClientProxy(Connection, Invoker, HubName, PrefixHelper.GetPrefixedConnectionIds(excludeConnectionIds));
}
/// <summary>
/// Returns a dynamic representation of the connection with the specified connectionid.
/// </summary>
/// <param name="connectionId">The connection id</param>
/// <returns>A dynamic representation of the specified client.</returns>
public dynamic Client(string connectionId)
{
if (String.IsNullOrEmpty(connectionId))
{
throw new ArgumentException(Resources.Error_ArgumentNullOrEmpty, "connectionId");
}
return new ConnectionIdProxy(Connection,
Invoker,
connectionId,
HubName);
}
/// <summary>
/// Returns a dynamic representation of the connections with the specified connectionids.
/// </summary>
/// <param name="connectionIds">The connection ids.</param>
/// <returns>A dynamic representation of the specified clients.</returns>
public dynamic Clients(IList<string> connectionIds)
{
if (connectionIds == null)
{
throw new ArgumentNullException("connectionIds");
}
return new MultipleSignalProxy(Connection,
Invoker,
connectionIds,
HubName,
PrefixHelper.HubConnectionIdPrefix,
ListHelper<string>.Empty);
}
/// <summary>
/// Returns a dynamic representation of the specified group.
/// </summary>
/// <param name="groupName">The name of the group</param>
/// <param name="excludeConnectionIds">The list of connection ids to exclude</param>
/// <returns>A dynamic representation of the specified group.</returns>
public dynamic Group(string groupName, params string[] excludeConnectionIds)
{
if (String.IsNullOrEmpty(groupName))
{
throw new ArgumentException(Resources.Error_ArgumentNullOrEmpty, "groupName");
}
return new GroupProxy(Connection,
Invoker,
groupName,
HubName,
PrefixHelper.GetPrefixedConnectionIds(excludeConnectionIds));
}
/// <summary>
/// Returns a dynamic representation of the specified groups.
/// </summary>
/// <param name="groupNames">The names of the groups.</param>
/// <param name="excludeConnectionIds">The list of connection ids to exclude</param>
/// <returns>A dynamic representation of the specified groups.</returns>
public dynamic Groups(IList<string> groupNames, params string[] excludeConnectionIds)
{
if (groupNames == null)
{
throw new ArgumentNullException("groupNames");
}
return new MultipleSignalProxy(Connection,
Invoker,
groupNames,
HubName,
PrefixHelper.HubGroupPrefix,
PrefixHelper.GetPrefixedConnectionIds(excludeConnectionIds));
}
public dynamic User(string userId)
{
if (userId == null)
{
throw new ArgumentNullException("userId");
}
return new UserProxy(Connection, Invoker, userId, HubName);
}
}
}
| 39.537313 | 132 | 0.549075 | [
"Apache-2.0"
] | Teleopti/SignalR | src/Microsoft.AspNet.SignalR.Core/Hubs/HubConnectionContextBase.cs | 5,300 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the events-2015-10-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudWatchEvents.Model
{
/// <summary>
/// Represents an event that a partner tried to generate, but failed.
/// </summary>
public partial class PutPartnerEventsResultEntry
{
private string _errorCode;
private string _errorMessage;
private string _eventId;
/// <summary>
/// Gets and sets the property ErrorCode.
/// <para>
/// The error code that indicates why the event submission failed.
/// </para>
/// </summary>
public string ErrorCode
{
get { return this._errorCode; }
set { this._errorCode = value; }
}
// Check to see if ErrorCode property is set
internal bool IsSetErrorCode()
{
return this._errorCode != null;
}
/// <summary>
/// Gets and sets the property ErrorMessage.
/// <para>
/// The error message that explains why the event submission failed.
/// </para>
/// </summary>
public string ErrorMessage
{
get { return this._errorMessage; }
set { this._errorMessage = value; }
}
// Check to see if ErrorMessage property is set
internal bool IsSetErrorMessage()
{
return this._errorMessage != null;
}
/// <summary>
/// Gets and sets the property EventId.
/// <para>
/// The ID of the event.
/// </para>
/// </summary>
public string EventId
{
get { return this._eventId; }
set { this._eventId = value; }
}
// Check to see if EventId property is set
internal bool IsSetEventId()
{
return this._eventId != null;
}
}
} | 28.526316 | 104 | 0.597048 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CloudWatchEvents/Generated/Model/PutPartnerEventsResultEntry.cs | 2,710 | C# |
// -----------------------------------------------------------------------
// <copyright file="EventStream.cs" company="Asynkron HB">
// Copyright (C) 2015-2018 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Proto.Mailbox;
namespace Proto
{
public class EventStream : EventStream<object>
{
public static readonly EventStream Instance = new EventStream();
private readonly ILogger _logger = Log.CreateLogger<EventStream>();
internal EventStream()
{
Subscribe(msg =>
{
if (msg is DeadLetterEvent letter)
{
_logger.LogInformation("[DeadLetter] '{0}' got '{1}:{2}' from '{3}'", letter.Pid.ToShortString(),
letter.Message.GetType().Name, letter.Message, letter.Sender?.ToShortString());
}
});
}
}
public class EventStream<T>
{
private readonly ILogger _logger = Log.CreateLogger<EventStream<T>>();
private readonly ConcurrentDictionary<Guid, Subscription<T>> _subscriptions =
new ConcurrentDictionary<Guid, Subscription<T>>();
internal EventStream()
{
}
public Subscription<T> Subscribe(Action<T> action, IDispatcher dispatcher = null)
{
var sub = new Subscription<T>(this, dispatcher ?? Dispatchers.SynchronousDispatcher, x =>
{
action(x);
return Actor.Done;
});
_subscriptions.TryAdd(sub.Id, sub);
return sub;
}
public Subscription<T> Subscribe(Func<T, Task> action, IDispatcher dispatcher = null)
{
var sub = new Subscription<T>(this, dispatcher ?? Dispatchers.SynchronousDispatcher, action);
_subscriptions.TryAdd(sub.Id, sub);
return sub;
}
public Subscription<T> Subscribe<TMsg>(Action<TMsg> action, IDispatcher dispatcher = null) where TMsg : T
{
var sub = new Subscription<T>(this, dispatcher ?? Dispatchers.SynchronousDispatcher, msg =>
{
if (msg is TMsg typed)
{
action(typed);
}
return Actor.Done;
});
_subscriptions.TryAdd(sub.Id, sub);
return sub;
}
public void Publish(T msg)
{
foreach (var sub in _subscriptions)
{
sub.Value.Dispatcher.Schedule(() =>
{
try
{
sub.Value.Action(msg);
}
catch (Exception ex)
{
_logger.LogWarning(0, ex, "Exception has occurred when publishing a message.");
}
return Actor.Done;
});
}
}
public void Unsubscribe(Guid id)
{
_subscriptions.TryRemove(id, out var _);
}
}
public class Subscription<T>
{
private readonly EventStream<T> _eventStream;
public Subscription(EventStream<T> eventStream, IDispatcher dispatcher, Func<T, Task> action)
{
Id = Guid.NewGuid();
_eventStream = eventStream;
Dispatcher = dispatcher;
Action = action;
}
public Guid Id { get; }
public IDispatcher Dispatcher { get; }
public Func<T, Task> Action { get; }
public void Unsubscribe()
{
_eventStream.Unsubscribe(Id);
}
}
} | 32.154472 | 118 | 0.490518 | [
"Apache-2.0"
] | IvanWhisper/protoactor-dotnet | src/Proto.Actor/EventStream.cs | 3,957 | C# |
using System;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayBusinessOrderQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipayBusinessOrderQueryModel : AlipayObject
{
/// <summary>
/// 商户外部订单号,和支付宝订单号不能同时为空。注:商户已获取order_no(支付宝订单号)的情况下必须优先传入order_no
/// </summary>
[JsonProperty("merchant_order_no")]
public string MerchantOrderNo { get; set; }
/// <summary>
/// 支付宝订单号,与商户外部订单号不能同时为空。注:商户已获取order_no的情况下必须优先传入order_no
/// </summary>
[JsonProperty("order_no")]
public string OrderNo { get; set; }
/// <summary>
/// 商户外部支付工具单据号。若不传,则认为是整单查询,将返回整个订单的所有支付工具信息。
/// </summary>
[JsonProperty("paytool_request_no")]
public string PaytoolRequestNo { get; set; }
}
}
| 28.677419 | 75 | 0.627672 | [
"MIT"
] | gebiWangshushu/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayBusinessOrderQueryModel.cs | 1,147 | C# |
using System.Web;
namespace CandidContribs.Core.Models.Shared
{
public class EventSignUpViewModel
{
public IHtmlString Text { get; set; }
public string MailchimpGroupId { get; set; }
}
} | 19.727273 | 52 | 0.668203 | [
"MIT"
] | CandidContributions/Candid-Contribs-Web | src/CandidContribs.Core/Models/Shared/EventSignUpViewModel.cs | 219 | C# |
#pragma checksum "C:\Users\sneha\Desktop\iCLASS\iCLASS\week.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "050B4E7F2E3C48A711F1D02BE33D9E4D"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace iCLASS {
public partial class week : System.Windows.Controls.UserControl {
internal System.Windows.Controls.Canvas LayoutRoot;
internal System.Windows.Controls.Button button14;
internal System.Windows.Controls.Image image33;
internal System.Windows.Controls.Button button561;
internal System.Windows.Shapes.Rectangle rectangle11;
internal System.Windows.Controls.Label label21;
internal System.Windows.Controls.Image image8;
internal System.Windows.Controls.Image image519;
internal System.Windows.Controls.Border border1;
internal System.Windows.Controls.Label label2;
internal System.Windows.Shapes.Rectangle rectangle1;
internal System.Windows.Shapes.Rectangle rectangle2;
internal System.Windows.Shapes.Rectangle rectangle3;
internal System.Windows.Shapes.Rectangle rectangle4;
internal System.Windows.Shapes.Rectangle rectangle5;
internal System.Windows.Shapes.Rectangle rectangle6;
internal System.Windows.Shapes.Rectangle rectangle7;
internal System.Windows.Controls.Border border2;
internal System.Windows.Controls.TextBlock textBlock2;
internal System.Windows.Controls.TextBlock textBlock3;
internal System.Windows.Controls.TextBlock textBlock4;
internal System.Windows.Controls.TextBlock textBlock5;
internal System.Windows.Controls.TextBlock textBlock6;
internal System.Windows.Controls.TextBlock textBlock7;
internal System.Windows.Controls.TextBlock textBlock8;
internal System.Windows.Controls.TextBlock textBlock9;
internal System.Windows.Controls.TextBlock textBlock11;
internal System.Windows.Controls.TextBlock textBlock12;
internal System.Windows.Controls.TextBlock textBlock13;
internal System.Windows.Controls.TextBlock textBlock14;
internal System.Windows.Controls.TextBlock textBlock15;
internal System.Windows.Controls.TextBlock textBlock16;
internal System.Windows.Controls.Primitives.Popup myPopup;
internal System.Windows.Controls.TextBlock PopUpText;
internal System.Windows.Controls.Button PopUpButton;
internal System.Windows.Controls.Label label1;
internal System.Windows.Controls.Label label4;
internal System.Windows.Controls.Label label5;
internal System.Windows.Controls.Label label6;
internal System.Windows.Controls.Label label7;
internal System.Windows.Controls.Label label10;
internal System.Windows.Controls.Label label11;
internal System.Windows.Controls.Label label2221;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/iCLASS;component/week.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Canvas)(this.FindName("LayoutRoot")));
this.button14 = ((System.Windows.Controls.Button)(this.FindName("button14")));
this.image33 = ((System.Windows.Controls.Image)(this.FindName("image33")));
this.button561 = ((System.Windows.Controls.Button)(this.FindName("button561")));
this.rectangle11 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle11")));
this.label21 = ((System.Windows.Controls.Label)(this.FindName("label21")));
this.image8 = ((System.Windows.Controls.Image)(this.FindName("image8")));
this.image519 = ((System.Windows.Controls.Image)(this.FindName("image519")));
this.border1 = ((System.Windows.Controls.Border)(this.FindName("border1")));
this.label2 = ((System.Windows.Controls.Label)(this.FindName("label2")));
this.rectangle1 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle1")));
this.rectangle2 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle2")));
this.rectangle3 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle3")));
this.rectangle4 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle4")));
this.rectangle5 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle5")));
this.rectangle6 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle6")));
this.rectangle7 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle7")));
this.border2 = ((System.Windows.Controls.Border)(this.FindName("border2")));
this.textBlock2 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock2")));
this.textBlock3 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock3")));
this.textBlock4 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock4")));
this.textBlock5 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock5")));
this.textBlock6 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock6")));
this.textBlock7 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock7")));
this.textBlock8 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock8")));
this.textBlock9 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock9")));
this.textBlock11 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock11")));
this.textBlock12 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock12")));
this.textBlock13 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock13")));
this.textBlock14 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock14")));
this.textBlock15 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock15")));
this.textBlock16 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock16")));
this.myPopup = ((System.Windows.Controls.Primitives.Popup)(this.FindName("myPopup")));
this.PopUpText = ((System.Windows.Controls.TextBlock)(this.FindName("PopUpText")));
this.PopUpButton = ((System.Windows.Controls.Button)(this.FindName("PopUpButton")));
this.label1 = ((System.Windows.Controls.Label)(this.FindName("label1")));
this.label4 = ((System.Windows.Controls.Label)(this.FindName("label4")));
this.label5 = ((System.Windows.Controls.Label)(this.FindName("label5")));
this.label6 = ((System.Windows.Controls.Label)(this.FindName("label6")));
this.label7 = ((System.Windows.Controls.Label)(this.FindName("label7")));
this.label10 = ((System.Windows.Controls.Label)(this.FindName("label10")));
this.label11 = ((System.Windows.Controls.Label)(this.FindName("label11")));
this.label2221 = ((System.Windows.Controls.Label)(this.FindName("label2221")));
}
}
}
| 48.950549 | 143 | 0.639466 | [
"MIT"
] | VikramadityaJakkula/MyLearnMateCode | iCLASS/obj/Debug/week.g.cs | 8,911 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace KickassUI.Banking.Droid
{
[Activity(Label = "KickassUI.Banking", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
} | 38.939394 | 192 | 0.715953 | [
"MIT"
] | sthewissen/KickassUI.Banking | KickassUI.Banking.Android/MainActivity.cs | 1,287 | C# |
using UnityEngine;
public class GTransitionView : GView
{
public const int STATE_ID_AWAITING = 0;
public const int STATE_ID_INTRO = 1;
public const int STATE_ID_ACTION = 2;
public const int STATE_ID_OUTRO = 3;
private int stateId_int = GTransitionView.STATE_ID_AWAITING;
private int targetGameStateId_int;
private GAdjustableValue alphaValue_gav;
public GTransitionView()
: base()
{
this.alphaValue_gav = new GAdjustableValue(10);
}
public void setStateId(int aStateId_int)
{
this.stateId_int = aStateId_int;
}
public int getStateId()
{
return this.stateId_int;
}
public void setTargetGameStateId(int aStateId_int)
{
this.targetGameStateId_int = aStateId_int;
}
public int getTargetGameStateId()
{
return this.targetGameStateId_int;
}
public float getAlpha()
{
switch(this.stateId_int)
{
case GTransitionView.STATE_ID_INTRO:
{
return this.alphaValue_gav.getValue();
}
case GTransitionView.STATE_ID_OUTRO:
{
return (1 - this.alphaValue_gav.getValue());
}
case GTransitionView.STATE_ID_ACTION:
{
return 1;
}
default:
{
return 0;
}
}
}
public void update()
{
if(this.alphaValue_gav.isFull())
{
switch(this.stateId_int)
{
case GTransitionView.STATE_ID_INTRO:
{
this.setStateId(GTransitionView.STATE_ID_ACTION);
}
break;
case GTransitionView.STATE_ID_ACTION:
{
this.alphaValue_gav.resetValue();
GMain.getGameController().onTransition();
this.setStateId(GTransitionView.STATE_ID_OUTRO);
}
break;
case GTransitionView.STATE_ID_OUTRO:
{
this.alphaValue_gav.resetValue();
this.setStateId(GTransitionView.STATE_ID_AWAITING);
GMain.getGameController().onTransitionEnd();
}
break;
}
}
switch(this.stateId_int)
{
case GTransitionView.STATE_ID_INTRO:
case GTransitionView.STATE_ID_OUTRO:
{
this.alphaValue_gav.update();
}
break;
}
}
} | 19.316832 | 61 | 0.705279 | [
"Apache-2.0"
] | PetrViitman/RobotsFactory | Assets/Scripts/MVC/view/GTransitionView.cs | 1,951 | C# |
// ------------------------------------------------------------------------------
// Copyright 版权所有。
// 项目名:Galaxy.Common
// 文件名:ChineseConverterHelper.cs
// 创建标识:梁桐铭 2017-03-20 11:13
// 创建描述:我们是OurGalaxy团队
//
// 修改标识:
// 修改描述:
// ------------------------------------------------------------------------------
#region 命名空间
using System.Text;
using Microsoft.International.Converters.PinYinConverter;
#endregion
namespace YoYo.Common.ChineseConverter
{
/// <summary>
/// 中英文转换帮助类
/// </summary>
public static class ChineseConverterHelper
{
/// <summary>
/// 中文转拼音
/// </summary>
/// <param name="chainessStr"></param>
/// <param name="isUppper">是否大写</param>
/// <returns></returns>
public static string ChineseConverterToSpell(this string chainessStr, bool isUppper = false)
{
//英文
var returnSpell = new StringBuilder();
foreach (var obj in chainessStr)
try
{
var chineseChar = new ChineseChar(obj);
var returnSpellChar = chineseChar.Pinyins[0]; //TODO 这里获取第一个拼音,但有可能是多音字的情况
var item = returnSpellChar.Substring(0, returnSpellChar.Length - 1);
if (!isUppper)
returnSpell.Append(item.Substring(0, 1).ToUpper() + item.Substring(1).ToLower());
else
returnSpell.Append(item);
}
catch
{
returnSpell.Append(obj.ToString());
}
return returnSpell.ToString();
}
}
} | 30.618182 | 105 | 0.478029 | [
"Apache-2.0"
] | 52ABP/YoYoCms | src/YoYo.Common/ChineseConverter/ChineseConverterHelper.cs | 1,856 | C# |
#nullable enable
// ReSharper disable once CheckNamespace
namespace Fluent
{
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using Fluent.Extensibility;
using Fluent.Internal.KnownBoxes;
/// <summary>
/// Represents button control that allows
/// you to add menu and handle clicks
/// </summary>
[TemplatePart(Name = "PART_Button", Type = typeof(ButtonBase))]
public class SplitButton : DropDownButton, IToggleButton, ICommandSource, IKeyTipInformationProvider
{
#region Fields
#pragma warning disable IDE0032
// Inner button
private ToggleButton? button;
#pragma warning restore IDE0032
private SplitButton? quickAccessButton;
#endregion
#region Properties
// ReSharper disable once ConvertToAutoPropertyWithPrivateSetter
internal ToggleButton? Button => this.button;
#region Command
/// <inheritdoc />
[Category("Action")]
[Localizability(LocalizationCategory.NeverLocalize)]
[Bindable(true)]
public ICommand Command
{
get
{
return (ICommand)this.GetValue(CommandProperty);
}
set
{
this.SetValue(CommandProperty, value);
}
}
/// <inheritdoc />
[Bindable(true)]
[Localizability(LocalizationCategory.NeverLocalize)]
[Category("Action")]
public object CommandParameter
{
get
{
return this.GetValue(CommandParameterProperty);
}
set
{
this.SetValue(CommandParameterProperty, value);
}
}
/// <inheritdoc />
[Bindable(true)]
[Category("Action")]
public IInputElement CommandTarget
{
get
{
return (IInputElement)this.GetValue(CommandTargetProperty);
}
set
{
this.SetValue(CommandTargetProperty, value);
}
}
/// <summary>Identifies the <see cref="CommandParameter"/> dependency property.</summary>
public static readonly DependencyProperty CommandParameterProperty = ButtonBase.CommandParameterProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata());
/// <summary>Identifies the <see cref="Command"/> dependency property.</summary>
public static readonly DependencyProperty CommandProperty = ButtonBase.CommandProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata());
/// <summary>Identifies the <see cref="CommandTarget"/> dependency property.</summary>
public static readonly DependencyProperty CommandTargetProperty = ButtonBase.CommandTargetProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata());
#endregion
#region GroupName
/// <inheritdoc />
public string? GroupName
{
get { return (string?)this.GetValue(GroupNameProperty); }
set { this.SetValue(GroupNameProperty, value); }
}
/// <summary>Identifies the <see cref="GroupName"/> dependency property.</summary>
public static readonly DependencyProperty GroupNameProperty = DependencyProperty.Register(nameof(GroupName), typeof(string), typeof(SplitButton));
#endregion
#region IsChecked
/// <inheritdoc />
public bool? IsChecked
{
get { return (bool?)this.GetValue(IsCheckedProperty); }
set { this.SetValue(IsCheckedProperty, BooleanBoxes.Box(value)); }
}
/// <summary>Identifies the <see cref="IsChecked"/> dependency property.</summary>
public static readonly DependencyProperty IsCheckedProperty = System.Windows.Controls.Primitives.ToggleButton.IsCheckedProperty.AddOwner(typeof(SplitButton), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, OnIsCheckedChanged, CoerceIsChecked));
private static void OnIsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var button = (SplitButton)d;
if (button.IsCheckable)
{
var nullable = (bool?)e.NewValue;
if (nullable is null)
{
button.RaiseEvent(new RoutedEventArgs(IndeterminateEvent, button));
}
else if (nullable.Value)
{
button.RaiseEvent(new RoutedEventArgs(CheckedEvent, button));
}
else
{
button.RaiseEvent(new RoutedEventArgs(UncheckedEvent, button));
}
}
}
private static object? CoerceIsChecked(DependencyObject d, object? basevalue)
{
var button = (SplitButton)d;
if (button.IsCheckable == false)
{
return BooleanBoxes.FalseBox;
}
return basevalue;
}
#endregion
#region IsCheckable
/// <summary>
/// Gets or sets a value indicating whether SplitButton can be checked
/// </summary>
public bool IsCheckable
{
get { return (bool)this.GetValue(IsCheckableProperty); }
set { this.SetValue(IsCheckableProperty, BooleanBoxes.Box(value)); }
}
/// <summary>Identifies the <see cref="IsCheckable"/> dependency property.</summary>
public static readonly DependencyProperty IsCheckableProperty =
DependencyProperty.Register(nameof(IsCheckable), typeof(bool), typeof(SplitButton), new PropertyMetadata(BooleanBoxes.FalseBox));
#endregion
#region DropDownToolTip
/// <summary>
/// Gets or sets tooltip of dropdown part of split button
/// </summary>
public object? DropDownToolTip
{
get { return this.GetValue(DropDownToolTipProperty); }
set { this.SetValue(DropDownToolTipProperty, value); }
}
/// <summary>Identifies the <see cref="DropDownToolTip"/> dependency property.</summary>
public static readonly DependencyProperty DropDownToolTipProperty =
DependencyProperty.Register(nameof(DropDownToolTip), typeof(object), typeof(SplitButton), new PropertyMetadata());
#endregion
#region IsButtonEnabled
/// <summary>
/// Gets or sets a value indicating whether the button part of split button is enabled.
/// If you want to disable the button part and the DropDown please use <see cref="UIElement.IsEnabled"/>.
/// </summary>
public bool IsButtonEnabled
{
get { return (bool)this.GetValue(IsButtonEnabledProperty); }
set { this.SetValue(IsButtonEnabledProperty, BooleanBoxes.Box(value)); }
}
/// <summary>Identifies the <see cref="IsButtonEnabled"/> dependency property.</summary>
public static readonly DependencyProperty IsButtonEnabledProperty =
DependencyProperty.Register(nameof(IsButtonEnabled), typeof(bool), typeof(SplitButton), new PropertyMetadata(BooleanBoxes.TrueBox));
#endregion
#region IsDefinitive
/// <summary>
/// Gets or sets whether ribbon control click must close backstage
/// </summary>
public bool IsDefinitive
{
get { return (bool)this.GetValue(IsDefinitiveProperty); }
set { this.SetValue(IsDefinitiveProperty, BooleanBoxes.Box(value)); }
}
/// <summary>Identifies the <see cref="IsDefinitive"/> dependency property.</summary>
public static readonly DependencyProperty IsDefinitiveProperty =
DependencyProperty.Register(nameof(IsDefinitive), typeof(bool), typeof(SplitButton), new PropertyMetadata(BooleanBoxes.TrueBox));
#endregion
#region KeyTipPostfix
/// <summary>Identifies the <see cref="PrimaryActionKeyTipPostfix"/> dependency property.</summary>
public static readonly DependencyProperty PrimaryActionKeyTipPostfixProperty = DependencyProperty.Register(nameof(PrimaryActionKeyTipPostfix), typeof(string), typeof(SplitButton), new PropertyMetadata("A"));
/// <summary>
/// Gets or sets the postfix for the primary keytip action.
/// </summary>
public string PrimaryActionKeyTipPostfix
{
get { return (string)this.GetValue(PrimaryActionKeyTipPostfixProperty); }
set { this.SetValue(PrimaryActionKeyTipPostfixProperty, value); }
}
/// <summary>Identifies the <see cref="SecondaryActionKeyTipPostfix"/> dependency property.</summary>
public static readonly DependencyProperty SecondaryActionKeyTipPostfixProperty = DependencyProperty.Register(nameof(SecondaryActionKeyTipPostfix), typeof(string), typeof(SplitButton), new PropertyMetadata("B"));
/// <summary>
/// Gets or sets the postfix for the secondary keytip action.
/// </summary>
public string SecondaryActionKeyTipPostfix
{
get { return (string)this.GetValue(SecondaryActionKeyTipPostfixProperty); }
set { this.SetValue(SecondaryActionKeyTipPostfixProperty, value); }
}
#endregion KeyTipPostfix
/// <summary>Identifies the <see cref="SecondaryKeyTip"/> dependency property.</summary>
public static readonly DependencyProperty SecondaryKeyTipProperty = DependencyProperty.Register(nameof(SecondaryKeyTip), typeof(string), typeof(SplitButton), new PropertyMetadata(StringBoxes.Empty));
/// <summary>
/// Gets or sets the keytip for the secondary action.
/// </summary>
public string SecondaryKeyTip
{
get { return (string)this.GetValue(SecondaryKeyTipProperty); }
set { this.SetValue(SecondaryKeyTipProperty, value); }
}
#endregion
#region Events
/// <summary>
/// Occurs when user clicks
/// </summary>
public static readonly RoutedEvent ClickEvent = ButtonBase.ClickEvent.AddOwner(typeof(SplitButton));
/// <summary>
/// Occurs when user clicks
/// </summary>
public event RoutedEventHandler Click
{
add
{
this.AddHandler(ClickEvent, value);
}
remove
{
this.RemoveHandler(ClickEvent, value);
}
}
/// <summary>
/// Occurs when button is checked
/// </summary>
public static readonly RoutedEvent CheckedEvent = System.Windows.Controls.Primitives.ToggleButton.CheckedEvent.AddOwner(typeof(SplitButton));
/// <summary>
/// Occurs when button is checked
/// </summary>
public event RoutedEventHandler Checked
{
add
{
this.AddHandler(CheckedEvent, value);
}
remove
{
this.RemoveHandler(CheckedEvent, value);
}
}
/// <summary>
/// Occurs when button is unchecked
/// </summary>
public static readonly RoutedEvent UncheckedEvent = System.Windows.Controls.Primitives.ToggleButton.UncheckedEvent.AddOwner(typeof(SplitButton));
/// <summary>
/// Occurs when button is unchecked
/// </summary>
public event RoutedEventHandler Unchecked
{
add
{
this.AddHandler(UncheckedEvent, value);
}
remove
{
this.RemoveHandler(UncheckedEvent, value);
}
}
/// <summary>
/// Occurs when button is unchecked
/// </summary>
public static readonly RoutedEvent IndeterminateEvent = System.Windows.Controls.Primitives.ToggleButton.IndeterminateEvent.AddOwner(typeof(SplitButton));
/// <summary>
/// Occurs when button is unchecked
/// </summary>
public event RoutedEventHandler Indeterminate
{
add
{
this.AddHandler(IndeterminateEvent, value);
}
remove
{
this.RemoveHandler(IndeterminateEvent, value);
}
}
#endregion
#region Constructors
static SplitButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(typeof(SplitButton)));
FocusVisualStyleProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata());
}
/// <summary>
/// Default constructor
/// </summary>
public SplitButton()
{
ContextMenuService.Coerce(this);
this.Click += this.OnClick;
this.Loaded += this.OnLoaded;
this.Unloaded += this.OnUnloaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.SubscribeEvents();
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
this.UnSubscribeEvents();
}
private void SubscribeEvents()
{
// Always unsubscribe events to ensure we don't subscribe twice
this.UnSubscribeEvents();
if (this.button is not null)
{
this.button.Click += this.OnButtonClick;
}
}
private void UnSubscribeEvents()
{
if (this.button is not null)
{
this.button.Click -= this.OnButtonClick;
}
}
private void OnClick(object sender, RoutedEventArgs e)
{
if (ReferenceEquals(e.OriginalSource, this) == false
&& ReferenceEquals(e.OriginalSource, this.quickAccessButton) == false)
{
e.Handled = true;
}
}
#endregion
#region Overrides
/// <inheritdoc />
public override void OnApplyTemplate()
{
this.UnSubscribeEvents();
this.button = this.GetTemplateChild("PART_Button") as ToggleButton;
base.OnApplyTemplate();
this.SubscribeEvents();
}
/// <inheritdoc />
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!PopupService.IsMousePhysicallyOver(this.button))
{
base.OnPreviewMouseLeftButtonDown(e);
}
else
{
this.IsDropDownOpen = false;
}
}
/// <inheritdoc />
protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonSplitButtonAutomationPeer(this);
#region Overrides of DropDownButton
/// <inheritdoc />
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter)
{
this.button?.InvokeClick();
}
}
#endregion
internal void AutomationButtonClick()
{
this.button?.InvokeClick();
}
private void OnButtonClick(object sender, RoutedEventArgs e)
{
e.Handled = true;
this.RaiseEvent(new RoutedEventArgs(ClickEvent, this));
}
#endregion
#region Quick Access Item Creating
/// <inheritdoc />
public override FrameworkElement CreateQuickAccessItem()
{
var buttonForQAT = new SplitButton
{
CanAddButtonToQuickAccessToolBar = false
};
buttonForQAT.Click += (sender, e) => this.RaiseEvent(e);
buttonForQAT.DropDownOpened += this.OnQuickAccessOpened;
RibbonProperties.SetSize(buttonForQAT, RibbonControlSize.Small);
this.BindQuickAccessItem(buttonForQAT);
this.BindQuickAccessItemDropDownEvents(buttonForQAT);
this.quickAccessButton = buttonForQAT;
return buttonForQAT;
}
/// <inheritdoc />
protected override void BindQuickAccessItem(FrameworkElement element)
{
RibbonControl.Bind(this, element, nameof(this.DisplayMemberPath), DisplayMemberPathProperty, BindingMode.OneWay);
RibbonControl.Bind(this, element, nameof(this.GroupStyleSelector), GroupStyleSelectorProperty, BindingMode.OneWay);
RibbonControl.Bind(this, element, nameof(this.ItemContainerStyle), ItemContainerStyleProperty, BindingMode.OneWay);
RibbonControl.Bind(this, element, nameof(this.ItemsPanel), ItemsPanelProperty, BindingMode.OneWay);
RibbonControl.Bind(this, element, nameof(this.ItemStringFormat), ItemStringFormatProperty, BindingMode.OneWay);
RibbonControl.Bind(this, element, nameof(this.ItemTemplate), ItemTemplateProperty, BindingMode.OneWay);
RibbonControl.Bind(this, element, nameof(this.MaxDropDownHeight), MaxDropDownHeightProperty, BindingMode.OneWay);
RibbonControl.Bind(this, element, nameof(this.IsChecked), IsCheckedProperty, BindingMode.TwoWay);
RibbonControl.Bind(this, element, nameof(this.DropDownToolTip), DropDownToolTipProperty, BindingMode.TwoWay);
RibbonControl.Bind(this, element, nameof(this.IsCheckable), IsCheckableProperty, BindingMode.Default);
RibbonControl.Bind(this, element, nameof(this.IsButtonEnabled), IsButtonEnabledProperty, BindingMode.Default);
RibbonControl.Bind(this, element, nameof(this.ContextMenu), ContextMenuProperty, BindingMode.Default);
RibbonControl.Bind(this, element, nameof(this.ResizeMode), ResizeModeProperty, BindingMode.Default);
RibbonControl.Bind(this, element, nameof(this.MaxDropDownHeight), MaxDropDownHeightProperty, BindingMode.Default);
RibbonControl.Bind(this, element, nameof(this.HasTriangle), HasTriangleProperty, BindingMode.Default);
RibbonControl.BindQuickAccessItem(this, element);
}
/// <summary>
/// Gets or sets whether button can be added to quick access toolbar
/// </summary>
public bool CanAddButtonToQuickAccessToolBar
{
get { return (bool)this.GetValue(CanAddButtonToQuickAccessToolBarProperty); }
set { this.SetValue(CanAddButtonToQuickAccessToolBarProperty, BooleanBoxes.Box(value)); }
}
/// <summary>Identifies the <see cref="CanAddButtonToQuickAccessToolBar"/> dependency property.</summary>
public static readonly DependencyProperty CanAddButtonToQuickAccessToolBarProperty = DependencyProperty.Register(nameof(CanAddButtonToQuickAccessToolBar), typeof(bool), typeof(SplitButton), new PropertyMetadata(BooleanBoxes.TrueBox, RibbonControl.OnCanAddToQuickAccessToolBarChanged));
#region Implementation of IKeyTipInformationProvider
/// <inheritdoc />
public IEnumerable<KeyTipInformation> GetKeyTipInformations(bool hide)
{
if (string.IsNullOrEmpty(this.KeyTip) == false
&& this.button is not null)
{
if (string.IsNullOrEmpty(this.SecondaryKeyTip))
{
yield return new KeyTipInformation(this.KeyTip + this.PrimaryActionKeyTipPostfix, this.button, hide)
{
VisualTarget = this
};
}
else
{
yield return new KeyTipInformation(this.KeyTip!, this.button, hide)
{
VisualTarget = this
};
}
}
if (string.IsNullOrEmpty(this.SecondaryKeyTip) == false)
{
yield return new KeyTipInformation(this.SecondaryKeyTip, this, hide);
}
else if (string.IsNullOrEmpty(this.KeyTip) == false)
{
yield return new KeyTipInformation(this.KeyTip + this.SecondaryActionKeyTipPostfix, this, hide);
}
}
#endregion
#endregion
/// <inheritdoc />
protected override IEnumerator LogicalChildren
{
get
{
var baseEnumerator = base.LogicalChildren;
while (baseEnumerator?.MoveNext() == true)
{
yield return baseEnumerator.Current;
}
if (this.button is not null)
{
yield return this.button;
}
}
}
}
}
| 35.964467 | 355 | 0.607057 | [
"MIT"
] | chandusekhar/Fluent.Ribbon | Fluent.Ribbon/Controls/SplitButton.cs | 21,257 | C# |
using Microsoft.AspNetCore.Http;
using NetDream.Web.Areas.Open.Entities;
using NetDream.Web.Base.Helpers;
using NetDream.Core.Helpers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace NetDream.Web.Areas.Open.Models
{
public class PlatformModel: PlatformEntity
{
/// <summary>
/// 根据路径判断是否允许访问此路径
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public bool VerifyRule(string uri)
{
var path = uri.Replace("/open/", "").ToLower();
if (string.IsNullOrEmpty(path))
{
return true;
}
foreach (var rule in Rules.Split("\n"))
{
if (string.IsNullOrWhiteSpace(rule))
{
continue;
}
if (rule.StartsWith('-'))
{
if (VerifyOneRule(rule.Trim()[1..], path))
{
return false;
}
continue;
}
if (VerifyOneRule(rule.Trim(), path))
{
return true;
}
}
return true;
}
private static bool VerifyOneRule(string rule, string path)
{
if (rule == "*")
{
return true;
}
return (rule[0]) switch
{
'@' => true,// 验证模块,暂缺
'^' => Regex.IsMatch(path, rule),
'~' => Regex.IsMatch(path, rule[1..]),
_ => rule == path,
};
}
public bool VerifyRest(HttpContext context)
{
if (SignType < 1)
{
return true;
}
if (SignType == 1)
{
var data = new Dictionary<string, string>();
foreach (var item in context.Request.Query)
{
if (item.Key == "sign")
{
continue;
}
data.Add(item.Key, item.Value.ToString());
}
return Sign(data) == context.Request.Query["sign"].ToString();
}
return false;
}
public string Sign(Dictionary<string, string> data)
{
if (SignType < 1)
{
return "";
}
var content = GetSignContent(data);
if (SignType == 1)
{
return Str.MD5Encode(content);
}
return "";
}
private string GetSignContent(Dictionary<string, string> data)
{
data.TryAdd("appid", Appid);
data.TryAdd("secret", Secret);
var sb = new StringBuilder();
if (SignKey.IndexOf('+') < 0)
{
var keys = data.Select(item => item.Key).OrderBy(item => item).ToArray();
foreach (var key in keys)
{
sb.Append(data[key]);
}
sb.Append(SignKey);
return sb.ToString();
}
foreach (var key in SignKey.Split('+'))
{
if (string.IsNullOrWhiteSpace(key))
{
sb.Append('+');
continue;
}
if (data.ContainsKey(key))
{
sb.Append(data[key]);
continue;
}
}
return sb.ToString();
}
}
}
| 28.454545 | 89 | 0.403088 | [
"MIT"
] | zx648383079/netdream | src/NetDream.Web/Areas/Open/Models/PlatformModel.cs | 3,802 | C# |
using System;
using UnityEngine;
using UnityEngine.UI;
namespace GameOver.Ranking
{
/// <summary>
/// ランキングコンテンツのプレイヤー要素
/// </summary>
internal class RankingElement : MonoBehaviour
{
[SerializeField] private Text _textRank;
[SerializeField] private Text _textValue;
[SerializeField] private Text _textPlayerName;
[SerializeField] private Image _imgMedal;
[SerializeField] private Image _imgRankBack;
[Serializable]
private struct RankColor
{
public int rank;
public Color text;
public Color back;
}
[SerializeField] private RankColor[] _rankColors;
[SerializeField] private RankColor _rankColorDefault;
[SerializeField] private Sprite _sprMedal1st;
[SerializeField] private Sprite _sprMedal2nd;
[SerializeField] private Sprite _sprMedal3rd;
public void Initialize(int rank, int value, string playerName)
{
_textRank.text = rank.ToString();
_textValue.text = value.ToString();
_textPlayerName.text = playerName;
switch (rank)
{
case 1:
_imgMedal.enabled = true;
_imgMedal.sprite = _sprMedal1st;
break;
case 2:
_imgMedal.enabled = true;
_imgMedal.sprite = _sprMedal2nd;
break;
case 3:
_imgMedal.enabled = true;
_imgMedal.sprite = _sprMedal3rd;
break;
default:
_imgMedal.enabled = false;
break;
}
var index = Array.FindIndex(_rankColors, x => x.rank == rank);
var rankColor = index >= 0 ? _rankColors[index] : _rankColorDefault;
_textRank.color = rankColor.text;
_imgRankBack.color = rankColor.back;
}
}
} | 30.102941 | 80 | 0.538349 | [
"MIT"
] | nekojara-city/neko-maze | Assets/Scripts/GameOver/Ranking/RankingElement.cs | 2,085 | C# |
namespace DataStructures.Continuous
{
/// <summary>
/// Possible redundancy types for items in a continuous set.
/// </summary>
public enum RedundancyType
{
/// <summary>
/// No redundancies.
/// </summary>
None,
/// <summary>
/// Only redundant negatives.
/// </summary>
Negative,
/// <summary>
/// Only redundant positives.
/// </summary>
Positive,
/// <summary>
/// All redundancies.
/// </summary>
All,
}
} | 20.178571 | 64 | 0.477876 | [
"MIT"
] | masbicudo/data-structures-net | DataStructures/Continuous/RedundancyType.cs | 565 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System
{
internal sealed class WasmConsoleStream : ConsoleStream
{
private readonly SafeFileHandle _handle;
internal WasmConsoleStream(SafeFileHandle handle, FileAccess access)
: base(access)
{
_handle = handle;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_handle.Dispose();
}
base.Dispose(disposing);
}
public override int Read(byte[] buffer, int offset, int count) => throw Error.GetReadNotSupported();
public override unsafe void Write(byte[] buffer, int offset, int count)
{
ValidateWrite(buffer, offset, count);
fixed (byte* bufPtr = buffer)
{
Write(_handle, bufPtr + offset, count);
}
}
private static unsafe void Write(SafeFileHandle fd, byte* bufPtr, int count)
{
while (count > 0)
{
int bytesWritten = Interop.Sys.Write(fd, bufPtr, count);
if (bytesWritten < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
{
return;
}
else
{
throw Interop.GetIOException(errorInfo);
}
}
count -= bytesWritten;
bufPtr += bytesWritten;
}
}
public override void Flush()
{
if (_handle.IsClosed)
{
throw Error.GetFileNotOpen();
}
base.Flush();
}
}
internal static class ConsolePal
{
private static Encoding? s_outputEncoding;
internal static void EnsureConsoleInitialized() { }
public static Stream OpenStandardInput() => throw new PlatformNotSupportedException();
public static Stream OpenStandardOutput()
{
return new WasmConsoleStream(Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDOUT_FILENO), FileAccess.Write);
}
public static Stream OpenStandardError()
{
return new WasmConsoleStream(Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDERR_FILENO), FileAccess.Write);
}
public static Encoding InputEncoding => throw new PlatformNotSupportedException();
public static void SetConsoleInputEncoding(Encoding enc) => throw new PlatformNotSupportedException();
public static Encoding OutputEncoding => s_outputEncoding ?? Encoding.UTF8;
public static void SetConsoleOutputEncoding(Encoding enc) => s_outputEncoding = enc;
public static bool IsInputRedirectedCore() => false;
public static bool IsOutputRedirectedCore() => false;
public static bool IsErrorRedirectedCore() => false;
internal static TextReader GetOrCreateReader() => throw new PlatformNotSupportedException();
public static bool NumberLock => throw new PlatformNotSupportedException();
public static bool CapsLock => throw new PlatformNotSupportedException();
public static bool KeyAvailable => false;
public static ConsoleKeyInfo ReadKey(bool intercept) => throw new PlatformNotSupportedException();
public static bool TreatControlCAsInput
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static ConsoleColor BackgroundColor
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static ConsoleColor ForegroundColor
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static void ResetColor() => throw new PlatformNotSupportedException();
public static int CursorSize
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static bool CursorVisible
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static (int Left, int Top) GetCursorPosition() => throw new PlatformNotSupportedException();
public static string Title
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static void Beep() => throw new PlatformNotSupportedException();
public static void Beep(int frequency, int duration) => throw new PlatformNotSupportedException();
public static void MoveBufferArea(int sourceLeft, int sourceTop,
int sourceWidth, int sourceHeight, int targetLeft, int targetTop,
char sourceChar, ConsoleColor sourceForeColor,
ConsoleColor sourceBackColor) => throw new PlatformNotSupportedException();
public static void Clear() => throw new PlatformNotSupportedException();
public static void SetCursorPosition(int left, int top) => throw new PlatformNotSupportedException();
public static int BufferWidth
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static int BufferHeight
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static void SetBufferSize(int width, int height) => throw new PlatformNotSupportedException();
public static int LargestWindowWidth => throw new PlatformNotSupportedException();
public static int LargestWindowHeight => throw new PlatformNotSupportedException();
public static int WindowLeft
{
get => 0;
set => throw new PlatformNotSupportedException();
}
public static int WindowTop
{
get => 0;
set => throw new PlatformNotSupportedException();
}
public static int WindowWidth
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static int WindowHeight
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public static void SetWindowPosition(int left, int top) => throw new PlatformNotSupportedException();
public static void SetWindowSize(int width, int height) => throw new PlatformNotSupportedException();
internal sealed class ControlCHandlerRegistrar
{
internal ControlCHandlerRegistrar() => throw new PlatformNotSupportedException();
internal void Register() => throw new PlatformNotSupportedException();
internal void Unregister() => throw new PlatformNotSupportedException();
}
}
}
| 33.76652 | 119 | 0.620091 | [
"MIT"
] | WonyoungChoi/runtime | src/libraries/System.Console/src/System/ConsolePal.WebAssembly.cs | 7,665 | C# |
namespace SkorinosGimnazija.Application.Authorization;
using Common.Interfaces;
using Dtos;
using FluentValidation;
using MediatR;
public static class UserAuthorize
{
public record Command(GoogleAuthDto GoogleAuth) : IRequest<UserAuthDto>;
public class Validator : AbstractValidator<Command>
{
public Validator()
{
RuleFor(v => v.GoogleAuth)
.NotNull()
.DependentRules(() =>
{
RuleFor(v => v.GoogleAuth.Token).NotEmpty();
});
}
}
public class Handler : IRequestHandler<Command, UserAuthDto>
{
private readonly IIdentityService _identityService;
public Handler(IIdentityService identityService)
{
_identityService = identityService;
}
public async Task<UserAuthDto> Handle(Command request, CancellationToken _)
{
return await _identityService.AuthorizeAsync(request.GoogleAuth.Token);
}
}
} | 26.25641 | 83 | 0.620117 | [
"MIT"
] | SkorinosGimnazija/api.skorinosgimnazija.lt | src/Application/Authorization/UserAuthorize.cs | 1,026 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BACnet.Types.Values
{
public class ObjectIdValue : IValue
{
/// <summary>
/// The value type for object id values
/// </summary>
public ValueType Type { get { return ValueType.ObjectId; } }
/// <summary>
/// The wrapped object id value
/// </summary>
public ObjectId Value { get; private set; }
/// <summary>
/// Constructs a new ObjectIdValue instance
/// </summary>
/// <param name="value">The value being wrapped</param>
public ObjectIdValue(ObjectId value)
{
this.Value = value;
}
}
}
| 24.612903 | 68 | 0.579292 | [
"MIT"
] | LorenVS/bacstack | BACnet.Types/Values/ObjectIdValue.cs | 765 | C# |
// MIT License
// Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns
// Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;
namespace Steropes.UI.Input.MouseInput
{
[Flags]
public enum MouseButton
{
None = 0,
Left = 1 << 0,
Middle = 1 << 1,
Right = 1 << 2,
XButton1 = 1 << 3,
XButton2 = 1 << 4
}
public static class MouseButtonExtensions
{
public static List<MouseButton> GetAll()
{
return new List<MouseButton> { MouseButton.Left, MouseButton.Middle, MouseButton.Right, MouseButton.XButton1, MouseButton.XButton2 };
}
public static ButtonState StateFor(this MouseState state, MouseButton b)
{
switch (b)
{
case MouseButton.None:
return ButtonState.Released;
case MouseButton.Left:
return state.LeftButton;
case MouseButton.Middle:
return state.MiddleButton;
case MouseButton.Right:
return state.RightButton;
case MouseButton.XButton1:
return state.XButton1;
case MouseButton.XButton2:
return state.XButton2;
default:
throw new ArgumentOutOfRangeException(nameof(b), b, null);
}
}
}
} | 34.014286 | 139 | 0.702226 | [
"MIT"
] | RabbitStewDio/Steropes.UI | src/Steropes.UI/Input/MouseInput/MouseButton.cs | 2,384 | C# |
using System.Drawing;
using System.Windows.Forms;
namespace BioMetrixCore
{
public partial class DataEmpty : UserControl
{
public DataEmpty()
{
InitializeComponent();
this.Dock = DockStyle.Fill;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
ControlPaint.DrawBorder(e.Graphics, ClientRectangle,
Color.FromArgb(214, 214, 214), 2, ButtonBorderStyle.Outset,
Color.FromArgb(214, 214, 214), 2, ButtonBorderStyle.Outset,
Color.FromArgb(214, 214, 214), 2, ButtonBorderStyle.Inset,
Color.FromArgb(214, 214, 214), 2, ButtonBorderStyle.Inset);
}
}
}
| 32.307692 | 100 | 0.522619 | [
"MIT"
] | geff-mutua/C-Sharp-FingurePring-Scanner | BioMatrix/BioMetrixCore/Controls/DataEmpty.cs | 842 | C# |
using System;
using System.Net;
using System.Net.Sockets;
namespace TcpS
{
class Program
{
static void Main(string[] args)
{
TcpListener server = null;
int port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
try
{
server = new TcpListener(localAddr, port);
server.Start();
byte[] bytes = new byte[1024];
string data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("连接上了!");
NetworkStream stream = client.GetStream();
int i = stream.Read(bytes, 0, bytes.Length);
data = System.Text.Encoding.Default.GetString(bytes, 0, i);
Console.WriteLine("服务端接收请求: {0}", data);
string str = "响应数据1";
bytes = System.Text.Encoding.Default.GetBytes(str);
stream.Write(bytes, 0, bytes.Length);
Console.WriteLine($"响应数据:{str}");
client.Close();
}
}
catch
{
Console.WriteLine("异常");
}
finally
{
server.Stop();
}
}
}
}
| 27.98 | 79 | 0.433881 | [
"Apache-2.0"
] | Lyd889911/tcp | TcpTest/TcpServer/Program.cs | 1,443 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetActiveToggle : MonoBehaviour
{
public GameObject toToggle;
public string tagToggle;
public void Toggle()
{
if(toToggle == null)
{
toToggle = GameObject.FindGameObjectWithTag(tagToggle);
}
toToggle.SetActive(!toToggle.activeInHierarchy);
}
}
| 20.2 | 67 | 0.670792 | [
"MIT"
] | renatusdev/Dig-Seek | Assets/Scripts/UI/SetActiveToggle.cs | 406 | C# |
using Photon;
using UnityEngine;
public class SmoothSyncMovement2 : Photon.MonoBehaviour
{
public float SmoothingDelay = 5f;
public bool disabled;
private Vector3 correctPlayerPos = Vector3.zero;
private Quaternion correctPlayerRot = Quaternion.identity;
public void Awake()
{
if (base.photonView == null || base.photonView.observed != this)
{
Debug.LogWarning(string.Concat(this, " is not observed by this object's photonView! OnPhotonSerializeView() in this class won't be used."));
}
if (IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.SINGLE)
{
base.enabled = false;
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
stream.SendNext(base.transform.position);
stream.SendNext(base.transform.rotation);
}
else
{
correctPlayerPos = (Vector3)stream.ReceiveNext();
correctPlayerRot = (Quaternion)stream.ReceiveNext();
}
}
public void Update()
{
if (!disabled && !base.photonView.isMine)
{
base.transform.position = Vector3.Lerp(base.transform.position, correctPlayerPos, Time.deltaTime * SmoothingDelay);
base.transform.rotation = Quaternion.Lerp(base.transform.rotation, correctPlayerRot, Time.deltaTime * SmoothingDelay);
}
}
}
| 25.612245 | 143 | 0.738645 | [
"MIT"
] | AoTTG-R/mocha | Assembly-CSharp/FengLi/Networking/SmoothSyncMovement2.cs | 1,255 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Roslynator.CSharp.Refactorings
{
internal static class RemoveRedundantCallRefactoring
{
public static Task<Document> RefactorAsync(
Document document,
InvocationExpressionSyntax invocation,
CancellationToken cancellationToken)
{
var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression;
ExpressionSyntax newExpression = memberAccess.Expression
.AppendToTrailingTrivia(
memberAccess.OperatorToken.GetLeadingAndTrailingTrivia()
.Concat(memberAccess.Name.GetLeadingAndTrailingTrivia())
.Concat(invocation.ArgumentList.OpenParenToken.GetLeadingAndTrailingTrivia())
.Concat(invocation.ArgumentList.CloseParenToken.GetLeadingAndTrailingTrivia()));
newExpression = newExpression.WithFormatterAnnotation();
return document.ReplaceNodeAsync(invocation, newExpression, cancellationToken);
}
}
} | 42.15625 | 160 | 0.706449 | [
"Apache-2.0"
] | TechnoridersForks/Roslynator | source/Analyzers/Refactorings/RemoveRedundantCallRefactoring.cs | 1,351 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace Decos.Fixi.Models
{
/// <summary>
/// Represents the modifiable properties of a user.
/// </summary>
public class UserData
{
/// <summary>
/// Gets or sets the person's address.
/// </summary>
public string Address { get; set; }
/// <summary>
/// Gets or sets the object ID of the associated Azure AD user account.
/// </summary>
public Guid? AzureADObjectId { get; set; }
/// <summary>
/// Gets or sets the Decos IDP User ID of the person, or a null reference if
/// the person does not use a Decos IDP account.
/// </summary>
public Guid? DecosUserID { get; set; }
/// <summary>
/// Gets or sets an email address for contacting the person.
/// </summary>
[MaxLength(254)]
public string EmailAddress { get; set; }
/// <summary>
/// Gets or sets the Facebook user ID of the person, or a null reference if
/// the person does not use a Facebook account.
/// </summary>
[MaxLength(128)]
public string FacebookUserID { get; set; }
/// <summary>
/// Gets or sets the Google user ID of the person, or a null reference if the
/// person does not use a Google account.
/// </summary>
[MaxLength(128)]
public string GoogleUserID { get; set; }
/// <summary>
/// Gets or sets the person's full name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets a phone number for contacting the person.
/// </summary>
public string PhoneNumber { get; set; }
/// <summary>
/// Returns a string representing the person.
/// </summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString()
{
return Name ?? EmailAddress ?? PhoneNumber;
}
}
} | 28.484848 | 81 | 0.61383 | [
"MIT"
] | DecosInformationSolutions/FixiClient-dotnet | Models/UserData.cs | 1,882 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Alphas.Analysis;
using QuantConnect.Algorithm.Framework.Alphas.Analysis.Providers;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Algorithm.Framework
{
/// <summary>
/// Algorithm framework base class that enforces a modular approach to algorithm development
/// </summary>
public partial class QCAlgorithmFramework : QCAlgorithm
{
private readonly ISecurityValuesProvider _securityValuesProvider;
/// <summary>
/// Enables additional logging of framework models including:
/// All insights, portfolio targets, order events, and any risk management altered targets
/// </summary>
public bool DebugMode { get; set; }
/// <summary>
/// Returns true since algorithms derived from this use the framework
/// </summary>
public override bool IsFrameworkAlgorithm => true;
/// <summary>
/// Gets or sets the universe selection model.
/// </summary>
public IUniverseSelectionModel UniverseSelection { get; set; }
/// <summary>
/// Gets or sets the alpha model
/// </summary>
public IAlphaModel Alpha { get; set; }
/// <summary>
/// Gets or sets the portoflio construction model
/// </summary>
public IPortfolioConstructionModel PortfolioConstruction { get; set; }
/// <summary>
/// Gets or sets the execution model
/// </summary>
public IExecutionModel Execution { get; set; }
/// <summary>
/// Gets or sets the risk management model
/// </summary>
public IRiskManagementModel RiskManagement { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="QCAlgorithmFramework"/> class
/// </summary>
public QCAlgorithmFramework()
{
_securityValuesProvider = new AlgorithmSecurityValuesProvider(this);
// set model defaults
Execution = new ImmediateExecutionModel();
RiskManagement = new NullRiskManagementModel();
}
/// <summary>
/// Called by setup handlers after Initialize and allows the algorithm a chance to organize
/// the data gather in the Initialize method
/// </summary>
public override void PostInitialize()
{
CheckModels();
foreach (var universe in UniverseSelection.CreateUniverses(this))
{
AddUniverse(universe);
}
if (DebugMode)
{
InsightsGenerated += (algorithm, data) => Log($"{Time}: {string.Join(" | ", data.Insights.OrderBy(i => i.Symbol.ToString()))}");
}
// emit warning message about using the framework with cash modelling
if (BrokerageModel.AccountType == AccountType.Cash)
{
Error("These models are currently unsuitable for Cash Modeled brokerages (e.g. GDAX) and may result in unexpected trades."
+ " To prevent possible user error we've restricted them to Margin trading. You can select margin account types with"
+ " SetBrokerage( ... AccountType.Margin)");
}
base.PostInitialize();
}
/// <summary>
/// Used to send data updates to algorithm framework models
/// </summary>
/// <param name="slice">The current data slice</param>
public sealed override void OnFrameworkData(Slice slice)
{
if (UtcTime >= UniverseSelection.GetNextRefreshTimeUtc())
{
var universes = UniverseSelection.CreateUniverses(this).ToDictionary(u => u.Configuration.Symbol);
// remove deselected universes by symbol
foreach (var ukvp in UniverseManager)
{
var universeSymbol = ukvp.Key;
var qcUserDefined = UserDefinedUniverse.CreateSymbol(ukvp.Value.SecurityType, ukvp.Value.Market);
if (universeSymbol.Equals(qcUserDefined))
{
// prevent removal of qc algorithm created user defined universes
continue;
}
Universe universe;
if (!universes.TryGetValue(universeSymbol, out universe))
{
if (ukvp.Value.DisposeRequested)
{
UniverseManager.Remove(universeSymbol);
}
// mark this universe as disposed to remove all child subscriptions
ukvp.Value.Dispose();
}
}
// add newly selected universes
foreach (var ukvp in universes)
{
// note: UniverseManager.Add uses TryAdd, so don't need to worry about duplicates here
UniverseManager.Add(ukvp);
}
}
// we only want to run universe selection if there's no data available in the slice
if (!slice.HasData)
{
return;
}
// insight timestamping handled via InsightsGenerated event handler
var insights = Alpha.Update(this, slice).ToArray();
// only fire insights generated event if we actually have insights
if (insights.Length != 0)
{
// debug printing of generated insights
if (DebugMode)
{
Log($"{Time}: ALPHA: {string.Join(" | ", insights.Select(i => i.ToString()).OrderBy(i => i))}");
}
OnInsightsGenerated(insights);
}
// construct portfolio targets from insights
var targets = PortfolioConstruction.CreateTargets(this, insights).ToArray();
// set security targets w/ those generated via portfolio construction module
foreach (var target in targets)
{
var security = Securities[target.Symbol];
security.Holdings.Target = target;
}
if (DebugMode)
{
// debug printing of generated targets
if (targets.Length > 0)
{
Log($"{Time}: PORTFOLIO: {string.Join(" | ", targets.Select(t => t.ToString()).OrderBy(t => t))}");
}
}
var riskTargetOverrides = RiskManagement.ManageRisk(this, targets).ToArray();
// override security targets w/ those generated via risk management module
foreach (var target in riskTargetOverrides)
{
var security = Securities[target.Symbol];
security.Holdings.Target = target;
}
if (DebugMode)
{
// debug printing of generated risk target overrides
if (riskTargetOverrides.Length > 0)
{
Log($"{Time}: RISK: {string.Join(" | ", riskTargetOverrides.Select(t => t.ToString()).OrderBy(t => t))}");
}
}
// execute on the targets, overriding targets for symbols w/ risk targets
var riskAdjustedTargets = riskTargetOverrides.Concat(targets).DistinctBy(pt => pt.Symbol).ToArray();
if (DebugMode)
{
// only log adjusted targets if we've performed an adjustment
if (riskTargetOverrides.Length > 0)
{
Log($"{Time}: RISK ADJUSTED TARGETS: {string.Join(" | ", riskAdjustedTargets.Select(t => t.ToString()).OrderBy(t => t))}");
}
}
Execution.Execute(this, riskAdjustedTargets);
}
/// <summary>
/// Used to send security changes to algorithm framework models
/// </summary>
/// <param name="changes">Security additions/removals for this time step</param>
public sealed override void OnFrameworkSecuritiesChanged(SecurityChanges changes)
{
if (DebugMode)
{
Log($"{Time}: {changes}");
}
Alpha.OnSecuritiesChanged(this, changes);
PortfolioConstruction.OnSecuritiesChanged(this, changes);
Execution.OnSecuritiesChanged(this, changes);
RiskManagement.OnSecuritiesChanged(this, changes);
}
/// <summary>
/// Sets the universe selection model
/// </summary>
/// <param name="universeSelection">Model defining universes for the algorithm</param>
public void SetUniverseSelection(IUniverseSelectionModel universeSelection)
{
UniverseSelection = universeSelection;
}
/// <summary>
/// Sets the alpha model
/// </summary>
/// <param name="alpha">Model that generates alpha</param>
public void SetAlpha(IAlphaModel alpha)
{
Alpha = alpha;
}
/// <summary>
/// Sets the portfolio construction model
/// </summary>
/// <param name="portfolioConstruction">Model defining how to build a portoflio from insights</param>
public void SetPortfolioConstruction(IPortfolioConstructionModel portfolioConstruction)
{
PortfolioConstruction = portfolioConstruction;
}
/// <summary>
/// Sets the execution model
/// </summary>
/// <param name="execution">Model defining how to execute trades to reach a portfolio target</param>
public void SetExecution(IExecutionModel execution)
{
Execution = execution;
}
/// <summary>
/// Sets the risk management model
/// </summary>
/// <param name="riskManagement">Model defining </param>
public void SetRiskManagement(IRiskManagementModel riskManagement)
{
RiskManagement = riskManagement;
}
/// <summary>
/// Event invocator for the <see cref="QCAlgorithm.InsightsGenerated"/> event
/// </summary>
/// <remarks>
/// This method is sealed because the framework must be able to force setting of the
/// generated and close times before any event handlers are run. Bind directly to the
/// <see cref="QCAlgorithm.InsightsGenerated"/> event insead of overriding.
/// </remarks>
/// <param name="insights">The collection of insights generaed at the current time step</param>
protected sealed override void OnInsightsGenerated(IEnumerable<Insight> insights)
{
// set values not required to be set by alpha models
base.OnInsightsGenerated(insights.Select(insight =>
{
insight.GeneratedTimeUtc = UtcTime;
insight.ReferenceValue = _securityValuesProvider.GetValues(insight.Symbol).Get(insight.Type);
insight.SourceModel = string.IsNullOrEmpty(insight.SourceModel) ? Alpha.GetModelName() : insight.SourceModel;
var exchangeHours = MarketHoursDatabase.GetExchangeHours(insight.Symbol.ID.Market, insight.Symbol, insight.Symbol.SecurityType);
insight.SetPeriodAndCloseTime(exchangeHours);
return insight;
}));
}
private void CheckModels()
{
if (UniverseSelection == null)
{
throw new Exception($"Framework algorithms must specify a portfolio selection model using the '{nameof(UniverseSelection)}' property.");
}
if (Alpha == null)
{
throw new Exception($"Framework algorithms must specify a alpha model using the '{nameof(Alpha)}' property.");
}
if (PortfolioConstruction == null)
{
throw new Exception($"Framework algorithms must specify a portfolio construction model using the '{nameof(PortfolioConstruction)}' property");
}
if (Execution == null)
{
throw new Exception($"Framework algorithms must specify an execution model using the '{nameof(Execution)}' property.");
}
if (RiskManagement == null)
{
throw new Exception($"Framework algorithms must specify an risk management model using the '{nameof(RiskManagement)}' property.");
}
}
}
}
| 39.950581 | 158 | 0.586771 | [
"Apache-2.0"
] | AdvaithD/Lean | Algorithm.Framework/QCAlgorithmFramework.cs | 13,745 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.WebSites.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Application logs configuration.
/// </summary>
public partial class ApplicationLogsConfig
{
/// <summary>
/// Initializes a new instance of the ApplicationLogsConfig class.
/// </summary>
public ApplicationLogsConfig()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ApplicationLogsConfig class.
/// </summary>
/// <param name="fileSystem">Application logs to file system
/// configuration.</param>
/// <param name="azureTableStorage">Application logs to azure table
/// storage configuration.</param>
/// <param name="azureBlobStorage">Application logs to blob storage
/// configuration.</param>
public ApplicationLogsConfig(FileSystemApplicationLogsConfig fileSystem = default(FileSystemApplicationLogsConfig), AzureTableStorageApplicationLogsConfig azureTableStorage = default(AzureTableStorageApplicationLogsConfig), AzureBlobStorageApplicationLogsConfig azureBlobStorage = default(AzureBlobStorageApplicationLogsConfig))
{
FileSystem = fileSystem;
AzureTableStorage = azureTableStorage;
AzureBlobStorage = azureBlobStorage;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets application logs to file system configuration.
/// </summary>
[JsonProperty(PropertyName = "fileSystem")]
public FileSystemApplicationLogsConfig FileSystem { get; set; }
/// <summary>
/// Gets or sets application logs to azure table storage configuration.
/// </summary>
[JsonProperty(PropertyName = "azureTableStorage")]
public AzureTableStorageApplicationLogsConfig AzureTableStorage { get; set; }
/// <summary>
/// Gets or sets application logs to blob storage configuration.
/// </summary>
[JsonProperty(PropertyName = "azureBlobStorage")]
public AzureBlobStorageApplicationLogsConfig AzureBlobStorage { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (AzureTableStorage != null)
{
AzureTableStorage.Validate();
}
}
}
}
| 36.880952 | 336 | 0.640736 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/websites/Microsoft.Azure.Management.WebSites/src/Generated/Models/ApplicationLogsConfig.cs | 3,098 | C# |
using System;
using System.Text;
using System.Runtime.InteropServices;
public class CellRecvStream {
byte[] _buffer = null;
private int _nReadPos = 0;
public CellRecvStream(IntPtr data,int len)
{
// C++ 传入的数据转为C#的字节数组
byte[] buffer = new byte[len];
Marshal.Copy(data, buffer, 0, len);
_buffer = buffer;
}
private void pop(int n)
{
_nReadPos += n;
}
private bool canRead(int n)
{
return _buffer.Length - _nReadPos >= n;
}
public NetCMD ReadNetCmd()
{
return (NetCMD)ReadUInt16();
}
// int
public sbyte ReadInt8(sbyte n = 0)
{
if (canRead(1))
{
n = (sbyte)_buffer[_nReadPos];
pop(1);
}
return n;
}
public Int16 ReadInt16 (Int16 n = 0)
{
if(canRead(2))
{
n = BitConverter.ToInt16(_buffer, _nReadPos);
pop(2);
}
return n;
}
public Int32 ReadInt32(Int32 n = 0)
{
if (canRead(4))
{
n = BitConverter.ToInt32(_buffer, _nReadPos);
pop(4);
}
return n;
}
public Int64 ReadInt64(Int64 n = 0)
{
if (canRead(8))
{
n = BitConverter.ToInt64(_buffer, _nReadPos);
pop(8);
}
return n;
}
// uint
public byte ReadUInt8(byte n = 0)
{
if (canRead(1))
{
n = (byte)_buffer[_nReadPos];
pop(1);
}
return n;
}
public UInt16 ReadUInt16(UInt16 n = 0)
{
if (canRead(2))
{
n = BitConverter.ToUInt16(_buffer, _nReadPos);
pop(2);
}
return n;
}
public UInt32 ReadUInt32(UInt32 n = 0)
{
if (canRead(4))
{
n = BitConverter.ToUInt32(_buffer, _nReadPos);
pop(4);
}
return n;
}
public UInt64 ReadUInt64(UInt64 n = 0)
{
if (canRead(8))
{
n = BitConverter.ToUInt64(_buffer, _nReadPos);
pop(8);
}
return n;
}
// float
public float ReadFloat(float n = 0)
{
if (canRead(4))
{
n = BitConverter.ToSingle(_buffer, _nReadPos);
pop(4);
}
return n;
}
public double ReadDouble(double n = 0)
{
if (canRead(8))
{
n = BitConverter.ToDouble(_buffer, _nReadPos);
pop(8);
}
return n;
}
// string
public string ReadString()
{
string s = string.Empty;
int len = ReadInt32();
if (canRead(len) && len>0)
{
s = Encoding.UTF8.GetString(_buffer, _nReadPos, len);
pop(len);
}
return s;
}
// array
public Int32[] ReadInt32s()
{
int len = ReadInt32();
if (len < 1)
{
// Error 处理 (try catch)
return null;
}
Int32[] data = new Int32[len];
for (int n = 0; n < len; n++)
{
data[n] = ReadInt32();
}
return data;
}
public void Release()
{
}
} | 19.557471 | 66 | 0.430209 | [
"MIT"
] | baitxaps/EasySocket | CppNetworkPlugin/Assets/CellRecvStream.cs | 3,433 | C# |
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Settings.Configuration;
using StreamDeckLib;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using System.Diagnostics;
namespace streamdeck_co2
{
class Program
{
static async Task Main(string[] args)
{
using (var config = StreamDeckLib.Config.ConfigurationBuilder.BuildDefaultConfiguration(args))
{
await ConnectionManager.Initialize(args, config.LoggerFactory)
.RegisterAllActions(typeof(Program).Assembly)
.StartAsync();
}
}
}
}
| 24.472222 | 106 | 0.620885 | [
"MIT"
] | christophbergemann/co2-streamdeck | Program.cs | 883 | C# |
using System.Collections.Generic;
namespace MyLab.ApiClient
{
/// <summary>
/// Contains api clients infrastructure options
/// </summary>
public class ApiClientsOptions
{
/// <summary>
/// List of api connections options
/// </summary>
public Dictionary<string, ApiConnectionOptions> List { get; set; }
}
/// <summary>
/// Contains api connection options
/// </summary>
public class ApiConnectionOptions
{
/// <summary>
/// API base url
/// </summary>
public string Url { get; set; }
}
} | 23.192308 | 74 | 0.570481 | [
"MIT"
] | mylab-tools/apiclient | src/MyLab.ApiClient/ApiClientsOptions.cs | 605 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace UserInterface {
[AddComponentMenu(NamingHelper.Button.Name, 0)]
public class GMButton : Button {
public List<Graphic> colorizeElements = new List<Graphic>();
public Color defaultColor;
public Color highlightColor;
public Color pressedColor;
public Color selectedColor;
public Color disabledColor;
public bool isPressed {
get; private set;
}
// Event delegate triggered on mouse or touch down.
[SerializeField]
GMButtonRightClickEvent _onRightClick = new GMButtonRightClickEvent();
[Serializable]
public class GMButtonRightClickEvent : UnityEvent { }
[SerializeField]
GMButtonPressedEvent _onPressed = new GMButtonPressedEvent();
[Serializable]
public class GMButtonPressedEvent : UnityEvent { }
[SerializeField]
GMButtonReleaseEvent _onRelease = new GMButtonReleaseEvent();
[Serializable]
public class GMButtonReleaseEvent : UnityEvent { }
[SerializeField]
GMButtonVisualsChangedEvent _onVisualsChanged = new GMButtonVisualsChangedEvent();
[Serializable]
public class GMButtonVisualsChangedEvent : UnityEvent { }
protected GMButton() { }
public override void OnPointerClick(PointerEventData eventData) {
if (eventData.button == PointerEventData.InputButton.Left) {
if (interactable && !isPressed) onClick.Invoke();
} else if (eventData.button == PointerEventData.InputButton.Right) {
if (interactable) onRightClick.Invoke();
}
}
public GMButtonRightClickEvent onRightClick {
get { return _onRightClick; }
set { _onRightClick = value; }
}
public GMButtonPressedEvent onPressed {
get { return _onPressed; }
set { _onPressed = value; }
}
public GMButtonReleaseEvent onRelease {
get { return _onRelease; }
set { _onRelease = value; }
}
public GMButtonVisualsChangedEvent onVisualsChanged {
get { return _onVisualsChanged; }
set { _onVisualsChanged = value; }
}
protected override void DoStateTransition(SelectionState state, bool instant) {
base.DoStateTransition(state, instant);
if (state == SelectionState.Disabled) {
SetColor(disabledColor);
} else if (state == SelectionState.Highlighted) {
SetColor(highlightColor);
} else if (state == SelectionState.Normal) {
SetColor(defaultColor);
} else if (state == SelectionState.Pressed) {
isPressed = true;
SetColor(pressedColor);
} else if (state == SelectionState.Selected) {
SetColor(selectedColor);
}
}
void SetColor(Color color) {
foreach (Graphic colorizeElement in colorizeElements) {
colorizeElement.color = color;
onVisualsChanged.Invoke();
}
}
public override void OnPointerExit(PointerEventData eventData) {
base.OnPointerExit(eventData);
if (isPressed) {
onRelease.Invoke();
isPressed = false;
}
}
public override void OnPointerUp(PointerEventData eventData) {
base.OnPointerUp(eventData);
if (isPressed && interactable) {
onRelease.Invoke();
isPressed = false;
}
}
private void Update() {
if (isPressed && interactable) {
onPressed.Invoke();
}
}
public void UpdateColors() {
DoStateTransition(currentSelectionState, true);
}
public void Highlight(bool highlight) {
if (highlight) {
DoStateTransition(SelectionState.Highlighted, true);
} else {
if (interactable) {
DoStateTransition(SelectionState.Normal, true);
} else {
DoStateTransition(SelectionState.Disabled, true);
}
}
}
}
}
| 31.048276 | 90 | 0.582408 | [
"MIT"
] | dotmos/uGameFramework | Unity/Assets/Scripts/UserInterface/Basics/GMButton.cs | 4,504 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Automation.Peers.DataGridAutomationPeer.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Automation.Peers
{
sealed public partial class DataGridAutomationPeer : ItemsControlAutomationPeer, System.Windows.Automation.Provider.ISelectionProvider, System.Windows.Automation.Provider.ITableProvider, System.Windows.Automation.Provider.IGridProvider
{
#region Methods and constructors
protected override ItemAutomationPeer CreateItemAutomationPeer(Object item)
{
return default(ItemAutomationPeer);
}
public DataGridAutomationPeer(System.Windows.Controls.DataGrid owner) : base (default(System.Windows.Controls.ItemsControl))
{
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return default(AutomationControlType);
}
protected override List<AutomationPeer> GetChildrenCore()
{
return default(List<AutomationPeer>);
}
protected override string GetClassNameCore()
{
return default(string);
}
public override Object GetPattern(PatternInterface patternInterface)
{
return default(Object);
}
System.Windows.Automation.Provider.IRawElementProviderSimple System.Windows.Automation.Provider.IGridProvider.GetItem(int row, int column)
{
return default(System.Windows.Automation.Provider.IRawElementProviderSimple);
}
System.Windows.Automation.Provider.IRawElementProviderSimple[] System.Windows.Automation.Provider.ISelectionProvider.GetSelection()
{
return default(System.Windows.Automation.Provider.IRawElementProviderSimple[]);
}
System.Windows.Automation.Provider.IRawElementProviderSimple[] System.Windows.Automation.Provider.ITableProvider.GetColumnHeaders()
{
return default(System.Windows.Automation.Provider.IRawElementProviderSimple[]);
}
System.Windows.Automation.Provider.IRawElementProviderSimple[] System.Windows.Automation.Provider.ITableProvider.GetRowHeaders()
{
return default(System.Windows.Automation.Provider.IRawElementProviderSimple[]);
}
#endregion
#region Properties and indexers
int System.Windows.Automation.Provider.IGridProvider.ColumnCount
{
get
{
return default(int);
}
}
int System.Windows.Automation.Provider.IGridProvider.RowCount
{
get
{
return default(int);
}
}
bool System.Windows.Automation.Provider.ISelectionProvider.CanSelectMultiple
{
get
{
return default(bool);
}
}
bool System.Windows.Automation.Provider.ISelectionProvider.IsSelectionRequired
{
get
{
return default(bool);
}
}
System.Windows.Automation.RowOrColumnMajor System.Windows.Automation.Provider.ITableProvider.RowOrColumnMajor
{
get
{
return default(System.Windows.Automation.RowOrColumnMajor);
}
}
#endregion
}
}
| 35.547445 | 463 | 0.74846 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/PresentationFramework/Sources/System.Windows.Automation.Peers.DataGridAutomationPeer.cs | 4,870 | C# |
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion Copyright
namespace WatiN.Core.DialogHandlers
{
public enum FileDownloadOptionEnum
{
Run,
Save,
Open,
Cancel
}
} | 28.821429 | 77 | 0.729864 | [
"Apache-2.0"
] | Toadstool/Fork-WatiN | source/src/Core/DialogHandlers/FileDownloadOptionEnum.cs | 807 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.open.app.members.query
/// </summary>
public class AlipayOpenAppMembersQueryRequest : IAopRequest<AlipayOpenAppMembersQueryResponse>
{
/// <summary>
/// 小程序查询成员
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.open.app.members.query";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.4 | 98 | 0.602564 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Request/AlipayOpenAppMembersQueryRequest.cs | 2,588 | C# |
#pragma checksum "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "af48c0eb9cf344183cf02f57f829aa647aae66d3"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(OdeToFood.Pages.R2.Pages_R2_Index), @"mvc.1.0.razor-page", @"/Pages/R2/Index.cshtml")]
namespace OdeToFood.Pages.R2
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\_ViewImports.cshtml"
using OdeToFood;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"af48c0eb9cf344183cf02f57f829aa647aae66d3", @"/Pages/R2/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5bd7a9498867045fbda097e3208cbd1c6a5a509f", @"/Pages/_ViewImports.cshtml")]
public class Pages_R2_Index : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./Details", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
#nullable restore
#line 4 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
ViewData["Title"] = "Index";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>Index</h1>\r\n\r\n<p>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "af48c0eb9cf344183cf02f57f829aa647aae66d34403", async() => {
WriteLiteral("Create New");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</p>\r\n<table class=\"table\">\r\n <thead>\r\n <tr>\r\n <th>\r\n ");
#nullable restore
#line 17 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
Write(Html.DisplayNameFor(model => model.Restaurant[0].Name));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </th>\r\n <th>\r\n ");
#nullable restore
#line 20 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
Write(Html.DisplayNameFor(model => model.Restaurant[0].Location));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </th>\r\n <th>\r\n ");
#nullable restore
#line 23 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
Write(Html.DisplayNameFor(model => model.Restaurant[0].Cuisine));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </th>\r\n <th></th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n");
#nullable restore
#line 29 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
foreach (var item in Model.Restaurant) {
#line default
#line hidden
#nullable disable
WriteLiteral(" <tr>\r\n <td>\r\n ");
#nullable restore
#line 32 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.Name));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n <td>\r\n ");
#nullable restore
#line 35 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.Location));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n <td>\r\n ");
#nullable restore
#line 38 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
Write(Html.DisplayFor(modelItem => item.Cuisine));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </td>\r\n <td>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "af48c0eb9cf344183cf02f57f829aa647aae66d38042", async() => {
WriteLiteral("Edit");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 41 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
WriteLiteral(item.Id);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(" |\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "af48c0eb9cf344183cf02f57f829aa647aae66d310222", async() => {
WriteLiteral("Details");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 42 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
WriteLiteral(item.Id);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(" |\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "af48c0eb9cf344183cf02f57f829aa647aae66d312409", async() => {
WriteLiteral("Delete");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 43 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
WriteLiteral(item.Id);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </td>\r\n </tr>\r\n");
#nullable restore
#line 46 "C:\Users\marcos\Documents\Everything C#\CSharpFoodProj\OdeToFood\OdeToFood\Pages\R2\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" </tbody>\r\n</table>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<OdeToFood.Pages.R2.IndexModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<OdeToFood.Pages.R2.IndexModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<OdeToFood.Pages.R2.IndexModel>)PageContext?.ViewData;
public OdeToFood.Pages.R2.IndexModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 62.523622 | 300 | 0.719728 | [
"MIT"
] | Mlira02/CSharpFoodProj | OdeToFood/OdeToFood/obj/Debug/netcoreapp3.1/Razor/Pages/R2/Index.cshtml.g.cs | 15,881 | C# |
using System;
using AutoStep.Definitions.Test;
using AutoStep.Tests.Utils;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace AutoStep.Tests.Definition.Test
{
public class ClassStepDefinitionSourceTests : LoggingTestBase
{
public ClassStepDefinitionSourceTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Fact]
public void CanRegisterClass()
{
var classDef = new ClassStepDefinitionSource(LogFactory);
classDef.AddClass<MyClass>();
var defs = classDef.GetStepDefinitions();
defs.Should().ContainSingle(x => x.Type == StepType.Given);
defs.Should().ContainSingle(x => x.Type == StepType.When);
defs.Should().ContainSingle(x => x.Type == StepType.Then);
}
[Fact]
public void CannotRegisterClassTwice()
{
var classDef = new ClassStepDefinitionSource(LogFactory);
classDef.AddClass<MyClass>();
classDef.Invoking(c => c.AddClass<MyClass>()).Should().Throw<InvalidOperationException>();
}
[Fact]
public void CannotRegisterAbstractClass()
{
var classDef = new ClassStepDefinitionSource(LogFactory);
classDef.Invoking(c => c.AddClass<AbstractClass>()).Should().Throw<ArgumentException>();
}
private class MyClass
{
[Given("I have")]
public void Given()
{
}
[When("I do")]
public void When()
{
}
[Then("this will")]
public void Then()
{
}
}
abstract class AbstractClass
{
}
}
}
| 24.506849 | 102 | 0.558971 | [
"MIT"
] | SivaGudivada/AutoStep | tests/AutoStep.Tests/Definition/Test/ClassStepDefinitionSourceTests.cs | 1,791 | C# |
using System.IO;
using VkNet.Utils;
namespace VkNet.Tests.Infrastructure
{
/// <summary>
/// Пути к общим json файлам
/// </summary>
public static class JsonPaths
{
/// <summary>
/// Путь к json файлу с ответом <c>true</c>
/// </summary>
public static readonly string True = Path.Combine("Common", bool.TrueString);
/// <summary>
/// Путь к json файлу с ответом <c>false</c>
/// </summary>
public static readonly string False = Path.Combine("Common", bool.FalseString);
/// <summary>
/// Путь к json файлу с пустым ответом <see cref="VkCollection{T}"/>
/// </summary>
public static readonly string EmptyVkCollection = Path.Combine("Common", nameof(EmptyVkCollection));
/// <summary>
/// Путь к json файлу с пустым массивом
/// </summary>
public static readonly string EmptyArray = Path.Combine("Common", nameof(EmptyArray));
/// <summary>
/// Путь к json файлу с пустым массивом
/// </summary>
public static readonly string EmptyObject = Path.Combine("Common", nameof(EmptyObject));
}
} | 28.833333 | 102 | 0.675337 | [
"MIT"
] | Fooxboy/vk | VkNet.Tests/Infrastructure/JsonPaths.cs | 1,164 | C# |
namespace Lego.Core.Models.Messaging
{
public enum MessageType : byte
{
Hub__Properties = 0x01,
Hub__Actions = 0x02,
Hub__Alerts = 0x03,
Hub__Attached_IO = 0x04,
Generic_Error_Messages = 0x05,
Hardware_Network_Commands = 0x08,
Firmware_Update__Go_Into_Boot_Mode = 0x10,
Firmware_Update__Lock_Memory = 0x11,
Firmware_Update__Lock_Status_Request = 0x12,
Firmware_Lock_Status = 0x13,
Port_Information_Request = 0x21,
Port_Mode_Information_Request = 0x22,
Port_Input_Format_Setup__Single = 0x41,
Port_Input_Format_Setup__Combined_Mode = 0x42,
Port_Information = 0x43,
Port_Mode_Information = 0x44,
Port_Value__Single = 0x45,
Port_Value__Combined_Mode = 0x46,
Port_Input_Format__Single = 0x47,
Port_Input_Format__Combined_Mode = 0x48,
Virtual_Port_Setup = 0x61,
Port_Output_Command = 0x81,
Port_Output_Command_Feedback = 0x82
}
}
| 34.066667 | 54 | 0.677104 | [
"MIT"
] | Vouzamo/Lego | src/Lego/Lego.Core/Models/Messaging/MessageType.cs | 1,024 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
namespace MOE.Common.Business
{
public class LinkPivotPair
{
private string signalId;
public string SignalId
{
get { return signalId; }
}
string signalDirection;
private string downSignalId;
public string DownSignalId
{
get { return downSignalId; }
}
string downSignalDirection;
public string DownSignalDirection
{
get { return downSignalDirection; }
}
private double secondsAdded = 0;
public double SecondsAdded
{
get { return secondsAdded; }
}
private double maxArrivalOnGreen = 0;
public double MaxArrivalOnGreen
{
get { return maxArrivalOnGreen; }
}
private double maxPercentAOG = 0;
public double MaxPercentAOG
{
get { return maxPercentAOG; }
}
private int upstreamApproach;
private List<MOE.Common.Business.SignalPhase> upstreamPCD = new List<SignalPhase>();
public List<MOE.Common.Business.SignalPhase> UpstreamPCD
{
get { return upstreamPCD; }
}
private List<MOE.Common.Business.SignalPhase> downstreamPCD = new List<SignalPhase>();
public List<MOE.Common.Business.SignalPhase> DownstreamPCD
{
get { return downstreamPCD; }
}
private double pAOGUpstreamBefore=0;
public double PAOGUpstreamBefore
{
get { return pAOGUpstreamBefore;}
}
private double pAOGDownstreamBefore = 0;
public double PAOGDownstreamBefore
{
get { return pAOGDownstreamBefore; }
}
private double pAOGDownstreamPredicted = 0;
public double PAOGDownstreamPredicted
{
get { return pAOGDownstreamPredicted; }
}
private double pAOGUpstreamPredicted = 0;
public double PAOGUpstreamPredicted
{
get { return pAOGUpstreamPredicted; }
}
private double aOGUpstreamBefore = 0;
public double AOGUpstreamBefore
{
get { return aOGUpstreamBefore; }
}
private double aOGDownstreamBefore = 0;
public double AOGDownstreamBefore
{
get { return aOGDownstreamBefore; }
}
private double aOGDownstreamPredicted = 0;
public double AOGDownstreamPredicted
{
get { return aOGDownstreamPredicted; }
}
private double aOGUpstreamPredicted = 0;
public double AOGUpstreamPredicted
{
get { return aOGUpstreamPredicted; }
}
private double totalVolumeUpstream = 0;
public double TotalVolumeUpstream
{
get { return totalVolumeUpstream; }
}
private double totalVolumeDownstream = 0;
public double TotalVolumeDownstream
{
get { return totalVolumeDownstream; }
}
private string location;
public string Location
{
get { return location; }
}
private string downstreamLocation;
public string DownstreamLocation
{
get { return downstreamLocation; }
}
private string downstreamApproachDirection;
public string DownstreamApproachDirection
{
get { return downstreamApproachDirection; }
}
private string upstreamApproachDirection;
public string UpstreamApproachDirection
{
get { return upstreamApproachDirection; }
}
private string resultChartLocation;
public string ResultChartLocation
{
get { return resultChartLocation; }
}
private Dictionary<int, double> resultsGraph = new Dictionary<int, double>();
public Dictionary<int, double> ResultsGraph
{
get { return resultsGraph; }
}
private Dictionary<int, double> upstreamResultsGraph = new Dictionary<int, double>();
public Dictionary<int, double> UpstreamResultsGraph
{
get { return upstreamResultsGraph; }
}
private Dictionary<int, double> downstreamResultsGraph = new Dictionary<int, double>();
public Dictionary<int, double> DownstreamResultsGraph
{
get { return downstreamResultsGraph; }
}
private List<LinkPivotPCDDisplay> display = new List<LinkPivotPCDDisplay>();
public List<LinkPivotPCDDisplay> Display
{
get { return display; }
}
private double _AOGTotalBefore;
public double AOGTotalBefore
{
get { return _AOGTotalBefore; }
set { _AOGTotalBefore = value; }
}
private double _PAOGTotalBefore;
public double PAOGTotalBefore
{
get { return _PAOGTotalBefore; }
set { _PAOGTotalBefore = value; }
}
private double _AOGTotalPredicted;
public double AOGTotalPredicted
{
get { return _AOGTotalPredicted; }
set { _AOGTotalPredicted = value; }
}
private double _PAOGTotalPredicted;
public double PAOGTotalPredicted
{
get { return _PAOGTotalPredicted; }
set { _PAOGTotalPredicted = value; }
}
private int _LinkNumber;
public int LinkNumber
{
get { return _LinkNumber; }
set { _LinkNumber = value; }
}
/// <summary>
/// Represents a pair of approaches to be compared for link pivot anaylisis
/// </summary>
/// <param name="signalId"></param>
/// <param name="signalDirection"></param>
/// <param name="signalLocation"></param>
/// <param name="downSignalId"></param>
/// <param name="downSignalDirection"></param>
/// <param name="downSignalLocation"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <param name="cycleTime"></param>
/// <param name="chartLocation"></param>
/// <param name="bias"></param>
/// <param name="biasDirection"></param>
/// <param name="dates"></param>
public LinkPivotPair(string signalId, string signalDirection, string signalLocation, string downSignalId,
string downSignalDirection, string downSignalLocation,
DateTime startDate, DateTime endDate, int cycleTime, string chartLocation
, double bias, string biasDirection, List<DateTime> dates, int linkNumber)
{
this.signalId = signalId;
this.signalDirection = signalDirection;
this.downSignalId = downSignalId;
this.downSignalDirection = downSignalDirection;
this.downstreamApproachDirection = downSignalDirection;
this.location = signalLocation;
this.downstreamLocation = downSignalLocation;
this._LinkNumber = linkNumber;
//Determine the direction of the approach to be analyzed. This will determine
//which approches are compared as downstream and upstream.
if(signalDirection == "Northbound")
{
upstreamApproachDirection = "Southbound";
}
else if (signalDirection == "Southbound")
{
upstreamApproachDirection = "Northbound";
}
else if (signalDirection == "Eastbound")
{
upstreamApproachDirection = "Westbound";
}
else if (signalDirection == "Westbound")
{
upstreamApproachDirection = "Eastbound";
}
//MOE.Common.Data.LinkPivotTableAdapters.Graph_DetectorsTableAdapter gdAdapter =
// new Data.LinkPivotTableAdapters.Graph_DetectorsTableAdapter();
MOE.Common.Models.SPM db = new Models.SPM();
//find the upstream approach
if (!String.IsNullOrEmpty(upstreamApproachDirection))
{
MOE.Common.Models.Repositories.ISignalsRepository repository =
MOE.Common.Models.Repositories.SignalsRepositoryFactory.Create();
var signal = repository.GetSignalBySignalID(signalId);
List<MOE.Common.Models.Detector> dets =
signal.GetDetectorsForSignalThatSupportAMetricByApproachDirection(6, upstreamApproachDirection);
foreach (MOE.Common.Models.Detector row in dets)
{
//Get the upstream pcd
foreach (DateTime dt in dates)
{
DateTime tempStartDate = dt;
DateTime tempEndDate = new DateTime(dt.Year, dt.Month, dt.Day, endDate.Hour,
endDate.Minute, endDate.Second);
SignalPhase usp = new MOE.Common.Business.SignalPhase(
tempStartDate, tempEndDate, row.Approach, false, 15,13);
upstreamPCD.Add(usp);
aOGUpstreamBefore += usp.TotalArrivalOnGreen;
totalVolumeUpstream += usp.TotalVolume;
}
pAOGUpstreamBefore = Math.Round(aOGUpstreamBefore / totalVolumeUpstream, 2) * 100;
//aOGUpstreamBefore = upstreamPCD.TotalArrivalOnGreen;
//upstreamBeforePCDPath = CreateChart(upstreamPCD, startDate, endDate, signalLocation,
// "before", chartLocation);
}
}
//find the downstream approach
if (!String.IsNullOrEmpty(downSignalDirection))
{
MOE.Common.Models.Repositories.ISignalsRepository repository =
MOE.Common.Models.Repositories.SignalsRepositoryFactory.Create();
var signal = repository.GetSignalBySignalID(downSignalId);
List<MOE.Common.Models.Detector> dets =
signal.GetDetectorsForSignalThatSupportAMetricByApproachDirection(6, downSignalDirection);
foreach (MOE.Common.Models.Detector row in dets)
{
//Get the downstream pcd
foreach (DateTime dt in dates)
{
DateTime tempStartDate = dt;
DateTime tempEndDate = new DateTime(dt.Year, dt.Month, dt.Day, endDate.Hour, endDate.Minute, endDate.Second);
SignalPhase dsp = new MOE.Common.Business.SignalPhase(
tempStartDate, tempEndDate, row.Approach, false, 15,13);
downstreamPCD.Add(dsp);
aOGDownstreamBefore += dsp.TotalArrivalOnGreen;
totalVolumeDownstream += dsp.TotalVolume;
}
pAOGDownstreamBefore = Math.Round(aOGDownstreamBefore / totalVolumeDownstream, 2) * 100;
//aOGDownstreamBefore = downstreamPCD.TotalArrivalOnGreen;
//downstreamBeforePCDPath = CreateChart(downstreamPCD, startDate, endDate, downSignalLocation,
// "before", chartLocation);
}
}
//Check to see if both directions have detection if so analyze both
if (upstreamPCD.Count > 0 && downstreamPCD.Count > 0)
{
//Data.LinkPivotTableAdapters.Graph_DetectorsTableAdapter gda =
// new Data.LinkPivotTableAdapters.Graph_DetectorsTableAdapter();
//int? recordedCycleTime = gda.GetCycleTime(startDate, Convert.ToInt32(signalId));
//if a bias was provided bias the results in the direction specified
if (bias != 0)
{
double upstreamBias = 1;
double downstreamBias = 1;
if (biasDirection == "Downstream")
{
downstreamBias = 1 + (bias/100);
}
else
{
upstreamBias = 1 + (bias / 100);
}
//set the original values to compare against
_AOGTotalBefore = (aOGDownstreamBefore * downstreamBias) +
(aOGUpstreamBefore * upstreamBias);
_PAOGTotalBefore = Math.Round(_AOGTotalBefore/((totalVolumeDownstream*downstreamBias)+(totalVolumeUpstream*upstreamBias)),2)*100;
double maxBiasArrivalOnGreen = _AOGTotalBefore;
maxArrivalOnGreen = aOGDownstreamBefore + aOGUpstreamBefore;
//add the total to the results grid
resultsGraph.Add(0, maxArrivalOnGreen);
upstreamResultsGraph.Add(0, aOGUpstreamBefore * upstreamBias);
downstreamResultsGraph.Add(0, aOGDownstreamBefore * downstreamBias);
aOGUpstreamPredicted = aOGUpstreamBefore;
aOGDownstreamPredicted = aOGDownstreamBefore;
pAOGDownstreamPredicted = Math.Round(aOGDownstreamBefore / totalVolumeDownstream, 2)*100 ;
pAOGUpstreamPredicted = Math.Round(aOGUpstreamBefore / totalVolumeUpstream, 2)*100;
secondsAdded = 0;
for (int i = 1; i <= cycleTime; i++)
{
double totalBiasArrivalOnGreen = 0;
double totalArrivalOnGreen = 0;
double totalUpstreamAog = 0;
double totalDownstreamAog = 0;
for (int index = 0; index < dates.Count; index++)
{
upstreamPCD[index].LinkPivotAddSeconds(-1);
downstreamPCD[index].LinkPivotAddSeconds(1);
totalBiasArrivalOnGreen += (upstreamPCD[index].TotalArrivalOnGreen * upstreamBias) +
(downstreamPCD[index].TotalArrivalOnGreen * downstreamBias);
totalArrivalOnGreen =+ (upstreamPCD[index].TotalArrivalOnGreen) +
(downstreamPCD[index].TotalArrivalOnGreen);
totalUpstreamAog += upstreamPCD[index].TotalArrivalOnGreen;
totalDownstreamAog += downstreamPCD[index].TotalArrivalOnGreen;
}
//Add the total aog to the dictionary
resultsGraph.Add(i, totalBiasArrivalOnGreen);
upstreamResultsGraph.Add(i, totalUpstreamAog);
downstreamResultsGraph.Add(i, totalDownstreamAog);
if (totalBiasArrivalOnGreen > maxBiasArrivalOnGreen)
{
maxBiasArrivalOnGreen = totalBiasArrivalOnGreen;
maxArrivalOnGreen = totalArrivalOnGreen;
aOGUpstreamPredicted = totalUpstreamAog;
aOGDownstreamPredicted = totalDownstreamAog;
pAOGDownstreamPredicted = Math.Round(totalDownstreamAog / totalVolumeDownstream, 2)*100;
pAOGUpstreamPredicted = Math.Round(totalUpstreamAog / totalVolumeUpstream, 2)*100;
maxPercentAOG =
secondsAdded = i;
}
}
//Get the link totals
_AOGTotalPredicted = maxArrivalOnGreen;
_PAOGTotalPredicted = Math.Round(_AOGTotalPredicted / (totalVolumeUpstream + totalVolumeDownstream), 2)*100;
}
//If no bias is provided
else
{
//set the original values to compare against
_AOGTotalBefore = aOGDownstreamBefore + aOGUpstreamBefore;
maxArrivalOnGreen = _AOGTotalBefore;
_PAOGTotalBefore = Math.Round(_AOGTotalBefore / (totalVolumeDownstream + totalVolumeUpstream),2)*100;
//add the total to the results grid
resultsGraph.Add(0, maxArrivalOnGreen);
upstreamResultsGraph.Add(0, aOGUpstreamBefore);
downstreamResultsGraph.Add(0, aOGDownstreamBefore);
aOGUpstreamPredicted = aOGUpstreamBefore;
aOGDownstreamPredicted = aOGDownstreamBefore;
pAOGDownstreamPredicted = Math.Round(aOGDownstreamBefore / totalVolumeDownstream, 2)*100;
pAOGUpstreamPredicted = Math.Round(aOGUpstreamBefore / totalVolumeUpstream, 2)*100;
secondsAdded = 0;
for (int i = 1; i <= cycleTime; i++)
{
double totalArrivalOnGreen = 0;
double totalUpstreamAog = 0;
double totalDownstreamAog = 0;
for (int index = 0; index < dates.Count; index++)
{
upstreamPCD[index].LinkPivotAddSeconds(-1);
downstreamPCD[index].LinkPivotAddSeconds(1);
totalArrivalOnGreen += (upstreamPCD[index].TotalArrivalOnGreen) +
(downstreamPCD[index].TotalArrivalOnGreen);
totalUpstreamAog += upstreamPCD[index].TotalArrivalOnGreen;
totalDownstreamAog += downstreamPCD[index].TotalArrivalOnGreen;
}
//Add the total aog to the dictionary
resultsGraph.Add(i, totalArrivalOnGreen);
upstreamResultsGraph.Add(i, totalUpstreamAog);
downstreamResultsGraph.Add(i, totalDownstreamAog);
if (totalArrivalOnGreen > maxArrivalOnGreen)
{
maxArrivalOnGreen = totalArrivalOnGreen;
aOGUpstreamPredicted = totalUpstreamAog;
aOGDownstreamPredicted = totalDownstreamAog;
pAOGDownstreamPredicted = Math.Round(totalDownstreamAog / totalVolumeDownstream, 2)*100;
pAOGUpstreamPredicted = Math.Round(totalUpstreamAog / totalVolumeUpstream, 2)*100;
secondsAdded = i;
}
}
//Get the link totals
_AOGTotalPredicted = maxArrivalOnGreen;
_PAOGTotalPredicted = Math.Round(_AOGTotalPredicted / (totalVolumeUpstream + totalVolumeDownstream), 2)*100;
}
//remove the seconds from the pcd to produce the optimized pcd
//int secondsToRemove = Convert.ToInt32(cycleTime - secondsAdded);
//upstreamPCD.LinkPivotAddSeconds(secondsToRemove);
//downstreamPCD.LinkPivotAddSeconds(secondsToRemove*-1);
//pAOGUpstreamPredicted = upstreamPCD.PercentArrivalOnGreen;
//aOGUpstreamPredicted = upstreamPCD.TotalArrivalOnGreen;
//pAOGDownstreamPredicted = downstreamPCD.PercentArrivalOnGreen;
//aOGDownstreamPredicted = downstreamPCD.TotalArrivalOnGreen;
//upstreamAfterPCDPath = CreateChart(upstreamPCD, startDate, endDate, signalLocation,
// "after", chartLocation);
//downstreamAfterPCDPath = CreateChart(downstreamPCD, startDate, endDate, downSignalLocation,
// "after", chartLocation);
}
//If only upstream has detection do analysis for upstream only
else if (downstreamPCD.Count == 0 && upstreamPCD.Count > 0)
{
//if a bias was provided by the user apply it to the upstream results
if (bias != 0)
{
double upstreamBias = 1;
double downstreamBias = 1;
if (biasDirection == "Downstream")
{
downstreamBias = 1 + (bias / 100);
}
else
{
upstreamBias = 1 + (bias / 100);
}
//set the original values to compare against
double maxBiasArrivalOnGreen = (aOGDownstreamBefore * downstreamBias) +
(aOGUpstreamBefore * upstreamBias);
maxArrivalOnGreen = aOGUpstreamBefore;
//Add the total to the results grid
resultsGraph.Add(0, maxArrivalOnGreen);
upstreamResultsGraph.Add(0, aOGUpstreamBefore * upstreamBias);
downstreamResultsGraph.Add(0, aOGDownstreamBefore * downstreamBias);
aOGUpstreamPredicted = aOGUpstreamBefore;
pAOGUpstreamPredicted = Math.Round(aOGUpstreamBefore / totalVolumeUpstream, 2)*100;
secondsAdded = 0;
for (int i = 1; i <= cycleTime; i++)
{
double totalBiasArrivalOnGreen = 0;
double totalArrivalOnGreen = 0;
double totalUpstreamAog = 0;
for (int index = 0; index < dates.Count; index++)
{
upstreamPCD[index].LinkPivotAddSeconds(-1);
totalBiasArrivalOnGreen += (upstreamPCD[index].TotalArrivalOnGreen * upstreamBias);
totalArrivalOnGreen = +(upstreamPCD[index].TotalArrivalOnGreen);
totalUpstreamAog += upstreamPCD[index].TotalArrivalOnGreen;
}
//Add the total aog to the dictionary
resultsGraph.Add(i, totalBiasArrivalOnGreen);
upstreamResultsGraph.Add(i, totalUpstreamAog);
if (totalBiasArrivalOnGreen > maxBiasArrivalOnGreen)
{
maxBiasArrivalOnGreen = totalBiasArrivalOnGreen;
maxArrivalOnGreen = totalArrivalOnGreen;
aOGUpstreamPredicted = totalUpstreamAog;
pAOGUpstreamPredicted = Math.Round(totalUpstreamAog / totalVolumeUpstream, 2)*100;
secondsAdded = i;
}
}
//Get the link totals
_AOGTotalPredicted = maxArrivalOnGreen;
_PAOGTotalPredicted = pAOGUpstreamPredicted;
}
//No bias provided
else
{
//set the original values to compare against
_AOGTotalBefore = aOGDownstreamBefore + aOGUpstreamBefore;
maxArrivalOnGreen = aOGUpstreamBefore;
_PAOGTotalBefore = Math.Round(_AOGTotalBefore / (totalVolumeDownstream + totalVolumeUpstream), 2) * 100;
//Add the total aog to the dictionary
resultsGraph.Add(0, maxArrivalOnGreen);
upstreamResultsGraph.Add(0, aOGUpstreamBefore);
downstreamResultsGraph.Add(0, aOGDownstreamBefore);
aOGUpstreamPredicted = aOGUpstreamBefore;
pAOGUpstreamPredicted = Math.Round(aOGUpstreamBefore / totalVolumeUpstream, 2)*100;
secondsAdded = 0;
for (int i = 1; i <= cycleTime; i++)
{
double totalArrivalOnGreen = 0;
double totalUpstreamAog = 0;
for (int index = 0; index < dates.Count; index++)
{
upstreamPCD[index].LinkPivotAddSeconds(-1);
totalArrivalOnGreen = +(upstreamPCD[index].TotalArrivalOnGreen);
totalUpstreamAog += upstreamPCD[index].TotalArrivalOnGreen;
}
//Add the total aog to the dictionary
resultsGraph.Add(i, totalArrivalOnGreen);
upstreamResultsGraph.Add(i, totalUpstreamAog);
if (totalArrivalOnGreen > maxArrivalOnGreen)
{
maxArrivalOnGreen = totalArrivalOnGreen;
aOGUpstreamPredicted = totalUpstreamAog;
pAOGUpstreamPredicted = Math.Round(totalUpstreamAog / totalVolumeUpstream, 2)*100;
secondsAdded = i;
}
//Get the link totals
_AOGTotalPredicted = maxArrivalOnGreen;
_PAOGTotalPredicted = pAOGUpstreamPredicted;
}
}
}
//If downsteam only has detection
else if (upstreamPCD.Count == 0 && downstreamPCD.Count > 0)
{
//if a bias was provided bias the results in the direction specified
if (bias != 0)
{
double upstreamBias = 1;
double downstreamBias = 1;
if (biasDirection == "Downstream")
{
downstreamBias = 1 + (bias / 100);
}
else
{
upstreamBias = 1 + (bias / 100);
}
//set the original values to compare against
double maxBiasArrivalOnGreen = (aOGDownstreamBefore * downstreamBias);
maxArrivalOnGreen = aOGDownstreamBefore + aOGUpstreamBefore;
//Add the total aog to the dictionary
resultsGraph.Add(0, maxArrivalOnGreen);
downstreamResultsGraph.Add(0, aOGDownstreamBefore * downstreamBias);
aOGDownstreamPredicted = aOGDownstreamBefore;
pAOGDownstreamPredicted = Math.Round(aOGDownstreamBefore / totalVolumeDownstream, 2)*100;
secondsAdded = 0;
for (int i = 1; i <= cycleTime; i++)
{
double totalBiasArrivalOnGreen = 0;
double totalArrivalOnGreen = 0;
double totalDownstreamAog = 0;
for (int index = 0; index < dates.Count; index++)
{
downstreamPCD[index].LinkPivotAddSeconds(1);
totalBiasArrivalOnGreen += (downstreamPCD[index].TotalArrivalOnGreen * downstreamBias);
totalArrivalOnGreen = + (downstreamPCD[index].TotalArrivalOnGreen);
totalDownstreamAog += downstreamPCD[index].TotalArrivalOnGreen;
}
//Add the total aog to the dictionary
resultsGraph.Add(i, totalBiasArrivalOnGreen);
downstreamResultsGraph.Add(i, totalDownstreamAog);
if (totalBiasArrivalOnGreen > maxBiasArrivalOnGreen)
{
maxBiasArrivalOnGreen = totalBiasArrivalOnGreen;
maxArrivalOnGreen = totalArrivalOnGreen;
aOGDownstreamPredicted = totalDownstreamAog;
pAOGDownstreamPredicted = Math.Round(totalDownstreamAog / totalVolumeDownstream, 2)*100;
secondsAdded = i;
}
}
//Get the link totals
_AOGTotalPredicted = maxArrivalOnGreen;
_PAOGTotalPredicted = pAOGDownstreamPredicted;
}
//if no bias was provided
else
{
//set the original values to compare against
maxArrivalOnGreen = aOGDownstreamBefore;
//Add the total aog to the dictionary
resultsGraph.Add(0, maxArrivalOnGreen);
downstreamResultsGraph.Add(0, aOGDownstreamBefore);
aOGDownstreamPredicted = aOGDownstreamBefore;
pAOGDownstreamPredicted = Math.Round(aOGDownstreamBefore / totalVolumeDownstream, 2) * 100;
secondsAdded = 0;
for (int i = 1; i <= cycleTime; i++)
{
double totalArrivalOnGreen = 0;
double totalDownstreamAog = 0;
for (int index = 0; index < dates.Count; index++)
{
downstreamPCD[index].LinkPivotAddSeconds(1);
totalArrivalOnGreen = +(downstreamPCD[index].TotalArrivalOnGreen);
totalDownstreamAog += downstreamPCD[index].TotalArrivalOnGreen;
}
//Add the total aog to the dictionary
resultsGraph.Add(i, totalArrivalOnGreen);
downstreamResultsGraph.Add(i, totalDownstreamAog);
if (totalArrivalOnGreen > maxArrivalOnGreen)
{
maxArrivalOnGreen = totalArrivalOnGreen;
aOGDownstreamPredicted = totalDownstreamAog;
pAOGDownstreamPredicted = Math.Round(totalDownstreamAog / totalVolumeDownstream, 2)*100;
secondsAdded = i;
}
}
//Get the link totals
_AOGTotalPredicted = maxArrivalOnGreen;
_PAOGTotalPredicted = pAOGDownstreamPredicted;
}
//pAOGDownstreamPredicted = downstreamPCD.PercentArrivalOnGreen;
//aOGDownstreamPredicted = downstreamPCD.TotalArrivalOnGreen;
//downstreamAfterPCDPath = CreateChart(downstreamPCD, startDate, endDate, downSignalLocation,
// "after", chartLocation);
}
GetNewResultsChart(chartLocation);
}
private void GetNewResultsChart(string chartLocation)
{
Chart chart = new Chart();
//Set the chart properties
chart.ImageType = ChartImageType.Jpeg;
chart.Height = 650;
chart.Width = 1100;
chart.ImageStorageMode = ImageStorageMode.UseImageLocation;
//Set the chart title
Title title = new Title();
title.Text = "Max Arrivals On Green By Second";
title.Font = new Font(FontFamily.GenericSansSerif, 20);
chart.Titles.Add(title);
//Create the chart legend
Legend chartLegend = new Legend();
chartLegend.Name = "MainLegend";
//chartLegend.LegendStyle = LegendStyle.Table;
chartLegend.Docking = Docking.Left;
//chartLegend.CustomItems.Add(Color.Blue, "AoG - Arrival On Green");
//chartLegend.CustomItems.Add(Color.Blue, "GT - Green Time");
//chartLegend.CustomItems.Add(Color.Maroon, "PR - Platoon Ratio");
//LegendCellColumn a = new LegendCellColumn();
//a.ColumnType = LegendCellColumnType.Text;
//a.Text = "test";
//chartLegend.CellColumns.Add(a);
chart.Legends.Add(chartLegend);
//Create the chart area
ChartArea chartArea = new ChartArea();
chartArea.Name = "ChartArea1";
chartArea.AxisY.Minimum = 0;
chartArea.AxisY.Title = "Arrivals On Green";
chartArea.AxisY.TitleFont = new Font(FontFamily.GenericSansSerif, 20);
chartArea.AxisY.LabelAutoFitStyle = LabelAutoFitStyles.None;
chartArea.AxisY.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 20);
chartArea.AxisX.Minimum = 0;
chartArea.AxisX.Title = "Adjustment(seconds)";
chartArea.AxisX.TitleFont = new Font(FontFamily.GenericSansSerif, 20);
chartArea.AxisX.Interval = 10;
chartArea.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.None;
chartArea.AxisX.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 20);
chart.ChartAreas.Add(chartArea);
//Add the line series
Series lineSeries = new Series();
lineSeries.ChartType = SeriesChartType.Line;
lineSeries.Color = Color.Black;
lineSeries.Name = "Total AOG";
lineSeries.XValueType = ChartValueType.Int32;
lineSeries.BorderWidth = 5;
chart.Series.Add(lineSeries);
foreach(KeyValuePair<int,double> d in ResultsGraph)
chart.Series["Total AOG"].Points.AddXY(
d.Key,
d.Value);
//Add the line series
Series downstreamLineSeries = new Series();
downstreamLineSeries.ChartType = SeriesChartType.Line;
downstreamLineSeries.Color = Color.Blue;
downstreamLineSeries.Name = "Downstream AOG";
downstreamLineSeries.XValueType = ChartValueType.Int32;
downstreamLineSeries.BorderWidth = 3;
chart.Series.Add(downstreamLineSeries);
foreach (KeyValuePair<int, double> d in DownstreamResultsGraph)
chart.Series["Downstream AOG"].Points.AddXY(
d.Key,
d.Value);
//Add the line series
Series upstreamLineSeries = new Series();
upstreamLineSeries.ChartType = SeriesChartType.Line;
upstreamLineSeries.Color = Color.Green;
upstreamLineSeries.Name = "Upstream AOG";
upstreamLineSeries.XValueType = ChartValueType.Int32;
upstreamLineSeries.BorderWidth = 3;
chart.Series.Add(upstreamLineSeries);
foreach (KeyValuePair<int, double> d in UpstreamResultsGraph)
chart.Series["Upstream AOG"].Points.AddXY(
d.Key,
d.Value);
string chartName = "LinkPivot-" + signalId + upstreamApproachDirection +
DownSignalId + DownstreamApproachDirection +
DateTime.Now.Day.ToString()+
DateTime.Now.Hour.ToString() +
DateTime.Now.Minute.ToString() +
DateTime.Now.Second.ToString() +
".jpg";
chart.SaveImage(chartLocation + @"LinkPivot\" + chartName,
System.Web.UI.DataVisualization.Charting.ChartImageFormat.Jpeg);
resultChartLocation = ConfigurationManager.AppSettings["ImageWebLocation"] +
@"LinkPivot/" + chartName;
}
/// <summary>
/// Creates a pcd chart specific to the Link Pivot
/// </summary>
/// <param name="sp"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <param name="location"></param>
/// <param name="chartNameSuffix"></param>
/// <param name="chartLocation"></param>
/// <returns></returns>
private string CreateChart(SignalPhase sp, DateTime startDate, DateTime endDate, string location,
string chartNameSuffix, string chartLocation)
{
Chart chart = new Chart();
//Display the PDC chart
chart = GetNewChart(startDate, endDate, sp.Approach.SignalID, sp.Approach.ProtectedPhaseNumber,
sp.Approach.DirectionType.Description,
location, sp.Approach.IsProtectedPhaseOverlap, 150, 2000, false, 2);
AddDataToChart(chart, sp, startDate, endDate, sp.Approach.SignalID, false, true);
//Create the File Name
string chartName = "LinkPivot-" +
sp.Approach.SignalID +
"-" +
sp.Approach.ProtectedPhaseNumber.ToString() +
"-" +
startDate.Year.ToString() +
startDate.ToString("MM") +
startDate.ToString("dd") +
startDate.ToString("HH") +
startDate.ToString("mm") +
"-" +
endDate.Year.ToString() +
endDate.ToString("MM") +
endDate.ToString("dd") +
endDate.ToString("HH") +
endDate.ToString("mm-") +
chartNameSuffix +
".jpg";
//Save an image of the chart
chart.SaveImage(chartLocation + chartName, System.Web.UI.DataVisualization.Charting.ChartImageFormat.Jpeg);
return chartName;
}
/// <summary>
/// Gets a new chart for the pcd Diagram
/// </summary>
/// <param name="graphStartDate"></param>
/// <param name="graphEndDate"></param>
/// <param name="signalId"></param>
/// <param name="phase"></param>
/// <param name="direction"></param>
/// <param name="location"></param>
/// <returns></returns>
private Chart GetNewChart(DateTime graphStartDate, DateTime graphEndDate, string signalId,
int phase, string direction, string location, bool isOverlap, double y1AxisMaximum,
double y2AxisMaximum, bool showVolume, int dotSize)
{
double y = 0;
Chart chart = new Chart();
string extendedDirection = string.Empty;
string movementType = "Phase";
if (isOverlap)
{
movementType = "Overlap";
}
//Gets direction for the title
switch (direction)
{
case "SB":
extendedDirection = "Southbound";
break;
case "NB":
extendedDirection = "Northbound";
break;
default:
extendedDirection = direction;
break;
}
//Set the chart properties
chart.ImageType = ChartImageType.Jpeg;
chart.Height = 650;
chart.Width = 1100;
chart.ImageStorageMode = ImageStorageMode.UseImageLocation;
//Set the chart title
Title title = new Title();
title.Text = location + "Signal " + signalId.ToString() + " "
+ movementType + ": " + phase.ToString() +
" " + extendedDirection + "\n" + graphStartDate.ToString("f") +
" - " + graphEndDate.ToString("f");
title.Font = new Font(FontFamily.GenericSansSerif, 20);
chart.Titles.Add(title);
//Create the chart legend
//Legend chartLegend = new Legend();
//chartLegend.Name = "MainLegend";
////chartLegend.LegendStyle = LegendStyle.Table;
//chartLegend.Docking = Docking.Left;
//chartLegend.CustomItems.Add(Color.Blue, "AoG - Arrival On Green");
//chartLegend.CustomItems.Add(Color.Blue, "GT - Green Time");
//chartLegend.CustomItems.Add(Color.Maroon, "PR - Platoon Ratio");
////LegendCellColumn a = new LegendCellColumn();
////a.ColumnType = LegendCellColumnType.Text;
////a.Text = "test";
////chartLegend.CellColumns.Add(a);
//chart.Legends.Add(chartLegend);
//Create the chart area
ChartArea chartArea = new ChartArea();
chartArea.Name = "ChartArea1";
chartArea.AxisY.Maximum = y1AxisMaximum;
chartArea.AxisY.Minimum = 0;
chartArea.AxisY.Title = "Cycle Time (Seconds) ";
chartArea.AxisY.TitleFont = new Font(FontFamily.GenericSansSerif, 20);
chartArea.AxisY.LabelAutoFitStyle = LabelAutoFitStyles.None;
chartArea.AxisY.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 20);
if (showVolume)
{
chartArea.AxisY2.Enabled = AxisEnabled.True;
chartArea.AxisY2.MajorTickMark.Enabled = true;
chartArea.AxisY2.MajorGrid.Enabled = false;
chartArea.AxisY2.IntervalType = DateTimeIntervalType.Number;
chartArea.AxisY2.Interval = 500;
chartArea.AxisY2.Maximum = y2AxisMaximum;
chartArea.AxisY2.Title = "Volume Per Hour ";
}
chartArea.AxisX.Title = "Time (Hour of Day)";
chartArea.AxisX.TitleFont = new Font(FontFamily.GenericSansSerif, 20);
chartArea.AxisX.Interval = 1;
chartArea.AxisX.IntervalType = DateTimeIntervalType.Hours;
chartArea.AxisX.LabelStyle.Format = "HH";
chartArea.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.None;
chartArea.AxisX.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 20);
//chartArea.AxisX.Minimum = 0;
chartArea.AxisX2.Enabled = AxisEnabled.True;
chartArea.AxisX2.MajorTickMark.Enabled = true;
chartArea.AxisX2.IntervalType = DateTimeIntervalType.Hours;
chartArea.AxisX2.LabelStyle.Format = "HH";
chartArea.AxisX2.LabelAutoFitStyle = LabelAutoFitStyles.None;
chartArea.AxisX2.Interval = 1;
chartArea.AxisX2.LabelStyle.Font = new Font(FontFamily.GenericSansSerif, 20);
//chartArea.AxisX.Minimum = 0;
chart.ChartAreas.Add(chartArea);
//Add the point series
Series pointSeries = new Series();
pointSeries.ChartType = SeriesChartType.Point;
pointSeries.Color = Color.Black;
pointSeries.Name = "Detector Activation";
pointSeries.XValueType = ChartValueType.DateTime;
pointSeries.MarkerSize = dotSize;
chart.Series.Add(pointSeries);
//Add the green series
Series greenSeries = new Series();
greenSeries.ChartType = SeriesChartType.Line;
greenSeries.Color = Color.DarkGreen;
greenSeries.Name = "Change to Green";
greenSeries.XValueType = ChartValueType.DateTime;
greenSeries.BorderWidth = 1;
chart.Series.Add(greenSeries);
//Add the yellow series
Series yellowSeries = new Series();
yellowSeries.ChartType = SeriesChartType.Line;
yellowSeries.Color = Color.Yellow;
yellowSeries.Name = "Change to Yellow";
yellowSeries.XValueType = ChartValueType.DateTime;
chart.Series.Add(yellowSeries);
//Add the red series
Series redSeries = new Series();
redSeries.ChartType = SeriesChartType.Line;
redSeries.Color = Color.Red;
redSeries.Name = "Change to Red";
redSeries.XValueType = ChartValueType.DateTime;
chart.Series.Add(redSeries);
//Add the red series
Series volumeSeries = new Series();
volumeSeries.ChartType = SeriesChartType.Line;
volumeSeries.Color = Color.Black;
volumeSeries.Name = "Volume Per Hour";
volumeSeries.XValueType = ChartValueType.DateTime;
volumeSeries.YAxisType = AxisType.Secondary;
chart.Series.Add(volumeSeries);
//Add points at the start and and of the x axis to ensure
//the graph covers the entire period selected by the user
//whether there is data or not
chart.Series["Detector Activation"].Points.AddXY(graphStartDate, 0);
chart.Series["Detector Activation"].Points.AddXY(graphEndDate, 0);
return chart;
}
/// <summary>
/// Adds data points to a graph with the series GreenLine, YellowLine, Redline
/// and Points already added.
/// </summary>
/// <param name="chart"></param>
/// <param name="signalPhase"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <param name="signalId"></param>
private void AddDataToChart(Chart chart, MOE.Common.Business.SignalPhase signalPhase, DateTime startDate,
DateTime endDate, string signalId, bool showVolume, bool showArrivalOnGreen)
{
decimal totalDetectorHits = 0;
decimal totalOnGreenArrivals = 0;
decimal percentArrivalOnGreen = 0;
foreach (MOE.Common.Business.Plan plan in signalPhase.Plans.PlanList)
{
if (plan.CycleCollection.Count > 0)
{
foreach (MOE.Common.Business.Cycle pcd in plan.CycleCollection)
{
chart.Series["Change to Green"].Points.AddXY(
//pcd.StartTime,
pcd.GreenEvent,
pcd.GreenLineY);
chart.Series["Change to Yellow"].Points.AddXY(
//pcd.StartTime,
pcd.YellowEvent,
pcd.YellowLineY);
chart.Series["Change to Red"].Points.AddXY(
//pcd.StartTime,
pcd.EndTime,
pcd.RedLineY);
totalDetectorHits += pcd.DetectorCollection.Count;
foreach (MOE.Common.Business.DetectorDataPoint detectorPoint in pcd.DetectorCollection)
{
chart.Series["Detector Activation"].Points.AddXY(
//pcd.StartTime,
detectorPoint.TimeStamp,
detectorPoint.YPoint);
if (detectorPoint.YPoint > pcd.GreenLineY && detectorPoint.YPoint < pcd.RedLineY)
{
totalOnGreenArrivals++;
}
}
}
}
}
if (showVolume)
{
foreach (MOE.Common.Business.Volume v in signalPhase.Volume.Items)
{
chart.Series["Volume Per Hour"].Points.AddXY(v.XAxis, v.YAxis);
}
}
//if arrivals on green is selected add the data to the chart
if (showArrivalOnGreen)
{
if (totalDetectorHits > 0)
{
percentArrivalOnGreen = (totalOnGreenArrivals / totalDetectorHits) * 100;
}
else
{
percentArrivalOnGreen = 0;
}
Title title = new Title();
title.Text = Math.Round(percentArrivalOnGreen).ToString() + "% AoG";
title.Font = new Font(FontFamily.GenericSansSerif, 20);
chart.Titles.Add(title);
SetPlanStrips(signalPhase.Plans.PlanList, chart, startDate);
}
//Add Comment to chart
//MOE.Common.Data.Signals.SPM_CommentDataTable commentTable = new MOE.Common.Data.Signals.SPM_CommentDataTable();
//MOE.Common.Data.SignalsTableAdapters.SPM_CommentTableAdapter commentTA = new MOE.Common.Data.SignalsTableAdapters.SPM_CommentTableAdapter();
//commentTA.FillByEntitybyChartType(commentTable, 4, signalId.ToString(), 2);
//MOE.Common.Models.SPM db = new MOE.Common.Models.SPM();
//var commentTable = from r in db.Comment
// where r.ChartType == 4 && r.Entity == signalId && r.EntityType == 2
// select r;
// if (commentTable.Count() > 0)
// {
// MOE.Common.Models.Comment comment = commentTable.FirstOrDefault();
// chart.Titles.Add(comment.Comment);
// chart.Titles[1].Docking = Docking.Bottom;
// chart.Titles[1].ForeColor = Color.Red;
//}
}
/// <summary>
/// Adds plan strips to the chart
/// </summary>
/// <param name="planCollection"></param>
/// <param name="chart"></param>
/// <param name="graphStartDate"></param>
protected void SetPlanStrips(List<MOE.Common.Business.Plan> planCollection, Chart chart, DateTime graphStartDate)
{
int backGroundColor = 1;
foreach (MOE.Common.Business.Plan plan in planCollection)
{
StripLine stripline = new StripLine();
//Creates alternating backcolor to distinguish the plans
if (backGroundColor % 2 == 0)
{
stripline.BackColor = Color.FromArgb(120, Color.LightGray);
}
else
{
stripline.BackColor = Color.FromArgb(120, Color.LightBlue);
}
//Set the stripline properties
stripline.IntervalOffset = (plan.StartTime - graphStartDate).TotalHours;
stripline.IntervalOffsetType = DateTimeIntervalType.Hours;
stripline.Interval = 1;
stripline.IntervalType = DateTimeIntervalType.Days;
stripline.StripWidth = (plan.EndTime - plan.StartTime).TotalHours;
stripline.StripWidthType = DateTimeIntervalType.Hours;
chart.ChartAreas["ChartArea1"].AxisX.StripLines.Add(stripline);
//Add a corrisponding custom label for each strip
CustomLabel Plannumberlabel = new CustomLabel();
Plannumberlabel.FromPosition = plan.StartTime.ToOADate();
Plannumberlabel.ToPosition = plan.EndTime.ToOADate();
switch (plan.PlanNumber)
{
case 254:
Plannumberlabel.Text = "Free";
break;
case 255:
Plannumberlabel.Text = "Flash";
break;
case 0:
Plannumberlabel.Text = "Unknown";
break;
default:
Plannumberlabel.Text = "Plan " + plan.PlanNumber.ToString();
break;
}
Plannumberlabel.ForeColor = Color.Black;
Plannumberlabel.RowIndex = 3;
chart.ChartAreas["ChartArea1"].AxisX2.CustomLabels.Add(Plannumberlabel);
CustomLabel aogLabel = new CustomLabel();
aogLabel.FromPosition = plan.StartTime.ToOADate();
aogLabel.ToPosition = plan.EndTime.ToOADate();
aogLabel.Text = plan.PercentArrivalOnGreen.ToString() + "% AoG\n" +
plan.PercentGreen.ToString() + "% GT";
aogLabel.LabelMark = LabelMarkStyle.LineSideMark;
aogLabel.ForeColor = Color.Blue;
aogLabel.RowIndex = 2;
chart.ChartAreas["ChartArea1"].AxisX2.CustomLabels.Add(aogLabel);
CustomLabel statisticlabel = new CustomLabel();
statisticlabel.FromPosition = plan.StartTime.ToOADate();
statisticlabel.ToPosition = plan.EndTime.ToOADate();
statisticlabel.Text =
plan.PlatoonRatio.ToString() + " PR";
statisticlabel.ForeColor = Color.Maroon;
statisticlabel.RowIndex = 1;
chart.ChartAreas["ChartArea1"].AxisX2.CustomLabels.Add(statisticlabel);
//CustomLabel PlatoonRatiolabel = new CustomLabel();
//PercentGreenlabel.FromPosition = plan.StartTime.ToOADate();
//PercentGreenlabel.ToPosition = plan.EndTime.ToOADate();
//PercentGreenlabel.Text = plan.PlatoonRatio.ToString() + " PR";
//PercentGreenlabel.ForeColor = Color.Black;
//PercentGreenlabel.RowIndex = 1;
//chart.ChartAreas["ChartArea1"].AxisX2.CustomLabels.Add(PercentGreenlabel);
//Change the background color counter for alternating color
backGroundColor++;
}
}
}
}
| 44.209927 | 154 | 0.533276 | [
"Apache-2.0"
] | OSADP/ATSPM | Version4.0.1/MOE.Common/Business/LinkPivotPair.cs | 54,336 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2020 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2020 Senparc
文件名:WiFiApi.cs
文件功能描述:微信连WiFi接口
创建标识:Senparc - 20150709
修改标识:Senparc - 20160506
修改描述:添加“获取公众号连网URL”接口(GetConnectUrl)
修改标识:Senparc - 20160511
修改描述:WiFiApi.AddDevice去掉bssid参数
修改标识:Senparc - 20160520
修改描述:添加获取Wi-Fi门店列表接口,查询门店Wi-Fi信息接口,修改门店网络信息接口,清空门店网络及设备接口,
添加portal型设备接口,设置微信首页欢迎语接口,设置连网完成页接口,设置门店卡券投放信息接口,
查询门店卡券投放信息接口,第三方平台获取开插件wifi_token接口
修改标识:Senparc - 20160719
修改描述:增加其接口的异步方法
修改标识:Senparc - 20170707
修改描述:v14.5.1 完善异步方法async/await
----------------------------------------------------------------*/
/*
官方文档:http://mp.weixin.qq.com/wiki/10/6232005bdc497f7cf8e19d4e843c70d2.html
*/
using System.Threading.Tasks;
using Senparc.NeuChar;
using Senparc.Weixin.CommonAPIs;
using Senparc.Weixin.Entities;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.MP.AdvancedAPIs.WiFi;
using Senparc.Weixin.MP.CommonAPIs;
namespace Senparc.Weixin.MP.AdvancedAPIs
{
/// <summary>
///
/// </summary>
public static class WiFiApi
{
#region 同步方法
/// <summary>
/// 获取Wi-Fi门店列表
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="pageIndex">分页下标,默认从1开始</param>
/// <param name="pageSize">每页的个数,默认10个,最大20个</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopList", true)]
public static WiFiShopListJsonResult ShopList(string accessTokenOrAppId, int pageIndex = 1, int pageSize = 10, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/list?access_token={0}";
var data = new
{
pageindex = pageIndex,
pagesize = pageSize
};
return CommonJsonSend.Send<WiFiShopListJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 查询门店Wi-Fi信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="pageindex">分页下标,默认从1开始</param>
/// <param name="pagesize">每页的个数,默认10个,最大20个</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopGet", true)]
public static WiFiShopGetJsonResult ShopGet(string accessTokenOrAppId, long shopId, int pageindex = 1, int pagesize = 10, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/get?access_token={0}";
var data = new
{
shop_id = shopId,
pageindex = pageindex,
pagesize = pagesize
};
return CommonJsonSend.Send<WiFiShopGetJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 修改门店网络信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="oldSsid">需要修改的ssid,当门店下有多个ssid时,必填</param>
/// <param name="ssid">无线网络设备的ssid。32个字符以内;ssid支持中文,但可能因设备兼容性问题导致显示乱码,或无法连接等问题,相关风险自行承担!当门店下是portal型设备时,ssid必填;当门店下是密码型设备时,ssid选填,且ssid和密码必须有一个以大写字母“WX”开头</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopUpdate", true)]
public static WxJsonResult ShopUpdate(string accessTokenOrAppId, long shopId, string oldSsid, string ssid, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/update?access_token={0}";
var data = new
{
shop_id = shopId,
old_ssid = oldSsid,
ssid = ssid
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 清空门店网络及设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="ssid">无线网络设备的ssid。若不填写ssid,默认为清空门店下所有设备;填写ssid则为清空该ssid下的所有设备</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopClean", true)]
public static WxJsonResult ShopClean(string accessTokenOrAppId, long shopId, string ssid, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/clean?access_token={0}";
var data = new object();
if (string.IsNullOrEmpty(ssid))
{
data = new
{
shop_id = shopId
};
}
else
{
data = new
{
shop_id = shopId,
ssid = ssid
};
}
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 添加设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="ssid">无线网络设备的ssid,不能包含中文字符,必需是“WX”开头(“WX”为大写字母)</param>
/// <param name="password">无线网络设备的密码,大于8个字符,不能包含中文字符</param>
///// <param name="bssid">无线网络设备无线mac地址,格式冒号分隔,字符长度17个,并且字母小写,例如:00:1f:7a:ad:5c:a8</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.AddDevice", true)]
public static WxJsonResult AddDevice(string accessTokenOrAppId, long shopId, string ssid, string password,
/*string bssid,*/ int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/device/add?access_token={0}";
var data = new
{
shop_id = shopId,
ssid = ssid,
password = password,
//bssid = bssid,
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 添加portal型设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="ssid">无线网络设备的ssid,限30个字符以内。ssid支持中文,但可能因设备兼容性问题导致显示乱码,或无法连接等问题,相关风险自行承担!</param>
/// <param name="reset">重置secretkey,false-不重置,true-重置,默认为false</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.WifeRegister", true)]
public static WiFiRegisterJsonResult WifeRegister(string accessTokenOrAppId, long shopId, string ssid, string reset,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/apportal/register?access_token={0}";
var data = new
{
shop_id = shopId,
ssid = ssid,
reset = reset,
};
return CommonJsonSend.Send<WiFiRegisterJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 查询设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="pageIndex">分页下标,默认从1开始</param>
/// <param name="pageSize">每页的个数,默认10个,最大20个</param>
/// <param name="shopId">根据门店id查询</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetDeviceList", true)]
public static GetDeviceListResult GetDeviceList(string accessTokenOrAppId, int pageIndex = 1, int pageSize = 10,
long? shopId = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/device/list?access_token={0}";
object data = new object();
if (shopId.HasValue)
{
data = new
{
pageindex = pageIndex,
pagesize = pageSize,
shop_id = shopId,
};
}
else
{
data = new
{
pageindex = pageIndex,
pagesize = pageSize
};
}
return CommonJsonSend.Send<GetDeviceListResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 删除设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="bssid">需要删除的无线网络设备无线mac地址,格式冒号分隔,字符长度17个,并且字母小写,例如:00:1f:7a:ad:5c:a8</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.DeleteDevice", true)]
public static WxJsonResult DeleteDevice(string accessTokenOrAppId, string bssid, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/device/delete?access_token={0}";
var data = new
{
bssid = bssid
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 获取物料二维码
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId"></param>
/// <param name="imgId"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetQrcode", true)]
public static GetQrcodeResult GetQrcode(string accessTokenOrAppId, long shopId, int imgId,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/qrcode/get?access_token={0}";
var data = new
{
shop_id = shopId,
img_id = imgId
};
return CommonJsonSend.Send<GetQrcodeResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 设置商家主页
/// 传入自定义链接则是使用自定义链接,否则使用默认模板
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="url">自定义链接(选择传入)</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetHomePage", true)]
public static WxJsonResult SetHomePage(string accessTokenOrAppId, long shopId, string url = null,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/homepage/set?access_token={0}";
var data = new object();
if (string.IsNullOrEmpty(url))
{
data = new
{
shop_id = shopId,
template_id = 0
};
}
else
{
data = new
{
shop_id = shopId,
template_id = 1,
@struct = new
{
url = url
}
};
}
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 查询商家主页
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">查询的门店id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetHomePage", true)]
public static GetHomePageResult GetHomePage(string accessTokenOrAppId, long shopId,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/homepage/get?access_token={0}";
var data = new
{
shop_id = shopId,
};
return CommonJsonSend.Send<GetHomePageResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 设置微信首页欢迎语
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="barType">微信首页欢迎语的文本内容:0--欢迎光临+公众号名称;1--欢迎光临+门店名称;2--已连接+公众号名称+WiFi;3--已连接+门店名称+Wi-Fi。</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetBar", true)]
public static WxJsonResult SetBar(string accessTokenOrAppId, long shopId, int barType,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/bar/set?access_token={0}";
var data = new
{
shop_id = shopId,
bar_type = barType
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 设置连网完成页
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="finishPageUrl">连网完成页URL。</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetFinishpage", true)]
public static WxJsonResult SetFinishpage(string accessTokenOrAppId, long shopId, string finishPageUrl,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/finishpage/set?access_token={0}";
var data = new
{
shop_id = shopId,
finishpage_url = finishPageUrl
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 数据统计
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="beginDate">起始日期时间,格式yyyy-mm-dd,最长时间跨度为30天</param>
/// <param name="endDate">结束日期时间戳,格式yyyy-mm-dd,最长时间跨度为30天</param>
/// <param name="shopId">按门店ID搜索,-1为总统计</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetStatistics", true)]
public static GetStatisticsResult GetStatistics(string accessTokenOrAppId, string beginDate, string endDate,
long shopId = -1,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/statistics/list?access_token={0}";
var data = new
{
begin_date = beginDate,
end_date = endDate,
shop_id = shopId,
};
return CommonJsonSend.Send<GetStatisticsResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 设置门店卡券投放信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID,可设置为0,表示所有门店</param>
/// <param name="cardId">卡券ID</param>
/// <param name="cardDescribe">卡券描述,不能超过18个字符</param>
///<param name="starTime">卡券投放开始时间(单位是秒)</param>
/// <param name="endTime">卡券投放结束时间(单位是秒)注:不能超过卡券的有效期时间</param>
/// <param name="cardQuantity">卡券库存</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetCouponPut", true)]
public static WxJsonResult SetCouponPut(string accessTokenOrAppId, long shopId, string cardId, string cardDescribe, string starTime, string endTime, int cardQuantity,
int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/couponput/set?access_token={0}";
var data = new
{
shop_id = shopId,
card_id = cardId,
card_describe = cardDescribe,
start_time = starTime,
end_time = endTime,
card_quantity = cardQuantity
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 查询门店卡券投放信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID,可设置为0,表示所有门店</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetCouponPut", true)]
public static WiFiGetCouponPutJsonResult GetCouponPut(string accessTokenOrAppId, long shopId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/couponput/get?access_token={0}";
var data = new
{
shop_id = shopId
};
return CommonJsonSend.Send<WiFiGetCouponPutJsonResult>(accessToken, urlFormat, data, timeOut: timeOut);
}, accessTokenOrAppId);
}
/// <summary>
/// 获取公众号连网URL
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetConnectUrl", true)]
public static WiFiConnectUrlResultJson GetConnectUrl(string accessTokenOrAppId)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/account/get_connecturl?access_token={0}";
return CommonJsonSend.Send<WiFiConnectUrlResultJson>(accessToken, urlFormat, null,
CommonJsonSendType.GET);
}, accessTokenOrAppId);
}
/// <summary>
/// 第三方平台获取开插件wifi_token
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="callBackUrl">回调URL,开通插件成功后的跳转页面。注:该参数域名必须与跳转进开通插件页面的页面域名保持一致,建议均采用第三方平台域名。</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.OpenPluginToken", true)]
public static WiFiOpenPluginTokenJsonResult OpenPluginToken(string accessTokenOrAppId, string callBackUrl, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/openplugin/token?access_token={0}";
var data = new
{
callback_url = callBackUrl
};
return CommonJsonSend.Send<WiFiOpenPluginTokenJsonResult>(accessToken, urlFormat, data, CommonJsonSendType.GET, timeOut: timeOut);
}, accessTokenOrAppId);
}
#endregion
#region 异步方法
/// <summary>
/// 【异步方法】获取Wi-Fi门店列表
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="pageIndex">分页下标,默认从1开始</param>
/// <param name="pageSize">每页的个数,默认10个,最大20个</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopListAsync", true)]
public static async Task<WiFiShopListJsonResult> ShopListAsync(string accessTokenOrAppId, int pageIndex = 1, int pageSize = 10, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/list?access_token={0}";
var data = new
{
pageindex = pageIndex,
pagesize = pageSize
};
return await Senparc .Weixin .CommonAPIs .CommonJsonSend.SendAsync<WiFiShopListJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】查询门店Wi-Fi信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="pageindex">分页下标,默认从1开始</param>
/// <param name="pagesize">每页的个数,默认10个,最大20个</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopGetAsync", true)]
public static async Task<WiFiShopGetJsonResult> ShopGetAsync(string accessTokenOrAppId, long shopId, int pageindex = 1, int pagesize = 10, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/get?access_token={0}";
var data = new
{
shop_id = shopId,
pageindex = pageindex,
pagesize = pagesize
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WiFiShopGetJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】修改门店网络信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="oldSsid">需要修改的ssid,当门店下有多个ssid时,必填</param>
/// <param name="ssid">无线网络设备的ssid。32个字符以内;ssid支持中文,但可能因设备兼容性问题导致显示乱码,或无法连接等问题,相关风险自行承担!当门店下是portal型设备时,ssid必填;当门店下是密码型设备时,ssid选填,且ssid和密码必须有一个以大写字母“WX”开头</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopUpdateAsync", true)]
public static async Task<WxJsonResult> ShopUpdateAsync(string accessTokenOrAppId, long shopId, string oldSsid, string ssid, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/update?access_token={0}";
var data = new
{
shop_id = shopId,
old_ssid = oldSsid,
ssid = ssid
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】清空门店网络及设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="ssid">无线网络设备的ssid。若不填写ssid,默认为清空门店下所有设备;填写ssid则为清空该ssid下的所有设备</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.ShopCleanAsync", true)]
public static async Task<WxJsonResult> ShopCleanAsync(string accessTokenOrAppId, long shopId, string ssid, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/shop/clean?access_token={0}";
var data = new object();
if (string.IsNullOrEmpty(ssid))
{
data = new
{
shop_id = shopId
};
}
else
{
data = new
{
shop_id = shopId,
ssid = ssid
};
}
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】添加设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="ssid">无线网络设备的ssid,不能包含中文字符,必需是“WX”开头(“WX”为大写字母)</param>
/// <param name="password">无线网络设备的密码,大于8个字符,不能包含中文字符</param>
///// <param name="bssid">无线网络设备无线mac地址,格式冒号分隔,字符长度17个,并且字母小写,例如:00:1f:7a:ad:5c:a8</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.AddDeviceAsync", true)]
public static async Task<WxJsonResult> AddDeviceAsync(string accessTokenOrAppId, long shopId, string ssid, string password,
/*string bssid,*/ int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/device/add?access_token={0}";
var data = new
{
shop_id = shopId,
ssid = ssid,
password = password,
//bssid = bssid,
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】添加portal型设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="ssid">无线网络设备的ssid,限30个字符以内。ssid支持中文,但可能因设备兼容性问题导致显示乱码,或无法连接等问题,相关风险自行承担!</param>
/// <param name="reset">重置secretkey,false-不重置,true-重置,默认为false</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.WifeRegisterAsync", true)]
public static async Task<WiFiRegisterJsonResult> WifeRegisterAsync(string accessTokenOrAppId, long shopId, string ssid, string reset,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/apportal/register?access_token={0}";
var data = new
{
shop_id = shopId,
ssid = ssid,
reset = reset,
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WiFiRegisterJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】查询设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="pageIndex">分页下标,默认从1开始</param>
/// <param name="pageSize">每页的个数,默认10个,最大20个</param>
/// <param name="shopId">根据门店id查询</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetDeviceListAsync", true)]
public static async Task<GetDeviceListResult> GetDeviceListAsync(string accessTokenOrAppId, int pageIndex = 1, int pageSize = 10,
long? shopId = null, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/device/list?access_token={0}";
object data = new object();
if (shopId.HasValue)
{
data = new
{
pageindex = pageIndex,
pagesize = pageSize,
shop_id = shopId,
};
}
else
{
data = new
{
pageindex = pageIndex,
pagesize = pageSize
};
}
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetDeviceListResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】删除设备
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="bssid">需要删除的无线网络设备无线mac地址,格式冒号分隔,字符长度17个,并且字母小写,例如:00:1f:7a:ad:5c:a8</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.DeleteDeviceAsync", true)]
public static async Task<WxJsonResult> DeleteDeviceAsync(string accessTokenOrAppId, string bssid, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/device/delete?access_token={0}";
var data = new
{
bssid = bssid
};
return await Senparc .Weixin .CommonAPIs .CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】获取物料二维码
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId"></param>
/// <param name="imgId"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetQrcodeAsync", true)]
public static async Task<GetQrcodeResult> GetQrcodeAsync(string accessTokenOrAppId, long shopId, int imgId,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/qrcode/get?access_token={0}";
var data = new
{
shop_id = shopId,
img_id = imgId
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetQrcodeResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】设置商家主页
/// 传入自定义链接则是使用自定义链接,否则使用默认模板
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="url">自定义链接(选择传入)</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetHomePageAsync", true)]
public static async Task<WxJsonResult> SetHomePageAsync(string accessTokenOrAppId, long shopId, string url = null,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/homepage/set?access_token={0}";
var data = new object();
if (string.IsNullOrEmpty(url))
{
data = new
{
shop_id = shopId,
template_id = 0
};
}
else
{
data = new
{
shop_id = shopId,
template_id = 1,
@struct = new
{
url = url
}
};
}
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
///【异步方法】 查询商家主页
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">查询的门店id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetHomePageaAsync", true)]
public static async Task<GetHomePageResult> GetHomePageaAsync(string accessTokenOrAppId, long shopId,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/homepage/get?access_token={0}";
var data = new
{
shop_id = shopId,
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetHomePageResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
///【异步方法】 设置微信首页欢迎语
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="barType">微信首页欢迎语的文本内容:0--欢迎光临+公众号名称;1--欢迎光临+门店名称;2--已连接+公众号名称+WiFi;3--已连接+门店名称+Wi-Fi。</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetBarAsync", true)]
public static async Task<WxJsonResult> SetBarAsync(string accessTokenOrAppId, long shopId, int barType,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/bar/set?access_token={0}";
var data = new
{
shop_id = shopId,
bar_type = barType
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
///【异步方法】 设置连网完成页
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID</param>
/// <param name="finishPageUrl">连网完成页URL。</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetFinishpageAsync", true)]
public static async Task<WxJsonResult> SetFinishpageAsync(string accessTokenOrAppId, long shopId, string finishPageUrl,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/finishpage/set?access_token={0}";
var data = new
{
shop_id = shopId,
finishpage_url = finishPageUrl
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】数据统计
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="beginDate">起始日期时间,格式yyyy-mm-dd,最长时间跨度为30天</param>
/// <param name="endDate">结束日期时间戳,格式yyyy-mm-dd,最长时间跨度为30天</param>
/// <param name="shopId">按门店ID搜索,-1为总统计</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetStatisticsAsync", true)]
public static async Task<GetStatisticsResult> GetStatisticsAsync(string accessTokenOrAppId, string beginDate, string endDate,
long shopId = -1,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/statistics/list?access_token={0}";
var data = new
{
begin_date = beginDate,
end_date = endDate,
shop_id = shopId,
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetStatisticsResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
///【异步方法】 设置门店卡券投放信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID,可设置为0,表示所有门店</param>
/// <param name="cardId">卡券ID</param>
/// <param name="cardDescribe">卡券描述,不能超过18个字符</param>
///<param name="starTime">卡券投放开始时间(单位是秒)</param>
/// <param name="endTime">卡券投放结束时间(单位是秒)注:不能超过卡券的有效期时间</param>
/// <param name="cardQuantity">卡券库存</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.SetCouponPutAsync", true)]
public static async Task<WxJsonResult> SetCouponPutAsync(string accessTokenOrAppId, long shopId, string cardId, string cardDescribe, string starTime, string endTime, int cardQuantity,
int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/couponput/set?access_token={0}";
var data = new
{
shop_id = shopId,
card_id = cardId,
card_describe = cardDescribe,
start_time = starTime,
end_time = endTime,
card_quantity = cardQuantity
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】查询门店卡券投放信息
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="shopId">门店ID,可设置为0,表示所有门店</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetCouponPutAsync", true)]
public static async Task<WiFiGetCouponPutJsonResult> GetCouponPutAsync(string accessTokenOrAppId, long shopId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/couponput/get?access_token={0}";
var data = new
{
shop_id = shopId
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WiFiGetCouponPutJsonResult>(accessToken, urlFormat, data, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
///【异步方法】 获取公众号连网URL
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.GetConnectUrlAsync", true)]
public static async Task<WiFiConnectUrlResultJson> GetConnectUrlAsync(string accessTokenOrAppId)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/account/get_connecturl?access_token={0}";
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WiFiConnectUrlResultJson>(accessToken, urlFormat, null,
CommonJsonSendType.GET).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】第三方平台获取开插件wifi_token
/// </summary>
/// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param>
/// <param name="callBackUrl">回调URL,开通插件成功后的跳转页面。注:该参数域名必须与跳转进开通插件页面的页面域名保持一致,建议均采用第三方平台域名。</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "WiFiApi.OpenPluginTokenAsync", true)]
public static async Task<WiFiOpenPluginTokenJsonResult> OpenPluginTokenAsync(string accessTokenOrAppId, string callBackUrl, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
string urlFormat = Config.ApiMpHost + "/bizwifi/openplugin/token?access_token={0}";
var data = new
{
callback_url = callBackUrl
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WiFiOpenPluginTokenJsonResult>(accessToken, urlFormat, data, CommonJsonSendType.GET, timeOut: timeOut).ConfigureAwait(false);
}, accessTokenOrAppId).ConfigureAwait(false);
}
#endregion
}
}
| 42.278175 | 205 | 0.571858 | [
"Apache-2.0"
] | 103556710/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/WiFi/WiFiApi.cs | 52,305 | 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 ds-2015-04-16.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.DirectoryService
{
/// <summary>
/// Constants used for properties of type DirectorySize.
/// </summary>
public class DirectorySize : ConstantClass
{
/// <summary>
/// Constant Large for DirectorySize
/// </summary>
public static readonly DirectorySize Large = new DirectorySize("Large");
/// <summary>
/// Constant Small for DirectorySize
/// </summary>
public static readonly DirectorySize Small = new DirectorySize("Small");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DirectorySize(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DirectorySize FindValue(string value)
{
return FindValue<DirectorySize>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DirectorySize(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DirectoryStage.
/// </summary>
public class DirectoryStage : ConstantClass
{
/// <summary>
/// Constant Active for DirectoryStage
/// </summary>
public static readonly DirectoryStage Active = new DirectoryStage("Active");
/// <summary>
/// Constant Created for DirectoryStage
/// </summary>
public static readonly DirectoryStage Created = new DirectoryStage("Created");
/// <summary>
/// Constant Creating for DirectoryStage
/// </summary>
public static readonly DirectoryStage Creating = new DirectoryStage("Creating");
/// <summary>
/// Constant Deleted for DirectoryStage
/// </summary>
public static readonly DirectoryStage Deleted = new DirectoryStage("Deleted");
/// <summary>
/// Constant Deleting for DirectoryStage
/// </summary>
public static readonly DirectoryStage Deleting = new DirectoryStage("Deleting");
/// <summary>
/// Constant Failed for DirectoryStage
/// </summary>
public static readonly DirectoryStage Failed = new DirectoryStage("Failed");
/// <summary>
/// Constant Impaired for DirectoryStage
/// </summary>
public static readonly DirectoryStage Impaired = new DirectoryStage("Impaired");
/// <summary>
/// Constant Inoperable for DirectoryStage
/// </summary>
public static readonly DirectoryStage Inoperable = new DirectoryStage("Inoperable");
/// <summary>
/// Constant Requested for DirectoryStage
/// </summary>
public static readonly DirectoryStage Requested = new DirectoryStage("Requested");
/// <summary>
/// Constant RestoreFailed for DirectoryStage
/// </summary>
public static readonly DirectoryStage RestoreFailed = new DirectoryStage("RestoreFailed");
/// <summary>
/// Constant Restoring for DirectoryStage
/// </summary>
public static readonly DirectoryStage Restoring = new DirectoryStage("Restoring");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DirectoryStage(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DirectoryStage FindValue(string value)
{
return FindValue<DirectoryStage>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DirectoryStage(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DirectoryType.
/// </summary>
public class DirectoryType : ConstantClass
{
/// <summary>
/// Constant ADConnector for DirectoryType
/// </summary>
public static readonly DirectoryType ADConnector = new DirectoryType("ADConnector");
/// <summary>
/// Constant MicrosoftAD for DirectoryType
/// </summary>
public static readonly DirectoryType MicrosoftAD = new DirectoryType("MicrosoftAD");
/// <summary>
/// Constant SimpleAD for DirectoryType
/// </summary>
public static readonly DirectoryType SimpleAD = new DirectoryType("SimpleAD");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DirectoryType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DirectoryType FindValue(string value)
{
return FindValue<DirectoryType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DirectoryType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type RadiusAuthenticationProtocol.
/// </summary>
public class RadiusAuthenticationProtocol : ConstantClass
{
/// <summary>
/// Constant CHAP for RadiusAuthenticationProtocol
/// </summary>
public static readonly RadiusAuthenticationProtocol CHAP = new RadiusAuthenticationProtocol("CHAP");
/// <summary>
/// Constant MSCHAPv1 for RadiusAuthenticationProtocol
/// </summary>
public static readonly RadiusAuthenticationProtocol MSCHAPv1 = new RadiusAuthenticationProtocol("MS-CHAPv1");
/// <summary>
/// Constant MSCHAPv2 for RadiusAuthenticationProtocol
/// </summary>
public static readonly RadiusAuthenticationProtocol MSCHAPv2 = new RadiusAuthenticationProtocol("MS-CHAPv2");
/// <summary>
/// Constant PAP for RadiusAuthenticationProtocol
/// </summary>
public static readonly RadiusAuthenticationProtocol PAP = new RadiusAuthenticationProtocol("PAP");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public RadiusAuthenticationProtocol(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static RadiusAuthenticationProtocol FindValue(string value)
{
return FindValue<RadiusAuthenticationProtocol>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator RadiusAuthenticationProtocol(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type RadiusStatus.
/// </summary>
public class RadiusStatus : ConstantClass
{
/// <summary>
/// Constant Completed for RadiusStatus
/// </summary>
public static readonly RadiusStatus Completed = new RadiusStatus("Completed");
/// <summary>
/// Constant Creating for RadiusStatus
/// </summary>
public static readonly RadiusStatus Creating = new RadiusStatus("Creating");
/// <summary>
/// Constant Failed for RadiusStatus
/// </summary>
public static readonly RadiusStatus Failed = new RadiusStatus("Failed");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public RadiusStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static RadiusStatus FindValue(string value)
{
return FindValue<RadiusStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator RadiusStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ReplicationScope.
/// </summary>
public class ReplicationScope : ConstantClass
{
/// <summary>
/// Constant Domain for ReplicationScope
/// </summary>
public static readonly ReplicationScope Domain = new ReplicationScope("Domain");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ReplicationScope(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ReplicationScope FindValue(string value)
{
return FindValue<ReplicationScope>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ReplicationScope(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SnapshotStatus.
/// </summary>
public class SnapshotStatus : ConstantClass
{
/// <summary>
/// Constant Completed for SnapshotStatus
/// </summary>
public static readonly SnapshotStatus Completed = new SnapshotStatus("Completed");
/// <summary>
/// Constant Creating for SnapshotStatus
/// </summary>
public static readonly SnapshotStatus Creating = new SnapshotStatus("Creating");
/// <summary>
/// Constant Failed for SnapshotStatus
/// </summary>
public static readonly SnapshotStatus Failed = new SnapshotStatus("Failed");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SnapshotStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SnapshotStatus FindValue(string value)
{
return FindValue<SnapshotStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SnapshotStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SnapshotType.
/// </summary>
public class SnapshotType : ConstantClass
{
/// <summary>
/// Constant Auto for SnapshotType
/// </summary>
public static readonly SnapshotType Auto = new SnapshotType("Auto");
/// <summary>
/// Constant Manual for SnapshotType
/// </summary>
public static readonly SnapshotType Manual = new SnapshotType("Manual");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SnapshotType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SnapshotType FindValue(string value)
{
return FindValue<SnapshotType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SnapshotType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TopicStatus.
/// </summary>
public class TopicStatus : ConstantClass
{
/// <summary>
/// Constant Deleted for TopicStatus
/// </summary>
public static readonly TopicStatus Deleted = new TopicStatus("Deleted");
/// <summary>
/// Constant Failed for TopicStatus
/// </summary>
public static readonly TopicStatus Failed = new TopicStatus("Failed");
/// <summary>
/// Constant Registered for TopicStatus
/// </summary>
public static readonly TopicStatus Registered = new TopicStatus("Registered");
/// <summary>
/// Constant TopicNotFound for TopicStatus
/// </summary>
public static readonly TopicStatus TopicNotFound = new TopicStatus("Topic not found");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TopicStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TopicStatus FindValue(string value)
{
return FindValue<TopicStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TopicStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TrustDirection.
/// </summary>
public class TrustDirection : ConstantClass
{
/// <summary>
/// Constant OneWayIncoming for TrustDirection
/// </summary>
public static readonly TrustDirection OneWayIncoming = new TrustDirection("One-Way: Incoming");
/// <summary>
/// Constant OneWayOutgoing for TrustDirection
/// </summary>
public static readonly TrustDirection OneWayOutgoing = new TrustDirection("One-Way: Outgoing");
/// <summary>
/// Constant TwoWay for TrustDirection
/// </summary>
public static readonly TrustDirection TwoWay = new TrustDirection("Two-Way");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TrustDirection(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TrustDirection FindValue(string value)
{
return FindValue<TrustDirection>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TrustDirection(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TrustState.
/// </summary>
public class TrustState : ConstantClass
{
/// <summary>
/// Constant Created for TrustState
/// </summary>
public static readonly TrustState Created = new TrustState("Created");
/// <summary>
/// Constant Creating for TrustState
/// </summary>
public static readonly TrustState Creating = new TrustState("Creating");
/// <summary>
/// Constant Deleted for TrustState
/// </summary>
public static readonly TrustState Deleted = new TrustState("Deleted");
/// <summary>
/// Constant Deleting for TrustState
/// </summary>
public static readonly TrustState Deleting = new TrustState("Deleting");
/// <summary>
/// Constant Failed for TrustState
/// </summary>
public static readonly TrustState Failed = new TrustState("Failed");
/// <summary>
/// Constant Verified for TrustState
/// </summary>
public static readonly TrustState Verified = new TrustState("Verified");
/// <summary>
/// Constant VerifyFailed for TrustState
/// </summary>
public static readonly TrustState VerifyFailed = new TrustState("VerifyFailed");
/// <summary>
/// Constant Verifying for TrustState
/// </summary>
public static readonly TrustState Verifying = new TrustState("Verifying");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TrustState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TrustState FindValue(string value)
{
return FindValue<TrustState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TrustState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TrustType.
/// </summary>
public class TrustType : ConstantClass
{
/// <summary>
/// Constant Forest for TrustType
/// </summary>
public static readonly TrustType Forest = new TrustType("Forest");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TrustType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TrustType FindValue(string value)
{
return FindValue<TrustType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TrustType(string value)
{
return FindValue(value);
}
}
} | 36.985915 | 117 | 0.602475 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | sdk/src/Services/DirectoryService/Generated/ServiceEnumerations.cs | 26,260 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PetSite.Models;
using Amazon.XRay.Recorder.Handlers.AwsSdk;
using System.Net.Http;
using Amazon.XRay.Recorder.Handlers.System.Net;
using Amazon.XRay.Recorder.Core;
using System.Text.Json;
using Amazon;
using PetSite.ViewModels;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Configuration;
using Prometheus;
namespace PetSite.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private static HttpClient _httpClient;
private static Variety _variety = new Variety();
private IConfiguration _configuration;
//Prometheus metric to count the number of searches performed
private static readonly Counter PetSearchCount =
Metrics.CreateCounter("petsite_petsearches_total", "Count the number of searches performed");
//Prometheus metric to count the number of puppy searches performed
private static readonly Counter PuppySearchCount =
Metrics.CreateCounter("petsite_pet_puppy_searches_total", "Count the number of puppy searches performed");
//Prometheus metric to count the number of kitten searches performed
private static readonly Counter KittenSearchCount =
Metrics.CreateCounter("petsite_pet_kitten_searches_total", "Count the number of kitten searches performed");
//Prometheus metric to count the number of bunny searches performed
private static readonly Counter BunnySearchCount =
Metrics.CreateCounter("petsite_pet_bunny_searches_total", "Count the number of bunny searches performed");
private static readonly Gauge PetsWaitingForAdoption = Metrics
.CreateGauge("petsite_pets_waiting_for_adoption", "Number of pets waiting for adoption.");
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
AWSXRayRecorder.RegisterLogger(LoggingOptions.Console);
_configuration = configuration;
AWSSDKHandler.RegisterXRayForAllServices();
_httpClient = new HttpClient(new HttpClientXRayTracingHandler(new HttpClientHandler()));
_logger = logger;
_variety.PetTypes = new List<SelectListItem>()
{
new SelectListItem() {Value = "all", Text = "All"},
new SelectListItem() {Value = "puppy", Text = "Puppy"},
new SelectListItem() {Value = "kitten", Text = "Kitten"},
new SelectListItem() {Value = "bunny", Text = "Bunny"}
};
_variety.PetColors = new List<SelectListItem>()
{
new SelectListItem() {Value = "all", Text = "All"},
new SelectListItem() {Value = "brown", Text = "Brown"},
new SelectListItem() {Value = "black", Text = "Black"},
new SelectListItem() {Value = "white", Text = "White"}
};
}
private async Task<string> GetPetDetails(string pettype, string petcolor, string petid)
{
string searchUri = string.Empty;
if (!String.IsNullOrEmpty(pettype) && pettype != "all") searchUri = $"pettype={pettype}";
if (!String.IsNullOrEmpty(petcolor) && petcolor != "all") searchUri = $"&{searchUri}&petcolor={petcolor}";
if (!String.IsNullOrEmpty(petid) && petid != "all") searchUri = $"&{searchUri}&petid={petid}";
switch (pettype)
{
case "puppy":
PuppySearchCount.Inc();
PetSearchCount.Inc();
break;
case "kitten":
KittenSearchCount.Inc();
PetSearchCount.Inc();
break;
case "bunny":
BunnySearchCount.Inc();
PetSearchCount.Inc();
break;
}
//string searchapiurl = _configuration["searchapiurl"];
string searchapiurl = SystemsManagerConfigurationProviderWithReloadExtensions.GetConfiguration(_configuration,"searchapiurl");
return await _httpClient.GetStringAsync($"{searchapiurl}{searchUri}");
}
[HttpGet("housekeeping")]
public async Task<IActionResult> HouseKeeping()
{
Console.WriteLine(
$"[{AWSXRayRecorder.Instance.TraceContext.GetEntity().RootSegment.TraceId}][{AWSXRayRecorder.Instance.GetEntity().TraceId}] - In Housekeeping, trying to reset the app.");
var result = await GetPetDetails(null, null, null);
var Pets = JsonSerializer.Deserialize<List<Pet>>(result);
var searchParams = new SearchParams();
//string updateadoptionstatusurl = _configuration["updateadoptionstatusurl"];
string updateadoptionstatusurl = SystemsManagerConfigurationProviderWithReloadExtensions.GetConfiguration(_configuration,"updateadoptionstatusurl");
foreach (var pet in Pets.Where(item => item.availability == "no"))
{
searchParams.pettype = pet.pettype;
searchParams.petid = pet.petid;
searchParams.petavailability = "yes";
StringContent putData = new StringContent(JsonSerializer.Serialize(searchParams));
await _httpClient.PutAsync(updateadoptionstatusurl, putData);
}
//string cleanupadoptionsurl = _configuration["cleanupadoptionsurl"];
string cleanupadoptionsurl = SystemsManagerConfigurationProviderWithReloadExtensions.GetConfiguration(_configuration,"cleanupadoptionsurl");
await _httpClient.PostAsync(cleanupadoptionsurl, null);
return View();
}
[HttpGet]
public async Task<IActionResult> Index(string selectedPetType, string selectedPetColor, string petid)
{
Console.WriteLine(
$"AWS_XRAY_DAEMON_ADDRESS:- {Environment.GetEnvironmentVariable("AWS_XRAY_DAEMON_ADDRESS")}");
AWSXRayRecorder.Instance.BeginSubsegment("Calling Search API");
AWSXRayRecorder.Instance.AddMetadata("PetType", selectedPetType);
AWSXRayRecorder.Instance.AddMetadata("PetId", petid);
AWSXRayRecorder.Instance.AddMetadata("PetColor", selectedPetColor);
Console.WriteLine(
$"[{AWSXRayRecorder.Instance.TraceContext.GetEntity().RootSegment.TraceId}]- Search string - PetType:{selectedPetType} PetColor:{selectedPetColor} PetId:{petid}");
// | SegmentId: [{AWSXRayRecorder.Instance.TraceContext.GetEntity().RootSegment.Id}
string result;
try
{
result = await GetPetDetails(selectedPetType, selectedPetColor, petid);
}
catch (Exception e)
{
AWSXRayRecorder.Instance.AddException(e);
throw e;
}
finally
{
AWSXRayRecorder.Instance.EndSubsegment();
}
var Pets = JsonSerializer.Deserialize<List<Pet>>(result);
var PetDetails = new PetDetails()
{
Pets = Pets,
Varieties = new Variety
{
PetTypes = _variety.PetTypes,
PetColors = _variety.PetColors,
SelectedPetColor = selectedPetColor,
SelectedPetType = selectedPetType
}
};
AWSXRayRecorder.Instance.AddMetadata("results", System.Text.Json.JsonSerializer.Serialize(PetDetails));
Console.WriteLine(
$" TraceId: [{AWSXRayRecorder.Instance.GetEntity().TraceId}] - {JsonSerializer.Serialize(PetDetails)}");
// Sets the metric value to the number of pets available for adoption at the moment
PetsWaitingForAdoption.Set(Pets.Where(pet => pet.availability == "yes").Count());
return View(PetDetails);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
}
}
} | 44.346734 | 187 | 0.607365 | [
"MIT-0"
] | Training-and-Development-SRE/one-observability-demo | PetAdoptions/petsite/petsite/Controllers/HomeController.cs | 8,827 | C# |
using System.Collections.Generic;
using OpenItems.Data;
namespace GSA.OpenItems.Web
{
using System;
using System.Data;
using System.Collections;
using System.Web;
using Data;
/// <summary>
/// Summary description for PageBase
/// </summary>
public class PageBase: System.Web.UI.Page
{
virtual protected void PageLoadEvent(object sender, System.EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
var s = "";
if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "alert2"))
{
s = Page.Request.Url.AbsoluteUri;
s = s.Substring(0, s.IndexOf("OpenItems") + 9) + "/include/alert2.js";
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert2",
"<script language='javascript' src='" + s + "'></script>");
}
if (Page.User.Identity.Name.Trim().Length > 0)
ClientScript.RegisterStartupScript(Page.GetType(), "ST",
"<script language='javascript'>_ST(" + (HttpContext.Current.Session.Timeout * 60000).ToString() + ");</script>");
if (!IsPostBack)
{
ClearErrors();
}
PageLoadEvent(sender, e);
}
#region ErrorHandling
public ArrayList Errors = new ArrayList();
public void AddError(Exception ex)
{
Errors.Add(ex);
}
public int ErrorCount
{
get
{
return Errors.Count;
}
}
public void ClearErrors()
{
Errors.Clear();
}
public string GetErrors()
{
var sError = "";
if (Errors.Count > 0)
{
foreach (Exception ex in Errors)
{
if (sError.Length > 0)
{
sError = sError + "<br/>" + ex.Message;
}
else
sError = ex.Message;
}
sError += "<br/><br/>";
}
return sError;
}
protected override void OnError(EventArgs e)
{
if (HttpContext.Current.Session == null)
{
Response.Redirect("Default.aspx");
}
else
{
if (!HttpContext.Current.Session.IsNewSession)
{
if (HttpContext.Current.Session.Count <= 0)
{
Response.Redirect("Default.aspx");
}
}
}
base.OnError(e);
}
#endregion ErrorHandling
//****************************************
//*** Key Constants ******************
//****************************************
private const string KEY_APP_DATA_SOURCE_TYPES = "App:DataSourceTypes:";
private const string KEY_APP_OPEN_ITEMS_TYPES = "App:OpenItemTypes:";
private const string KEY_APP_ORGANIZATION_LIST = "App:OrgList:";
private const string KEY_APP_DEFAULT_JUSTIFICATIONS = "App:DefaultJustifications:";
private const string KEY_APP_VALIDATION_VALUES = "App:ValidValues:";
private const string KEY_APP_ACTIVE_CODE_LIST = "App:ActiveCodeList:";
private const string KEY_APP_FULL_CODE_LIST = "App:FullCodeList:";
private const string KEY_APP_CONTACT_ROLE_LIST = "App:ContactRoles:";
private const string KEY_APP_ACCRUAL_TYPES = "App:AccrualTypes:";
private const string KEY_APP_ACCRUAL_TYPE_ACTIONS = "App:AccrualActionTypes:";
private const string KEY_APP_REVIEWER_REASON_CODES = "App:ReviewerReasonCodes:";
private const string INVALID_KEY_APP_REVIEWER_REASON_CODES = "App:InvalidReviewerReasonCodes:";
private const string KEY_SESSION_LOAD_FULL_INFO_LIST = "Session:LoadFullInfoList:";
private const string KEY_SESSION_LOAD_LIST = "Session:LoadList:";
private const string KEY_SESSION_DOC_TYPES = "Session:DocTypes:";
private const string KEY_SESSION_CURRENT_USER_ID = "Session:CurrentUserID:";
private const string KEY_SESSION_CURRENT_USER_NAME = "Session:UserName:";
private const string KEY_SESSION_CURRENT_USER_LOGIN_NAME = "Session:UserLogin:";
private const string KEY_SESSION_CURRENT_USER_ORG = "Session:UserOrg:";
private const string KEY_SESSION_CURRENT_USER_ROLE = "Session:UserRole:";
private const string KEY_SESSION_CURRENT_USER_DEFAULT_APP = "Session:UserApp:";
private const string KEY_SESSION_ITEMS_VIEW = "Session:ItemsDataView:";
private const string KEY_SESSION_ITEMS_SORT_EXP = "Session:ItemsSortExp:";
private const string KEY_SESSION_ITEMS_PAGE = "Session:ItemsPage:";
private const string KEY_SESSION_ITEMS_FILTER = "Session:ItemsFilter:";
private const string KEY_SESSION_ITEMS_SELECTED = "Session:ItemsSelectedValues:";
private const string KEY_SESSION_ITEMS_SOURCE_URL = "Session:ItemsSourceURL:";
private const string KEY_SESSION_ITEMS_VIEW_MODE = "Session:ItemsViewMode:";
private const string KEY_SESSION_LOAD_ID = "Session:LoadID:";
private const string KEY_SESSION_OI_REVIEWER_ID = "Session:ItemReviewerID:";
private const string KEY_SESSION_OI_ID = "Session:OItemID:";
private const string KEY_SESSION_ORG_CODE = "Session:OrgCode:";
private const string KEY_SESSION_DOC_NUM = "Session:DocNumber:";
private const string KEY_SESSION_LINE_NUM = "Session:LineNum:";
private const string KEY_SESSION_ITEM_LINES = "Session:ItemLines:";
private const string KEY_SESSION_FUNDS_TABLE = "Session:FundsTable:";
private const string KEY_SESSION_FUNDS_CRITERIA = "Session:FundsCriteria:";
private const string KEY_SESSION_FUNDS_SEARCH_CRITERIA = "Session:FundsSearchCrt:";
private const string KEY_SESSION_FUNDS_STATUS_CRITERIA = "Session:FundsStatusCrt:";
private const string KEY_SESSION_FUNDS_SUMMARY_REPORT_CRITERIA = "Session:FundsSumRepCrt:";
private const string KEY_STATE_LOADS_LIST = "State:LoadList:";
private const string KEY_STATE_ITEMS_LINES_SORT = "State:LinesSort:";
protected readonly IDataLayer Dal = new DataLayer(new zoneFinder(), new ULOContext());
//****************************************
//*** Application Storage ************
//****************************************
public List<spGetDataSourceTypes_Result> DataSourceTypes
{
get
{
if (HttpContext.Current.Application[KEY_APP_DATA_SOURCE_TYPES] != null)
return (List<spGetDataSourceTypes_Result>)HttpContext.Current.Application[KEY_APP_DATA_SOURCE_TYPES];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_DATA_SOURCE_TYPES] = value;
}
}
public DataTable BA53AccrualTypes
{
get
{
if (HttpContext.Current.Application[KEY_APP_ACCRUAL_TYPES] != null)
return (DataTable)HttpContext.Current.Application[KEY_APP_ACCRUAL_TYPES];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_ACCRUAL_TYPES] = value;
}
}
public DataTable BA53AccrualTypeActions
{
get
{
if (HttpContext.Current.Application[KEY_APP_ACCRUAL_TYPE_ACTIONS] != null)
return (DataTable)HttpContext.Current.Application[KEY_APP_ACCRUAL_TYPE_ACTIONS];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_ACCRUAL_TYPE_ACTIONS] = value;
}
}
public DataTable ReviewerReasonCodes
{
get
{
if (HttpContext.Current.Application[KEY_APP_REVIEWER_REASON_CODES] != null)
return (DataTable)HttpContext.Current.Application[KEY_APP_REVIEWER_REASON_CODES];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_REVIEWER_REASON_CODES] = value;
}
}
public DataTable InvalidReviewerReasonCodes
{
get
{
if (HttpContext.Current.Application[INVALID_KEY_APP_REVIEWER_REASON_CODES] != null)
return (DataTable)HttpContext.Current.Application[INVALID_KEY_APP_REVIEWER_REASON_CODES];
else
return null;
}
set
{
HttpContext.Current.Application[INVALID_KEY_APP_REVIEWER_REASON_CODES] = value;
}
}
public List<spGetOpenItemsTypes_Result> OpenItemsTypes
{
get
{
if (HttpContext.Current.Application[KEY_APP_OPEN_ITEMS_TYPES] != null)
return (List<spGetOpenItemsTypes_Result>)HttpContext.Current.Application[KEY_APP_OPEN_ITEMS_TYPES];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_OPEN_ITEMS_TYPES] = value;
}
}
public DataSet OrganizationsList
{
get
{
if (HttpContext.Current.Application[KEY_APP_ORGANIZATION_LIST] != null)
return (DataSet)HttpContext.Current.Application[KEY_APP_ORGANIZATION_LIST];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_ORGANIZATION_LIST] = value;
}
}
public DataTable DefaultJustificationValues
{
get
{
if (HttpContext.Current.Application[KEY_APP_DEFAULT_JUSTIFICATIONS] != null)
return (DataTable)HttpContext.Current.Application[KEY_APP_DEFAULT_JUSTIFICATIONS];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_DEFAULT_JUSTIFICATIONS] = value;
}
}
public DataView ValidationValues
{
get
{
if (HttpContext.Current.Application[KEY_APP_VALIDATION_VALUES] != null)
return (DataView)HttpContext.Current.Application[KEY_APP_VALIDATION_VALUES];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_VALIDATION_VALUES] = value;
}
}
public DataTable ActiveCodesList
{
get
{
if (HttpContext.Current.Application[KEY_APP_ACTIVE_CODE_LIST] != null)
return (DataTable)HttpContext.Current.Application[KEY_APP_ACTIVE_CODE_LIST];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_ACTIVE_CODE_LIST] = value;
}
}
public DataTable ActiveAndExpiredCodesList
{
get
{
if (HttpContext.Current.Application[KEY_APP_FULL_CODE_LIST] != null)
return (DataTable)HttpContext.Current.Application[KEY_APP_FULL_CODE_LIST];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_FULL_CODE_LIST] = value;
}
}
public DataView ContactRolesList
{
get
{
if (HttpContext.Current.Application[KEY_APP_CONTACT_ROLE_LIST] != null)
return (DataView)HttpContext.Current.Application[KEY_APP_CONTACT_ROLE_LIST];
else
return null;
}
set
{
HttpContext.Current.Application[KEY_APP_CONTACT_ROLE_LIST] = value;
}
}
//****************************************
//*** Session Storage ****************
//****************************************
/*
public DataTable FundsReviewTable
{
get
{
if (Session[KEY_SESSION_FUNDS_TABLE] != null)
return (DataTable)Session[KEY_SESSION_FUNDS_TABLE];
else
return null;
}
set
{
Session[KEY_SESSION_FUNDS_TABLE] = value;
}
}
*/
public DataTable LoadListFullInfo
{
get
{
if (Session[KEY_SESSION_LOAD_FULL_INFO_LIST] != null)
return (DataTable)Session[KEY_SESSION_LOAD_FULL_INFO_LIST];
else
return null;
}
set
{
Session[KEY_SESSION_LOAD_FULL_INFO_LIST] = value;
}
}
public DataSet LoadList
{
get
{
if (Session[KEY_SESSION_LOAD_LIST] != null)
return (DataSet)Session[KEY_SESSION_LOAD_LIST];
else
return null;
}
set
{
Session[KEY_SESSION_LOAD_LIST] = value;
}
}
public DataSet DocumentTypes
{
get
{
if (Session[KEY_SESSION_DOC_TYPES] != null)
return (DataSet)Session[KEY_SESSION_DOC_TYPES];
else
return null;
}
set
{
Session[KEY_SESSION_DOC_TYPES] = value;
}
}
public int CurrentUserID
{
get
{
if (Session[KEY_SESSION_CURRENT_USER_ID] != null)
return (int)Session[KEY_SESSION_CURRENT_USER_ID];
else
return 0;
}
set
{
Session[KEY_SESSION_CURRENT_USER_ID] = value;
}
}
public int CurrentUserDefaultApp
{
get
{
return Session[KEY_SESSION_CURRENT_USER_DEFAULT_APP] != null ? (int)Session[KEY_SESSION_CURRENT_USER_DEFAULT_APP] : 0;
}
set
{
Session[KEY_SESSION_CURRENT_USER_DEFAULT_APP] = value;
}
}
public string CurrentUserRoles
{
get
{
if (Session[KEY_SESSION_CURRENT_USER_ROLE] != null)
return (string)Session[KEY_SESSION_CURRENT_USER_ROLE];
else
return "";
}
set
{
Session[KEY_SESSION_CURRENT_USER_ROLE] = value;
}
}
public string CurrentUserName
{
get
{
if (Session[KEY_SESSION_CURRENT_USER_NAME] != null)
return (string)Session[KEY_SESSION_CURRENT_USER_NAME];
else
return "";
}
set
{
Session[KEY_SESSION_CURRENT_USER_NAME] = value;
}
}
public string CurrentUserLogin
{
get
{
if (Session[KEY_SESSION_CURRENT_USER_LOGIN_NAME] != null)
return (string)Session[KEY_SESSION_CURRENT_USER_LOGIN_NAME];
else
return "";
}
set
{
Session[KEY_SESSION_CURRENT_USER_LOGIN_NAME] = value;
}
}
public string CurrentUserOrganization
{
get
{
if (Session[KEY_SESSION_CURRENT_USER_ORG] != null)
return (string)Session[KEY_SESSION_CURRENT_USER_ORG];
else
return "";
}
set
{
Session[KEY_SESSION_CURRENT_USER_ORG] = value;
}
}
public DataView ItemsDataView
{
get
{
if (Session[KEY_SESSION_ITEMS_VIEW] != null)
return (DataView)Session[KEY_SESSION_ITEMS_VIEW];
else
return null;
}
set
{
Session[KEY_SESSION_ITEMS_VIEW] = value;
}
}
public string ItemsSortExpression
{
get
{
if (Session[KEY_SESSION_ITEMS_SORT_EXP] != null)
return (string)Session[KEY_SESSION_ITEMS_SORT_EXP];
else
return "DocNumber";
return "DocNumber";
}
set
{
Session[KEY_SESSION_ITEMS_SORT_EXP] = value;
}
}
public int ItemsPageNumber
{
get
{
if (Session[KEY_SESSION_ITEMS_PAGE] != null)
return (int)Session[KEY_SESSION_ITEMS_PAGE];
else
return 0;
}
set
{
Session[KEY_SESSION_ITEMS_PAGE] = value;
}
}
public string ItemsOrgFilter
{
get
{
if (Session[KEY_SESSION_ITEMS_FILTER] != null)
return (string)Session[KEY_SESSION_ITEMS_FILTER];
else
return "0";
}
set
{
Session[KEY_SESSION_ITEMS_FILTER] = value;
}
}
public Hashtable ItemsViewSelectedValues
{
get
{
return (Hashtable)Session[KEY_SESSION_ITEMS_SELECTED];
}
set
{
Session[KEY_SESSION_ITEMS_SELECTED] = value;
}
}
public Hashtable FundsReviewSelectedValues
{
get
{
return (Hashtable)Session[KEY_SESSION_FUNDS_CRITERIA];
}
set
{
Session[KEY_SESSION_FUNDS_CRITERIA] = value;
}
}
public Hashtable FundsSearchSelectedValues
{
get
{
return (Hashtable)Session[KEY_SESSION_FUNDS_SEARCH_CRITERIA];
}
set
{
Session[KEY_SESSION_FUNDS_SEARCH_CRITERIA] = value;
}
}
public Hashtable FundsStatusSelectedValues
{
get
{
return (Hashtable)Session[KEY_SESSION_FUNDS_STATUS_CRITERIA];
}
set
{
Session[KEY_SESSION_FUNDS_STATUS_CRITERIA] = value;
}
}
public Hashtable FundsSummaryReportSelectedValues
{
get
{
return (Hashtable)Session[KEY_SESSION_FUNDS_SUMMARY_REPORT_CRITERIA];
}
set
{
Session[KEY_SESSION_FUNDS_SUMMARY_REPORT_CRITERIA] = value;
}
}
public int LoadID
{
get
{
if (Session[KEY_SESSION_LOAD_ID] != null)
return (int)Session[KEY_SESSION_LOAD_ID];
else
return 0;
}
set
{
Session[KEY_SESSION_LOAD_ID] = value;
}
}
public int CurrentItemReviewerID
{
get
{
if (Session[KEY_SESSION_OI_REVIEWER_ID] != null)
return (int)Session[KEY_SESSION_OI_REVIEWER_ID];
else
return 0;
}
set
{
Session[KEY_SESSION_OI_REVIEWER_ID] = value;
}
}
public int OItemID
{
get
{
if (Session[KEY_SESSION_OI_ID] != null)
return (int)Session[KEY_SESSION_OI_ID];
else
return 0;
}
set
{
Session[KEY_SESSION_OI_ID] = value;
}
}
public int LineNum
{
get
{
if (Session[KEY_SESSION_LINE_NUM] != null)
return (int)Session[KEY_SESSION_LINE_NUM];
else
return 0;
}
set
{
Session[KEY_SESSION_LINE_NUM] = value;
}
}
public string OrgCode
{
get
{
if (Session[KEY_SESSION_ORG_CODE] != null)
return (string)Session[KEY_SESSION_ORG_CODE];
else
return "";
}
set
{
Session[KEY_SESSION_ORG_CODE] = value;
}
}
public string DocNumber
{
get
{
if (Session[KEY_SESSION_DOC_NUM] != null)
return (string)Session[KEY_SESSION_DOC_NUM];
else
return "";
}
set
{
Session[KEY_SESSION_DOC_NUM] = value;
}
}
public DataView ItemLinesDataView
{
get
{
if (Session[KEY_SESSION_ITEM_LINES] != null)
return (DataView)Session[KEY_SESSION_ITEM_LINES];
else
return null;
}
set
{
Session[KEY_SESSION_ITEM_LINES] = value;
}
}
public string ItemsViewSourcePath
{
get
{
if (Session[KEY_SESSION_ITEMS_SOURCE_URL] == null)
//return default page:
return "ReviewOpenItems.aspx";
else
return (string)Session[KEY_SESSION_ITEMS_SOURCE_URL];
}
set
{
Session[KEY_SESSION_ITEMS_SOURCE_URL] = value;
}
}
public string ItemsViewMode
{
get
{
if (Session[KEY_SESSION_ITEMS_VIEW_MODE] != null)
return (string)Session[KEY_SESSION_ITEMS_VIEW_MODE];
else
return "load";
}
set
{
Session[KEY_SESSION_ITEMS_VIEW_MODE] = value;
}
}
//public bool FundStatusReportRefresh
//{
// get
// {
// if (Session[KEY_SESSION_FUNDS_STATUS_REFRESH] != null && Session[KEY_SESSION_FUNDS_STATUS_REFRESH] == 1)
// return true;
// else
// return false;
// }
// set
// {
// Session[KEY_SESSION_FUNDS_STATUS_REFRESH] = (value) ? 1 : 0;
// }
//}
//****************************************
//*** View State Storage *************
//****************************************
public DataSet LoadsList
{
get
{
if (ViewState[KEY_STATE_LOADS_LIST] != null)
return (DataSet)ViewState[KEY_STATE_LOADS_LIST];
else
return null;
}
set
{
ViewState[KEY_STATE_LOADS_LIST] = value;
}
}
public string ItemLinesSortExp
{
get
{
if (ViewState[KEY_STATE_ITEMS_LINES_SORT] != null)
return (string)ViewState[KEY_STATE_ITEMS_LINES_SORT];
else
return "ItemLNum";
}
set
{
ViewState[KEY_STATE_ITEMS_LINES_SORT] = value;
}
}
}
} | 30.592593 | 134 | 0.4864 | [
"CC0-1.0"
] | gaybro8777/FM-ULO | Archive/OpenItems/PageBase.cs | 24,780 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Primjer_6._1
{
class Program
{
static void Main(string[] args)
{
//Deklaracija niza od 3 elementa
int[] niz = new int[3];
//inicijalizacija niza
niz[0] = 55;
niz[2] = 22;
niz[1] = 77;
for (int i = 0; i < niz.Length; i++)
{
Console.WriteLine("{0}. element niza: {1}", i, niz[i]);
}
Console.ReadKey();
}
}
}
| 19.09375 | 71 | 0.481178 | [
"MIT"
] | dklaic3006/AlgebraCSharp2019-1 | ConsoleApp1/Primjer 6.1/Program.cs | 613 | C# |
using Volo.Abp.Domain.Entities;
namespace Volo.Abp.Ddd.Domain.Extensions
{
public interface IProxiedEntity
{
IProxiedEntity Entity { get; set; }
}
} | 18.888889 | 43 | 0.682353 | [
"MIT"
] | BrianCodeman/Volo.Abp.Ddd.Domain.Extensions | IProxiedEntity.cs | 172 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Client.Web.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;
public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
} | 19.736842 | 57 | 0.616 | [
"MIT"
] | geraldmaale/AspnetMicroservices | src/Clients/Client.Web/Pages/Privacy.cshtml.cs | 377 | C# |
using UnityEngine;
using UnityEngine.UI;
using MainGame.UserInterface;
namespace MainGame
{
public class GameRestarter : MonoBehaviour
{
[SerializeField]
private GameStarter _starter;
[SerializeField]
private EndGamePanel _endGamePanel;
[SerializeField]
private StorageCollectionCounter _counter;
[SerializeField]
private Button _restartButton;
private void OnEnable()
{
_restartButton.onClick.AddListener(Restart);
}
private void OnDisable()
{
_restartButton.onClick.RemoveListener(Restart);
}
public void Restart()
{
_endGamePanel.Hide();
_counter.ResetToDefault();
_starter.StartGame();
}
}
} | 19.853659 | 59 | 0.59828 | [
"Apache-2.0"
] | Ellamanate/FirstPerson | Assets/Scripts/Game/GameRestarter.cs | 816 | 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("PPWCode.Util.SharePoint.UnitTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PPWCode.Util.SharePoint.UnitTest")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. 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("410c2944-4166-4b49-ba71-eb249398df15")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.805556 | 85 | 0.733426 | [
"Apache-2.0"
] | jandockx/ppwcode | dotnet/Util/SharePoint/I/2.n/2.0.1/src/PPWCode.Util.SharePoint.UnitTest/Properties/AssemblyInfo.cs | 1,436 | C# |
// Copyright (C) 2018 Mohammad Javad HoseinPour. All rights reserved.
// Licensed under the Private License. See LICENSE in the project root for license information.
// Author: Mohammad Javad HoseinPour <mjavadhpour@gmail.com>
namespace ShopPromotion.Domain.Infrastructure.Models.Resource
{
public sealed class MinimumAppUserImageResource : AbstractMinimumImageResource
{
}
} | 38.9 | 95 | 0.789203 | [
"MIT"
] | mjavadhpour/shop-promotion | src/ShopPromotion.Domain/Infrastructure/Models/Resource/MinimumAppUserImageResource.cs | 391 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.