content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
/*
Copyright 2006 - 2010 Intel 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.Threading;
using System.Collections;
using OpenSource.UPnP;
namespace UPnPRelay
{
/// <summary>
/// Summary description for UPnPRelayDevice.
/// </summary>
public class UPnPRelayDevice
{
public delegate void InvokeResponseHandler(int ErrorCode, string ErrorString, byte[] Args, int Handle);
public InvokeResponseHandler ILCB;
private long ActionCounter = 0;
private long EventCounter = 0;
private int InitCounter = 0;
public delegate void ActionCounterHandler(UPnPRelayDevice sender, long ActionCounter);
public delegate void EventCounterHandler(UPnPRelayDevice sender, long EventCounter);
public event ActionCounterHandler OnAction;
public event EventCounterHandler OnEvent;
public string DV = "";
public Gatekeeper Creator = null;
private UPnPDevice ProxyDevice;
public readonly CpGateKeeper CP;
private Hashtable UDNTable = new Hashtable();
private Hashtable ReverseUDNTable = new Hashtable();
private Hashtable PendingActionTable = new Hashtable();
~UPnPRelayDevice()
{
OpenSource.Utilities.InstanceTracker.Remove(this);
if (ProxyDevice != null)
{
ProxyDevice.StopDevice();
ProxyDevice = null;
}
}
public UPnPRelayDevice(UPnPDevice device, CpGateKeeper _CP)
{
OpenSource.Utilities.InstanceTracker.Add(this);
ILCB = new InvokeResponseHandler(InvokeResponseSink);
CP = _CP;
ProxyDevice = UPnPDevice.CreateRootDevice(750, double.Parse(device.Version), "");
ProxyDevice.UniqueDeviceName = Guid.NewGuid().ToString();
ProxyDevice.HasPresentation = false;
ProxyDevice.FriendlyName = "*" + device.FriendlyName;
ProxyDevice.Manufacturer = device.Manufacturer;
ProxyDevice.ManufacturerURL = device.ManufacturerURL;
ProxyDevice.ModelName = device.ModelName;
ProxyDevice.DeviceURN = device.DeviceURN;
foreach (UPnPService S in device.Services)
{
UPnPService S2 = (UPnPService)S.Clone();
foreach (UPnPAction A in S2.Actions)
{
A.ParentService = S2;
A.SpecialCase += new UPnPAction.SpecialInvokeCase(InvokeSink);
}
UPnPDebugObject dbg = new UPnPDebugObject(S2);
dbg.SetField("SCPDURL", "_" + S2.ServiceID + "_scpd.xml");
dbg.SetProperty("ControlURL", "_" + S2.ServiceID + "_control");
dbg.SetProperty("EventURL", "_" + S2.ServiceID + "_event");
ProxyDevice.AddService(S2);
}
UDNTable[device.UniqueDeviceName] = ProxyDevice;
ReverseUDNTable[ProxyDevice.UniqueDeviceName] = device.UniqueDeviceName;
foreach (UPnPDevice _ed in device.EmbeddedDevices)
{
ProcessDevice(_ed);
}
}
public void InitStateTableThenStart()
{
InitCounter = CountServices(ProxyDevice);
InitStateTable(ProxyDevice);
}
private int CountServices(UPnPDevice d)
{
int RetVal = 0;
RetVal += d.Services.Length;
foreach (UPnPDevice ed in d.EmbeddedDevices)
{
RetVal += CountServices(ed);
}
return (RetVal);
}
private void InitStateTable(UPnPDevice d)
{
foreach (UPnPService s in d.Services)
{
InitStateTable(d, s);
}
foreach (UPnPDevice ed in d.EmbeddedDevices)
{
InitStateTable(ed);
}
}
private void InitStateTable(UPnPDevice d, UPnPService s)
{
string _udn = (string)this.ReverseUDNTable[d.UniqueDeviceName];
CP.GetStateTable(_udn, s.ServiceID, s, new CpGateKeeper.Delegate_OnResult_GetStateTable(GetStateTableSink));
}
private void GetStateTableSink(CpGateKeeper sender, System.String DeviceUDN, System.String ServiceID, System.Byte[] Variables, UPnPInvokeException e, object _Tag)
{
UPnPService s = (UPnPService)_Tag;
UPnPArgument[] Vars = Gatekeeper.ParseArguments(Variables);
foreach (UPnPArgument var in Vars)
{
(new UPnPDebugObject(s)).SetProperty("ValidationMode", false);
s.SetStateVariable(var.Name, var.DataValue);
}
if (Interlocked.Decrement(ref InitCounter) == 0)
{
ProxyDevice.StartDevice();
}
if (Vars.Length > 0)
{
EventCounter += Vars.Length;
if (this.OnEvent != null) OnEvent(this, EventCounter);
}
}
private void ProcessDevice(UPnPDevice device)
{
UPnPDevice d = UPnPDevice.CreateEmbeddedDevice(double.Parse(device.Version), Guid.NewGuid().ToString());
d.FriendlyName = "*" + device.FriendlyName;
d.Manufacturer = device.Manufacturer;
d.ManufacturerURL = device.ManufacturerURL;
d.ModelDescription = device.ModelDescription;
d.ModelURL = device.ModelURL;
d.DeviceURN = device.DeviceURN;
UDNTable[device.UniqueDeviceName] = d;
ReverseUDNTable[d.UniqueDeviceName] = device.UniqueDeviceName;
foreach (UPnPService S in device.Services)
{
UPnPService S2 = (UPnPService)S.Clone();
foreach (UPnPAction A in S2.Actions)
{
A.ParentService = S2;
A.SpecialCase += new UPnPAction.SpecialInvokeCase(InvokeSink);
}
UPnPDebugObject dbg = new UPnPDebugObject(S2);
dbg.SetField("SCPDURL", "_" + S2.ServiceID + "_scpd.xml");
dbg.SetProperty("ControlURL", "_" + S2.ServiceID + "_control");
dbg.SetProperty("EventURL", "_" + S2.ServiceID + "_event");
d.AddService(S2);
}
((UPnPDevice)UDNTable[device.ParentDevice.UniqueDeviceName]).AddDevice(d);
foreach (UPnPDevice _ed in device.EmbeddedDevices)
{
ProcessDevice(_ed);
}
}
public void StartDevice()
{
ProxyDevice.StartDevice();
}
public void StopDevice()
{
ProxyDevice.StopDevice();
}
public string FriendlyName
{
get
{
return (ProxyDevice.FriendlyName);
}
}
public Uri Origin
{
get
{
UPnPDevice d = CP.GetUPnPService().ParentDevice;
while (d.ParentDevice != null)
d = d.ParentDevice;
return (d.BaseURL);
}
}
public string UDN
{
get
{
return ((string)ReverseUDNTable[ProxyDevice.UniqueDeviceName]);
}
}
public bool ContainsUDN(string UDN)
{
return (UDNTable.ContainsKey(UDN));
}
public void FireEvent(string UDN, string ID, string VarName, string VarValue)
{
++EventCounter;
UPnPDevice d = (UPnPDevice)UDNTable[UDN];
UPnPService s = d.GetService(ID);
(new UPnPDebugObject(s)).SetProperty("ValidationMode", false);
s.SetStateVariable(VarName, VarValue);
if (this.OnEvent != null) OnEvent(this, EventCounter);
}
private void InvokeResponseSink(int ErrorCode, string ErrorString, byte[] Args, int Handle)
{
try
{
UPnPAction A = (UPnPAction)this.PendingActionTable[Handle];
PendingActionTable.Remove(Handle);
if (ErrorCode == 0)
{
UPnPArgument[] OutArgs = Gatekeeper.ParseArguments(Args);
object RetObj = null;
if (A.HasReturnValue)
{
UPnPArgument RA = A.GetRetArg();
foreach (UPnPArgument OA in OutArgs)
{
if (OA.Name == RA.Name)
{
RetObj = OA.DataValue;
break;
}
}
}
A.ParentService.DelayedInvokeResponse(0, RetObj, OutArgs, null);
}
else
{
A.ParentService.DelayedInvokeResponse(0, null, null, new UPnPCustomException(ErrorCode, ErrorString));
}
}
catch (Exception) { }
}
private void InvokeSink(UPnPAction sender, UPnPArgument[] _Args, out object RetVal, out UPnPArgument[] _OutArgs)
{
string DeviceUDN = (string)ReverseUDNTable[sender.ParentService.ParentDevice.UniqueDeviceName];
string ServiceID = sender.ParentService.ServiceID;
byte[] InArgs = Gatekeeper.BuildArguments(_Args);
//byte[] OutArgs;
++ActionCounter;
if (this.OnAction != null) OnAction(this, ActionCounter);
int Handle = Creator.GetNewHandle();
Creator.InvokeLaterTable[Handle] = ILCB;
PendingActionTable[Handle] = sender;
CP.InvokeAsync(DV, DeviceUDN, ServiceID, sender.Name, InArgs, Handle);
UPnPArgument[] Args;
sender.ParentService.DelayInvokeRespose(0, out Args);
throw (new DelayedResponseException());
/*
CP.Sync_Invoke(DeviceUDN,ServiceID,sender.Name,
InArgs, out OutArgs);
UPnPArgument[] Outputs = Gatekeeper.ParseArguments(OutArgs);
ArrayList alist = new ArrayList();
RetVal = null;
foreach(UPnPArgument A in Outputs)
{
if(A.IsReturnValue)
{
RetVal = A.DataValue;
}
else
{
alist.Add(A);
}
}
_OutArgs = (UPnPArgument[])alist.ToArray(typeof(UPnPArgument));
*/
}
}
}
| 36.763578 | 171 | 0.536891 | [
"Apache-2.0"
] | okertanov/Developer-Tools-for-UPnP-Technologies | Tools/DeviceRelay/UPnPRelayDevice.cs | 11,507 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using SafeTrend.Data;
using SafeTrend.Data.SqlClient;
using IAM.GlobalDefs;
namespace IAMWebServer._admin._chartdata
{
public partial class flow : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!EnterpriseIdentify.Identify(this)) //Se houver falha na identificação da empresa finaliza a resposta
return;
if ((Page.Session["enterprise_data"] == null) || !(Page.Session["enterprise_data"] is EnterpriseData))
return;
String type = "";
if (!String.IsNullOrWhiteSpace((String)RouteData.Values["type"]))
type = (String)RouteData.Values["type"];
switch (type.ToLower())
{
case "context":
Retorno.Controls.Add(new LiteralControl(ContextFlow()));
break;
case "user":
Retorno.Controls.Add(new LiteralControl(UserFlow()));
break;
case "enterprise":
Retorno.Controls.Add(new LiteralControl(ContextFlow()));
break;
case "plugin":
Retorno.Controls.Add(new LiteralControl(Plugin()));
break;
}
}
public String Plugin()
{
String pluginId = "";
if (!String.IsNullOrWhiteSpace((String)RouteData.Values["id"]))
pluginId = (String)RouteData.Values["id"];
EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"];
FlowData flowData = new FlowData();
DataTable dtPlugins = null;
using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
dtPlugins = db.Select("select * from plugin where (enterprise_id = "+ ent.Id +" or enterprise_id = 0) and id = " + pluginId);
if (dtPlugins == null)
return "";
Node pNode = flowData.AddNode(dtPlugins.Rows[0]["name"].ToString(), 0, 1);
using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
{
switch (dtPlugins.Rows[0]["scheme"].ToString().ToLower())
{
case "connector":
DataTable dtResources = db.Select("select r.* from resource_plugin rp inner join resource r on r.id = rp.resource_id where rp.plugin_id = " + dtPlugins.Rows[0]["id"]);
if ((dtResources == null) && (dtResources.Rows.Count == 0))
{
Node resNode = flowData.AddNode("Nenhum recurso vinculado a este plugin", 1, 1, true);
flowData.AddConnection(pNode, resNode, "");
}
else
{
foreach (DataRow drRes in dtResources.Rows)
{
Node nResource = flowData.AddNode("Recurso: " + drRes["name"], 2, 1, true);
flowData.AddConnection(pNode, nResource, "");
}
}
break;
case "agent":
DataTable dtProxy = db.Select("select * from proxy_plugin pp inner join proxy p on pp.proxy_id = p.id where pp.plugin_id = " + dtPlugins.Rows[0]["id"]);
if ((dtProxy == null) && (dtProxy.Rows.Count == 0))
{
Node errProxyNode = flowData.AddNode("Nenhum proxy vinculado a este plugin", 1, 1, true);
flowData.AddConnection(pNode, errProxyNode, "");
}
else
{
foreach (DataRow drProxy in dtProxy.Rows)
{
Node nProxy = flowData.AddNode("Proxy: " + drProxy["name"], 2, 1, true);
flowData.AddConnection(pNode, nProxy, "");
}
}
break;
default:
Node errNode = flowData.AddNode("Tipo de plugin não reconhecido", 1, 1, true);
flowData.AddConnection(pNode, errNode, "");
break;
}
}
return flowData.ToJson();
}
public String UserFlow()
{
String userId = "";
if (!String.IsNullOrWhiteSpace((String)RouteData.Values["id"]))
userId = (String)RouteData.Values["id"];
EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"];
FlowData flowData = new FlowData();
using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
{
DataTable dtEntity = db.Select("select e.*, c.name context_name from entity e inner join context c on e.context_id = c.id where e.id = " + userId);
if (dtEntity == null)
return "";
Node eNode = flowData.AddNode(dtEntity.Rows[0]["full_name"].ToString(), 0, 1);
Node ctxNode = flowData.AddNode("Contexto: " + dtEntity.Rows[0]["context_name"].ToString(), 1, 1);
flowData.AddConnection(eNode, ctxNode, "");
Node entNode = flowData.AddNode("Entidade", 2, 1);
flowData.AddConnection(ctxNode, entNode, "");
DataTable dtIdentity = db.Select("select ROW_NUMBER() OVER (ORDER BY r.name, i.id) AS [row_number], i.id identity_id, r.name resource_name, p.name from [identity] i inner join resource_plugin rp on i.resource_plugin_id = rp.id inner join resource r on rp.resource_id = r.id inner join plugin p on rp.plugin_id = p.id where i.entity_id = " + userId);
foreach (DataRow drI in dtIdentity.Rows)
{
Node nIdentity = flowData.AddNode("Identidade " + drI["row_number"], 3, 1, true);
flowData.AddConnection(entNode, nIdentity, "");
Node nSubIdentity = flowData.AddNode(drI["resource_name"].ToString(), 4, 1);
flowData.AddConnection(nIdentity, nSubIdentity, "");
DataTable dtRole = db.Select("select r.name role_name from identity_role ir inner join role r on ir.role_id = r.id where ir.identity_id = " + drI["identity_id"] + " order by r.name");
foreach (DataRow drRole in dtRole.Rows)
{
Node nRole = flowData.AddNode("Perfil", 5, 1, true);
flowData.AddConnection(nSubIdentity, nRole, "");
Node nRoleName = flowData.AddNode(drRole["role_name"].ToString(), 6, 1);
flowData.AddConnection(nRole, nRoleName, "");
}
}
Node systemNode = flowData.AddNode("Sistema", 1, 1);
flowData.AddConnection(eNode, systemNode, "");
Node nSysRole = flowData.AddNode("Perfis de sistema", 2, 1);
flowData.AddConnection(systemNode, nSysRole, "");
DataTable dtSysRole = db.Select("select r.* from sys_entity_role er inner join sys_role r on er.role_id = r.id where er.entity_id = " + userId);
if ((dtSysRole == null) || (dtSysRole.Rows.Count == 0))
{
Node nRoleName = flowData.AddNode("Nenhum perfil", 3, 1);
flowData.AddConnection(nSysRole, nRoleName, "");
}
else
{
foreach (DataRow drRole in dtSysRole.Rows)
{
Node nRoleName = flowData.AddNode(drRole["name"].ToString(), 3, 1);
flowData.AddConnection(nSysRole, nRoleName, "");
if ((Boolean)drRole["sa"])
{
nRoleName.name += "\n(Administrador)";
}
else
{
DataTable dtSysEnt = db.Select("select * from enterprise e where e.id = " + drRole["enterprise_id"]);
foreach (DataRow drEnt in dtSysEnt.Rows)
{
Node nRoleEntName = flowData.AddNode(drEnt["name"].ToString(), 4, 1);
flowData.AddConnection(nRoleName, nRoleEntName, "");
if ((Boolean)drRole["ea"])
nRoleEntName.name += "\n(Administrador)";
}
}
}
}
}
return flowData.ToJson();
}
public String ContextFlow()
{
String contextid = "";
if (!String.IsNullOrWhiteSpace((String)RouteData.Values["id"]))
contextid = (String)RouteData.Values["id"];
EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"];
FlowData flowData = new FlowData();
Node eNode = flowData.AddNode(ent.Name, 0, 1);
using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
{
DataTable dtCtx = db.Select("select * from context where enterprise_id = " + ent.Id + (contextid != "" ? " and id = " + contextid : ""));
if (dtCtx == null)
return "";
foreach (DataRow dr in dtCtx.Rows)
{
Int64 contextID = (Int64)dr["id"];
String cName = "Contexto: " + dr["name"];
Node cNode = flowData.AddNode(cName, 1, 1);
flowData.AddConnection(eNode, cNode, "");
Node roleNode = null;
/*
DataTable dtRoles1 = DB.Select("select * from [role] e where e.context_id = " + contextID);
if (dtRoles1 != null)
{
roleNode = flowData.AddNode("Perfis", 6, dtRoles1.Rows.Count);
flowData.AddConnection(cNode, roleNode, "");
foreach (DataRow drR in dtRoles1.Rows)
{
Int64 irId = (Int64)drR["id"];
Node roleNameNode = flowData.AddNode("Perfil: " + drR["name"].ToString(), 7, 1);
flowData.AddConnection(roleNode, roleNameNode, "");
}
}*/
Node userNode = flowData.AddNode("Usuários", 3, 1, true);
flowData.AddConnection(cNode, userNode, "");
DataTable dtEntity = db.Select("select count(*) qty from [entity] e where e.context_id = " + contextID);
if ((dtEntity == null) || (dtEntity.Rows.Count == 0) || ((Int32)dtEntity.Rows[0]["qty"] == 0))
{
Node entNode = flowData.AddNode("Nenhuma entidade vinculada a este contexto", 4, 1, true);
flowData.AddConnection(userNode, entNode, "");
}
else
{
String rpEntName = "Entidades";
Node entNode = flowData.AddNode(rpEntName, 4, (Int32)dtEntity.Rows[0]["qty"], true);
flowData.AddConnection(userNode, entNode, dtEntity.Rows[0]["qty"] + " entidades");
DataTable dtIdentity = db.Select("select COUNT(distinct i.id) qty from [identity] i inner join entity e on i.entity_id = e.id where e.context_id = " + contextID);
if ((dtIdentity == null) || (dtIdentity.Rows.Count == 0))
{
Node identNode = flowData.AddNode("Nenhuma identidade vinculado a esta entidade", 4, 1, true);
flowData.AddConnection(entNode, identNode, "");
}
else
{
String rpIdentName = "Identidades";
Node identNode = flowData.AddNode(rpIdentName, 5, (Int32)dtIdentity.Rows[0]["qty"], true);
flowData.AddConnection(entNode, identNode, dtIdentity.Rows[0]["qty"] + " identidades");
DataTable dtResources = db.Select("select name, qty = (select COUNT(distinct i.id) from resource r1 inner join resource_plugin rp on r1.id = rp.resource_id inner join [identity] i on i.resource_plugin_id = rp.id inner join entity e on i.entity_id = e.id where r1.name = r.name and r1.context_id = r.context_id) from resource r where r.context_id = " + contextID + " group by r.name, r.context_id");
if (dtResources != null)
{
foreach (DataRow drR in dtResources.Rows)
{
String resourceName = drR["name"].ToString();
Node resNode = flowData.AddNode(resourceName, 6, (Int32)drR["qty"], true);
flowData.AddConnection(identNode, resNode, drR["qty"] + " identidades");
}
}
}
}
Node confNode = flowData.AddNode("Configuração", 3, 1, true);
flowData.AddConnection(cNode, confNode, "");
DataTable dtProxy = db.Select("select p.id, p.name from resource r inner join proxy p on r.proxy_id = p.id where r.context_id = " + contextID + " group by p.id, p.name order by p.name");
if ((dtProxy == null) || (dtProxy.Rows.Count == 0))
{
Node pNode = flowData.AddNode("Nenhuma configuração vinculada a este contexto", 4, 1, true);
flowData.AddConnection(confNode, pNode, "");
}
else
{
//Node proxyNode = flowData.AddNode("Proxy", 2, dtProxy.Rows.Count, false);
//flowData.AddConnection(cNode, proxyNode, "");
foreach (DataRow drP in dtProxy.Rows)
{
Int64 pId = (Int64)drP["id"];
Node pNode = flowData.AddNode("Proxy: " + drP["name"], 4, 1, true);
flowData.AddConnection(confNode, pNode, "");
DataTable dtResource = db.Select("select r.*, p.name proxy_name from resource r inner join proxy p on r.proxy_id = p.id where r.context_id = " + contextID + " and p.id = " + pId);
if (dtResource != null)
{
foreach (DataRow drR in dtResource.Rows)
{
Int64 rId = (Int64)drR["id"];
Node rNode = flowData.AddNode("Recurso: " + drR["name"], 5, 1, true);
flowData.AddConnection(pNode, rNode, "");
DataTable dtResPlugin = db.Select("select p.name plugin_name, rp.* from resource_plugin rp inner join plugin p on rp.plugin_id = p.id where rp.resource_id = " + rId);
if (dtResPlugin != null)
{
foreach (DataRow drRP in dtResPlugin.Rows)
{
Int64 rpId = (Int64)drRP["id"];
Node rpNode = flowData.AddNode("Plugin: " + drRP["plugin_name"].ToString(), 6, 1, true);
flowData.AddConnection(rNode, rpNode, "");
DataTable dtRoles = db.Select("select r.id, r.name from role r inner join resource_plugin_role rpr on rpr.role_id = r.id where rpr.resource_plugin_id = " + rpId + " group by r.id, r.name");
if (dtRoles != null)
{
foreach (DataRow drRol in dtRoles.Rows)
{
String roleName = "Perfil: " + drRol["name"];
//if (roleNode != null)
//{
//Node roleNameNode = flowData.Find(roleNode, roleName, 6);
Node roleNameNode = flowData.Find(rpNode, roleName, 6);
if (roleNameNode == null)
roleNameNode = flowData.AddNode("Perfil: " + drRol["name"].ToString(), 7, 1, true);
if (roleNameNode != null)
flowData.AddConnection(rpNode, roleNameNode, "");
//Int32 roleNameNodeIndex = flowData.AddNode("Perfil: " + drRol["name"].ToString(), true);
//flowData.AddLink(rpNodeIndex, roleNameNodeIndex, 1, "");
//}
}
}
}
}
}
}
}
}
}
}
return flowData.ToJson();
}
[Serializable()]
class NodeBase
{
/*"nodeID": 0,
"name": "Node 1 name",
"column": 0,
"value": 1,
"cssClass": "class-to-add"*/
public Int32 nodeID;
public NodeBase(Int32 nodeID)
{
this.nodeID = nodeID;
}
}
[Serializable()]
class Node : NodeBase
{
/*"nodeID": 0,
"name": "Node 1 name",
"column": 0,
"value": 1,
"cssClass": "class-to-add"*/
public String name;
public Int32 column;
public Int32 value;
public String cssClass;
public Node(Int32 nodeID, String name, Int32 column, Int32 value, String cssClass)
: base(nodeID)
{
this.name = name;
this.column = column;
this.value = value;
this.cssClass = cssClass;
}
}
[Serializable()]
class Connection
{
public NodeBase source;
public NodeBase dest;
public String title;
public Connection(Node source, Node destination, String title)
{
this.source = new NodeBase(source.nodeID);
this.dest = new NodeBase(destination.nodeID);
this.title = title;
}
}
[Serializable()]
class FlowData
{
public List<Node> nodes = new List<Node>();
public List<Connection> connections = new List<Connection>();
public Node AddNode(String name, Int32 column, Int32 value)
{
return AddNode(name, column, value, false);
}
public Node AddNode(String name, Int32 column, Int32 value, Boolean forceNew)
{
Node ret = new Node(nodes.Count, name, column, value, "");
if (!nodes.Exists(n => (n.name == name && n.column == column)) || forceNew)
nodes.Add(ret);
else
ret = nodes.Find(n => (n.name == name && n.column == column));
return ret;
}
public Node Find(Node parent, String name, Int32 column)
{
foreach (Node node in nodes.FindAll(n => (n.name == name)))
{
if (connections.Exists(c => (c.source.nodeID == parent.nodeID && c.dest.nodeID == node.nodeID)))
return node;
}
return null;
}
public void AddConnection(Node source, Node destination, String title)
{
connections.Add(new Connection(source, destination, title));
}
public string ToJson()
{
try
{
//return SafeTrend.Json.JSON.Serialize<Connection>(connections[0]);
return SafeTrend.Json.JSON.Serialize<FlowData>(this);
}
catch (Exception ex)
{
return "{ \"error\": \"" + ex.Message + "\"";
}
}
}
}
} | 42.441406 | 427 | 0.4578 | [
"Apache-2.0"
] | helviojunior/safeid | IAMWebServer/IAMWebServer/_admin/chartdata/flow.aspx.cs | 21,740 | C# |
using System;
using ExtenFlow.Messages;
namespace ExtenFlow.Identity.Roles.Domain.Commands
{
/// <summary>
/// Base Role command class
/// </summary>
/// <seealso cref="Command"/>
public abstract class RoleNameRegistryCommand : Command
{
/// <summary>
/// Initializes a new instance of the <see cref="RoleNameRegistryCommand"/> class.
/// </summary>
/// <remarks>Do not use this constructor. It has been added for serializers</remarks>
[Obsolete("Can only be used by serializers")]
protected RoleNameRegistryCommand()
{
AggregateType = string.Empty;
}
/// <summary>
/// Initializes a new instance of the <see cref="RoleCommand"/> class.
/// </summary>
/// <param name="aggregateId">Aggragate Id.</param>
/// <param name="userId">The user submitting the command.</param>
/// <param name="concurrencyCheckStamp">
/// Concurrency stamp used for optimistic concurrency check.
/// </param>
/// <param name="correlationId">
/// The correlation id used to chain messages, queries, commands and events.
/// </param>
/// <param name="id">The Id of this command.</param>
/// <param name="dateTime">The date time of the command submission.</param>
protected RoleNameRegistryCommand(string aggregateId,
string userId,
string? concurrencyCheckStamp = null,
string? correlationId = null,
string? id = null,
DateTimeOffset? dateTime = null)
: base(AggregateName.RoleNameRegistry, aggregateId, userId, concurrencyCheckStamp, correlationId, id, dateTime)
{
}
}
} | 40.065217 | 123 | 0.577862 | [
"Apache-2.0"
] | jpiquot/ExtenFlow | ExtenFlow/src/Core/Identity/ExtenFlow.Identity.Roles.Domain.Abstractions/Commands/RoleNameRegistryCommand.cs | 1,845 | C# |
// Copyright 2018 by JCoder58. See License.txt for license
// Auto-generated --- Do not modify.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UE4.Core;
using UE4.CoreUObject;
using UE4.CoreUObject.Native;
using UE4.InputCore;
using UE4.Native;
namespace UE4.Engine{
///<summary>This defines what constraint it is defined</summary>
[StructLayout( LayoutKind.Explicit, Size=16 )]
public unsafe struct TransformBaseConstraint {
[FieldOffset(0)] byte TransformConstraints; //TODO: array TArray TransformConstraints
}
}
| 29 | 97 | 0.732348 | [
"MIT"
] | UE4DotNet/Plugin | DotNet/DotNet/UE4/Generated/Engine/TransformBaseConstraint.cs | 609 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using DslShell = global::Microsoft.VisualStudio.Modeling.Shell;
using VSShell = global::Microsoft.VisualStudio.Shell;
using DslModeling = global::Microsoft.VisualStudio.Modeling;
using DslDiagrams = global::Microsoft.VisualStudio.Modeling.Diagrams;
using DslValidation = global::Microsoft.VisualStudio.Modeling.Validation;
namespace EPAM.NHModelingLanguage
{
/// <summary>
/// Double-derived class to allow easier code customization.
/// </summary>
internal partial class NHModelingLanguageCommandSet : NHModelingLanguageCommandSetBase
{
/// <summary>
/// Constructs a new NHModelingLanguageCommandSet.
/// </summary>
public NHModelingLanguageCommandSet(global::System.IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
}
/// <summary>
/// Class containing handlers for commands supported by this DSL.
/// </summary>
internal abstract class NHModelingLanguageCommandSetBase : DslShell::CommandSet
{
/// <summary>
/// Constructs a new NHModelingLanguageCommandSetBase.
/// </summary>
protected NHModelingLanguageCommandSetBase(global::System.IServiceProvider serviceProvider) : base(serviceProvider)
{
}
/// <summary>
/// Provide the menu commands that this command set handles
/// </summary>
protected override global::System.Collections.Generic.IList<global::System.ComponentModel.Design.MenuCommand> GetMenuCommands()
{
// Get the standard commands
global::System.Collections.Generic.IList<global::System.ComponentModel.Design.MenuCommand> commands = base.GetMenuCommands();
global::System.ComponentModel.Design.MenuCommand menuCommand;
// Add command handler for the "view explorer" command in the top-level menu.
// We use a ContextBoundMenuCommand because the visibility of this command is
// based on whether or not the command context of our DSL editor is active.
menuCommand = new DslShell::CommandContextBoundMenuCommand(this.ServiceProvider,
new global::System.EventHandler(OnMenuViewModelExplorer),
Constants.ViewNHModelingLanguageExplorerCommand,
typeof(NHModelingLanguageEditorFactory).GUID);
commands.Add(menuCommand);
// Add handler for "Validate All" menu command (validates the entire model).
menuCommand = new DslShell::DynamicStatusMenuCommand(new global::System.EventHandler(OnStatusValidateModel),
new global::System.EventHandler(OnMenuValidateModel),
DslShell::CommonModelingCommands.ValidateModel);
commands.Add(menuCommand);
// Add handler for "Validate" menu command (validates the current selection).
menuCommand = new DslShell::DynamicStatusMenuCommand(new global::System.EventHandler(OnStatusValidate),
new global::System.EventHandler(OnMenuValidate),
DslShell::CommonModelingCommands.Validate);
commands.Add(menuCommand);
return commands;
}
/// <summary>
/// Command handler that shows the explorer tool window.
/// </summary>
internal virtual void OnMenuViewModelExplorer(object sender, global::System.EventArgs e)
{
NHModelingLanguageExplorerToolWindow explorer = this.NHModelingLanguageExplorerToolWindow;
if (explorer != null)
{
explorer.Show();
}
}
/// <summary>
/// Status event handler for validating the model.
/// </summary>
internal virtual void OnStatusValidateModel(object sender, global::System.EventArgs e)
{
System.ComponentModel.Design.MenuCommand cmd = sender as System.ComponentModel.Design.MenuCommand;
cmd.Enabled = cmd.Visible = true;
}
/// <summary>
/// Handler for validating the model.
/// </summary>
internal virtual void OnMenuValidateModel(object sender, System.EventArgs e)
{
if (this.CurrentNHModelingLanguageDocData != null && this.CurrentNHModelingLanguageDocData.Store != null)
{
this.CurrentNHModelingLanguageDocData.ValidationController.Validate(this.CurrentNHModelingLanguageDocData.GetAllElementsForValidation(), DslValidation::ValidationCategories.Menu);
}
}
/// <summary>
/// Status event handler for validating the current selection.
/// </summary>
internal virtual void OnStatusValidate(object sender, System.EventArgs e)
{
global::System.ComponentModel.Design.MenuCommand cmd = sender as global::System.ComponentModel.Design.MenuCommand;
cmd.Visible = cmd.Enabled = false;
foreach (object selectedObject in this.CurrentSelection)
{
DslModeling::ModelElement element = GetValidationTarget(selectedObject);
if (element != null)
{
cmd.Visible = cmd.Enabled = true;
break;
}
}
}
/// <summary>
/// Handler for validating the current selection.
/// </summary>
internal virtual void OnMenuValidate(object sender, global::System.EventArgs e)
{
if (this.CurrentNHModelingLanguageDocData != null && this.CurrentNHModelingLanguageDocData.Store != null)
{
System.Collections.Generic.List<DslModeling::ModelElement> elementList = new System.Collections.Generic.List<Microsoft.VisualStudio.Modeling.ModelElement>();
DslModeling::DepthFirstElementWalker elementWalker = new DslModeling::DepthFirstElementWalker(new ValidateCommandVisitor(elementList), new DslModeling::EmbeddingVisitorFilter(), true);
foreach (object selectedObject in this.CurrentSelection)
{
// Build list of elements embedded beneath the selected root.
DslModeling::ModelElement element = GetValidationTarget(selectedObject);
if (element != null && !elementList.Contains(element))
{
elementWalker.DoTraverse(element);
}
}
this.CurrentNHModelingLanguageDocData.ValidationController.Validate(elementList, DslValidation::ValidationCategories.Menu);
}
}
/// <summary>
/// Helper method to retrieve the target root element for validation from the selected object.
/// </summary>
protected static DslModeling::ModelElement GetValidationTarget(object selectedObject)
{
DslModeling::ModelElement element = null;
DslDiagrams::PresentationElement presentation = selectedObject as DslDiagrams::PresentationElement;
if (presentation != null)
{
if (presentation.Subject != null)
{
element = presentation.Subject;
}
}
else
{
element = selectedObject as DslModeling::ModelElement;
}
return element;
}
#region ValidateCommandVisitor
/// <summary>
/// Helper class for building the list of elements to validate when the Validate command is executed.
/// </summary>
protected sealed class ValidateCommandVisitor : DslModeling::IElementVisitor
{
private System.Collections.Generic.IList<DslModeling::ModelElement> validationList;
/// <summary>
/// Construct a ValidateCommandVisitor that adds elements to be validated to the specified list.
/// </summary>
public ValidateCommandVisitor(System.Collections.Generic.IList<DslModeling::ModelElement> elementList)
{
this.validationList = elementList;
}
/// <summary>
/// Called when traversal begins.
/// </summary>
public void StartTraverse(Microsoft.VisualStudio.Modeling.ElementWalker walker) { }
/// <summary>
/// Called when traversal ends.
/// </summary>
public void EndTraverse(Microsoft.VisualStudio.Modeling.ElementWalker walker) { }
/// <summary>
/// Called for each element in the traversal.
/// </summary>
public bool Visit(Microsoft.VisualStudio.Modeling.ElementWalker walker, Microsoft.VisualStudio.Modeling.ModelElement element)
{
this.validationList.Add(element);
return true;
}
}
#endregion
/// <summary>
/// Returns the currently focused document.
/// </summary>
[global::System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
protected NHModelingLanguageDocData CurrentNHModelingLanguageDocData
{
get
{
return this.MonitorSelection.CurrentDocument as NHModelingLanguageDocData;
}
}
/// <summary>
/// Returns the currently focused document view.
/// </summary>
[global::System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
protected NHModelingLanguageDocView CurrentNHModelingLanguageDocView
{
get
{
return this.MonitorSelection.CurrentDocumentView as NHModelingLanguageDocView;
}
}
/// <summary>
/// Returns the explorer tool window.
/// </summary>
protected NHModelingLanguageExplorerToolWindow NHModelingLanguageExplorerToolWindow
{
get
{
NHModelingLanguageExplorerToolWindow explorerWindow = null;
DslShell::ModelingPackage package = this.ServiceProvider.GetService(typeof(VSShell::Package)) as DslShell::ModelingPackage;
if (package != null)
{
explorerWindow = package.GetToolWindow(typeof(NHModelingLanguageExplorerToolWindow), true) as NHModelingLanguageExplorerToolWindow;
}
return explorerWindow;
}
}
/// <summary>
/// Returns the currently selected object in the model explorer.
/// </summary>
[global::System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
protected object ExplorerSelection
{
get
{
object selection = null;
NHModelingLanguageExplorerToolWindow explorerWindow = this.NHModelingLanguageExplorerToolWindow;
if(explorerWindow != null)
{
foreach (object o in explorerWindow.GetSelectedComponents())
{
selection = o;
break;
}
}
return selection;
}
}
}
/// <summary>
/// Double-derived class to allow easier code customization.
/// </summary>
internal partial class NHModelingLanguageClipboardCommandSet : NHModelingLanguageClipboardCommandSetBase
{
/// <summary>
/// Constructs a new NHModelingLanguageClipboardCommandSet.
/// </summary>
public NHModelingLanguageClipboardCommandSet(global::System.IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
}
/// <summary>
/// Class containing handlers for cut/copy/paste commands supported by this DSL.
/// </summary>
internal abstract partial class NHModelingLanguageClipboardCommandSetBase : DslShell::ClipboardCommandSet
{
/// <summary>
/// Constructs a new NHModelingLanguageClipboardCommandSetBase.
/// </summary>
protected NHModelingLanguageClipboardCommandSetBase(global::System.IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
/// <summary>
/// Provide the menu commands that this command set handles
/// </summary>
protected override global::System.Collections.Generic.IList<global::System.ComponentModel.Design.MenuCommand> GetMenuCommands()
{
// Get the standard commands
var commands = new global::System.Collections.Generic.List<global::System.ComponentModel.Design.MenuCommand>(3);
global::System.ComponentModel.Design.MenuCommand menuCommand;
menuCommand = new DslShell::DynamicStatusMenuCommand(
new global::System.EventHandler(this.OnStatusCut),
new global::System.EventHandler(this.OnMenuCut),
global::System.ComponentModel.Design.StandardCommands.Cut);
commands.Add(menuCommand);
menuCommand = new DslShell::DynamicStatusMenuCommand(
new global::System.EventHandler(this.OnStatusCopy),
new global::System.EventHandler(this.OnMenuCopy),
global::System.ComponentModel.Design.StandardCommands.Copy);
commands.Add(menuCommand);
menuCommand = new DslShell::DynamicStatusMenuCommand(
new global::System.EventHandler(this.OnStatusPaste),
new global::System.EventHandler(this.OnMenuPaste),
global::System.ComponentModel.Design.StandardCommands.Paste);
commands.Add(menuCommand);
return commands;
}
/// <summary>
/// Determines whether Cut menu item should be visible and if so, enabled.
/// </summary>
/// <param name="sender">The sender of the message</param>
/// <param name="args">empty</param>
private void OnStatusCut(object sender, global::System.EventArgs args)
{
System.ComponentModel.Design.MenuCommand cmd = sender as System.ComponentModel.Design.MenuCommand;
this.ProcessOnStatusCutCommand(cmd);
}
/// <summary>
/// Determines whether Copy menu item should be visible and if so, enabled.
/// </summary>
/// <param name="sender">The sender of the message</param>
/// <param name="args">empty</param>
private void OnStatusCopy(object sender, global::System.EventArgs args)
{
System.ComponentModel.Design.MenuCommand cmd = sender as System.ComponentModel.Design.MenuCommand;
this.ProcessOnStatusCopyCommand(cmd);
}
/// <summary>
/// Updates the UI for the Paste command
/// </summary>
/// <param name="sender">The sender of the message</param>
/// <param name="args">Message parameters</param>
private void OnStatusPaste(object sender, global::System.EventArgs args)
{
System.ComponentModel.Design.MenuCommand cmd = sender as System.ComponentModel.Design.MenuCommand;
this.ProcessOnStatusPasteCommand(cmd);
}
/// <summary>
/// Event handler to cut the selected objects to the clipboard then delete the original.
/// </summary>
/// <param name="sender">The MenuCommand selected.</param>
/// <param name="args">not used</param>
private void OnMenuCut(object sender, global::System.EventArgs args)
{
this.ProcessOnMenuCutCommand();
}
/// <summary>
/// Event handler to copy the selected objects to the clipboard.
/// </summary>
/// <param name="sender">The MenuCommand selected.</param>
/// <param name="args">not used</param>
private void OnMenuCopy(object sender, global::System.EventArgs args)
{
this.ProcessOnMenuCopyCommand();
}
/// <summary>
/// Event handler to paste a copy of the object on the clipboard.
/// </summary>
/// <param name="sender">The MenuCommand selected.</param>
/// <param name="args">not used</param>
private void OnMenuPaste(object sender, global::System.EventArgs args)
{
this.ProcessOnMenuPasteCommand();
}
}
}
| 35.535 | 188 | 0.730829 | [
"MIT"
] | MihailRomanov/TechTalks_DSL_in_Net | VsExtensions/NHModelingLanguage/DslPackage/GeneratedCode/CommandSet.cs | 14,216 | C# |
#pragma checksum "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "eb0135ab559d26003f650c55efbb4e31272277bd"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Account_Manage__ManageNav), @"mvc.1.0.view", @"/Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\_ViewImports.cshtml"
using BlazorApp.Server.Areas.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\_ViewImports.cshtml"
using BlazorApp.Server.Areas.Identity.Pages;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\_ViewImports.cshtml"
using BlazorApp.Server.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\_ViewImports.cshtml"
using BlazorApp.Server.Areas.Identity.Pages.Account;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml"
using BlazorApp.Server.Areas.Identity.Pages.Account.Manage;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"eb0135ab559d26003f650c55efbb4e31272277bd", @"/Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"117e1c08363642f8d901354dd37bc740936b8052", @"/Areas/Identity/Pages/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"f1fd563825d5a2a67b5803e104aec1716fe602d2", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c67891d2b5223f963cb72a01a27eb38ddb7f5f30", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")]
public class Areas_Identity_Pages_Account_Manage__ManageNav : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("profile"), 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", "./Index", 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("id", new global::Microsoft.AspNetCore.Html.HtmlString("email"), 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", "./Email", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("change-password"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./ChangePassword", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("external-login"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./ExternalLogins", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("two-factor"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./TwoFactorAuthentication", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("personal-data"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./PersonalData", 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()
{
#nullable restore
#line 2 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
var hasExternalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).Any();
#line default
#line hidden
#nullable disable
WriteLiteral("<ul class=\"nav nav-pills flex-column\">\r\n <li class=\"nav-item\">");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "eb0135ab559d26003f650c55efbb4e31272277bd8890", async() => {
WriteLiteral("Profile");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
AddHtmlAttributeValue("", 234, "nav-link", 234, 8, true);
#nullable restore
#line 6 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
AddHtmlAttributeValue(" ", 242, ManageNavPages.IndexNavClass(ViewContext), 243, 42, false);
#line default
#line hidden
#nullable disable
EndAddHtmlAttributeValues(__tagHelperExecutionContext);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("</li>\r\n <li class=\"nav-item\">");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "eb0135ab559d26003f650c55efbb4e31272277bd10749", async() => {
WriteLiteral("Email");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
AddHtmlAttributeValue("", 372, "nav-link", 372, 8, true);
#nullable restore
#line 7 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
AddHtmlAttributeValue(" ", 380, ManageNavPages.EmailNavClass(ViewContext), 381, 42, false);
#line default
#line hidden
#nullable disable
EndAddHtmlAttributeValues(__tagHelperExecutionContext);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("</li>\r\n <li class=\"nav-item\">");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "eb0135ab559d26003f650c55efbb4e31272277bd12607", async() => {
WriteLiteral("Password");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
AddHtmlAttributeValue("", 506, "nav-link", 506, 8, true);
#nullable restore
#line 8 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
AddHtmlAttributeValue(" ", 514, ManageNavPages.ChangePasswordNavClass(ViewContext), 515, 51, false);
#line default
#line hidden
#nullable disable
EndAddHtmlAttributeValues(__tagHelperExecutionContext);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("</li>\r\n");
#nullable restore
#line 9 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
if (hasExternalLogins)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <li id=\"external-logins\" class=\"nav-item\">");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "eb0135ab559d26003f650c55efbb4e31272277bd14761", async() => {
WriteLiteral("External logins");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
AddHtmlAttributeValue("", 752, "nav-link", 752, 8, true);
#nullable restore
#line 11 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
AddHtmlAttributeValue(" ", 760, ManageNavPages.ExternalLoginsNavClass(ViewContext), 761, 51, false);
#line default
#line hidden
#nullable disable
EndAddHtmlAttributeValues(__tagHelperExecutionContext);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("</li>\r\n");
#nullable restore
#line 12 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" <li class=\"nav-item\">");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "eb0135ab559d26003f650c55efbb4e31272277bd16868", async() => {
WriteLiteral("Two-factor authentication");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
AddHtmlAttributeValue("", 910, "nav-link", 910, 8, true);
#nullable restore
#line 13 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
AddHtmlAttributeValue(" ", 918, ManageNavPages.TwoFactorAuthenticationNavClass(ViewContext), 919, 60, false);
#line default
#line hidden
#nullable disable
EndAddHtmlAttributeValues(__tagHelperExecutionContext);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("</li>\r\n <li class=\"nav-item\">");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "eb0135ab559d26003f650c55efbb4e31272277bd18765", async() => {
WriteLiteral("Personal data");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
AddHtmlAttributeValue("", 1105, "nav-link", 1105, 8, true);
#nullable restore
#line 14 "I:\XpertLab\BlazorXpertlabBD\BlazorApp\BlazorApp\Server\Areas\Identity\Pages\Account\Manage\_ManageNav.cshtml"
AddHtmlAttributeValue(" ", 1113, ManageNavPages.PersonalDataNavClass(ViewContext), 1114, 49, false);
#line default
#line hidden
#nullable disable
EndAddHtmlAttributeValues(__tagHelperExecutionContext);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_11.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_11);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("</li>\r\n</ul>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public SignInManager<ApplicationUser> SignInManager { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 70.496711 | 350 | 0.76716 | [
"MIT"
] | MizaN13/BlazorXpertlabBD | BlazorApp/BlazorApp/Server/obj/Debug/netcoreapp3.1/Razor/Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml.g.cs | 21,431 | C# |
using JetBrains.Annotations;
using UnityEditor;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
class FoldoutWithCheckbox : PersistedFoldout
{
[UsedImplicitly]
public new class UxmlFactory : UxmlFactory<FoldoutWithCheckbox, UxmlTraits> { }
public new class UxmlTraits : PersistedFoldout.UxmlTraits { }
const string k_UssPath = BuilderConstants.UtilitiesPath + "/FoldoutWithCheckbox/FoldoutWithCheckbox.uss";
const string k_CheckboxClassName = "unity-foldout__checkbox";
const string k_LabelClassName = "unity-foldout-with-checkbox__label";
readonly Toggle m_Checkbox;
readonly Label m_Label;
public FoldoutWithCheckbox()
{
m_Toggle.text = string.Empty;
m_Toggle.style.flexGrow = 0;
m_Checkbox = new Toggle();
m_Checkbox.style.flexGrow = 0;
m_Checkbox.AddToClassList(k_CheckboxClassName);
m_Checkbox.RegisterValueChangedCallback(e
=> SetCheckboxValueWithoutNotify(e.newValue));
m_Header.hierarchy.Add(m_Checkbox);
m_Label = new Label();
m_Label.AddToClassList(k_LabelClassName);
m_Label.AddManipulator(new Clickable(evt =>
{
if ((evt as MouseUpEvent)?.button == (int)MouseButton.LeftMouse)
{
m_Toggle.value = !m_Toggle.value;
}
}));
m_Header.hierarchy.Add(m_Label);
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPath));
}
public override string text
{
get => m_Label.text;
set => m_Label.text = value;
}
public void SetCheckboxValueWithoutNotify(bool newValue)
{
m_Checkbox.SetValueWithoutNotify(newValue);
contentContainer.SetEnabled(newValue);
}
public void RegisterCheckboxValueChangedCallback(EventCallback<ChangeEvent<bool>> callback)
{
m_Checkbox.RegisterCallback(callback);
}
}
}
| 31.656716 | 113 | 0.623762 | [
"Apache-2.0"
] | kawaitenshi/fools-run | Library/PackageCache/com.unity.ui.builder@1.0.0-preview.18/Editor/Utilities/FoldoutWithCheckbox/FoldoutWithCheckbox.cs | 2,121 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System.Collections.Generic;
namespace SixLabors.ImageSharp.Formats.Jpeg
{
/// <summary>
/// Contains jpeg constant values defined in the specification.
/// </summary>
internal static class JpegConstants
{
/// <summary>
/// The maximum allowable length in each dimension of a jpeg image.
/// </summary>
public const ushort MaxLength = 65535;
/// <summary>
/// The list of mimetypes that equate to a jpeg.
/// </summary>
public static readonly IEnumerable<string> MimeTypes = new[] { "image/jpeg", "image/pjpeg" };
/// <summary>
/// The list of file extensions that equate to a jpeg.
/// </summary>
public static readonly IEnumerable<string> FileExtensions = new[] { "jpg", "jpeg", "jfif" };
/// <summary>
/// Contains marker specific constants
/// </summary>
// ReSharper disable InconsistentNaming
internal static class Markers
{
/// <summary>
/// The prefix used for all markers.
/// </summary>
public const byte XFF = 0xFF;
/// <summary>
/// Same as <see cref="XFF"/> but of type <see cref="int"/>
/// </summary>
public const int XFFInt = XFF;
/// <summary>
/// The Start of Image marker
/// </summary>
public const byte SOI = 0xD8;
/// <summary>
/// The End of Image marker
/// </summary>
public const byte EOI = 0xD9;
/// <summary>
/// Application specific marker for marking the jpeg format.
/// <see href="http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html"/>
/// </summary>
public const byte APP0 = 0xE0;
/// <summary>
/// Application specific marker for marking where to store metadata.
/// </summary>
public const byte APP1 = 0xE1;
/// <summary>
/// Application specific marker for marking where to store ICC profile information.
/// </summary>
public const byte APP2 = 0xE2;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP3 = 0xE3;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP4 = 0xE4;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP5 = 0xE5;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP6 = 0xE6;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP7 = 0xE7;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP8 = 0xE8;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP9 = 0xE9;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP10 = 0xEA;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP11 = 0xEB;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP12 = 0xEC;
/// <summary>
/// Application specific marker.
/// </summary>
public const byte APP13 = 0xED;
/// <summary>
/// Application specific marker used by Adobe for storing encoding information for DCT filters.
/// </summary>
public const byte APP14 = 0xEE;
/// <summary>
/// Application specific marker used by GraphicConverter to store JPEG quality.
/// </summary>
public const byte APP15 = 0xEF;
/// <summary>
/// The text comment marker
/// </summary>
public const byte COM = 0xFE;
/// <summary>
/// Define Quantization Table(s) marker
/// <remarks>
/// Specifies one or more quantization tables.
/// </remarks>
/// </summary>
public const byte DQT = 0xDB;
/// <summary>
/// Start of Frame (baseline DCT)
/// <remarks>
/// Indicates that this is a baseline DCT-based JPEG, and specifies the width, height, number of components,
/// and component subsampling (e.g., 4:2:0).
/// </remarks>
/// </summary>
public const byte SOF0 = 0xC0;
/// <summary>
/// Start Of Frame (Extended Sequential DCT)
/// <remarks>
/// Indicates that this is a progressive DCT-based JPEG, and specifies the width, height, number of components,
/// and component subsampling (e.g., 4:2:0).
/// </remarks>
/// </summary>
public const byte SOF1 = 0xC1;
/// <summary>
/// Start Of Frame (progressive DCT)
/// <remarks>
/// Indicates that this is a progressive DCT-based JPEG, and specifies the width, height, number of components,
/// and component subsampling (e.g., 4:2:0).
/// </remarks>
/// </summary>
public const byte SOF2 = 0xC2;
/// <summary>
/// Define Huffman Table(s)
/// <remarks>
/// Specifies one or more Huffman tables.
/// </remarks>
/// </summary>
public const byte DHT = 0xC4;
/// <summary>
/// Define Restart Interval
/// <remarks>
/// Specifies the interval between RSTn markers, in macroblocks.This marker is followed by two bytes indicating the fixed size so
/// it can be treated like any other variable size segment.
/// </remarks>
/// </summary>
public const byte DRI = 0xDD;
/// <summary>
/// Start of Scan
/// <remarks>
/// Begins a top-to-bottom scan of the image. In baseline DCT JPEG images, there is generally a single scan.
/// Progressive DCT JPEG images usually contain multiple scans. This marker specifies which slice of data it
/// will contain, and is immediately followed by entropy-coded data.
/// </remarks>
/// </summary>
public const byte SOS = 0xDA;
/// <summary>
/// Define First Restart
/// <remarks>
/// Inserted every r macroblocks, where r is the restart interval set by a DRI marker.
/// Not used if there was no DRI marker. The low three bits of the marker code cycle in value from 0 to 7.
/// </remarks>
/// </summary>
public const byte RST0 = 0xD0;
/// <summary>
/// Define Eigth Restart
/// <remarks>
/// Inserted every r macroblocks, where r is the restart interval set by a DRI marker.
/// Not used if there was no DRI marker. The low three bits of the marker code cycle in value from 0 to 7.
/// </remarks>
/// </summary>
public const byte RST7 = 0xD7;
}
/// <summary>
/// Contains Adobe specific constants
/// </summary>
internal static class Adobe
{
/// <summary>
/// The color transform is unknown.(RGB or CMYK)
/// </summary>
public const byte ColorTransformUnknown = 0;
/// <summary>
/// The color transform is YCbCr (luminance, red chroma, blue chroma)
/// </summary>
public const byte ColorTransformYCbCr = 1;
/// <summary>
/// The color transform is YCCK (luminance, red chroma, blue chroma, keyline)
/// </summary>
public const byte ColorTransformYcck = 2;
}
}
} | 35.157025 | 141 | 0.506112 | [
"Apache-2.0"
] | Davidsv/ImageSharp | src/ImageSharp/Formats/Jpeg/JpegConstants.cs | 8,510 | C# |
namespace Thrift.Net.Compilation.Symbols
{
/// <summary>
/// Represents an unresolved type (i.e. where a type has been referenced, but
/// no definition can be found).
/// </summary>
public interface IUnresolvedType : INamedTypeSymbol
{
}
} | 26.8 | 81 | 0.656716 | [
"MIT"
] | Roarster/Thrift.Net | src/Thrift.Net.Compilation/Symbols/IUnresolvedType.cs | 268 | C# |
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_WindZoneMode : LuaObject {
static public void reg(IntPtr l) {
getEnumTable(l,"UnityEngine.WindZoneMode");
addMember(l,0,"Directional");
addMember(l,1,"Spherical");
LuaDLL.lua_pop(l, 1);
}
}
| 23.5 | 55 | 0.756839 | [
"MIT"
] | zhukunqian/unity5-slua | Assets/Slua/LuaObject/Unity/Lua_UnityEngine_WindZoneMode.cs | 331 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace WebWindows
{
[StructLayout(LayoutKind.Sequential)]
struct NativeRect
{
public int x, y;
public int width, height;
}
[StructLayout(LayoutKind.Sequential)]
struct NativeMonitor
{
public NativeRect monitor;
public NativeRect work;
}
public readonly struct Monitor
{
public readonly Rectangle MonitorArea;
public readonly Rectangle WorkArea;
public Monitor(Rectangle monitor, Rectangle work)
{
MonitorArea = monitor;
WorkArea = work;
}
internal Monitor(NativeRect monitor, NativeRect work)
: this(new Rectangle(monitor.x, monitor.y, monitor.width, monitor.height), new Rectangle(work.x, work.y, work.width, work.height))
{ }
internal Monitor(NativeMonitor nativeMonitor)
: this(nativeMonitor.monitor, nativeMonitor.work)
{ }
}
public class WebWindow
{
// Here we use auto charset instead of forcing UTF-8.
// Thus the native code for Windows will be much more simple.
// Auto charset is UTF-16 on Windows and UTF-8 on Unix(.NET Core 3.0 and later and Mono).
// As we target .NET Standard 2.1, we assume it runs on .NET Core 3.0 and later.
// We should specify using auto charset because the default value is ANSI.
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)] delegate void OnWebMessageReceivedCallback(string message);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)] delegate IntPtr OnWebResourceRequestedCallback(string url, out int numBytes, out string contentType);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void InvokeCallback();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int GetAllMonitorsCallback(in NativeMonitor monitor);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ResizedCallback(int width, int height);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void MovedCallback(int x, int y);
const string DllName = "WebWindow.Native";
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr WebWindow_register_win32(IntPtr hInstance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr WebWindow_register_mac();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern IntPtr WebWindow_ctor(string title, IntPtr parentWebWindow, OnWebMessageReceivedCallback webMessageReceivedCallback);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_dtor(IntPtr instance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr WebWindow_getHwnd_win32(IntPtr instance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern void WebWindow_SetTitle(IntPtr instance, string title);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_Show(IntPtr instance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_WaitForExit(IntPtr instance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_Invoke(IntPtr instance, InvokeCallback callback);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern void WebWindow_NavigateToString(IntPtr instance, string content);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern void WebWindow_NavigateToUrl(IntPtr instance, string url);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern void WebWindow_ShowMessage(IntPtr instance, string title, string body, uint type);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern void WebWindow_SendMessage(IntPtr instance, string message);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern void WebWindow_AddCustomScheme(IntPtr instance, string scheme, OnWebResourceRequestedCallback requestHandler);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_SetResizable(IntPtr instance, int resizable);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_GetSize(IntPtr instance, out int width, out int height);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_SetSize(IntPtr instance, int width, int height);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_SetResizedCallback(IntPtr instance, ResizedCallback callback);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_GetAllMonitors(IntPtr instance, GetAllMonitorsCallback callback);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern uint WebWindow_GetScreenDpi(IntPtr instance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_GetPosition(IntPtr instance, out int x, out int y);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_SetPosition(IntPtr instance, int x, int y);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_SetMovedCallback(IntPtr instance, MovedCallback callback);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] static extern void WebWindow_SetTopmost(IntPtr instance, int topmost);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static extern void WebWindow_SetIconFile(IntPtr instance, string filename);
private readonly List<GCHandle> _gcHandlesToFree = new List<GCHandle>();
private readonly List<IntPtr> _hGlobalToFree = new List<IntPtr>();
private readonly IntPtr _nativeWebWindow;
private readonly int _ownerThreadId;
private string _title;
static WebWindow()
{
// Workaround for a crashing issue on Linux. Without this, applications
// are crashing when running in Debug mode (but not Release) if the very
// first line of code in Program::Main references the WebWindow type.
// It's unclear why.
Thread.Sleep(1);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var hInstance = Marshal.GetHINSTANCE(typeof(WebWindow).Module);
WebWindow_register_win32(hInstance);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
WebWindow_register_mac();
}
}
public WebWindow(string title) : this(title, _ => { })
{
}
public WebWindow(string title, Action<WebWindowOptions> configure)
{
_ownerThreadId = Thread.CurrentThread.ManagedThreadId;
if (configure is null)
{
throw new ArgumentNullException(nameof(configure));
}
var options = new WebWindowOptions();
configure.Invoke(options);
WriteTitleField(title);
var onWebMessageReceivedDelegate = (OnWebMessageReceivedCallback)ReceiveWebMessage;
_gcHandlesToFree.Add(GCHandle.Alloc(onWebMessageReceivedDelegate));
var parentPtr = options.Parent?._nativeWebWindow ?? default;
_nativeWebWindow = WebWindow_ctor(_title, parentPtr, onWebMessageReceivedDelegate);
foreach (var (schemeName, handler) in options.SchemeHandlers)
{
AddCustomScheme(schemeName, handler);
}
var onResizedDelegate = (ResizedCallback)OnResized;
_gcHandlesToFree.Add(GCHandle.Alloc(onResizedDelegate));
WebWindow_SetResizedCallback(_nativeWebWindow, onResizedDelegate);
var onMovedDelegate = (MovedCallback)OnMoved;
_gcHandlesToFree.Add(GCHandle.Alloc(onMovedDelegate));
WebWindow_SetMovedCallback(_nativeWebWindow, onMovedDelegate);
// Auto-show to simplify the API, but more importantly because you can't
// do things like navigate until it has been shown
Show();
}
~WebWindow()
{
// TODO: IDisposable
WebWindow_SetResizedCallback(_nativeWebWindow, null);
WebWindow_SetMovedCallback(_nativeWebWindow, null);
foreach (var gcHandle in _gcHandlesToFree)
{
gcHandle.Free();
}
_gcHandlesToFree.Clear();
foreach (var handle in _hGlobalToFree)
{
Marshal.FreeHGlobal(handle);
}
_hGlobalToFree.Clear();
WebWindow_dtor(_nativeWebWindow);
}
public void Show() => WebWindow_Show(_nativeWebWindow);
public void WaitForExit() => WebWindow_WaitForExit(_nativeWebWindow);
public string Title
{
get => _title;
set
{
WriteTitleField(value);
WebWindow_SetTitle(_nativeWebWindow, _title);
}
}
public void ShowMessage(string title, string body)
{
WebWindow_ShowMessage(_nativeWebWindow, title, body, /* MB_OK */ 0);
}
public void Invoke(Action workItem)
{
// If we're already on the UI thread, no need to dispatch
if (Thread.CurrentThread.ManagedThreadId == _ownerThreadId)
{
workItem();
}
else
{
WebWindow_Invoke(_nativeWebWindow, workItem.Invoke);
}
}
public IntPtr Hwnd
{
get
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return WebWindow_getHwnd_win32(_nativeWebWindow);
}
else
{
throw new PlatformNotSupportedException($"{nameof(Hwnd)} is only supported on Windows");
}
}
}
public void NavigateToString(string content)
{
WebWindow_NavigateToString(_nativeWebWindow, content);
}
public void NavigateToUrl(string url)
{
WebWindow_NavigateToUrl(_nativeWebWindow, url);
}
public void NavigateToLocalFile(string path)
{
var absolutePath = Path.GetFullPath(path);
var url = new Uri(absolutePath, UriKind.Absolute);
NavigateToUrl(url.ToString());
}
public void SendMessage(string message)
{
WebWindow_SendMessage(_nativeWebWindow, message);
}
public event EventHandler<string> OnWebMessageReceived;
private void WriteTitleField(string value)
{
if (string.IsNullOrEmpty(value))
{
value = "Untitled window";
}
// Due to Linux/Gtk platform limitations, the window title has to be no more than 31 chars
if (value.Length > 31 && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
value = value.Substring(0, 31);
}
_title = value;
}
private void ReceiveWebMessage(string message)
{
OnWebMessageReceived?.Invoke(this, message);
}
private void AddCustomScheme(string scheme, ResolveWebResourceDelegate requestHandler)
{
// Because of WKWebView limitations, this can only be called during the constructor
// before the first call to Show. To enforce this, it's private and is only called
// in response to the constructor options.
OnWebResourceRequestedCallback callback = (string url, out int numBytes, out string contentType) =>
{
var responseStream = requestHandler(url, out contentType);
if (responseStream == null)
{
// Webview should pass through request to normal handlers (e.g., network)
// or handle as 404 otherwise
numBytes = 0;
return default;
}
// Read the stream into memory and serve the bytes
// In the future, it would be possible to pass the stream through into C++
using (responseStream)
using (var ms = new MemoryStream())
{
responseStream.CopyTo(ms);
numBytes = (int)ms.Position;
var buffer = Marshal.AllocHGlobal(numBytes);
Marshal.Copy(ms.GetBuffer(), 0, buffer, numBytes);
_hGlobalToFree.Add(buffer);
return buffer;
}
};
_gcHandlesToFree.Add(GCHandle.Alloc(callback));
WebWindow_AddCustomScheme(_nativeWebWindow, scheme, callback);
}
private bool _resizable = true;
public bool Resizable
{
get => _resizable;
set
{
if (_resizable != value)
{
_resizable = value;
Invoke(() => WebWindow_SetResizable(_nativeWebWindow, _resizable ? 1 : 0));
}
}
}
private int _width;
private int _height;
private void GetSize() => WebWindow_GetSize(_nativeWebWindow, out _width, out _height);
private void SetSize() => Invoke(() => WebWindow_SetSize(_nativeWebWindow, _width, _height));
public int Width
{
get
{
GetSize();
return _width;
}
set
{
GetSize();
if (_width != value)
{
_width = value;
SetSize();
}
}
}
public int Height
{
get
{
GetSize();
return _height;
}
set
{
GetSize();
if (_height != value)
{
_height = value;
SetSize();
}
}
}
public Size Size
{
get
{
GetSize();
return new Size(_width, _height);
}
set
{
if (_width != value.Width || _height != value.Height)
{
_width = value.Width;
_height = value.Height;
SetSize();
}
}
}
private void OnResized(int width, int height) => SizeChanged?.Invoke(this, new Size(width, height));
public event EventHandler<Size> SizeChanged;
private int _x;
private int _y;
private void GetPosition() => WebWindow_GetPosition(_nativeWebWindow, out _x, out _y);
private void SetPosition() => Invoke(() => WebWindow_SetPosition(_nativeWebWindow, _x, _y));
public int Left
{
get
{
GetPosition();
return _x;
}
set
{
GetPosition();
if (_x != value)
{
_x = value;
SetPosition();
}
}
}
public int Top
{
get
{
GetPosition();
return _y;
}
set
{
GetPosition();
if (_y != value)
{
_y = value;
SetPosition();
}
}
}
public Point Location
{
get
{
GetPosition();
return new Point(_x, _y);
}
set
{
if (_x != value.X || _y != value.Y)
{
_x = value.X;
_y = value.Y;
SetPosition();
}
}
}
private void OnMoved(int x, int y) => LocationChanged?.Invoke(this, new Point(x, y));
public event EventHandler<Point> LocationChanged;
public IReadOnlyList<Monitor> Monitors
{
get
{
List<Monitor> monitors = new List<Monitor>();
int callback(in NativeMonitor monitor)
{
monitors.Add(new Monitor(monitor));
return 1;
}
WebWindow_GetAllMonitors(_nativeWebWindow, callback);
return monitors;
}
}
public uint ScreenDpi => WebWindow_GetScreenDpi(_nativeWebWindow);
private bool _topmost = false;
public bool Topmost
{
get => _topmost;
set
{
if (_topmost != value)
{
_topmost = value;
Invoke(() => WebWindow_SetTopmost(_nativeWebWindow, _topmost ? 1 : 0));
}
}
}
public void SetIconFile(string filename) => WebWindow_SetIconFile(_nativeWebWindow, Path.GetFullPath(filename));
}
}
| 38.450526 | 229 | 0.587276 | [
"Apache-2.0"
] | Berrysoft/WebWindow | src/WebWindow/WebWindow.cs | 18,266 | C# |
using System.Text.Json.Serialization;
namespace HPlusSport.API.Models
{
public class Product
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Sku { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public decimal Price { get; set; }
public bool IsAvailable { get; set; }
public Guid CategoryId { get; set; } = Guid.NewGuid();
[JsonIgnore]
public virtual Category? Category { get; set; }
}
} | 22.384615 | 63 | 0.592784 | [
"MIT"
] | vishipayyallore/mini-projects-2022 | .NET6WebAPIs/hplussport/Source/HPlusSport.API/Models/Product.cs | 584 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementFieldToMatchSingleQueryArgument
{
/// <summary>
/// The name of the query header to inspect. This setting must be provided as lower case characters.
/// </summary>
public readonly string Name;
[OutputConstructor]
private WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementFieldToMatchSingleQueryArgument(string name)
{
Name = name;
}
}
}
| 34.071429 | 154 | 0.735849 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementByteMatchStatementFieldToMatchSingleQueryArgument.cs | 954 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Collections_Generic_List_1_Object_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Collections.Generic.List<System.Object>);
args = new Type[]{};
method = type.GetMethod("get_Count", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_Count_0);
args = new Type[]{typeof(System.Int32)};
method = type.GetMethod("get_Item", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_Item_1);
}
static StackObject* get_Count_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Collections.Generic.List<System.Object> instance_of_this_method = (System.Collections.Generic.List<System.Object>)typeof(System.Collections.Generic.List<System.Object>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.Count;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* get_Item_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Int32 @index = ptr_of_this_method->Value;
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Collections.Generic.List<System.Object> instance_of_this_method = (System.Collections.Generic.List<System.Object>)typeof(System.Collections.Generic.List<System.Object>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method[index];
object obj_result_of_this_method = result_of_this_method;
if(obj_result_of_this_method is CrossBindingAdaptorType)
{
return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance, true);
}
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method, true);
}
}
}
| 43.455696 | 264 | 0.699097 | [
"MIT"
] | AlunWorker/ET- | Unity/Assets/ThirdParty/ILRuntime/Generated/System_Collections_Generic_List_1_Object_Binding.cs | 3,433 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
using System.Text;
/**
* Implementation for Excel function OFFSet()<p/>
*
* OFFSet returns an area reference that Is a specified number of rows and columns from a
* reference cell or area.<p/>
*
* <b>Syntax</b>:<br/>
* <b>OFFSet</b>(<b>reference</b>, <b>rows</b>, <b>cols</b>, height, width)<p/>
* <b>reference</b> Is the base reference.<br/>
* <b>rows</b> Is the number of rows up or down from the base reference.<br/>
* <b>cols</b> Is the number of columns left or right from the base reference.<br/>
* <b>height</b> (default same height as base reference) Is the row Count for the returned area reference.<br/>
* <b>width</b> (default same width as base reference) Is the column Count for the returned area reference.<br/>
*
* @author Josh Micich
*/
public class Offset : Function
{
// These values are specific to BIFF8
private static int LAST_VALID_ROW_INDEX = 0xFFFF;
private static int LAST_VALID_COLUMN_INDEX = 0xFF;
/**
* Exceptions are used within this class to help simplify flow control when error conditions
* are enCountered
*/
[Serializable]
private class EvalEx : Exception
{
private ErrorEval _error;
public EvalEx(ErrorEval error)
{
_error = error;
}
public ErrorEval GetError()
{
return _error;
}
}
/**
* A one dimensional base + offset. Represents either a row range or a column range.
* Two instances of this class toGether specify an area range.
*/
/* package */
public class LinearOffsetRange
{
private int _offset;
private int _Length;
public LinearOffsetRange(int offset, int length)
{
if (length == 0)
{
// handled that condition much earlier
throw new ArgumentException("Length may not be zero");
}
_offset = offset;
_Length = length;
}
public short FirstIndex
{
get
{
return (short)_offset;
}
}
public short LastIndex
{
get
{
return (short)(_offset + _Length - 1);
}
}
/**
* Moves the range by the specified translation amount.<p/>
*
* This method also 'normalises' the range: Excel specifies that the width and height
* parameters (Length field here) cannot be negative. However, OFFSet() does produce
* sensible results in these cases. That behavior Is replicated here. <p/>
*
* @param translationAmount may be zero negative or positive
*
* @return the equivalent <c>LinearOffsetRange</c> with a positive Length, moved by the
* specified translationAmount.
*/
public LinearOffsetRange NormaliseAndTranslate(int translationAmount)
{
if (_Length > 0)
{
if (translationAmount == 0)
{
return this;
}
return new LinearOffsetRange(translationAmount + _offset, _Length);
}
return new LinearOffsetRange(translationAmount + _offset + _Length + 1, -_Length);
}
public bool IsOutOfBounds(int lowValidIx, int highValidIx)
{
if (_offset < lowValidIx)
{
return true;
}
if (LastIndex > highValidIx)
{
return true;
}
return false;
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(_offset).Append("...").Append(LastIndex);
sb.Append("]");
return sb.ToString();
}
}
/**
* Encapsulates either an area or cell reference which may be 2d or 3d.
*/
private class BaseRef
{
private const int INVALID_SHEET_INDEX = -1;
private int _firstRowIndex;
private int _firstColumnIndex;
private int _width;
private int _height;
private RefEval _refEval;
private AreaEval _areaEval;
public BaseRef(RefEval re)
{
_refEval = re;
_areaEval = null;
_firstRowIndex = re.Row;
_firstColumnIndex = re.Column;
_height = 1;
_width = 1;
}
public BaseRef(AreaEval ae)
{
_refEval = null;
_areaEval = ae;
_firstRowIndex = ae.FirstRow;
_firstColumnIndex = ae.FirstColumn;
_height = ae.LastRow - ae.FirstRow + 1;
_width = ae.LastColumn - ae.FirstColumn + 1;
}
public int Width
{
get
{
return _width;
}
}
public int Height
{
get
{
return _height;
}
}
public int FirstRowIndex
{
get
{
return _firstRowIndex;
}
}
public int FirstColumnIndex
{
get
{
return _firstColumnIndex;
}
}
public AreaEval Offset(int relFirstRowIx, int relLastRowIx,int relFirstColIx, int relLastColIx)
{
if (_refEval == null)
{
return _areaEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
}
return _refEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
}
}
public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol)
{
if (args.Length < 3 || args.Length > 5)
{
return ErrorEval.VALUE_INVALID;
}
try
{
BaseRef baseRef = EvaluateBaseRef(args[0]);
int rowOffset = EvaluateIntArg(args[1], srcCellRow, srcCellCol);
int columnOffset = EvaluateIntArg(args[2], srcCellRow, srcCellCol);
int height = baseRef.Height;
int width = baseRef.Width;
switch (args.Length)
{
case 5:
width = EvaluateIntArg(args[4], srcCellRow, srcCellCol);
break;
case 4:
height = EvaluateIntArg(args[3], srcCellRow, srcCellCol);
break;
}
// Zero height or width raises #REF! error
if (height == 0 || width == 0)
{
return ErrorEval.REF_INVALID;
}
LinearOffsetRange rowOffsetRange = new LinearOffsetRange(rowOffset, height);
LinearOffsetRange colOffsetRange = new LinearOffsetRange(columnOffset, width);
return CreateOffset(baseRef, rowOffsetRange, colOffsetRange);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
private static AreaEval CreateOffset(BaseRef baseRef,
LinearOffsetRange orRow, LinearOffsetRange orCol)
{
LinearOffsetRange absRows = orRow.NormaliseAndTranslate(baseRef.FirstRowIndex);
LinearOffsetRange absCols = orCol.NormaliseAndTranslate(baseRef.FirstColumnIndex);
if (absRows.IsOutOfBounds(0, LAST_VALID_ROW_INDEX))
{
throw new EvaluationException(ErrorEval.REF_INVALID);
}
if (absCols.IsOutOfBounds(0, LAST_VALID_COLUMN_INDEX))
{
throw new EvaluationException(ErrorEval.REF_INVALID);
}
return baseRef.Offset(orRow.FirstIndex, orRow.LastIndex, orCol.FirstIndex, orCol.LastIndex);
}
private static BaseRef EvaluateBaseRef(ValueEval eval)
{
if (eval is RefEval)
{
return new BaseRef((RefEval)eval);
}
if (eval is AreaEval)
{
return new BaseRef((AreaEval)eval);
}
if (eval is ErrorEval)
{
throw new EvalEx((ErrorEval)eval);
}
throw new EvalEx(ErrorEval.VALUE_INVALID);
}
/**
* OFFSet's numeric arguments (2..5) have similar Processing rules
*/
public static int EvaluateIntArg(ValueEval eval, int srcCellRow, int srcCellCol)
{
double d = EvaluateDoubleArg(eval, srcCellRow, srcCellCol);
return ConvertDoubleToInt(d);
}
/**
* Fractional values are silently truncated by Excel.
* Truncation Is toward negative infinity.
*/
/* package */
public static int ConvertDoubleToInt(double d)
{
// Note - the standard java type conversion from double to int truncates toward zero.
// but Math.floor() truncates toward negative infinity
return (int)Math.Floor(d);
}
private static double EvaluateDoubleArg(ValueEval eval, int srcCellRow, int srcCellCol)
{
ValueEval ve = OperandResolver.GetSingleValue(eval, srcCellRow, srcCellCol);
if (ve is NumericValueEval)
{
return ((NumericValueEval)ve).NumberValue;
}
if (ve is StringEval)
{
StringEval se = (StringEval)ve;
double d = OperandResolver.ParseDouble(se.StringValue);
if (double.IsNaN(d))
{
throw new EvalEx(ErrorEval.VALUE_INVALID);
}
return d;
}
if (ve is BoolEval)
{
// in the context of OFFSet, bools resolve to 0 and 1.
if (((BoolEval)ve).BooleanValue)
{
return 1;
}
return 0;
}
throw new Exception("Unexpected eval type (" + ve.GetType().Name + ")");
}
}
} | 34.473389 | 117 | 0.495409 | [
"Apache-2.0"
] | sunshinele/npoi | main/SS/Formula/Functions/Offset.cs | 12,307 | C# |
// -----------------------------------------------------------------------
// <copyright file="UserRoleInputDto.cs" company="Hybrid开源团队">
// Copyright (c) 2014-2018 Hybrid. All rights reserved.
// </copyright>
// <site>https://www.lxking.cn</site>
// <last-editor>ArcherTrister</last-editor>
// <last-date>2018-06-27 4:44</last-date>
// -----------------------------------------------------------------------
using Hybrid.Identity.Dtos;
using Hybrid.Mapping;
using LeXun.Demo.Identity.Entities;
using System;
namespace LeXun.Demo.Identity.Dtos
{
/// <summary>
/// 输入DTO:用户角色信息
/// </summary>
[MapTo(typeof(UserRole))]
public class UserRoleInputDto : UserRoleInputDtoBase<Guid, int, int>
{ }
} | 29.24 | 75 | 0.540356 | [
"Apache-2.0"
] | ArcherTrister/ESoftor | samples/web/IdentityServer4/LeXun.Demo.Core/Identity/Dtos/UserRoleInputDto.cs | 759 | C# |
namespace ParticleEditor
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.glControl1 = new OpenTK.GLControl();
this.featureCollection = new System.Windows.Forms.GroupBox();
this.featureFlowLayout = new System.Windows.Forms.FlowLayoutPanel();
this.particleSystemPropGrid = new System.Windows.Forms.PropertyGrid();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.featureCollection.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1532, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadToolStripMenuItem,
this.saveToolStripMenuItem,
this.exportToolStripMenuItem,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// loadToolStripMenuItem
//
this.loadToolStripMenuItem.Name = "loadToolStripMenuItem";
this.loadToolStripMenuItem.Size = new System.Drawing.Size(107, 22);
this.loadToolStripMenuItem.Text = "Load";
this.loadToolStripMenuItem.Click += new System.EventHandler(this.loadToolStripMenuItem_Click);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(107, 22);
this.saveToolStripMenuItem.Text = "Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// exportToolStripMenuItem
//
this.exportToolStripMenuItem.Name = "exportToolStripMenuItem";
this.exportToolStripMenuItem.Size = new System.Drawing.Size(107, 22);
this.exportToolStripMenuItem.Text = "Export";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(107, 22);
this.exitToolStripMenuItem.Text = "Exit";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "Edit";
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Size = new System.Drawing.Size(102, 22);
this.copyToolStripMenuItem.Text = "Copy";
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(102, 22);
this.pasteToolStripMenuItem.Text = "Paste";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem,
this.aboutToolStripMenuItem1});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(107, 22);
this.aboutToolStripMenuItem.Text = "Help";
//
// aboutToolStripMenuItem1
//
this.aboutToolStripMenuItem1.Name = "aboutToolStripMenuItem1";
this.aboutToolStripMenuItem1.Size = new System.Drawing.Size(107, 22);
this.aboutToolStripMenuItem1.Text = "About";
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 24);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.glControl1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.featureCollection);
this.splitContainer1.Panel2.Controls.Add(this.particleSystemPropGrid);
this.splitContainer1.Size = new System.Drawing.Size(1532, 732);
this.splitContainer1.SplitterDistance = 1242;
this.splitContainer1.TabIndex = 1;
//
// glControl1
//
this.glControl1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.glControl1.BackColor = System.Drawing.Color.Black;
this.glControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.glControl1.Location = new System.Drawing.Point(0, 0);
this.glControl1.Name = "glControl1";
this.glControl1.Size = new System.Drawing.Size(1242, 732);
this.glControl1.TabIndex = 0;
this.glControl1.VSync = false;
this.glControl1.Load += new System.EventHandler(this.glControl1_Load);
this.glControl1.Paint += new System.Windows.Forms.PaintEventHandler(this.glControl1_Paint);
this.glControl1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.glControl1_KeyDown);
this.glControl1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.glControl1_KeyUp);
this.glControl1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.glControl1_MouseDown);
this.glControl1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.glControl1_MouseMove);
this.glControl1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.glControl1_MouseUp);
this.glControl1.Resize += new System.EventHandler(this.glControl1_Resize);
//
// featureCollection
//
this.featureCollection.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.featureCollection.Controls.Add(this.featureFlowLayout);
this.featureCollection.Location = new System.Drawing.Point(3, 302);
this.featureCollection.Name = "featureCollection";
this.featureCollection.Size = new System.Drawing.Size(283, 427);
this.featureCollection.TabIndex = 2;
this.featureCollection.TabStop = false;
this.featureCollection.Text = "Features";
//
// featureFlowLayout
//
this.featureFlowLayout.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.featureFlowLayout.AutoScroll = true;
this.featureFlowLayout.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.featureFlowLayout.Location = new System.Drawing.Point(3, 16);
this.featureFlowLayout.Name = "featureFlowLayout";
this.featureFlowLayout.Size = new System.Drawing.Size(277, 408);
this.featureFlowLayout.TabIndex = 0;
this.featureFlowLayout.WrapContents = false;
//
// particleSystemPropGrid
//
this.particleSystemPropGrid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.particleSystemPropGrid.Location = new System.Drawing.Point(2, 3);
this.particleSystemPropGrid.Name = "particleSystemPropGrid";
this.particleSystemPropGrid.Size = new System.Drawing.Size(281, 275);
this.particleSystemPropGrid.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1532, 756);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Form1";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.featureCollection.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.PropertyGrid particleSystemPropGrid;
private System.Windows.Forms.GroupBox featureCollection;
private System.Windows.Forms.FlowLayoutPanel featureFlowLayout;
private OpenTK.GLControl glControl1;
}
}
| 50.049618 | 165 | 0.67597 | [
"MIT"
] | bholcomb/gameEngine | src/particleEditor/Form1.Designer.cs | 13,115 | C# |
// Copyright (c) Zuzana Dankovcikova. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using BugHunter.Analyzers.CmsApiReplacementRules.Analyzers;
using BugHunter.Analyzers.CmsApiReplacementRules.CodeFixes;
using BugHunter.Analyzers.Test.CmsApiReplacementsTests.Constants;
using BugHunter.Core.Constants;
using BugHunter.TestUtils;
using BugHunter.TestUtils.Helpers;
using BugHunter.TestUtils.Verifiers;
using Microsoft.CodeAnalysis;
using NUnit.Framework;
namespace BugHunter.Analyzers.Test.CmsApiReplacementsTests
{
[TestFixture]
public class HttpResponseRedirectTest : CodeFixVerifier<HttpResponseRedirectAnalyzer, HttpResponseRedirectCodeFixProvider>
{
protected override MetadataReference[] AdditionalReferences
=> ReferencesHelper.CMSBasicReferences.Union(new[] { ReferencesHelper.SystemWebReference }).ToArray();
[Test]
public void EmptyInput_NoDiagnostic()
{
var test = string.Empty;
VerifyCSharpDiagnostic(test);
}
[TestCase(@"new System.Web.HttpResponse(null)", "Redirect", 0)]
[TestCase(@"new System.Web.HttpResponse(null)", "LocalRedirect", 1)]
[TestCase(@"new System.Web.HttpResponseWrapper(new System.Web.HttpResponse(null))", "Redirect", 0)]
[TestCase(@"new System.Web.HttpResponseWrapper(new System.Web.HttpResponse(null))", "LocalRedirect", 1)]
public void InputWithIncident_SipleMemberAccess_SurfacesDiagnostic(string instance, string codeFix, int codeFixNumber)
{
var test = $@"
namespace SampleTestProject.CsSamples
{{
public class SampleClass
{{
public void SampleMethod()
{{
var r = {instance};
r.Redirect(""url"");
}}
}}
}}";
var expectedDiagnostic = CreateDiagnosticResult(@"r.Redirect(""url"")").WithLocation(9, 13);
VerifyCSharpDiagnostic(test, expectedDiagnostic);
var expectedFix = $@"using CMS.Helpers;
namespace SampleTestProject.CsSamples
{{
public class SampleClass
{{
public void SampleMethod()
{{
var r = {instance};
UrlHelper.{codeFix}(""url"");
}}
}}
}}";
VerifyCSharpFix(test, expectedFix, codeFixNumber);
}
[TestCase(@"new System.Web.HttpResponse(null)", "Redirect", 0)]
[TestCase(@"new System.Web.HttpResponse(null)", "LocalRedirect", 1)]
[TestCase(@"new System.Web.HttpResponseWrapper(new System.Web.HttpResponse(null))", "Redirect", 0)]
[TestCase(@"new System.Web.HttpResponseWrapper(new System.Web.HttpResponse(null))", "LocalRedirect", 1)]
public void InputWithIncident_ChainedMemberAccess_SurfacesDiagnostic(string instance, string codeFix, int codeFixNumber)
{
var test = $@"
namespace SampleTestProject.CsSamples
{{
public class SampleClass
{{
public void SampleMethod()
{{
{instance}.Redirect(""url"");
}}
}}
}}";
var expectedDiagnostic = CreateDiagnosticResult($@"{instance}.Redirect(""url"")").WithLocation(8, 13);
VerifyCSharpDiagnostic(test, expectedDiagnostic);
var expectedFix = $@"using CMS.Helpers;
namespace SampleTestProject.CsSamples
{{
public class SampleClass
{{
public void SampleMethod()
{{
UrlHelper.{codeFix}(""url"");
}}
}}
}}";
VerifyCSharpFix(test, expectedFix, codeFixNumber);
}
[TestCase(@"new System.Web.HttpResponse(null)")]
[TestCase(@"new System.Web.HttpResponse(null)")]
[TestCase(@"new System.Web.HttpResponseWrapper(new System.Web.HttpResponse(null))")]
[TestCase(@"new System.Web.HttpResponseWrapper(new System.Web.HttpResponse(null))")]
public void InputWithIncident_ConditionalAccess_SurfacesDiagnostic_NoCodeFix(string instance)
{
var test = $@"
namespace SampleTestProject.CsSamples
{{
public class SampleClass
{{
public void SampleMethod()
{{
var r = {instance};
r?.Redirect(""url"");
}}
}}
}}";
var expectedDiagnostic = CreateDiagnosticResult(@".Redirect(""url"")").WithLocation(9, 15);
VerifyCSharpDiagnostic(test, expectedDiagnostic);
VerifyCSharpFix(test, test);
}
private static DiagnosticResult CreateDiagnosticResult(params object[] messageArgs)
=> new DiagnosticResult
{
Id = DiagnosticIds.HttpResponseRedirect,
Message = string.Format(MessagesConstants.MessageNoSuggestion, messageArgs),
Severity = DiagnosticSeverity.Warning,
};
}
} | 34.535714 | 128 | 0.651499 | [
"MIT"
] | Suzii/thesis-roslyn | test/BugHunter.Analyzers.Test/CmsApiReplacementsTests/HttpResponseRedirectTest.cs | 4,837 | C# |
using System;
using System.IO;
using System.Data;
using ProtCidSettingsLib;
using System.Collections.Generic;
using DbLib;
using AuxFuncLib;
using PfamLib.Settings;
using InterfaceClusterLib.DomainInterfaces.PfamPeptide;
using InterfaceClusterLib.DomainInterfaces.PfamLigand;
using InterfaceClusterLib.DomainInterfaces.PfamNetwork;
using CrystalInterfaceLib.Settings;
namespace InterfaceClusterLib.DomainInterfaces
{
/// <summary>
/// Summary description for DomainInterfaceBuilder.
/// </summary>
public class DomainInterfaceBuilder
{
#region member variables
public static StreamWriter nonAlignDomainsWriter = null;
private PfamPeptideInterfaceBuilder pepInterfaceBuilder = new PfamPeptideInterfaceBuilder();
private PfamLigandInteractionBuilder ligandInteractBuilder = new PfamLigandInteractionBuilder();
#endregion
public DomainInterfaceBuilder()
{
}
#region build
/// <summary>
///
/// </summary>
/// <param name="stepNum"></param>
public void BuildDomainInterfaces(int stepNum)
{
InitializeThread();
DomainInterfaceTables.InitializeTables();
ProtCidSettings.progressInfo.Reset();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Retrieving domain-domain interactions.");
/* ProtCidSettings.progressInfo.progStrQueue.Enqueue("Creating database tables.");
DomainInterfaceTables.InitializeDbTables();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Done.");
*/
switch (stepNum)
{
case 1:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Detecting domain-domain interactions from cryst chain interfaces.");
DomainClassifier domainClassifier = new DomainClassifier();
domainClassifier.RetrieveDomainInterfaces();
ProtCidSettings.progressInfo.currentOperationIndex++;
// goto case 1;
break;
case 2:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Write domain interface files.");
DomainInterfaceWriter domainInterfaceWriter = new DomainInterfaceWriter();
domainInterfaceWriter.WriteDomainInterfaceFiles ();
// domainInterfaceWriter.UpdateDomainInterfaceFiles();
// domainInterfaceWriter.WriteMultiChainDomainInterfaces();
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Calculate SAs of domain interface files.");
DomainInterfaceSA interfaceSa = new DomainInterfaceSA();
// interfaceSa.UpdateDomainInterfaceSAs();
interfaceSa.CalculateDomainInterfaceSAs();
ProtCidSettings.progressInfo.currentOperationIndex++;
// goto case 2;
break;
case 3:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Comparing domain interfaces.");
PfamDomainInterfaceComp domainComp = new PfamDomainInterfaceComp();
domainComp.CompareDomainInterfaces();
/* domainComp.SynchronizeDomainChainInterfaceComp();
* domainComp.CompareSpecificDomainInterfaces ();
* domainComp.UpdateMultiChainDomainInterfaces();
*/
ProtCidSettings.progressInfo.currentOperationIndex++;
break;
case 4:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Comparing entry domain interfaces.");
DomainInterfaceBuComp.CrystBuDomainInterfaceComp domainInterfaceComp =
new InterfaceClusterLib.DomainInterfaces.DomainInterfaceBuComp.CrystBuDomainInterfaceComp();
// int[] relSeqIds = {10515 };
// domainInterfaceComp.UpdateCrystBuDomainInterfaceComp(relSeqIds);
domainInterfaceComp.CompareCrystBuDomainInterfaces();
ProtCidSettings.progressInfo.currentOperationIndex++;
break;
case 5:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Cluster domain interfaces.");
DomainInterfaceCluster interfaceCluster = new DomainInterfaceCluster();
int[] relSeqIds = { 2 };
interfaceCluster.UpdateDomainInterfaceClusters(relSeqIds);
// interfaceCluster.ClusterDomainInterfaces();
// interfaceCluster.ClusterLeftRelations();
break;
// goto case 4;
case 6:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Print Domain Interface Cluster Info.");
DomainClusterStat clusterStat = new DomainClusterStat();
int[] updateRelSeqIds = { 2 };
clusterStat.UpdateDomainClusterInfo(updateRelSeqIds);
// clusterStat.PrintDomainClusterInfo();
// clusterStat.PrintDomainDbSumInfo("PfamDomain");
// clusterStat.AddNumCFsToIPfamInPdbMetaData();
// clusterStat.PrintPartialDomainClusterInfo();
// clusterStat.GetPfamDomainSumInfo();
/* DomainInterfaceStatInfo statInfo = new DomainInterfaceStatInfo();
// statInfo.PrintPepInteractingHmmSites();
// statInfo.GetPfamPepInterfaceClusterInfo();
// statInfo.PrintPepLigandHmmSites ();
statInfo.PrintPfamDomainRelationInfo();
// statInfo.GetGenAsymChainDomainInterfaces();*/
break;
// goto case 7;
case 7:
PfamClusterFilesCompress clusterFileCompress = new PfamClusterFilesCompress();
clusterFileCompress.CompressPfamClusterChainInterfaceFiles();
clusterFileCompress.RetrieveCrystInterfaceFilesNotInClusters(true);
DomainSeqFasta seqFasta = new DomainSeqFasta();
seqFasta.PrintClusterDomainSequences();
DomainInterfaceImageGen imageGen = new DomainInterfaceImageGen();
imageGen.GenerateDomainInterfaceImages();
PfamRelNetwork pfamNetWriter = new PfamRelNetwork();
pfamNetWriter.GeneratePfamNetworkGraphmlFiles();
// build the unp-unp interaction table based on pdb domain interfaces
UnpInteractionStr unpInteract = new UnpInteractionStr ();
unpInteract.BuildUnpInteractionNetTable();
break;
case 8: // about peptide interfaces
PfamPeptideInterfaces pepInterfaces = new PfamPeptideInterfaces();
pepInterfaceBuilder.BuildPfamPeptideInterfaces();
break;
case 9:
// ligandInteractBuilder.AddClusterInfoToPfamDomainAlign();
ligandInteractBuilder.BuildPfamLigandInteractions();
break;
default:
break;
}
ProtCidSettings.logWriter.Close();
ProtCidSettings.progressInfo.threadFinished = true;
}
#endregion
#region update
/// <summary>
/// update domain interfaces for same version of Pfam
/// </summary>
public void UpdateDomainInterfaces()
{
InitializeThread();
ProtCidSettings.logWriter.WriteLine(DateTime.Today.ToShortDateString());
ProtCidSettings.logWriter.WriteLine("Updating Pfam domain interface clusters.");
DomainInterfaceTables.InitializeTables();
ProtCidSettings.progressInfo.Reset();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Pfam domain-domain interface info.");
string[] updateEntries = GetUpdateEntries();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain interface database");
UpdateDomainInterfacesDb(updateEntries);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Pfam-Peptide interactions");
PfamPepInterfaceWriter pepInterfaceWriter = new PfamPepInterfaceWriter();
pepInterfaceBuilder.UpdatePfamPeptideInteractions(updateEntries);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Pfam-ligand interactions");
ligandInteractBuilder.UpdatePfamLigandInteractions(updateEntries);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update peptide-chain comparison");
pepInterfaceBuilder.UpdatePfamPepChainComparison(updateEntries);
ProtCidSettings.logWriter.Close();
ProtCidSettings.progressInfo.threadFinished = true;
}
/// <summary>
///
/// </summary>
public void UpdateDomainInterfaces(int step)
{
InitializeThread();
ProtCidSettings.logWriter.WriteLine(DateTime.Today.ToShortDateString());
ProtCidSettings.logWriter.WriteLine("Updating Pfam domain interface clusters.");
DomainInterfaceTables.InitializeTables();
ProtCidSettings.progressInfo.Reset();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Pfam domain-domain interface info.");
// string[] updateEntries = GetUpdateEntries();
// for update peptide/ligands
// string[] updateEntries = GetOtherUpdateEntries(@"D:\Qifang\ProjectData\DbProjectData\PDB\updateEntries_ligandsDif.txt");
// string[] updateEntries = GetOtherUpdateEntries(@"D:\Qifang\ProjectData\DbProjectData\PDB\MissingChainPepEntries.txt");
// string[] updateEntries = GetMissingDomainInterfaceEntries();
string[] updateEntries = {"2gs0" };
switch (step)
{
case 1:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain interface database");
UpdateDomainInterfacesDb(updateEntries);
/* int[] updateRelSeqIds = { 10348 };
PfamClusterFilesCompress clusterFileCompress = new PfamClusterFilesCompress();
clusterFileCompress.UpdateRelationClusterChainInterfaceFiles(updateRelSeqIds);
string updateRelEntryFile = "UpdateRelationEntries.txt";
UpdateDomainInterfacesDb(updateRelEntryFile);
//
// updateEntries = GetOtherUpdateEntries();
updateEntries = new string[1];
updateEntries[0] = "3mtj";
DomainInterfaceBuComp.CrystBuDomainInterfaceComp domainInterfaceComp =
new InterfaceClusterLib.DomainInterfaces.DomainInterfaceBuComp.CrystBuDomainInterfaceComp();
domainInterfaceComp.UpdateCrystBuDomainInterfaceComp(updateEntries);
DomainClusterStat clusterStat = new DomainClusterStat();
clusterStat.UpdateBACompInfo();
DomainSeqFasta seqFasta = new DomainSeqFasta();
int[] updateRelSeqIds = { 2986};
seqFasta.UpdateClusterDomainSequences(updateRelSeqIds);*/
break;
case 2:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Pfam-Peptide interactions");
// pepInterfaceBuilder.UpdatePfamPeptideInteractions(updateEntries);
pepInterfaceBuilder.UpdateSomePfamPeptideInteractionsDebug();
break;
case 3:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Pfam-ligand interactions");
ligandInteractBuilder.UpdatePfamLigandInteractions(updateEntries);
/* ligandInteractBuilder.DebugPfamLigandInteractions();
ligandInteractBuilder.UpdatePfamLigandInteractions(updateDnaEntries, updateEntries);
PfamDomainFileCompress domainCompress = new PfamDomainFileCompress();
domainCompress.CompressPfamDomainFiles ();*/
ProtCidSettings.logWriter.Flush();
break;
case 4:
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update peptide-chain comparison");
pepInterfaceBuilder.UpdatePfamPepChainComparison(updateEntries);
break;
default:
break;
}
ProtCidSettings.logWriter.Close();
ProtCidSettings.progressInfo.threadFinished = true;
}
/// <summary>
///
/// </summary>
public void UpdateDomainInterfacesDb(string[] updateEntries)
{
Dictionary<int, string[]> updateRelEntryDict = new Dictionary<int, string[]>();
string updateRelEntryFile = "UpdateRelationEntries_missing.txt";
// string updateRelEntryFile = "NoCompRepHomoEntriesRel1.txt";
string line = "";
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Detecting domain-domain interactions from cryst chain interfaces.");
ProtCidSettings.logWriter.WriteLine("Detecting domain-domain interactions from cryst chain interfaces.");
DomainClassifier domainClassifier = new DomainClassifier();
updateRelEntryDict = domainClassifier.UpdateDomainInterfaces(updateEntries);
ProtCidSettings.progressInfo.currentOperationIndex++;
if (updateRelEntryDict.Count == 0)
{
if (File.Exists(updateRelEntryFile))
{
List<string> updateEntryList = new List<string>();
StreamReader dataReader = new StreamReader(updateRelEntryFile);
while ((line = dataReader.ReadLine()) != null)
{
string[] fields = line.Split(' ');
string[] entries = new string[fields.Length - 1];
Array.Copy(fields, 1, entries, 0, entries.Length);
updateRelEntryDict.Add(Convert.ToInt32(fields[0]), entries);
for (int i = 1; i < fields.Length; i++)
{
if (!updateEntryList.Contains(fields[i]))
{
updateEntryList.Add(fields[i]);
}
}
}
dataReader.Close();
if (updateEntries == null)
{
updateEntries = updateEntryList.ToArray();
}
}
}
if (updateRelEntryDict.Count == 0)
{
ProtCidSettings.progressInfo.progStrQueue.Enqueue("No relations need to be updated, program terminated, and return.");
return;
}
List<int> updateRelationList = new List<int>(updateRelEntryDict.Keys);
updateRelationList.Sort();
int[] updateRelSeqIds = updateRelationList.ToArray();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Updating domain interface files.");
ProtCidSettings.logWriter.WriteLine("Updating domain interface files.");
DomainInterfaceWriter domainInterfaceFileGen = new DomainInterfaceWriter();
domainInterfaceFileGen.UpdateDomainInterfaceFiles(updateRelEntryDict);
// domainInterfaceFileGen.WriteMissingDomainInterfaceFiles();
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update the surface areas for the domain interfaces.");
ProtCidSettings.logWriter.WriteLine("Update the surfacea areas for the domain interfaces");
DomainInterfaceSA interfaceSa = new DomainInterfaceSA();
interfaceSa.UpdateDomainInterfaceSAs(updateEntries);
// interfaceSa.CalculateDomainInterfaceSAs ();
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Updating the comparison of domain interfaces in each relation.");
ProtCidSettings.logWriter.WriteLine("Updating the comparison of domain interfaces in each relation.");
PfamDomainInterfaceComp domainComp = new PfamDomainInterfaceComp();
domainComp.UpdateEntryDomainInterfaceComp(updateRelEntryDict);
// domainComp.SynchronizeDomainChainInterfaceComp(updateEntries);
// domainComp.CompareRepHomoEntryDomainInterfaces();
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Updating the comparison between cryst and BU entry domain interfaces.");
ProtCidSettings.logWriter.WriteLine("Updating the comparison between cryst and BU entry domain interfaces.");
DomainInterfaceBuComp.CrystBuDomainInterfaceComp domainInterfaceComp =
new InterfaceClusterLib.DomainInterfaces.DomainInterfaceBuComp.CrystBuDomainInterfaceComp();
domainInterfaceComp.UpdateCrystBuDomainInterfaceComp(updateEntries);
// string[] buUpdateEntries = GetOtherUpdateEntries(@"D:\Qifang\ProjectData\DbProjectData\PDB\newls-pdb_bucomp.txt");
// domainInterfaceComp.UpdateCrystBuDomainInterfaceComp(buUpdateEntries);
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain interface clusters.");
ProtCidSettings.logWriter.WriteLine("Update domain interface clusters.");
DomainInterfaceCluster domainInterfaceCluster = new DomainInterfaceCluster();
domainInterfaceCluster.UpdateDomainInterfaceClusters(updateRelSeqIds);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Domain Interface Cluster Info.");
ProtCidSettings.logWriter.WriteLine("Update Domain Interface Cluster Info.");
DomainClusterStat clusterStat = new DomainClusterStat();
clusterStat.UpdateDomainClusterInfo(updateRelEntryDict);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update cluster file compressing.");
ProtCidSettings.logWriter.WriteLine("Update compressing cluster interface files.");
PfamClusterFilesCompress clusterFileCompress = new PfamClusterFilesCompress();
clusterFileCompress.UpdateRelationClusterChainInterfaceFiles(updateRelSeqIds);
ProtCidSettings.logWriter.WriteLine("Copy interfaces not in any clusters");
clusterFileCompress.UpdateCrystInterfaceFilesNotInClusters(updateRelSeqIds, true);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain cluster interface images.");
ProtCidSettings.logWriter.WriteLine("Update domain cluster interface images");
DomainInterfaceImageGen imageGen = new DomainInterfaceImageGen();
imageGen.UpdateDomainInterfaceImages(updateRelSeqIds);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain cluster sequence files.");
ProtCidSettings.logWriter.WriteLine("Update domain cluster sequence files.");
DomainSeqFasta seqFasta = new DomainSeqFasta();
seqFasta.UpdateClusterDomainSequences(updateRelSeqIds);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Pfam-Pfam network files.");
ProtCidSettings.logWriter.WriteLine("Update Pfam-Pfam network files.");
PfamRelNetwork pfamNetWriter = new PfamRelNetwork();
pfamNetWriter.UpdatePfamNetworkGraphmlFiles(updateEntries);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Uniprot-uniprot domain interactions.");
ProtCidSettings.logWriter.WriteLine("Update Uniprot-uniprot domain interactions.");
// build the unp-unp interaction table based on pdb domain interfaces
UnpInteractionStr unpInteract = new UnpInteractionStr();
unpInteract.UpdateUnpInteractionNetTable(updateEntries);
ProtCidSettings.logWriter.Flush();
// update the domain alignment pymol session files
// move the code after clustering ligands on May 2, 2017, so the cluster info can be included in the Pfam-ligands file
/* ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update compiling domain alignment pymol sessions");
PfamDomainFileCompress domainFileCompress = new PfamDomainFileCompress();
domainFileCompress.UpdatePfamDomainFiles(updateEntries);*/
ProtCidSettings.logWriter.WriteLine("Done!");
ProtCidSettings.logWriter.Flush();
}
/// <summary>
///
/// </summary>
public void UpdateDomainInterfacesDb(string updateRelEntryFile)
{
Dictionary<int, string[]> updateRelEntryDict = new Dictionary<int,string[]> ();
string line = "";
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Detecting domain-domain interactions from cryst chain interfaces.");
ProtCidSettings.logWriter.WriteLine("Detecting domain-domain interactions from cryst chain interfaces.");
ProtCidSettings.progressInfo.currentOperationIndex++;
List<string> updateEntryList = new List<string>();
List<int> updateRelationList = new List<int>();
int relSeqId = 0;
if (File.Exists(updateRelEntryFile))
{
StreamReader dataReader = new StreamReader(updateRelEntryFile);
while ((line = dataReader.ReadLine()) != null)
{
string[] fields = line.Split(' ');
relSeqId = Convert.ToInt32(fields[0]);
string[] entries = new string[fields.Length - 1];
Array.Copy(fields, 1, entries, 0, entries.Length);
updateRelEntryDict.Add(relSeqId, entries);
updateRelationList.Add(relSeqId);
for (int i = 1; i < fields.Length; i++)
{
if (!updateEntryList.Contains(fields[i]))
{
updateEntryList.Add(fields[i]);
}
}
}
dataReader.Close();
}
string[] updateEntries = updateEntryList.ToArray();
if (updateRelEntryDict.Count == 0)
{
ProtCidSettings.progressInfo.progStrQueue.Enqueue("No relations need to be updated, program terminated, and return.");
return;
}
int[] updateRelSeqIds = updateRelationList.ToArray();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Updating domain interface files.");
ProtCidSettings.logWriter.WriteLine("Updating domain interface files.");
DomainInterfaceWriter domainInterfaceFileGen = new DomainInterfaceWriter();
domainInterfaceFileGen.UpdateDomainInterfaceFiles(updateRelEntryDict);
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update the surface areas for the domain interfaces.");
ProtCidSettings.logWriter.WriteLine("Update the surfacea areas for the domain interfaces");
DomainInterfaceSA interfaceSa = new DomainInterfaceSA();
interfaceSa.UpdateDomainInterfaceSAs(updateEntries);
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Updating the comparison of domain interfaces in each relation.");
ProtCidSettings.logWriter.WriteLine("Updating the comparison of domain interfaces in each relation.");
PfamDomainInterfaceComp domainComp = new PfamDomainInterfaceComp();
domainComp.UpdateEntryDomainInterfaceComp(updateRelEntryDict);
// domainComp.CompareRepHomoEntryDomainInterfaces();
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Updating the comparison between cryst and BU entry domain interfaces.");
ProtCidSettings.logWriter.WriteLine("Updating the comparison between cryst and BU entry domain interfaces.");
DomainInterfaceBuComp.CrystBuDomainInterfaceComp domainInterfaceComp =
new InterfaceClusterLib.DomainInterfaces.DomainInterfaceBuComp.CrystBuDomainInterfaceComp();
domainInterfaceComp.UpdateCrystBuDomainInterfaceComp(updateEntries);
ProtCidSettings.progressInfo.currentOperationIndex++;
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain interface clusters.");
ProtCidSettings.logWriter.WriteLine("Update domain interface clusters.");
DomainInterfaceCluster domainInterfaceCluster = new DomainInterfaceCluster();
domainInterfaceCluster.UpdateDomainInterfaceClusters(updateRelSeqIds);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Domain Interface Cluster Info.");
ProtCidSettings.logWriter.WriteLine("Update Domain Interface Cluster Info.");
DomainClusterStat clusterStat = new DomainClusterStat();
clusterStat.UpdateDomainClusterInfo(updateRelEntryDict);
// clusterStat.UpdateIPfamInPdbMetaData(updateRelSeqIds);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update cluster file compressing.");
ProtCidSettings.logWriter.WriteLine("Update compressing cluster interface files.");
PfamClusterFilesCompress clusterFileCompress = new PfamClusterFilesCompress();
clusterFileCompress.UpdateRelationClusterChainInterfaceFiles(updateRelSeqIds);
ProtCidSettings.logWriter.WriteLine("Copy interfaces not in any clusters");
clusterFileCompress.UpdateCrystInterfaceFilesNotInClusters(updateRelSeqIds, true);
ProtCidSettings.logWriter.Flush();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain cluster interface images.");
ProtCidSettings.logWriter.WriteLine("Update domain cluster interface images");
DomainInterfaceImageGen imageGen = new DomainInterfaceImageGen();
imageGen.UpdateDomainInterfaceImages(updateRelSeqIds);
ProtCidSettings.logWriter.Flush();
DomainSeqFasta seqFasta = new DomainSeqFasta();
seqFasta.UpdateClusterDomainSequences(updateRelSeqIds);
PfamRelNetwork pfamNetWriter = new PfamRelNetwork();
pfamNetWriter.UpdatePfamNetworkGraphmlFiles(updateEntries);
// build the unp-unp interaction table based on pdb domain interfaces
UnpInteractionStr unpInteract = new UnpInteractionStr();
unpInteract.UpdateUnpInteractionNetTable(updateEntries);
// update the domain alignment pymol session files
// move the code after clustering ligands on May 2, 2017, so the cluster info can be included in the Pfam-ligands file
/* ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update compiling domain alignment pymol sessions");
PfamDomainFileCompress domainFileCompress = new PfamDomainFileCompress();
domainFileCompress.UpdatePfamDomainFiles(updateEntries);*/
ProtCidSettings.logWriter.WriteLine("Done!");
ProtCidSettings.logWriter.Flush();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private Dictionary<string, string[]> ReadRelUpdateEntryHash()
{
string relUpdateEntryFile = "UpdatePepInteractPfamEntries.txt";
Dictionary<string, List<string>> relUpdateEntryHash = new Dictionary<string,List<string>> ();
ReadRelUpdateEntryHash(relUpdateEntryFile, ref relUpdateEntryHash);
relUpdateEntryFile = "UpdatePepInteractPfamEntries_missing.txt";
ReadRelUpdateEntryHash(relUpdateEntryFile, ref relUpdateEntryHash);
relUpdateEntryFile = "UpdatePepInteractPfamEntries0.txt";
ReadRelUpdateEntryHash(relUpdateEntryFile, ref relUpdateEntryHash);
List<string> pfamIdList = new List<string> (relUpdateEntryHash.Keys);
Dictionary<string, string[]> relUpdateEntriesHash = new Dictionary<string, string[]>();
foreach (string pfamId in pfamIdList)
{
relUpdateEntriesHash.Add (pfamId, relUpdateEntryHash[pfamId].ToArray ());
}
return relUpdateEntriesHash;
}
/// <summary>
///
/// </summary>
/// <param name="relUpdateEntryFile"></param>
/// <param name="relUpdateEntryHash"></param>
private void ReadRelUpdateEntryHash(string relUpdateEntryFile, ref Dictionary<string, List<string>> relUpdateEntryHash)
{
StreamReader dataReader = new StreamReader(relUpdateEntryFile);
string line = "";
string pfamId = "";
string[] entries = null;
while ((line = dataReader.ReadLine()) != null)
{
string[] fields = line.Split(' ');
pfamId = fields[0];
entries = fields[1].Split(',');
if (relUpdateEntryHash.ContainsKey(pfamId))
{
foreach (string pdbId in entries)
{
if (!relUpdateEntryHash[pfamId].Contains(pdbId))
{
relUpdateEntryHash[pfamId].Add(pdbId);
}
}
}
else
{
List<string> entryList = new List<string> (entries);
relUpdateEntryHash.Add(pfamId, entryList);
}
}
dataReader.Close();
}
/// <summary>
///
/// </summary>
public static void InitializeThread()
{
if (ProtCidSettings.dirSettings == null)
{
ProtCidSettings.LoadDirSettings();
}
if (AppSettings.parameters == null)
{
AppSettings.LoadParameters();
}
if (ProtCidSettings.pdbfamDbConnection == null)
{
ProtCidSettings.pdbfamDbConnection = new DbConnect();
ProtCidSettings.pdbfamDbConnection.ConnectString = "DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=fbmonkeyox;DATABASE=" +
ProtCidSettings.dirSettings.pdbfamDbPath;
ProtCidSettings.pdbfamQuery = new DbQuery(ProtCidSettings.pdbfamDbConnection);
}
if (ProtCidSettings.protcidDbConnection == null)
{
ProtCidSettings.protcidDbConnection = new DbConnect();
ProtCidSettings.protcidDbConnection.ConnectString = "DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=fbmonkeyox;DATABASE=" +
ProtCidSettings.dirSettings.protcidDbPath;
ProtCidSettings.protcidQuery = new DbQuery(ProtCidSettings.protcidDbConnection);
}
if (ProtCidSettings.alignmentDbConnection == null)
{
ProtCidSettings.alignmentDbConnection = new DbConnect();
ProtCidSettings.alignmentDbConnection.ConnectString = "DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=fbmonkeyox;DATABASE=" +
ProtCidSettings.dirSettings.alignmentDbPath;
ProtCidSettings.alignmentQuery = new DbQuery(ProtCidSettings.alignmentDbConnection);
}
if (ProtCidSettings.buCompConnection == null)
{
ProtCidSettings.buCompConnection = new DbConnect();
ProtCidSettings.buCompConnection.ConnectString = "DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=fbmonkeyox;DATABASE=" +
ProtCidSettings.dirSettings.baInterfaceDbPath;
ProtCidSettings.buCompQuery = new DbQuery(ProtCidSettings.buCompConnection);
}
ProtCidSettings.tempDir = "X:\\xtal_temp";
if (! Directory.Exists (ProtCidSettings.tempDir))
{
Directory.CreateDirectory(ProtCidSettings.tempDir);
}
PfamLibSettings.pdbfamConnection = ProtCidSettings.pdbfamDbConnection;
PfamLibSettings.pdbfamDbQuery = new DbQuery(PfamLibSettings.pdbfamConnection);
PfamLibSettings.alignmentDbConnection = ProtCidSettings.alignmentDbConnection;
}
/// <summary>
/// the list of entries needed to be updated
/// </summary>
/// <returns></returns>
private string[] GetUpdateEntries()
{
string newLsFile = Path.Combine(ProtCidSettings.dirSettings.xmlPath, "newls-pdb.txt");
// string newLsFile = "MessyDomainInterfaces_more.txt";
StreamReader entryReader = new StreamReader(newLsFile);
string line = "";
string pdbId = "";
List<string> updateEntryList = new List<string> ();
while ((line = entryReader.ReadLine()) != null)
{
if (line == "")
{
continue;
}
pdbId = line.Substring(0, 4);
if (!updateEntryList.Contains(pdbId))
{
updateEntryList.Add(pdbId);
}
}
entryReader.Close();
return updateEntryList.ToArray ();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string[] GetOtherUpdateEntries(string listFile)
{
StreamReader dataReader = new StreamReader(listFile);
string line = "";
List<string> entryList = new List<string>();
string pdbId = "";
while ((line = dataReader.ReadLine ()) != null)
{
string[] fields = line.Split('\t');
pdbId = fields[0].Substring(0, 4);
if (!entryList.Contains(pdbId))
{
entryList.Add(pdbId);
}
}
dataReader.Close();
return entryList.ToArray();
}
private bool IsEntryDomainExist (string pdbId)
{
string queryString = string.Format("Select * From PfamDomainInterfaces Where PdbID = '{0}';", pdbId);
DataTable dinterfaceTable = ProtCidSettings.protcidQuery.Query(queryString);
if (dinterfaceTable.Rows.Count > 0)
{
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string[] GetMissingDomainInterfaceEntries ()
{
List<string> domainMissingEntryList = new List<string>();
string domainMissingEntryLsFile = "DomainMissingEntryList.txt";
if (File.Exists(domainMissingEntryLsFile))
{
StreamReader entryReader = new StreamReader(domainMissingEntryLsFile);
string line = "";
while ((line = entryReader.ReadLine ()) != null)
{
domainMissingEntryList.Add(line);
}
entryReader.Close();
}
else
{
StreamWriter entryWriter = new StreamWriter(domainMissingEntryLsFile);
string queryString = "Select Distinct PdbID From CrystEntryInterfaces;";
DataTable crystEntryTable = ProtCidSettings.protcidQuery.Query(queryString);
queryString = "Select Distinct PdbID From PfamDomainInterfaces;";
DataTable domainEntryTable = ProtCidSettings.protcidQuery.Query(queryString);
List<string> domainEntryList = new List<string>();
string pdbId = "";
foreach (DataRow entryRow in domainEntryTable.Rows)
{
domainEntryList.Add(entryRow["PdbID"].ToString());
}
domainEntryList.Sort();
foreach (DataRow entryRow in crystEntryTable.Rows)
{
pdbId = entryRow["PdbID"].ToString();
if (domainEntryList.BinarySearch(pdbId) < 0)
{
domainMissingEntryList.Add(pdbId);
entryWriter.WriteLine(pdbId);
}
}
entryWriter.Close();
}
return domainMissingEntryList.ToArray();
}
#endregion
#region partial update for debug
public void UpdatePfamDomainInterfaceClusters()
{
InitializeThread();
DomainInterfaceTables.InitializeTables();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Comparing entry domain interfaces.");
// string[] updateEntries = {/* "4yc3",*/ "4y72"};
string[] updateEntries = GetReversedOrderDomainInterfaces();
DomainInterfaceBuComp.CrystBuDomainInterfaceComp domainInterfaceComp =
new InterfaceClusterLib.DomainInterfaces.DomainInterfaceBuComp.CrystBuDomainInterfaceComp();
domainInterfaceComp.UpdateCrystBuDomainInterfaceComp(updateEntries);
/* UnpInteractionStr unpInterInPdb = new UnpInteractionStr();
unpInterInPdb.UpdateUnpInteractionNetTableFromXml ();
string[] updateEntries = {"4xr8"};
unpInterInPdb.UpdateUnpInteractionNetTable(updateEntries);
PfamDomainInterfaceComp domainComp = new PfamDomainInterfaceComp();
string[] entries = {"5vam", "6cad", "6b8u"};
domainComp.SynchronizeDomainChainInterfaceComp(entries);
*/
/* DomainClusterStat clusterStat = new DomainClusterStat();
int[] relSeqIds = { 14511 };
clusterStat.PrintDomainClusteStatInfo(relSeqIds);
// clusterStat.AddMissingRedundantInterfacesToClusterTable ();
int[] updateRelSeqIds = GetUpdateRelSeqIds();
PfamClusterFilesCompress clusterFileCompress = new PfamClusterFilesCompress();
clusterFileCompress.UpdateRelationClusterChainInterfaceFiles(updateRelSeqIds);
string[] updateEntries = GetOtherUpdateEntries();
UpdateDomainInterfacesDb(updateEntries);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Comparing entry domain interfaces.");
DomainInterfaceBuComp.CrystBuDomainInterfaceComp domainInterfaceComp =
new InterfaceClusterLib.DomainInterfaces.DomainInterfaceBuComp.CrystBuDomainInterfaceComp();
domainInterfaceComp.UpdateCrystBuDomainInterfaceComp (updateEntries);
int[] updateRelSeqIds = GetUpdateRelSeqIds ();
Dictionary<int, string[]> updateRelEntryDict = ReadUpdateRelEntries();
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Updating the comparison of domain interfaces in each relation.");
ProtCidSettings.logWriter.WriteLine("Updating the comparison of domain interfaces in each relation.");
PfamDomainInterfaceComp domainComp = new PfamDomainInterfaceComp();
// domainComp.UpdateEntryDomainInterfaceComp(updateEntries);
domainComp.UpdateEntryDomainInterfaceComp(updateRelEntryDict);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain interface clusters.");
ProtCidSettings.logWriter.WriteLine("Update domain interface clusters.");
DomainInterfaceCluster domainInterfaceCluster = new DomainInterfaceCluster();
domainInterfaceCluster.ClusterDomainInterfaces();
// int[] updateRelSeqIds = domainInterfaceCluster.GetUpdateRelSeqIds();
// domainInterfaceCluster.UpdateDomainInterfaceClusters(updateRelSeqIds);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update Domain Interface Cluster Info.");
ProtCidSettings.logWriter.WriteLine("Update Domain Interface Cluster Info.");
DomainClusterStat clusterStat = new DomainClusterStat();
// clusterStat.PrintDomainDbSumInfo("PfamDomain");
clusterStat.PrintDomainClusterInfo();
// clusterStat.UpdateDomainClusterInfo(updateRelSeqIds);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update cluster file compressing.");
PfamClusterFilesCompress clusterFileCompress = new PfamClusterFilesCompress();
clusterFileCompress.UpdateRelationClusterChainInterfaceFiles(updateRelSeqIds);
ProtCidSettings.progressInfo.progStrQueue.Enqueue("Update domain cluster interface images.");
ProtCidSettings.logWriter.WriteLine("Update domain cluster interface images");
DomainInterfaceImageGen imageGen = new DomainInterfaceImageGen();
// imageGen.GenerateDomainInterfaceImages();
imageGen.UpdateDomainInterfaceImages(updateRelSeqIds);
DomainSeqFasta seqFasta = new DomainSeqFasta();
seqFasta.PrintClusterDomainSequences();
// seqFasta.UpdateClusterDomainSequences(updateRelSeqIds); */
}
private Dictionary<int, string[]> ReadUpdateRelEntries()
{
Dictionary<int, string[]> updateRelEntryDict = new Dictionary<int,string[]> ();
string updateRelEntryFile = "DifRelSeqIdEntries.txt";
StreamReader dataReader = new StreamReader(updateRelEntryFile);
string line = "";
int relSeqId = 0;
while ((line = dataReader.ReadLine()) != null)
{
string[] fields = line.Split(' ');
string[] entries = new string[fields.Length - 1];
Array.Copy(fields, 1, entries, 0, entries.Length);
relSeqId = Convert.ToInt32(fields[0]);
updateRelEntryDict.Add(relSeqId, entries);
}
dataReader.Close();
return updateRelEntryDict;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private int[] GetUpdateRelSeqIds()
{
string relTarDataDir = @"D:\protcid_update31Fromv30\UpdateDomainClusterInterfaces";
string[] tarFiles = Directory.GetFiles(relTarDataDir, "*.tar");
List<int> updateRelList = new List<int>();
DateTime dt = new DateTime (2018,1, 1);
int relSeqId = 0;
foreach (string tarFile in tarFiles)
{
FileInfo fileInfo = new FileInfo(tarFile);
if (DateTime.Compare (fileInfo.LastWriteTime, dt) < 0)
{
relSeqId = Convert.ToInt32(fileInfo.Name.Replace (".tar", ""));
if (! updateRelList.Contains (relSeqId))
{
updateRelList.Add(relSeqId);
}
}
}
return updateRelList.ToArray();
/*
string updateRelSeqIdFile = "UpdateRelSeqIds_100.txt";
ArrayList updateRelSeqIdList = new ArrayList();
int relSeqId = 0;
StreamReader dataReader = new StreamReader(updateRelSeqIdFile);
string line = "";
while ((line = dataReader.ReadLine()) != null)
{
relSeqId = Convert.ToInt32(line);
updateRelSeqIdList.Add(relSeqId);
}
dataReader.Close();
string difRelSeqIdsFile = "DifRelSeqIDs.txt";
dataReader = new StreamReader(difRelSeqIdsFile);
while ((line = dataReader.ReadLine()) != null)
{
string[] fields = line.Split();
relSeqId = Convert.ToInt32(fields[0]);
if (! updateRelSeqIdList.Contains(relSeqId))
{
updateRelSeqIdList.Add(relSeqId);
}
relSeqId = Convert.ToInt32(fields[1]);
if (!updateRelSeqIdList.Contains(relSeqId))
{
updateRelSeqIdList.Add(relSeqId);
}
}
dataReader.Close();
int[] updateRelSeqIds = new int[updateRelSeqIdList.Count];
updateRelSeqIdList.CopyTo(updateRelSeqIds);
return updateRelSeqIds;*/
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string[] GetReversedOrderDomainInterfaces ()
{
string queryString = "Select Distinct PfamDomainInterfaces.PdbID As PdbID " +
" From PfamDomainInterfaces, CrystPdbBuInterfaceComp " +
" Where PfamDomainInterfaces.PdbID = CrystPdbBuInterfaceComp.PdbID AND PfamDomainInterfaces.InterfaceID = CrystPdbBuInterfaceComp.InterfaceID AND " +
" IsReversed = '1' AND Qscore > 0.5;";
DataTable entryReversedChainsTable = ProtCidSettings.protcidQuery.Query(queryString);
List<string> entryList = new List<string>();
foreach (DataRow entryRow in entryReversedChainsTable.Rows)
{
entryList.Add(entryRow["PdbID"].ToString());
}
return entryList.ToArray();
}
#endregion
}
}
| 50.308824 | 166 | 0.61112 | [
"BSD-3-Clause"
] | DunbrackLab/ProtCID | InterfaceClusterLib/DomainInterfaces/DomainInterfaceBuilder.cs | 47,894 | C# |
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Ludiq.PeekCore
{
public class StaticFieldAccessor<TField> : IOptimizedAccessor
{
public StaticFieldAccessor(FieldInfo fieldInfo)
{
if (OptimizedReflection.safeMode)
{
if (fieldInfo == null)
{
throw new ArgumentNullException(nameof(fieldInfo));
}
if (fieldInfo.FieldType != typeof(TField))
{
throw new ArgumentException("Field type of field info doesn't match generic type.", nameof(fieldInfo));
}
if (!fieldInfo.IsStatic)
{
throw new ArgumentException("The field isn't static.", nameof(fieldInfo));
}
}
this.fieldInfo = fieldInfo;
targetType = fieldInfo.DeclaringType;
}
private readonly FieldInfo fieldInfo;
private Func<TField> getter;
private Action<TField> setter;
private Type targetType;
public void Compile()
{
if (fieldInfo.IsLiteral)
{
var constant = (TField)fieldInfo.GetValue(null);
getter = () => constant;
}
else
{
if (OptimizedReflection.useJit)
{
// Getter
var fieldExpression = Expression.Field(null, fieldInfo);
getter = Expression.Lambda<Func<TField>>(fieldExpression).Compile();
// Setter
if (fieldInfo.CanWrite())
{
#if UNITY_2018_3_OR_NEWER
var valueExpression = Expression.Parameter(typeof(TField));
var assignExpression = Expression.Assign(fieldExpression, valueExpression);
setter = Expression.Lambda<Action<TField>>(assignExpression, valueExpression).Compile();
#else
var setterMethod = new DynamicMethod
(
"setter",
typeof(void),
new[] { typeof(TField) },
targetType,
true
);
var setterIL = setterMethod.GetILGenerator();
setterIL.Emit(OpCodes.Ldarg_0);
setterIL.Emit(OpCodes.Stsfld, fieldInfo);
setterIL.Emit(OpCodes.Ret);
setter = (Action<TField>)setterMethod.CreateDelegate(typeof(Action<TField>));
#endif
}
}
else
{
// If no JIT is available, we can only use reflection.
getter = () => (TField)fieldInfo.GetValue(null);
if (fieldInfo.CanWrite())
{
setter = (value) => fieldInfo.SetValue(null, value);
}
}
}
}
public object GetValue(object target)
{
if (OptimizedReflection.safeMode)
{
OptimizedReflection.VerifyStaticTarget(targetType, target);
try
{
return GetValueUnsafe(target);
}
catch (TargetInvocationException)
{
throw;
}
catch (Exception ex)
{
throw new TargetInvocationException(ex);
}
}
else
{
return GetValueUnsafe(target);
}
}
private object GetValueUnsafe(object target)
{
return getter.Invoke();
}
public void SetValue(object target, object value)
{
if (OptimizedReflection.safeMode)
{
OptimizedReflection.VerifyStaticTarget(targetType, target);
if (setter == null)
{
throw new TargetException($"The field '{targetType}.{fieldInfo.Name}' cannot be assigned.");
}
if (!typeof(TField).IsInstanceOfTypeNullable(value))
{
throw new ArgumentException($"The provided value for '{targetType}.{fieldInfo.Name}' does not match the field type.\nProvided: {value?.GetType()?.ToString() ?? "null"}\nExpected: {typeof(TField)}");
}
try
{
SetValueUnsafe(target, value);
}
catch (TargetInvocationException)
{
throw;
}
catch (Exception ex)
{
throw new TargetInvocationException(ex);
}
}
else
{
SetValueUnsafe(target, value);
}
}
private void SetValueUnsafe(object target, object value)
{
setter.Invoke((TField)value);
}
}
} | 22.414634 | 203 | 0.651251 | [
"MIT"
] | 3-Delta/Unity-UGUI-UI | Assets/3rd/Ludiq/Ludiq.PeekCore/Runtime/Reflection/Optimization/StaticFieldAccessor.cs | 3,678 | C# |
using System.Collections.Generic;
using System.Linq;
using AccidentalFish.ExpressionParser.Nodes;
using AccidentalFish.ExpressionParser.Nodes.Functions;
using AccidentalFish.ExpressionParser.Nodes.Operators;
using AccidentalFish.ExpressionParser.Nodes.Structural;
using AccidentalFish.ExpressionParser.Nodes.Values;
namespace AccidentalFish.ExpressionParser.Parsers
{
public class ParserProvider : IParserProvider
{
public static readonly IReadOnlyCollection<IParser> DefaultParsers;
static ParserProvider()
{
DefaultParsers = new List<IParser>
{
// TODO: I am wandering in the below if we an always say that a node cannot be preceded by a node of the same type.
// I think even with functions and function parameters that is still the case.
// Functions
new SimpleLiteralParser(MaxNode.Literal, token => new MaxNode()),
new SimpleLiteralParser(MinNode.Literal, token => new MinNode()),
new SimpleLiteralParser(PowNode.Literal, token => new PowNode()),
new SimpleLiteralParser(SqrtNode.Literal, token => new SqrtNode()),
new SimpleLiteralParser(LengthNode.Literal, token => new LengthNode()),
// Operators
new SimpleLiteralParser(ConditionalAndNode.Literal, token => new ConditionalAndNode()),
new SimpleLiteralParser(EqualNode.Literal, token => new EqualNode()),
new SimpleLiteralParser(GreaterThanEqualNode.Literal, token => new GreaterThanEqualNode()),
new SimpleLiteralParser(GreaterThanNode.Literal, token => new GreaterThanNode()),
new SimpleLiteralParser(LessThanEqualNode.Literal, token => new LessThanEqualNode()),
new SimpleLiteralParser(LessThanNode.Literal, token => new LessThanNode()),
new SimpleLiteralParser(NotEqualNode.Literal, token => new NotEqualNode()),
new SimpleLiteralParser(NotNode.Literal, token => new NotNode()),
new SimpleLiteralParser(ConditionalOrNode.Literal, token => new ConditionalOrNode()),
new LookbackLiteralParser(AdditionNode.Literal, // we use a lookback operator to deal with negation and positive syntax e.g. 5+-3
(previous) => !(previous is OperatorNode),
token => new AdditionNode()),
new LookbackLiteralParser(SubtractionNode.Literal,
(previous) => !(previous is OperatorNode),
token => new SubtractionNode()),
new SimpleLiteralParser(MultiplicationNode.Literal, token => new MultiplicationNode()),
new SimpleLiteralParser(DivisionNode.Literal, token => new DivisionNode()),
new SimpleLiteralParser(ModuloNode.Literal, token => new ModuloNode()),
new LookbackLiteralParser(
NegateNode.Literal,
previous => previous is OperatorNode,
token => new NegateNode()),
new LookbackLiteralParser(
AdditionNode.Literal,
previous => previous is OperatorNode,
token => null), // we basically strip out non-additive + operators
// Values
new NumericParser(token => token.Contains(".") ? new DoubleValueNode(token) : (ExpressionNode)new IntValueNode(token)),
new VariableParser((token) => new VariableNode(token)),
// Structural
new SimpleLiteralParser(OpenBracketNode.Literal, token => new OpenBracketNode()),
new SimpleLiteralParser(CloseBracketNode.Literal, token => new CloseBracketNode()),
new SimpleLiteralParser(ParameterDelimiterNode.Literal, token => new ParameterDelimiterNode())
};
}
private readonly IReadOnlyCollection<IParser> _parsers;
public ParserProvider(IEnumerable<IParser> parsers = null)
{
if (parsers != null && parsers.Any())
{
_parsers = parsers.ToList();
}
else
{
_parsers = DefaultParsers;
}
}
public IReadOnlyCollection<IParser> Get()
{
return _parsers;
}
}
}
| 51.658824 | 145 | 0.620588 | [
"MIT"
] | JTOne123/AccidentalFish.ExpressionParser | Source/AccidentalFish.ExpressionParser/Parsers/ParserProvider.cs | 4,393 | C# |
// <copyright file="ProcessCreationEventGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
using Microsoft.Azure.IoT.Agent.Core.Configuration;
using Microsoft.Azure.IoT.Agent.Core.Utils;
using Microsoft.Azure.IoT.Contracts.Events;
using Microsoft.Azure.Security.IoT.Agent.EventGenerators.Linux.Audit;
using Microsoft.Azure.Security.IoT.Agent.EventGenerators.Linux.Utils;
using Microsoft.Azure.Security.IoT.Contracts.Events.Events;
using Microsoft.Azure.Security.IoT.Contracts.Events.Payloads;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.Azure.Security.IoT.Agent.EventGenerators.Linux
{
/// <summary>
/// Process creation event generator for Linux
/// </summary>
public class ProcessCreationEventGenerator : AuditEventGeneratorBase
{
private Dictionary<string,string> executableHash;
private string searchIntegrityRuleCommand = "sudo ausearch -m INTEGRITY_RULE --input-logs";
/// <inheritdoc />
protected override IEnumerable<string> AuditRulesPrerequisites { get; } = new List<string>()
{
"-A always,exit -F arch={0} -S execve,execveat"
};
/// <inheritdoc />
protected override IEnumerable<AuditEventType> AuditEventTypes => new[] { AuditEventType.ProcessExecution, AuditEventType.Integrity };
/// <inheritdoc />
public override EventPriority Priority => AgentConfiguration.GetEventPriority<ProcessCreate>();
/// <summary>
/// Ctor - creates a new event generator
/// use default ProcessUtil
/// </summary>
public ProcessCreationEventGenerator() : this(ProcessUtil.Instance) { }
/// <inheritdoc />
public ProcessCreationEventGenerator(IProcessUtil processUtil) : base(processUtil)
{
executableHash = new Dictionary<string,string>();
string searchResultsString = processUtil.ExecuteBashShellCommand(searchIntegrityRuleCommand);
IEnumerable<string> searchResults = searchResultsString.Split("----", StringSplitOptions.RemoveEmptyEntries);
IEnumerable<AuditEvent> auditEvents = searchResults.Select(AuditEvent.ParseFromAusearchLine);
foreach(AuditEvent auditEvent in auditEvents){
updateExecutablesDictonary(auditEvent);
}
}
/// <inheritdoc />
protected override IEnumerable<IEvent> GetEventsImpl(IEnumerable<AuditEvent> auditEvents)
{
foreach(AuditEvent auditEvent in auditEvents){
updateExecutablesDictonary(auditEvent);
}
return auditEvents.Select(AuditEventToDeviceEvent);
}
private void updateExecutablesDictonary(AuditEvent auditEvent){
var hash = auditEvent.GetPropertyValue(AuditEvent.AuditMessageProperty.ExecutableHash, false);
if(hash != null){
hash = hash.Substring(7);
var exec = auditEvent.GetPropertyValue(AuditEvent.AuditMessageProperty.FilePath);
executableHash[exec] = hash;
}
}
/// <summary>
/// Converts an audit event to a device event
/// </summary>
/// <param name="auditEvent">Audit event to convert</param>
/// <returns>Device event based on the input</returns>
private IEvent AuditEventToDeviceEvent(AuditEvent auditEvent)
{
var executable = auditEvent.GetPropertyValue(AuditEvent.AuditMessageProperty.Executable);
bool isExecutableExist = executableHash.TryGetValue(executable, out string hash);
hash = isExecutableExist ? hash : "";
ProcessCreationPayload payload = new ProcessCreationPayload
{
CommandLine = EncodedAuditFieldsUtils.DecodeHexStringIfNeeded(auditEvent.GetPropertyValue(AuditEvent.AuditMessageProperty.CommandLine), Encoding.UTF8),
Executable = executable,
ProcessId = Convert.ToUInt32(auditEvent.GetPropertyValue(AuditEvent.AuditMessageProperty.ProcessId)),
ParentProcessId = Convert.ToUInt32(auditEvent.GetPropertyValue(AuditEvent.AuditMessageProperty.ParentProcessId)),
Time = auditEvent.TimeUTC,
UserId = auditEvent.GetPropertyValue(AuditEvent.AuditMessageProperty.UserId),
ExtraDetails = new Dictionary<string,string>(){ {"Hash", hash} }
};
return new ProcessCreate(Priority, payload);
}
}
} | 46.846939 | 167 | 0.681115 | [
"MIT"
] | Azure/Azure-IoT-Security-Agent-CS | src/Modules/Security/EventGenerators/Linux/ProcessCreationEventGenerator.cs | 4,593 | C# |
namespace Grayscale.TileToPng.CommandLineModel
{
/// <summary>
/// マージン。
/// </summary>
public class Margin : IMargin
{
/// <summary>
/// Initializes a new instance of the <see cref="Margin"/> class.
/// </summary>
public Margin()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Margin"/> class.
/// </summary>
/// <param name="north">北側。</param>
/// <param name="east">東側。</param>
/// <param name="south">南側。</param>
/// <param name="west">西側。</param>
public Margin(
int north,
int east,
int south,
int west)
{
this.North = north;
this.East = east;
this.South = south;
this.West = west;
}
/// <summary>
/// Gets or sets 北側。
/// </summary>
public int North { get; set; }
/// <summary>
/// Gets or sets 東側。
/// </summary>
public int East { get; set; }
/// <summary>
/// Gets or sets 南側。
/// </summary>
public int South { get; set; }
/// <summary>
/// Gets or sets 西側。
/// </summary>
public int West { get; set; }
/// <summary>
/// デバッグ出力。
/// </summary>
/// <returns>文字列。</returns>
public override string ToString()
{
return this.North + ", " + this.East + ", " + this.South + ", " + this.West;
}
}
}
| 24.53125 | 88 | 0.433121 | [
"MIT"
] | muzudho/csharp-tile-to-png | Source/TileToPng/CommandLineModel/Margin.cs | 1,652 | C# |
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.AccessApi.Enums
{
/// <summary>
/// SupportByVersion Access 10, 11, 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Access.AcPrintOrientation"/> </remarks>
[SupportByVersion("Access", 10,11,12,14,15,16)]
[EntityType(EntityType.IsEnum)]
public enum AcPrintOrientation
{
/// <summary>
/// SupportByVersion Access 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("Access", 10,11,12,14,15,16)]
acPRORPortrait = 1,
/// <summary>
/// SupportByVersion Access 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("Access", 10,11,12,14,15,16)]
acPRORLandscape = 2
}
} | 29.607143 | 140 | 0.659831 | [
"MIT"
] | NetOfficeFw/NetOffice | Source/Access/Enums/AcPrintOrientation.cs | 831 | 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.IO
{
public partial class ErrorEventArgs : System.EventArgs
{
public ErrorEventArgs(System.Exception exception) { }
public virtual System.Exception GetException() { throw null; }
}
public delegate void ErrorEventHandler(object sender, System.IO.ErrorEventArgs e);
public partial class FileSystemEventArgs : System.EventArgs
{
public FileSystemEventArgs(System.IO.WatcherChangeTypes changeType, string directory, string name) { }
public System.IO.WatcherChangeTypes ChangeType { get { throw null; } }
public string FullPath { get { throw null; } }
public string Name { get { throw null; } }
}
public delegate void FileSystemEventHandler(object sender, System.IO.FileSystemEventArgs e);
public partial class FileSystemWatcher : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
{
public FileSystemWatcher() { }
public FileSystemWatcher(string path) { }
public FileSystemWatcher(string path, string filter) { }
public bool EnableRaisingEvents { get { throw null; } set { } }
public string Filter { get { throw null; } set { } }
public bool IncludeSubdirectories { get { throw null; } set { } }
public int InternalBufferSize { get { throw null; } set { } }
public System.IO.NotifyFilters NotifyFilter { get { throw null; } set { } }
public string Path { get { throw null; } set { } }
public override System.ComponentModel.ISite Site { get { throw null; } set { } }
public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get { throw null; } set { } }
public event System.IO.FileSystemEventHandler Changed { add { } remove { } }
public event System.IO.FileSystemEventHandler Created { add { } remove { } }
public event System.IO.FileSystemEventHandler Deleted { add { } remove { } }
public event System.IO.ErrorEventHandler Error { add { } remove { } }
public event System.IO.RenamedEventHandler Renamed { add { } remove { } }
public void BeginInit() { }
protected override void Dispose(bool disposing) { }
public void EndInit() { }
protected void OnChanged(System.IO.FileSystemEventArgs e) { }
protected void OnCreated(System.IO.FileSystemEventArgs e) { }
protected void OnDeleted(System.IO.FileSystemEventArgs e) { }
protected void OnError(System.IO.ErrorEventArgs e) { }
protected void OnRenamed(System.IO.RenamedEventArgs e) { }
public System.IO.WaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType) { throw null; }
public System.IO.WaitForChangedResult WaitForChanged(System.IO.WatcherChangeTypes changeType, int timeout) { throw null; }
}
public partial class InternalBufferOverflowException : System.SystemException
{
public InternalBufferOverflowException() { }
protected InternalBufferOverflowException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public InternalBufferOverflowException(string message) { }
public InternalBufferOverflowException(string message, System.Exception inner) { }
}
[System.FlagsAttribute]
public enum NotifyFilters
{
Attributes = 4,
CreationTime = 64,
DirectoryName = 2,
FileName = 1,
LastAccess = 32,
LastWrite = 16,
Security = 256,
Size = 8,
}
public partial class RenamedEventArgs : System.IO.FileSystemEventArgs
{
public RenamedEventArgs(System.IO.WatcherChangeTypes changeType, string directory, string name, string oldName) : base (default(System.IO.WatcherChangeTypes), default(string), default(string)) { }
public string OldFullPath { get { throw null; } }
public string OldName { get { throw null; } }
}
public delegate void RenamedEventHandler(object sender, System.IO.RenamedEventArgs e);
public partial struct WaitForChangedResult
{
private object _dummy;
public System.IO.WatcherChangeTypes ChangeType { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
public string OldName { get { throw null; } set { } }
public bool TimedOut { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum WatcherChangeTypes
{
All = 15,
Changed = 4,
Created = 1,
Deleted = 2,
Renamed = 8,
}
}
| 51.752577 | 204 | 0.656972 | [
"MIT"
] | BigBadBleuCheese/corefx | src/System.IO.FileSystem.Watcher/ref/System.IO.FileSystem.Watcher.cs | 5,020 | C# |
using Com.Atomatus.Bootstarter.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Com.Atomatus.Bootstarter.Context
{
/// <summary>
/// <para>
/// Allows configuration for an entity type to be factored into a separate class,
/// rather than in-line in <see cref="ContextBase.OnModelCreating(ModelBuilder)"/>.
/// </para>
/// Implement this abstract class, applying configuration for the entity in the <see cref="Configure(EntityTypeBuilder{TEntity})"/><br/>
/// method, and then apply the configuration to the model using <see cref="ModelBuilder.ApplyConfiguration{TEntity}(IEntityTypeConfiguration{TEntity})"/><br/>
/// in <see cref="ContextBase.OnModelCreating(ModelBuilder)"/>.
/// <para>
/// By default the <see cref="Configure(EntityTypeBuilder{TEntity})"/> set the <see cref="IModel{ID}.Id"/> as primary key and<br/>
/// if <typeparamref name="TEntity"/> is <see cref="IModelAltenateKey"/>,
/// set the <see cref="IModelAltenateKey.Uuid"/> as alternate key generating value on add.
/// </para>
/// <para>
/// <i>
/// Remember: the properties <see cref="IModel{ID}.Id"/>,
/// <see cref="IModelAltenateKey.Uuid"/> are already set by default.<br/>
/// Configure only your own properties defined.
/// </i>
/// </para>
/// </summary>
/// <typeparam name="TEntity">entity type</typeparam>
/// <typeparam name="ID">entity id type</typeparam>
public abstract class EntityTypeConfigurationBase<TEntity, ID> :
IEntityTypeConfiguration<TEntity>
where TEntity : class, IModel<ID>
{
/// <summary>
/// Configures the entity of type TEntity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity type.</param>
public void Configure(EntityTypeBuilder<TEntity> builder)
{
builder.HasKey(e => e.Id);
if(typeof(IModelAltenateKey).IsAssignableFrom(typeof(TEntity)))
{
builder.HasAlternateKey(nameof(IModelAltenateKey.Uuid));
builder.Property(nameof(IModelAltenateKey.Uuid)).ValueGeneratedOnAdd();
}
this.OnConfigure(builder);
}
/// <summary>
/// Configures the entity of type TEntity.
/// <para>
/// <i>
/// Remember: the properties <see cref="IModel{ID}.Id"/>,
/// <see cref="IModelAltenateKey.Uuid"/> are already set by default.<br/>
/// Configure only your own properties defined.
/// </i>
/// </para>
/// </summary>
/// <param name="builder">The builder to be used to configure the entity type.</param>
protected abstract void OnConfigure(EntityTypeBuilder<TEntity> builder);
}
}
| 43.769231 | 162 | 0.630228 | [
"Apache-2.0"
] | atomatus/dot-net-boot-starter | Atomatus.Bootstarter/Com.Atomatus.Bootstarter/Context/Configuration/EntityTypeConfigurationBase.cs | 2,847 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LottoryUWP.DataModel
{
public class DrawItem
{
public string MajorColumnValue { get; set; }
public string SecondaryColumnValue { get; set; }
public int DrawWeight { get; set; } = 1;
public string DisplayName
{
get
{
return string.Format("{0} {1}", MajorColumnValue, SecondaryColumnValue).TrimEnd();
}
}
public WinnerItem ToWinnerItem(int histroyGroupIndex)
{
return new WinnerItem(this, histroyGroupIndex);
}
}
public class WinnerItem : DrawItem
{
public DateTime? DrawnTimeStamp { get; set; }
public int HistroyGroupIndex { get; set; }
public WinnerItem(DrawItem item, int historyGroupIndex)
{
this.MajorColumnValue = item.MajorColumnValue;
this.SecondaryColumnValue = item.SecondaryColumnValue;
this.DrawWeight = item.DrawWeight;
this.DrawnTimeStamp = DateTime.Now;
this.HistroyGroupIndex = historyGroupIndex;
}
}
}
| 27.613636 | 98 | 0.611523 | [
"MIT"
] | Cherubimlee/Lottery | LottoryUWP/LottoryUWP/DataModel/DrawItem.cs | 1,217 | C# |
using Serilog;
namespace Nancy.Serilog.Simple
{
public class NancySerilogConfiguration
{
public string[] Blacklist { get; set; }
public string InformationTitle { get; set; }
public string ErrorTitle { get; set; }
public string Version { get; set; }
public ILogger Logger { get; set; }
}
} | 19.277778 | 52 | 0.616715 | [
"MIT"
] | ThiagoBarradas/nancy-serilog | Nancy.Serilog.Simple/NancySerilogConfiguration.cs | 349 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace PhoneApiService
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.44 | 76 | 0.695581 | [
"Apache-2.0"
] | staneee/OceIdentity | PhoneApiService/Program.cs | 613 | C# |
using FluentValidation.Results;
using System;
using System.Collections.Generic;
namespace Application.Exceptions
{
public class ExcepcionDeValidador : Exception
{
// Creamos una propiedad
public List<string> ListaErrores { get; }
// constructor vacio y heredamos del constructor base y le mandamos el parametro
public ExcepcionDeValidador() : base("Se ha producido uno o mas errores de Validacion")
{
ListaErrores = new List<string>();
}
// se crea otro constructor , le pasamor un ienumerable recolectando las validaciones
// que nos arroja el FluentValidation
// este contructor recibe un IEnumerable de tipo validationFailure
public ExcepcionDeValidador(IEnumerable<ValidationFailure> fallosDeValidacion) : this()
{
// hacemos un foreach
// para recorrer todos esos errores para gregarlos a ListaErrores
foreach (ValidationFailure falloDeValidacion in fallosDeValidacion)
{
ListaErrores.Add(falloDeValidacion.ErrorMessage);
}
}
}
}
| 34.484848 | 95 | 0.663445 | [
"MIT"
] | NSysX/NSysC | NSysApiPedidos/src/Core/Application/Exceptions/ExcepcionDeValidador.cs | 1,140 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void Main()
{
var s = Console.ReadLine();
var map = new Map<(char, char), long>();
foreach (var c in s)
{
for (char c0 = 'a'; c0 <= 'z'; c0++)
{
map[(c0, c)] += map[(c0, '/')];
}
map[(c, '/')]++;
}
Console.WriteLine(map.Values.Max());
}
}
class Map<TK, TV> : Dictionary<TK, TV>
{
TV _v0;
public Map(TV v0 = default(TV)) { _v0 = v0; }
public new TV this[TK key]
{
get { return ContainsKey(key) ? base[key] : _v0; }
set { base[key] = value; }
}
}
| 16.944444 | 53 | 0.518033 | [
"MIT"
] | sakapon/Codeforces-Contests | CSharp/Contests2020/CFR621/C.cs | 612 | C# |
using System;
namespace MTGAHelper.Lib.OutputLogParser.Models
{
public interface IMtgaOutputLogPartResult
{
string Part { get; }
string Prefix { get; }
DateTime LogDateTime { get; }
string SubPart { get; set; }
long Timestamp { get; set; }
string MatchId { get; set; }
string LogTextKey { get; set; }
IMtgaOutputLogPartResult SetCommonFields(string part, string prefix, DateTime logDateTime);
}
public interface IMtgaOutputLogPartResult<T> : IMtgaOutputLogPartResult
{
T Raw { get; set; }
}
public class MtgaOutputLogPartResultBase<T> : IMtgaOutputLogPartResult<T>
{
//public virtual ReaderMtgaOutputLogPartTypeEnum ResultType => ReaderMtgaOutputLogPartTypeEnum.Unknown;
public string Part { get; private set; }
public string SubPart { get; set; }
public string Prefix { get; private set; }
public long Timestamp { get; set; }
public string MatchId { get; set; }
public string LogTextKey { get; set; }
public DateTime LogDateTime { get; set; }
public virtual T Raw { get; set; }
//public bool IsMessageSummarized { get; set; }
public MtgaOutputLogPartResultBase()
{
}
public MtgaOutputLogPartResultBase(long timestamp)
{
Timestamp = timestamp;
}
public IMtgaOutputLogPartResult SetCommonFields(string part, string prefix, DateTime logDateTime)
{
Part = part;
Prefix = prefix;
LogDateTime = logDateTime;
return this;
}
}
[AddMessageEvenIfDateNull]
public class DetailedLoggingResult : MtgaOutputLogPartResultBase<string>
{
public DetailedLoggingResult(bool isEnabled)
{
IsDetailedLoggingEnabled = isEnabled;
}
public bool IsDetailedLoggingEnabled { get; }
public bool IsDetailedLoggingDisabled => !IsDetailedLoggingEnabled;
}
public class IgnoredResult : MtgaOutputLogPartResultBase<string>
{
//public override ReaderMtgaOutputLogPartTypeEnum ResultType => ReaderMtgaOutputLogPartTypeEnum.Ignored;
public IgnoredResult(long timestamp = 0)
: base(timestamp)
{
}
}
public class IgnoredResultRequestToServer : IgnoredResult
{
public IgnoredResultRequestToServer(long timestamp = 0)
: base(timestamp)
{
}
}
public class UnknownResult : MtgaOutputLogPartResultBase<string>
{
public UnknownResult(long timestamp = 0)
: base(timestamp)
{
}
}
public class IgnoredMatchResult : IgnoredResult, ITagMatchResult
{
//public override ReaderMtgaOutputLogPartTypeEnum ResultType => ReaderMtgaOutputLogPartTypeEnum.Ignored;
public IgnoredMatchResult(long timestamp = 0)
: base(timestamp)
{
}
}
public class SummarizedMatchResult : MtgaOutputLogPartResultBase<string>, ITagMatchResult
{
//public override ReaderMtgaOutputLogPartTypeEnum ResultType => ReaderMtgaOutputLogPartTypeEnum.Ignored;
public SummarizedMatchResult(long timestamp = 0)
: base(timestamp)
{
}
}
public class UnknownMatchResult : UnknownResult, ITagMatchResult
{
public UnknownMatchResult(long timestamp = 0)
: base(timestamp)
{
}
}
public class IgnoredClientToMatchResult : IgnoredMatchResult, ITagMatchResult
{
//public override ReaderMtgaOutputLogPartTypeEnum ResultType => ReaderMtgaOutputLogPartTypeEnum.Ignored;
public IgnoredClientToMatchResult(long timestamp = 0)
: base(timestamp)
{
}
}
}
| 29.206107 | 112 | 0.639571 | [
"MIT"
] | DuncanmaMSFT/MTGAHelper-Windows-Client | MTGAHelper.Lib.OutputLogParser.Models/MtgaOutputLogPartResultBase.cs | 3,828 | C# |
using System;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace PomodoroClock.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage.
/// </summary>
/// <example><code>
/// [CanBeNull] object Test() => null;
///
/// void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>.
/// </summary>
/// <example><code>
/// [NotNull] object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can never be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemNotNullAttribute : Attribute { }
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemCanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form.
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// void ShowError(string message, params object[] args) { /* do something */ }
///
/// void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Delegate)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; private set; }
}
/// <summary>
/// For a parameter that is expected to be one of the limited set of values.
/// Specify fields of which type should be used as values for this parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class ValueProviderAttribute : Attribute
{
public ValueProviderAttribute(string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>.
/// </summary>
/// <example><code>
/// void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method
/// is used to notify that some property value changed.
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
///
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// string _name;
///
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output.
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br/>
/// <c>canbenull</c> annotation is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// class Foo {
/// string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
///
/// class UsesNoEquality {
/// void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// class ComponentAttribute : Attribute { }
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections).
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes
/// as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used.</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member.</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type.</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly when marked
/// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>.
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used.</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used.</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used.
/// </summary>
[MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack.
/// If the parameter is a delegate, indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>.
/// </summary>
/// <example><code>
/// [Pure] int Multiply(int x, int y) => x * y;
///
/// void M() {
/// Multiply(123, 42); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that the return value of method invocation must be used.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class MustUseReturnValueAttribute : Attribute
{
public MustUseReturnValueAttribute() { }
public MustUseReturnValueAttribute([NotNull] string justification)
{
Justification = justification;
}
public string Justification { get; private set; }
}
/// <summary>
/// Indicates the type member or parameter of some type, that should be used instead of all other ways
/// to get the value that type. This annotation is useful when you have some "context" value evaluated
/// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one.
/// </summary>
/// <example><code>
/// class Foo {
/// [ProvidesContext] IBarService _barService = ...;
///
/// void ProcessNode(INode node) {
/// DoSomething(node, node.GetGlobalServices().Bar);
/// // ^ Warning: use value of '_barService' field
/// }
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter |
AttributeTargets.Method)]
public sealed class ProvidesContextAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~).
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
public string BasePath { get; private set; }
}
/// <summary>
/// An extension method marked with this attribute is processed by ReSharper code completion
/// as a 'Source Template'. When extension method is completed over some expression, it's source code
/// is automatically expanded like a template at call site.
/// </summary>
/// <remarks>
/// Template method body can contain valid source code and/or special comments starting with '$'.
/// Text inside these comments is added as source code when the template is applied. Template parameters
/// can be used either as additional method parameters or as identifiers wrapped in two '$' signs.
/// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters.
/// </remarks>
/// <example>
/// In this example, the 'forEach' method is a source template available over all values
/// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block:
/// <code>
/// [SourceTemplate]
/// public static void forEach<T>(this IEnumerable<T> xs) {
/// foreach (var x in xs) {
/// //$ $END$
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SourceTemplateAttribute : Attribute { }
/// <summary>
/// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>.
/// </summary>
/// <remarks>
/// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression
/// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target
/// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently
/// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1.
/// </remarks>
/// <example>
/// Applying the attribute on a source template method:
/// <code>
/// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")]
/// public static void forEach<T>(this IEnumerable<T> collection) {
/// foreach (var item in collection) {
/// //$ $END$
/// }
/// }
/// </code>
/// Applying the attribute on a template method parameter:
/// <code>
/// [SourceTemplate]
/// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) {
/// /*$ var $x$Id = "$newguid$" + x.ToString();
/// x.DoSomething($x$Id); */
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)]
public sealed class MacroAttribute : Attribute
{
/// <summary>
/// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see>
/// parameter when the template is expanded.
/// </summary>
public string Expression { get; set; }
/// <summary>
/// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed.
/// </summary>
/// <remarks>
/// If the target parameter is used several times in the template, only one occurrence becomes editable;
/// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence,
/// use values >= 0. To make the parameter non-editable when the template is expanded, use -1.
/// </remarks>>
public int Editable { get; set; }
/// <summary>
/// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the
/// <see cref="MacroAttribute"/> is applied on a template method.
/// </summary>
public string Target { get; set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : Attribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is
/// an MVC controller. If applied to a method, the MVC controller name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC
/// partial view. If applied to a method, the MVC partial view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSuppressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component name.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcViewComponentAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component view. If applied to a method, the MVC view component view name is default.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewComponentViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name.
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class RazorSectionAttribute : Attribute { }
/// <summary>
/// Indicates how method, constructor invocation or property access
/// over collection type affects content of the collection.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)]
public sealed class CollectionAccessAttribute : Attribute
{
public CollectionAccessAttribute(CollectionAccessType collectionAccessType)
{
CollectionAccessType = collectionAccessType;
}
public CollectionAccessType CollectionAccessType { get; private set; }
}
[Flags]
public enum CollectionAccessType
{
/// <summary>Method does not use or modify content of the collection.</summary>
None = 0,
/// <summary>Method only reads content of the collection but does not modify it.</summary>
Read = 1,
/// <summary>Method can change content of the collection but does not add new elements.</summary>
ModifyExistingContent = 2,
/// <summary>Method can add new elements to the collection.</summary>
UpdatedContent = ModifyExistingContent | 4
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if
/// one of the conditions is satisfied. To set the condition, mark one of the parameters with
/// <see cref="AssertionConditionAttribute"/> attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class AssertionMethodAttribute : Attribute { }
/// <summary>
/// Indicates the condition parameter of the assertion method. The method itself should be
/// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of
/// the attribute is the assertion type.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AssertionConditionAttribute : Attribute
{
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
ConditionType = conditionType;
}
public AssertionConditionType ConditionType { get; private set; }
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisfies the condition,
/// then the execution continues. Otherwise, execution is assumed to be halted.
/// </summary>
public enum AssertionConditionType
{
/// <summary>Marked parameter should be evaluated to true.</summary>
IS_TRUE = 0,
/// <summary>Marked parameter should be evaluated to false.</summary>
IS_FALSE = 1,
/// <summary>Marked parameter should be evaluated to null value.</summary>
IS_NULL = 2,
/// <summary>Marked parameter should be evaluated to not null value.</summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception.
/// </summary>
[Obsolete("Use [ContractAnnotation('=> halt')] instead")]
[AttributeUsage(AttributeTargets.Method)]
public sealed class TerminatesProgramAttribute : Attribute { }
/// <summary>
/// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select,
/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters
/// of delegate type by analyzing LINQ method chains.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class LinqTunnelAttribute : Attribute { }
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class NoEnumerationAttribute : Attribute { }
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RegexPatternAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated
/// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class XamlItemsControlAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that
/// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will
/// enable the <c>DataContext</c> type resolve for XAML bindings for such properties.
/// </summary>
/// <remarks>
/// Property should have the tree ancestor of the <c>ItemsControl</c> type or
/// marked with the <see cref="XamlItemsControlAttribute"/> attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspChildControlTypeAttribute : Attribute
{
public AspChildControlTypeAttribute(string tagName, Type controlType)
{
TagName = tagName;
ControlType = controlType;
}
public string TagName { get; private set; }
public Type ControlType { get; private set; }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldsAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspMethodPropertyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspRequiredAttributeAttribute : Attribute
{
public AspRequiredAttributeAttribute([NotNull] string attribute)
{
Attribute = attribute;
}
public string Attribute { get; private set; }
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspTypePropertyAttribute : Attribute
{
public bool CreateConstructorReferences { get; private set; }
public AspTypePropertyAttribute(bool createConstructorReferences)
{
CreateConstructorReferences = createConstructorReferences;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorImportNamespaceAttribute : Attribute
{
public RazorImportNamespaceAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorInjectionAttribute : Attribute
{
public RazorInjectionAttribute(string type, string fieldName)
{
Type = type;
FieldName = fieldName;
}
public string Type { get; private set; }
public string FieldName { get; private set; }
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorHelperCommonAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class RazorLayoutAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteLiteralMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RazorWriteMethodParameterAttribute : Attribute { }
/// <summary>
/// Prevents the Member Reordering feature from tossing members of the marked class.
/// </summary>
/// <remarks>
/// The attribute must be mentioned in your member reordering patterns
/// </remarks>
[AttributeUsage(AttributeTargets.All)]
public sealed class NoReorder : Attribute { }
} | 38.552209 | 119 | 0.703709 | [
"MIT"
] | vii33/PomodoroClock | SourceCode/PomodoroClock/Properties/Annotations.cs | 38,400 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201
{
using static Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Extensions;
/// <summary>Publishing Credentials Policies entity collection ARM resource.</summary>
public partial class PublishingCredentialsPoliciesCollection
{
/// <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.Websites.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.Websites.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.Websites.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.Websites.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.Websites.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.IPublishingCredentialsPoliciesCollection.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.IPublishingCredentialsPoliciesCollection.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.IPublishingCredentialsPoliciesCollection FromJson(Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonObject json ? new PublishingCredentialsPoliciesCollection(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonObject into a new instance of <see cref="PublishingCredentialsPoliciesCollection" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonObject instance to deserialize from.</param>
internal PublishingCredentialsPoliciesCollection(Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_value = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonArray>("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonArray, out var __v) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.ICsmPublishingCredentialsPoliciesEntity[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.ICsmPublishingCredentialsPoliciesEntity) (Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.CsmPublishingCredentialsPoliciesEntity.FromJson(__u) )) ))() : null : Value;}
{_nextLink = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonString>("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="PublishingCredentialsPoliciesCollection" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode"
/// />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.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.Websites.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="PublishingCredentialsPoliciesCollection" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode"
/// />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (null != this._value)
{
var __w = new Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.XNodeArray();
foreach( var __x in this._value )
{
AddIf(__x?.ToJson(null, serializationMode) ,__w.Add);
}
container.Add("value",__w);
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add );
}
AfterToJson(ref container);
return container;
}
}
} | 70.272727 | 716 | 0.689521 | [
"MIT"
] | Agazoth/azure-powershell | src/Websites/Websites.Autorest/generated/api/Models/Api20210201/PublishingCredentialsPoliciesCollection.json.cs | 8,383 | C# |
using Patreon.Api.Core.V2.Builders;
using Patreon.Api.Core.V2.Resources;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Patreon.Api.Core.V2.Endpoints
{
/// <summary> A patreon client which interacts with webhook endpoints.</summary>
/// <typeparam name="TWebhook"> The webhook type the client will retrieve.</typeparam>
/// <typeparam name="TToken"> The token type to be sent in the request for authorization.</typeparam>
public interface IWebhookClient<TWebhook, TToken>
where TWebhook : IWebhook
where TToken : ITokenResponse
{
/// <summary> Retrieves a collection of webhooks from the patreon API.</summary>
/// <param name="token"> The token used for autorization.</param>
/// <param name="builder"> The builder used for forming the webhook collection.</param>
/// <returns> Colletion of webhooks.</returns>
Task<IReadOnlyCollection<TWebhook>> GetWebhooks(TToken token, IWebhookCollectionBuilder<TWebhook> builder);
/// <summary> Adds webhook through the patreon API.</summary>
/// <typeparam name="TWebhookData"> The webhook data type</typeparam>
/// <param name="token"> The token used for autorization.</param>
/// <param name="webhook"> The webhook data to add.</param>
/// <returns> Newly created webhook.</returns>
Task<TWebhook> PostWebhook<TWebhookData>(TToken token, TWebhookData webhook) where TWebhookData : IWebhook;
/// <summary> Changes the webhook through the patreon API.</summary>
/// <typeparam name="TWebhookData"> The webhook data type</typeparam>
/// <param name="token"> The token used for autorization.</param>
/// <param name="webhook"> The webhook data to patch with.</param>
/// <returns> Patched webhook.</returns>
Task<TWebhook> PatchWebhook<TWebhookData>(TToken token, TWebhookData webhook) where TWebhookData : IWebhook;
}
}
| 54.833333 | 116 | 0.687437 | [
"MIT"
] | Pheubel/Patreon | src/Patreon.Api.Core/V2/Endpoints/IWebhookClient.cs | 1,976 | C# |
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace Models
{
public class User : KeyBase
{
[BsonElement("user-code")]
public string Code { get; set; }
[BsonElement("name")]
public string Name { get; set; }
}
} | 19.928571 | 44 | 0.609319 | [
"Apache-2.0"
] | ruben69695/todolist-aspnetcore3 | Models/User.cs | 279 | C# |
using System.Collections.Generic;
namespace lp73.designPatterns.Mediator
{
public class Formulaire
{
protected IList<Controle> Controles =
new List<Controle>();
protected IList<Controle> ControlesCoemprunteur =
new List<Controle>();
public PopupMenu MenuCoemprunteur { protected get; set; }
public Bouton BoutonOk { protected get; set; }
protected bool EnCours = true;
public void AjouteControle(Controle controle)
{
Controles.Add(controle);
controle.Directeur = this;
}
public void AjouteControleCoemprunteur(Controle
controle)
{
ControlesCoemprunteur.Add(controle);
controle.Directeur = this;
}
public void ControleModifie(Controle controle)
{
if (controle == MenuCoemprunteur)
if (controle.Valeur == "avec coemprunteur")
{
foreach (Controle elementCoemprunteur in
ControlesCoemprunteur)
elementCoemprunteur.Saisie();
}
if (controle == BoutonOk)
{
EnCours = false;
}
}
public void Saisie()
{
while (true)
{
foreach (Controle controle in Controles)
{
controle.Saisie();
if (!EnCours)
return ;
}
}
}
}
}
| 27.103448 | 65 | 0.495547 | [
"CC0-1.0"
] | proced/Design-patterns | Design-pattern/designPatterns/Mediator/Formulaire.cs | 1,572 | C# |
namespace Crimson.Tweening
{
public enum AnimationType
{
Tween,
Sequence,
}
} | 13.25 | 29 | 0.566038 | [
"MIT"
] | aszecsei/Crimson | Crimson/Tweening/AnimationType.cs | 108 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Mundipagg.Models.Request
{
[JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class CreateOrderItemRequest
{
public int Amount { get; set; }
public string Category { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public CreateSellerRequest Seller { get; set; }
public string SellerId { get; set; }
}
} | 23.695652 | 70 | 0.653211 | [
"MIT"
] | AmandaMaiaPessanha/mundipagg-dotnet | Mundipagg/Models/Request/CreateOrderItemRequest.cs | 545 | 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("ConsoleFull")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleFull")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("07f966b7-8f2d-45a2-acb4-f207b7e0c513")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.567568 | 84 | 0.747482 | [
"MIT"
] | bigdnf/DependencyFinder | Test/Nasted/ConsoleFull/ConsoleFull/Properties/AssemblyInfo.cs | 1,393 | C# |
#region License
// Copyright (c) 2010-2016, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation 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 HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
namespace Installer
{
public static partial class CommandLineImplementation
{
public static void
Convert(
this IDiskImageSettings settings,
Bam.Core.StringArray commandLine)
{
switch (settings.Verbosity)
{
case EDiskImageVerbosity.Default:
break;
case EDiskImageVerbosity.Quiet:
commandLine.Add("-quiet");
break;
case EDiskImageVerbosity.Verbose:
commandLine.Add("-verbose");
break;
case EDiskImageVerbosity.Debug:
commandLine.Add("-debug");
break;
default:
throw new Bam.Core.Exception("Unknown disk image verbosity level, {0}", settings.Verbosity.ToString());
}
// Note: intentionally not parsing ImageSize - used later in the builder scripts
}
}
}
| 39.984375 | 119 | 0.684642 | [
"BSD-3-Clause"
] | ChrigiGee/BuildAMation | packages/Installer/bam/Scripts/DiskImageSettings/CommandLine/IDiskImageSettings.cs | 2,559 | C# |
namespace GeuzePortal
{
using System.Reflection;
/// <summary>The globals.</summary>
public class Globals
{
/// <summary>The website title.</summary>
public const string WebsiteTitle = "World of Raul";
/// <summary>The version.</summary>
public static readonly string Version = "v" + Assembly.GetExecutingAssembly().GetName().Version;
}
} | 28.071429 | 104 | 0.641221 | [
"MIT"
] | andregeuze/andregeuze.github.io | threejs-game/GeuzePortal/Globals.cs | 395 | C# |
using Stump.DofusProtocol.Enums;
using Stump.Server.WorldServer.Database.World;
using Stump.Server.WorldServer.Game.Actors.Fight;
using Stump.Server.WorldServer.Game.Effects.Instances;
using Stump.Server.WorldServer.Game.Fights.Buffs.Customs;
using Spell = Stump.Server.WorldServer.Game.Spells.Spell;
using Stump.Server.WorldServer.Game.Spells.Casts;
using System.Linq;
namespace Stump.Server.WorldServer.Game.Effects.Handlers.Spells.Buffs
{
[EffectHandler(EffectsEnum.Effect_SubResistances)]
[EffectHandler(EffectsEnum.Effect_AddResistances)]
public class Resistances : SpellEffectHandler
{
public Resistances(EffectDice effect, FightActor caster, SpellCastHandler castHandler, Cell targetedCell, bool critical)
: base(effect, caster, castHandler, targetedCell, critical)
{
}
protected override bool InternalApply()
{
var integerEffect = GenerateEffect();
if (integerEffect == null)
return false;
foreach (var actor in GetAffectedActors())
{
var buff = new ResistancesBuff(actor.PopNextBuffId(), actor, Caster, this, Spell,
(short) ((Effect.EffectId == EffectsEnum.Effect_SubResistances) ? -integerEffect.Value : integerEffect.Value),
false, FightDispellableEnum.DISPELLABLE);
actor.AddBuff(buff);
}
return true;
}
}
} | 35.853659 | 130 | 0.67483 | [
"Apache-2.0"
] | Daymortel/Stump | src/Stump.Server.WorldServer/game/effects/handlers/Spells/Buffs/Resistances.cs | 1,470 | C# |
// This file was @generated with LibOVRPlatform/codegen/main. Do not modify it!
namespace Oculus.Platform
{
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Oculus.Platform.Models;
public abstract class Message<T> : Message
{
public delegate void Callback(Message<T> message);
public Message(IntPtr c_message) : base(c_message) {
if (!IsError)
{
data = GetDataFromMessage(c_message);
}
}
public T Data { get { return data; } }
protected abstract T GetDataFromMessage(IntPtr c_message);
private T data;
}
public class Message
{
public delegate void Callback(Message message);
public Message(IntPtr c_message)
{
type = (MessageType)CAPI.ovr_Message_GetType(c_message);
var isError = CAPI.ovr_Message_IsError(c_message);
requestID = CAPI.ovr_Message_GetRequestID(c_message);
if (isError)
{
IntPtr errorHandle = CAPI.ovr_Message_GetError(c_message);
error = new Error(
CAPI.ovr_Error_GetCode(errorHandle),
CAPI.ovr_Error_GetMessage(errorHandle),
CAPI.ovr_Error_GetHttpCode(errorHandle));
}
else if (Core.LogMessages)
{
var message = CAPI.ovr_Message_GetString(c_message);
if (message != null)
{
Debug.Log(message);
}
else
{
Debug.Log(string.Format("null message string {0}", c_message));
}
}
}
~Message()
{
}
// Keep this enum in sync with ovrMessageType in OVR_Platform.h
public enum MessageType : uint
{ //TODO - rename this to type; it's already in Message class
Unknown,
Achievements_AddCount = 0x03E76231,
Achievements_AddFields = 0x14AA2129,
Achievements_GetAllDefinitions = 0x03D3458D,
Achievements_GetAllProgress = 0x4F9FDE1D,
Achievements_GetDefinitionsByName = 0x629101BC,
Achievements_GetNextAchievementDefinitionArrayPage = 0x2A7DD255,
Achievements_GetNextAchievementProgressArrayPage = 0x2F42E727,
Achievements_GetProgressByName = 0x152663B1,
Achievements_Unlock = 0x593CCBDD,
ApplicationLifecycle_GetRegisteredPIDs = 0x04E5CF62,
ApplicationLifecycle_GetSessionKey = 0x3AAF591D,
ApplicationLifecycle_RegisterSessionKey = 0x4DB6AFF8,
Application_GetVersion = 0x68670A0E,
CloudStorage_Delete = 0x28DA456D,
CloudStorage_GetNextCloudStorageMetadataArrayPage = 0x5C07A2EF,
CloudStorage_Load = 0x40846B41,
CloudStorage_LoadBucketMetadata = 0x7327A50D,
CloudStorage_LoadConflictMetadata = 0x445A52F2,
CloudStorage_LoadHandle = 0x326ADA36,
CloudStorage_LoadMetadata = 0x03E6A292,
CloudStorage_ResolveKeepLocal = 0x30588D05,
CloudStorage_ResolveKeepRemote = 0x7525A306,
CloudStorage_Save = 0x4BBB5C2E,
Entitlement_GetIsViewerEntitled = 0x186B58B1,
IAP_ConsumePurchase = 0x1FBB72D9,
IAP_GetNextProductArrayPage = 0x1BD94AAF,
IAP_GetNextPurchaseArrayPage = 0x47570A95,
IAP_GetProductsBySKU = 0x7E9ACAF5,
IAP_GetViewerPurchases = 0x3A0F8419,
IAP_LaunchCheckoutFlow = 0x3F9B0D0D,
Leaderboard_GetEntries = 0x5DB3474C,
Leaderboard_GetEntriesAfterRank = 0x18378BEF,
Leaderboard_GetNextEntries = 0x4E207CD9,
Leaderboard_GetPreviousEntries = 0x4901DAC0,
Leaderboard_WriteEntry = 0x117FC8FE,
Livestreaming_GetStatus = 0x489A6995,
Livestreaming_PauseStream = 0x369C7683,
Livestreaming_ResumeStream = 0x22526D8F,
Matchmaking_Browse = 0x1E6532C8,
Matchmaking_Browse2 = 0x66429E5B,
Matchmaking_Cancel = 0x206849AF,
Matchmaking_Cancel2 = 0x10FE8DD4,
Matchmaking_CreateAndEnqueueRoom = 0x604C5DC8,
Matchmaking_CreateAndEnqueueRoom2 = 0x295BEADB,
Matchmaking_CreateRoom = 0x033B132A,
Matchmaking_CreateRoom2 = 0x496DA384,
Matchmaking_Enqueue = 0x40C16C71,
Matchmaking_Enqueue2 = 0x121212B5,
Matchmaking_EnqueueRoom = 0x708A4064,
Matchmaking_EnqueueRoom2 = 0x5528DBA4,
Matchmaking_GetAdminSnapshot = 0x3C215F94,
Matchmaking_GetStats = 0x42FC9438,
Matchmaking_JoinRoom = 0x4D32D7FD,
Matchmaking_ReportResultInsecure = 0x1A36D18D,
Matchmaking_StartMatch = 0x44D40945,
Notification_GetNextRoomInviteNotificationArrayPage = 0x0621FB77,
Notification_GetRoomInvites = 0x6F916B92,
Notification_MarkAsRead = 0x717259E3,
Party_GetCurrent = 0x47933760,
Room_CreateAndJoinPrivate = 0x75D6E377,
Room_CreateAndJoinPrivate2 = 0x5A3A6243,
Room_Get = 0x659A8FB8,
Room_GetCurrent = 0x09A6A504,
Room_GetCurrentForUser = 0x0E0017E5,
Room_GetInvitableUsers = 0x1E325792,
Room_GetInvitableUsers2 = 0x4F53E8B0,
Room_GetModeratedRooms = 0x0983FD77,
Room_GetNextRoomArrayPage = 0x4E8379C6,
Room_InviteUser = 0x4129EC13,
Room_Join = 0x16CA8F09,
Room_Join2 = 0x4DAB1C42,
Room_KickUser = 0x49835736,
Room_LaunchInvitableUserFlow = 0x323FE273,
Room_Leave = 0x72382475,
Room_SetDescription = 0x3044852F,
Room_UpdateDataStore = 0x026E4028,
Room_UpdateMembershipLockStatus = 0x370BB7AC,
Room_UpdateOwner = 0x32B63D1D,
Room_UpdatePrivateRoomJoinPolicy = 0x1141029B,
User_Get = 0x6BCF9E47,
User_GetAccessToken = 0x06A85ABE,
User_GetLoggedInUser = 0x436F345D,
User_GetLoggedInUserFriends = 0x587C2A8D,
User_GetLoggedInUserFriendsAndRooms = 0x5E870B87,
User_GetLoggedInUserRecentlyMetUsersAndRooms = 0x295FBA30,
User_GetNextUserAndRoomArrayPage = 0x7FBDD2DF,
User_GetNextUserArrayPage = 0x267CF743,
User_GetOrgScopedID = 0x18F0B01B,
User_GetSdkAccounts = 0x67526A83,
User_GetUserProof = 0x22810483,
User_LaunchProfile = 0x0A397297,
Voip_SetSystemVoipSuppressed = 0x453FC9AA,
/// Sent to indicate that more data has been read or an error occured.
Notification_HTTP_Transfer = 0x7DD46E2F,
/// Indicates that the livestreaming session has been updated. You can use this
/// information to throttle your game performance or increase CPU/GPU
/// performance. Use Message.GetLivestreamingStatus() to extract the updated
/// livestreaming status.
Notification_Livestreaming_StatusChange = 0x2247596E,
/// Indicates that a match has been found, for example after calling
/// Matchmaking.Enqueue(). Use Message.GetRoom() to extract the matchmaking
/// room.
Notification_Matchmaking_MatchFound = 0x0BC3FCD7,
/// Indicates that a connection has been established or there's been an error.
/// Use NetworkingPeer.GetState() to get the result; as above,
/// NetworkingPeer.GetID() returns the ID of the peer this message is for.
Notification_Networking_ConnectionStateChange = 0x5E02D49A,
/// Indicates that another user is attempting to establish a P2P connection
/// with us. Use NetworkingPeer.GetID() to extract the ID of the peer.
Notification_Networking_PeerConnectRequest = 0x4D31E2CF,
/// Generated in response to Net.Ping(). Either contains ping time in
/// microseconds or indicates that there was a timeout.
Notification_Networking_PingResult = 0x51153012,
/// Indicates that the user has accepted an invitation, for example in Oculus
/// Home. Use Message.GetString() to extract the ID of the room that the user
/// has been inivted to as a string. Then call ovrID_FromString() to parse it
/// into an ovrID.
///
/// Note that you must call Room.Join() if you want to actually join the room.
Notification_Room_InviteAccepted = 0x6D1071B1,
/// Handle this to notify the user when they've received an invitation to join
/// a room in your game. You can use this in lieu of, or in addition to,
/// polling for room invitations via Notification.GetRoomInviteNotifications().
Notification_Room_InviteReceived = 0x6A499D54,
/// Indicates that the current room has been updated. Use Message.GetRoom() to
/// extract the updated room.
Notification_Room_RoomUpdate = 0x60EC3C2F,
/// Sent when another user is attempting to establish a VoIP connection. Use
/// Message.GetNetworkingPeer() to extract information about the user, and
/// Voip.Accept() to accept the connection.
Notification_Voip_ConnectRequest = 0x36243816,
/// Sent to indicate that the state of the VoIP connection changed. Use
/// Message.GetNetworkingPeer() and NetworkingPeer.GetState() to extract the
/// current state.
Notification_Voip_StateChange = 0x34EFA660,
/// Sent to indicate that some part of the overall state of SystemVoip has
/// changed. Use Message.GetSystemVoipState() and the properties of
/// SystemVoipState to extract the state that triggered the notification.
///
/// Note that the state may have changed further since the notification was
/// generated, and that you may call the `GetSystemVoip...()` family of
/// functions at any time to get the current state directly.
Notification_Voip_SystemVoipState = 0x58D254A5,
Platform_InitializeStandaloneOculus = 0x51F8CE0C,
Platform_InitializeAndroidAsynchronous = 0x1AD307B4,
Platform_InitializeWindowsAsynchronous = 0x6DA7BA8F,
};
public MessageType Type { get { return type; } }
public bool IsError { get { return error != null; } }
public ulong RequestID { get { return requestID; } }
private MessageType type;
private ulong requestID;
private Error error;
public virtual Error GetError() { return error; }
public virtual PingResult GetPingResult() { return null; }
public virtual NetworkingPeer GetNetworkingPeer() { return null; }
public virtual HttpTransferUpdate GetHttpTransferUpdate() { return null; }
public virtual PlatformInitialize GetPlatformInitialize() { return null; }
public virtual AchievementDefinitionList GetAchievementDefinitions() { return null; }
public virtual AchievementProgressList GetAchievementProgressList() { return null; }
public virtual AchievementUpdate GetAchievementUpdate() { return null; }
public virtual ApplicationVersion GetApplicationVersion() { return null; }
public virtual CloudStorageConflictMetadata GetCloudStorageConflictMetadata() { return null; }
public virtual CloudStorageData GetCloudStorageData() { return null; }
public virtual CloudStorageMetadata GetCloudStorageMetadata() { return null; }
public virtual CloudStorageMetadataList GetCloudStorageMetadataList() { return null; }
public virtual CloudStorageUpdateResponse GetCloudStorageUpdateResponse() { return null; }
public virtual InstalledApplicationList GetInstalledApplicationList() { return null; }
public virtual bool GetLeaderboardDidUpdate() { return false; }
public virtual LeaderboardEntryList GetLeaderboardEntryList() { return null; }
public virtual LivestreamingApplicationStatus GetLivestreamingApplicationStatus() { return null; }
public virtual LivestreamingStartResult GetLivestreamingStartResult() { return null; }
public virtual LivestreamingStatus GetLivestreamingStatus() { return null; }
public virtual LivestreamingVideoStats GetLivestreamingVideoStats() { return null; }
public virtual MatchmakingAdminSnapshot GetMatchmakingAdminSnapshot() { return null; }
public virtual MatchmakingBrowseResult GetMatchmakingBrowseResult() { return null; }
public virtual MatchmakingEnqueueResult GetMatchmakingEnqueueResult() { return null; }
public virtual MatchmakingEnqueueResultAndRoom GetMatchmakingEnqueueResultAndRoom() { return null; }
public virtual MatchmakingStats GetMatchmakingStats() { return null; }
public virtual OrgScopedID GetOrgScopedID() { return null; }
public virtual Party GetParty() { return null; }
public virtual PartyID GetPartyID() { return null; }
public virtual PidList GetPidList() { return null; }
public virtual ProductList GetProductList() { return null; }
public virtual Purchase GetPurchase() { return null; }
public virtual PurchaseList GetPurchaseList() { return null; }
public virtual Room GetRoom() { return null; }
public virtual RoomInviteNotification GetRoomInviteNotification() { return null; }
public virtual RoomInviteNotificationList GetRoomInviteNotificationList() { return null; }
public virtual RoomList GetRoomList() { return null; }
public virtual SdkAccountList GetSdkAccountList() { return null; }
public virtual string GetString() { return null; }
public virtual SystemPermission GetSystemPermission() { return null; }
public virtual SystemVoipState GetSystemVoipState() { return null; }
public virtual User GetUser() { return null; }
public virtual UserAndRoomList GetUserAndRoomList() { return null; }
public virtual UserList GetUserList() { return null; }
public virtual UserProof GetUserProof() { return null; }
internal static Message ParseMessageHandle(IntPtr messageHandle)
{
if (messageHandle.ToInt64() == 0)
{
return null;
}
Message message = null;
Message.MessageType message_type = (Message.MessageType)CAPI.ovr_Message_GetType(messageHandle);
switch(message_type) {
// OVR_MESSAGE_TYPE_START
case Message.MessageType.Achievements_GetAllDefinitions:
case Message.MessageType.Achievements_GetDefinitionsByName:
case Message.MessageType.Achievements_GetNextAchievementDefinitionArrayPage:
message = new MessageWithAchievementDefinitions(messageHandle);
break;
case Message.MessageType.Achievements_GetAllProgress:
case Message.MessageType.Achievements_GetNextAchievementProgressArrayPage:
case Message.MessageType.Achievements_GetProgressByName:
message = new MessageWithAchievementProgressList(messageHandle);
break;
case Message.MessageType.Achievements_AddCount:
case Message.MessageType.Achievements_AddFields:
case Message.MessageType.Achievements_Unlock:
message = new MessageWithAchievementUpdate(messageHandle);
break;
case Message.MessageType.Application_GetVersion:
message = new MessageWithApplicationVersion(messageHandle);
break;
case Message.MessageType.CloudStorage_LoadConflictMetadata:
message = new MessageWithCloudStorageConflictMetadata(messageHandle);
break;
case Message.MessageType.CloudStorage_Load:
case Message.MessageType.CloudStorage_LoadHandle:
message = new MessageWithCloudStorageData(messageHandle);
break;
case Message.MessageType.CloudStorage_LoadMetadata:
message = new MessageWithCloudStorageMetadataUnderLocal(messageHandle);
break;
case Message.MessageType.CloudStorage_GetNextCloudStorageMetadataArrayPage:
case Message.MessageType.CloudStorage_LoadBucketMetadata:
message = new MessageWithCloudStorageMetadataList(messageHandle);
break;
case Message.MessageType.CloudStorage_Delete:
case Message.MessageType.CloudStorage_ResolveKeepLocal:
case Message.MessageType.CloudStorage_ResolveKeepRemote:
case Message.MessageType.CloudStorage_Save:
message = new MessageWithCloudStorageUpdateResponse(messageHandle);
break;
case Message.MessageType.ApplicationLifecycle_RegisterSessionKey:
case Message.MessageType.Entitlement_GetIsViewerEntitled:
case Message.MessageType.IAP_ConsumePurchase:
case Message.MessageType.Matchmaking_Cancel:
case Message.MessageType.Matchmaking_Cancel2:
case Message.MessageType.Matchmaking_ReportResultInsecure:
case Message.MessageType.Matchmaking_StartMatch:
case Message.MessageType.Notification_MarkAsRead:
case Message.MessageType.Room_LaunchInvitableUserFlow:
case Message.MessageType.Room_UpdateOwner:
case Message.MessageType.User_LaunchProfile:
message = new Message(messageHandle);
break;
case Message.MessageType.Leaderboard_GetEntries:
case Message.MessageType.Leaderboard_GetEntriesAfterRank:
case Message.MessageType.Leaderboard_GetNextEntries:
case Message.MessageType.Leaderboard_GetPreviousEntries:
message = new MessageWithLeaderboardEntryList(messageHandle);
break;
case Message.MessageType.Leaderboard_WriteEntry:
message = new MessageWithLeaderboardDidUpdate(messageHandle);
break;
case Message.MessageType.Livestreaming_GetStatus:
case Message.MessageType.Livestreaming_PauseStream:
case Message.MessageType.Livestreaming_ResumeStream:
case Message.MessageType.Notification_Livestreaming_StatusChange:
message = new MessageWithLivestreamingStatus(messageHandle);
break;
case Message.MessageType.Matchmaking_GetAdminSnapshot:
message = new MessageWithMatchmakingAdminSnapshot(messageHandle);
break;
case Message.MessageType.Matchmaking_Browse:
case Message.MessageType.Matchmaking_Browse2:
message = new MessageWithMatchmakingBrowseResult(messageHandle);
break;
case Message.MessageType.Matchmaking_Enqueue:
case Message.MessageType.Matchmaking_Enqueue2:
case Message.MessageType.Matchmaking_EnqueueRoom:
case Message.MessageType.Matchmaking_EnqueueRoom2:
message = new MessageWithMatchmakingEnqueueResult(messageHandle);
break;
case Message.MessageType.Matchmaking_CreateAndEnqueueRoom:
case Message.MessageType.Matchmaking_CreateAndEnqueueRoom2:
message = new MessageWithMatchmakingEnqueueResultAndRoom(messageHandle);
break;
case Message.MessageType.Matchmaking_GetStats:
message = new MessageWithMatchmakingStatsUnderMatchmakingStats(messageHandle);
break;
case Message.MessageType.User_GetOrgScopedID:
message = new MessageWithOrgScopedID(messageHandle);
break;
case Message.MessageType.Party_GetCurrent:
message = new MessageWithPartyUnderCurrentParty(messageHandle);
break;
case Message.MessageType.ApplicationLifecycle_GetRegisteredPIDs:
message = new MessageWithPidList(messageHandle);
break;
case Message.MessageType.IAP_GetNextProductArrayPage:
case Message.MessageType.IAP_GetProductsBySKU:
message = new MessageWithProductList(messageHandle);
break;
case Message.MessageType.IAP_LaunchCheckoutFlow:
message = new MessageWithPurchase(messageHandle);
break;
case Message.MessageType.IAP_GetNextPurchaseArrayPage:
case Message.MessageType.IAP_GetViewerPurchases:
message = new MessageWithPurchaseList(messageHandle);
break;
case Message.MessageType.Room_Get:
message = new MessageWithRoom(messageHandle);
break;
case Message.MessageType.Room_GetCurrent:
case Message.MessageType.Room_GetCurrentForUser:
message = new MessageWithRoomUnderCurrentRoom(messageHandle);
break;
case Message.MessageType.Matchmaking_CreateRoom:
case Message.MessageType.Matchmaking_CreateRoom2:
case Message.MessageType.Matchmaking_JoinRoom:
case Message.MessageType.Notification_Room_RoomUpdate:
case Message.MessageType.Room_CreateAndJoinPrivate:
case Message.MessageType.Room_CreateAndJoinPrivate2:
case Message.MessageType.Room_InviteUser:
case Message.MessageType.Room_Join:
case Message.MessageType.Room_Join2:
case Message.MessageType.Room_KickUser:
case Message.MessageType.Room_Leave:
case Message.MessageType.Room_SetDescription:
case Message.MessageType.Room_UpdateDataStore:
case Message.MessageType.Room_UpdateMembershipLockStatus:
case Message.MessageType.Room_UpdatePrivateRoomJoinPolicy:
message = new MessageWithRoomUnderViewerRoom(messageHandle);
break;
case Message.MessageType.Room_GetModeratedRooms:
case Message.MessageType.Room_GetNextRoomArrayPage:
message = new MessageWithRoomList(messageHandle);
break;
case Message.MessageType.Notification_Room_InviteReceived:
message = new MessageWithRoomInviteNotification(messageHandle);
break;
case Message.MessageType.Notification_GetNextRoomInviteNotificationArrayPage:
case Message.MessageType.Notification_GetRoomInvites:
message = new MessageWithRoomInviteNotificationList(messageHandle);
break;
case Message.MessageType.User_GetSdkAccounts:
message = new MessageWithSdkAccountList(messageHandle);
break;
case Message.MessageType.ApplicationLifecycle_GetSessionKey:
case Message.MessageType.Notification_Room_InviteAccepted:
case Message.MessageType.User_GetAccessToken:
message = new MessageWithString(messageHandle);
break;
case Message.MessageType.Voip_SetSystemVoipSuppressed:
message = new MessageWithSystemVoipState(messageHandle);
break;
case Message.MessageType.User_Get:
case Message.MessageType.User_GetLoggedInUser:
message = new MessageWithUser(messageHandle);
break;
case Message.MessageType.User_GetLoggedInUserFriendsAndRooms:
case Message.MessageType.User_GetLoggedInUserRecentlyMetUsersAndRooms:
case Message.MessageType.User_GetNextUserAndRoomArrayPage:
message = new MessageWithUserAndRoomList(messageHandle);
break;
case Message.MessageType.Room_GetInvitableUsers:
case Message.MessageType.Room_GetInvitableUsers2:
case Message.MessageType.User_GetLoggedInUserFriends:
case Message.MessageType.User_GetNextUserArrayPage:
message = new MessageWithUserList(messageHandle);
break;
case Message.MessageType.User_GetUserProof:
message = new MessageWithUserProof(messageHandle);
break;
case Message.MessageType.Notification_Networking_ConnectionStateChange:
case Message.MessageType.Notification_Networking_PeerConnectRequest:
message = new MessageWithNetworkingPeer(messageHandle);
break;
case Message.MessageType.Notification_Networking_PingResult:
message = new MessageWithPingResult(messageHandle);
break;
case Message.MessageType.Notification_Matchmaking_MatchFound:
message = new MessageWithMatchmakingNotification(messageHandle);
break;
case Message.MessageType.Notification_Voip_ConnectRequest:
case Message.MessageType.Notification_Voip_StateChange:
message = new MessageWithNetworkingPeer(messageHandle);
break;
case Message.MessageType.Notification_Voip_SystemVoipState:
message = new MessageWithSystemVoipState(messageHandle);
break;
case Message.MessageType.Notification_HTTP_Transfer:
message = new MessageWithHttpTransferUpdate(messageHandle);
break;
case Message.MessageType.Platform_InitializeStandaloneOculus:
case Message.MessageType.Platform_InitializeAndroidAsynchronous:
case Message.MessageType.Platform_InitializeWindowsAsynchronous:
message = new MessageWithPlatformInitialize(messageHandle);
break;
default:
message = PlatformInternal.ParseMessageHandle(messageHandle, message_type);
if (message == null)
{
Debug.LogError(string.Format("Unrecognized message type {0}\n", message_type));
}
break;
// OVR_MESSAGE_TYPE_END
}
return message;
}
public static Message PopMessage()
{
if (!Core.IsInitialized())
{
return null;
}
var messageHandle = CAPI.ovr_PopMessage();
Message message = ParseMessageHandle(messageHandle);
CAPI.ovr_FreeMessage(messageHandle);
return message;
}
internal delegate Message ExtraMessageTypesHandler(IntPtr messageHandle, Message.MessageType message_type);
internal static ExtraMessageTypesHandler HandleExtraMessageTypes { set; private get; }
}
public class MessageWithAchievementDefinitions : Message<AchievementDefinitionList>
{
public MessageWithAchievementDefinitions(IntPtr c_message) : base(c_message) { }
public override AchievementDefinitionList GetAchievementDefinitions() { return Data; }
protected override AchievementDefinitionList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetAchievementDefinitionArray(msg);
return new AchievementDefinitionList(obj);
}
}
public class MessageWithAchievementProgressList : Message<AchievementProgressList>
{
public MessageWithAchievementProgressList(IntPtr c_message) : base(c_message) { }
public override AchievementProgressList GetAchievementProgressList() { return Data; }
protected override AchievementProgressList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetAchievementProgressArray(msg);
return new AchievementProgressList(obj);
}
}
public class MessageWithAchievementUpdate : Message<AchievementUpdate>
{
public MessageWithAchievementUpdate(IntPtr c_message) : base(c_message) { }
public override AchievementUpdate GetAchievementUpdate() { return Data; }
protected override AchievementUpdate GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetAchievementUpdate(msg);
return new AchievementUpdate(obj);
}
}
public class MessageWithApplicationVersion : Message<ApplicationVersion>
{
public MessageWithApplicationVersion(IntPtr c_message) : base(c_message) { }
public override ApplicationVersion GetApplicationVersion() { return Data; }
protected override ApplicationVersion GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetApplicationVersion(msg);
return new ApplicationVersion(obj);
}
}
public class MessageWithCloudStorageConflictMetadata : Message<CloudStorageConflictMetadata>
{
public MessageWithCloudStorageConflictMetadata(IntPtr c_message) : base(c_message) { }
public override CloudStorageConflictMetadata GetCloudStorageConflictMetadata() { return Data; }
protected override CloudStorageConflictMetadata GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetCloudStorageConflictMetadata(msg);
return new CloudStorageConflictMetadata(obj);
}
}
public class MessageWithCloudStorageData : Message<CloudStorageData>
{
public MessageWithCloudStorageData(IntPtr c_message) : base(c_message) { }
public override CloudStorageData GetCloudStorageData() { return Data; }
protected override CloudStorageData GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetCloudStorageData(msg);
return new CloudStorageData(obj);
}
}
public class MessageWithCloudStorageMetadataUnderLocal : Message<CloudStorageMetadata>
{
public MessageWithCloudStorageMetadataUnderLocal(IntPtr c_message) : base(c_message) { }
public override CloudStorageMetadata GetCloudStorageMetadata() { return Data; }
protected override CloudStorageMetadata GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetCloudStorageMetadata(msg);
return new CloudStorageMetadata(obj);
}
}
public class MessageWithCloudStorageMetadataList : Message<CloudStorageMetadataList>
{
public MessageWithCloudStorageMetadataList(IntPtr c_message) : base(c_message) { }
public override CloudStorageMetadataList GetCloudStorageMetadataList() { return Data; }
protected override CloudStorageMetadataList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetCloudStorageMetadataArray(msg);
return new CloudStorageMetadataList(obj);
}
}
public class MessageWithCloudStorageUpdateResponse : Message<CloudStorageUpdateResponse>
{
public MessageWithCloudStorageUpdateResponse(IntPtr c_message) : base(c_message) { }
public override CloudStorageUpdateResponse GetCloudStorageUpdateResponse() { return Data; }
protected override CloudStorageUpdateResponse GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetCloudStorageUpdateResponse(msg);
return new CloudStorageUpdateResponse(obj);
}
}
public class MessageWithInstalledApplicationList : Message<InstalledApplicationList>
{
public MessageWithInstalledApplicationList(IntPtr c_message) : base(c_message) { }
public override InstalledApplicationList GetInstalledApplicationList() { return Data; }
protected override InstalledApplicationList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetInstalledApplicationArray(msg);
return new InstalledApplicationList(obj);
}
}
public class MessageWithLeaderboardEntryList : Message<LeaderboardEntryList>
{
public MessageWithLeaderboardEntryList(IntPtr c_message) : base(c_message) { }
public override LeaderboardEntryList GetLeaderboardEntryList() { return Data; }
protected override LeaderboardEntryList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetLeaderboardEntryArray(msg);
return new LeaderboardEntryList(obj);
}
}
public class MessageWithLivestreamingApplicationStatus : Message<LivestreamingApplicationStatus>
{
public MessageWithLivestreamingApplicationStatus(IntPtr c_message) : base(c_message) { }
public override LivestreamingApplicationStatus GetLivestreamingApplicationStatus() { return Data; }
protected override LivestreamingApplicationStatus GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetLivestreamingApplicationStatus(msg);
return new LivestreamingApplicationStatus(obj);
}
}
public class MessageWithLivestreamingStartResult : Message<LivestreamingStartResult>
{
public MessageWithLivestreamingStartResult(IntPtr c_message) : base(c_message) { }
public override LivestreamingStartResult GetLivestreamingStartResult() { return Data; }
protected override LivestreamingStartResult GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetLivestreamingStartResult(msg);
return new LivestreamingStartResult(obj);
}
}
public class MessageWithLivestreamingStatus : Message<LivestreamingStatus>
{
public MessageWithLivestreamingStatus(IntPtr c_message) : base(c_message) { }
public override LivestreamingStatus GetLivestreamingStatus() { return Data; }
protected override LivestreamingStatus GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetLivestreamingStatus(msg);
return new LivestreamingStatus(obj);
}
}
public class MessageWithLivestreamingVideoStats : Message<LivestreamingVideoStats>
{
public MessageWithLivestreamingVideoStats(IntPtr c_message) : base(c_message) { }
public override LivestreamingVideoStats GetLivestreamingVideoStats() { return Data; }
protected override LivestreamingVideoStats GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetLivestreamingVideoStats(msg);
return new LivestreamingVideoStats(obj);
}
}
public class MessageWithMatchmakingAdminSnapshot : Message<MatchmakingAdminSnapshot>
{
public MessageWithMatchmakingAdminSnapshot(IntPtr c_message) : base(c_message) { }
public override MatchmakingAdminSnapshot GetMatchmakingAdminSnapshot() { return Data; }
protected override MatchmakingAdminSnapshot GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetMatchmakingAdminSnapshot(msg);
return new MatchmakingAdminSnapshot(obj);
}
}
public class MessageWithMatchmakingEnqueueResult : Message<MatchmakingEnqueueResult>
{
public MessageWithMatchmakingEnqueueResult(IntPtr c_message) : base(c_message) { }
public override MatchmakingEnqueueResult GetMatchmakingEnqueueResult() { return Data; }
protected override MatchmakingEnqueueResult GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetMatchmakingEnqueueResult(msg);
return new MatchmakingEnqueueResult(obj);
}
}
public class MessageWithMatchmakingEnqueueResultAndRoom : Message<MatchmakingEnqueueResultAndRoom>
{
public MessageWithMatchmakingEnqueueResultAndRoom(IntPtr c_message) : base(c_message) { }
public override MatchmakingEnqueueResultAndRoom GetMatchmakingEnqueueResultAndRoom() { return Data; }
protected override MatchmakingEnqueueResultAndRoom GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetMatchmakingEnqueueResultAndRoom(msg);
return new MatchmakingEnqueueResultAndRoom(obj);
}
}
public class MessageWithMatchmakingStatsUnderMatchmakingStats : Message<MatchmakingStats>
{
public MessageWithMatchmakingStatsUnderMatchmakingStats(IntPtr c_message) : base(c_message) { }
public override MatchmakingStats GetMatchmakingStats() { return Data; }
protected override MatchmakingStats GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetMatchmakingStats(msg);
return new MatchmakingStats(obj);
}
}
public class MessageWithOrgScopedID : Message<OrgScopedID>
{
public MessageWithOrgScopedID(IntPtr c_message) : base(c_message) { }
public override OrgScopedID GetOrgScopedID() { return Data; }
protected override OrgScopedID GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetOrgScopedID(msg);
return new OrgScopedID(obj);
}
}
public class MessageWithParty : Message<Party>
{
public MessageWithParty(IntPtr c_message) : base(c_message) { }
public override Party GetParty() { return Data; }
protected override Party GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetParty(msg);
return new Party(obj);
}
}
public class MessageWithPartyUnderCurrentParty : Message<Party>
{
public MessageWithPartyUnderCurrentParty(IntPtr c_message) : base(c_message) { }
public override Party GetParty() { return Data; }
protected override Party GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetParty(msg);
return new Party(obj);
}
}
public class MessageWithPartyID : Message<PartyID>
{
public MessageWithPartyID(IntPtr c_message) : base(c_message) { }
public override PartyID GetPartyID() { return Data; }
protected override PartyID GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetPartyID(msg);
return new PartyID(obj);
}
}
public class MessageWithPidList : Message<PidList>
{
public MessageWithPidList(IntPtr c_message) : base(c_message) { }
public override PidList GetPidList() { return Data; }
protected override PidList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetPidArray(msg);
return new PidList(obj);
}
}
public class MessageWithProductList : Message<ProductList>
{
public MessageWithProductList(IntPtr c_message) : base(c_message) { }
public override ProductList GetProductList() { return Data; }
protected override ProductList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetProductArray(msg);
return new ProductList(obj);
}
}
public class MessageWithPurchase : Message<Purchase>
{
public MessageWithPurchase(IntPtr c_message) : base(c_message) { }
public override Purchase GetPurchase() { return Data; }
protected override Purchase GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetPurchase(msg);
return new Purchase(obj);
}
}
public class MessageWithPurchaseList : Message<PurchaseList>
{
public MessageWithPurchaseList(IntPtr c_message) : base(c_message) { }
public override PurchaseList GetPurchaseList() { return Data; }
protected override PurchaseList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetPurchaseArray(msg);
return new PurchaseList(obj);
}
}
public class MessageWithRoom : Message<Room>
{
public MessageWithRoom(IntPtr c_message) : base(c_message) { }
public override Room GetRoom() { return Data; }
protected override Room GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetRoom(msg);
return new Room(obj);
}
}
public class MessageWithRoomUnderCurrentRoom : Message<Room>
{
public MessageWithRoomUnderCurrentRoom(IntPtr c_message) : base(c_message) { }
public override Room GetRoom() { return Data; }
protected override Room GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetRoom(msg);
return new Room(obj);
}
}
public class MessageWithRoomUnderViewerRoom : Message<Room>
{
public MessageWithRoomUnderViewerRoom(IntPtr c_message) : base(c_message) { }
public override Room GetRoom() { return Data; }
protected override Room GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetRoom(msg);
return new Room(obj);
}
}
public class MessageWithRoomList : Message<RoomList>
{
public MessageWithRoomList(IntPtr c_message) : base(c_message) { }
public override RoomList GetRoomList() { return Data; }
protected override RoomList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetRoomArray(msg);
return new RoomList(obj);
}
}
public class MessageWithRoomInviteNotification : Message<RoomInviteNotification>
{
public MessageWithRoomInviteNotification(IntPtr c_message) : base(c_message) { }
public override RoomInviteNotification GetRoomInviteNotification() { return Data; }
protected override RoomInviteNotification GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetRoomInviteNotification(msg);
return new RoomInviteNotification(obj);
}
}
public class MessageWithRoomInviteNotificationList : Message<RoomInviteNotificationList>
{
public MessageWithRoomInviteNotificationList(IntPtr c_message) : base(c_message) { }
public override RoomInviteNotificationList GetRoomInviteNotificationList() { return Data; }
protected override RoomInviteNotificationList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetRoomInviteNotificationArray(msg);
return new RoomInviteNotificationList(obj);
}
}
public class MessageWithSdkAccountList : Message<SdkAccountList>
{
public MessageWithSdkAccountList(IntPtr c_message) : base(c_message) { }
public override SdkAccountList GetSdkAccountList() { return Data; }
protected override SdkAccountList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetSdkAccountArray(msg);
return new SdkAccountList(obj);
}
}
public class MessageWithString : Message<string>
{
public MessageWithString(IntPtr c_message) : base(c_message) { }
public override string GetString() { return Data; }
protected override string GetDataFromMessage(IntPtr c_message)
{
return CAPI.ovr_Message_GetString(c_message);
}
}
public class MessageWithSystemPermission : Message<SystemPermission>
{
public MessageWithSystemPermission(IntPtr c_message) : base(c_message) { }
public override SystemPermission GetSystemPermission() { return Data; }
protected override SystemPermission GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetSystemPermission(msg);
return new SystemPermission(obj);
}
}
public class MessageWithSystemVoipState : Message<SystemVoipState>
{
public MessageWithSystemVoipState(IntPtr c_message) : base(c_message) { }
public override SystemVoipState GetSystemVoipState() { return Data; }
protected override SystemVoipState GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetSystemVoipState(msg);
return new SystemVoipState(obj);
}
}
public class MessageWithUser : Message<User>
{
public MessageWithUser(IntPtr c_message) : base(c_message) { }
public override User GetUser() { return Data; }
protected override User GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetUser(msg);
return new User(obj);
}
}
public class MessageWithUserAndRoomList : Message<UserAndRoomList>
{
public MessageWithUserAndRoomList(IntPtr c_message) : base(c_message) { }
public override UserAndRoomList GetUserAndRoomList() { return Data; }
protected override UserAndRoomList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetUserAndRoomArray(msg);
return new UserAndRoomList(obj);
}
}
public class MessageWithUserList : Message<UserList>
{
public MessageWithUserList(IntPtr c_message) : base(c_message) { }
public override UserList GetUserList() { return Data; }
protected override UserList GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetUserArray(msg);
return new UserList(obj);
}
}
public class MessageWithUserProof : Message<UserProof>
{
public MessageWithUserProof(IntPtr c_message) : base(c_message) { }
public override UserProof GetUserProof() { return Data; }
protected override UserProof GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetUserProof(msg);
return new UserProof(obj);
}
}
public class MessageWithNetworkingPeer : Message<NetworkingPeer>
{
public MessageWithNetworkingPeer(IntPtr c_message) : base(c_message) { }
public override NetworkingPeer GetNetworkingPeer() { return Data; }
protected override NetworkingPeer GetDataFromMessage(IntPtr c_message)
{
var peer = CAPI.ovr_Message_GetNetworkingPeer(c_message);
return new NetworkingPeer(
CAPI.ovr_NetworkingPeer_GetID(peer),
CAPI.ovr_NetworkingPeer_GetState(peer)
);
}
}
public class MessageWithPingResult : Message<PingResult>
{
public MessageWithPingResult(IntPtr c_message) : base(c_message) { }
public override PingResult GetPingResult() { return Data; }
protected override PingResult GetDataFromMessage(IntPtr c_message)
{
var ping = CAPI.ovr_Message_GetPingResult(c_message);
bool is_timeout = CAPI.ovr_PingResult_IsTimeout(ping);
return new PingResult(
CAPI.ovr_PingResult_GetID(ping),
is_timeout ? (UInt64?)null : CAPI.ovr_PingResult_GetPingTimeUsec(ping)
);
}
}
public class MessageWithLeaderboardDidUpdate : Message<bool>
{
public MessageWithLeaderboardDidUpdate(IntPtr c_message) : base(c_message) { }
public override bool GetLeaderboardDidUpdate() { return Data; }
protected override bool GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetLeaderboardUpdateStatus(msg);
return CAPI.ovr_LeaderboardUpdateStatus_GetDidUpdate(obj);
}
}
public class MessageWithMatchmakingNotification : Message<Room>
{
public MessageWithMatchmakingNotification(IntPtr c_message) : base(c_message) {}
public override Room GetRoom() { return Data; }
protected override Room GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetRoom(msg);
return new Room(obj);
}
}
public class MessageWithMatchmakingBrowseResult : Message<MatchmakingBrowseResult>
{
public MessageWithMatchmakingBrowseResult(IntPtr c_message) : base(c_message) {}
public override MatchmakingEnqueueResult GetMatchmakingEnqueueResult() { return Data.EnqueueResult; }
public override RoomList GetRoomList() { return Data.Rooms; }
protected override MatchmakingBrowseResult GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetMatchmakingBrowseResult(msg);
return new MatchmakingBrowseResult(obj);
}
}
public class MessageWithHttpTransferUpdate : Message<HttpTransferUpdate>
{
public MessageWithHttpTransferUpdate(IntPtr c_message) : base(c_message) {}
public override HttpTransferUpdate GetHttpTransferUpdate() { return Data; }
protected override HttpTransferUpdate GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetHttpTransferUpdate(msg);
return new HttpTransferUpdate(obj);
}
}
public class MessageWithPlatformInitialize : Message<PlatformInitialize>
{
public MessageWithPlatformInitialize(IntPtr c_message) : base(c_message) {}
public override PlatformInitialize GetPlatformInitialize() { return Data; }
protected override PlatformInitialize GetDataFromMessage(IntPtr c_message)
{
var msg = CAPI.ovr_Message_GetNativeMessage(c_message);
var obj = CAPI.ovr_Message_GetPlatformInitialize(msg);
return new PlatformInitialize(obj);
}
}
}
| 44.051304 | 111 | 0.706745 | [
"BSD-3-Clause"
] | AustinScottDavis/3D-VR-Tetris | Assets/OculusPlatform/Scripts/Message.cs | 50,659 | C# |
using System;
using System.Windows.Controls;
using System.Windows;
namespace Microsoft.Windows.Controls
{
/// <summary>
/// Base class for controls that represents controls that can spin.
/// </summary>
public abstract class Spinner : Control
{
#region Properties
/// <summary>
/// Identifies the ValidSpinDirection dependency property.
/// </summary>
public static readonly DependencyProperty ValidSpinDirectionProperty = DependencyProperty.Register("ValidSpinDirection", typeof(ValidSpinDirections), typeof(Spinner), new PropertyMetadata(ValidSpinDirections.Increase | ValidSpinDirections.Decrease, OnValidSpinDirectionPropertyChanged));
public ValidSpinDirections ValidSpinDirection
{
get { return (ValidSpinDirections)GetValue(ValidSpinDirectionProperty); }
set { SetValue(ValidSpinDirectionProperty, value); }
}
/// <summary>
/// ValidSpinDirectionProperty property changed handler.
/// </summary>
/// <param name="d">ButtonSpinner that changed its ValidSpinDirection.</param>
/// <param name="e">Event arguments.</param>
private static void OnValidSpinDirectionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Spinner source = (Spinner)d;
ValidSpinDirections oldvalue = (ValidSpinDirections)e.OldValue;
ValidSpinDirections newvalue = (ValidSpinDirections)e.NewValue;
source.OnValidSpinDirectionChanged(oldvalue, newvalue);
}
#endregion //Properties
/// <summary>
/// Occurs when spinning is initiated by the end-user.
/// </summary>
public event EventHandler<SpinEventArgs> Spin;
/// <summary>
/// Initializes a new instance of the Spinner class.
/// </summary>
protected Spinner() { }
/// <summary>
/// Raises the OnSpin event when spinning is initiated by the end-user.
/// </summary>
/// <param name="e">Spin event args.</param>
protected virtual void OnSpin(SpinEventArgs e)
{
ValidSpinDirections valid = e.Direction == SpinDirection.Increase ? ValidSpinDirections.Increase : ValidSpinDirections.Decrease;
//Only raise the event if spin is allowed.
if ((ValidSpinDirection & valid) == valid)
{
EventHandler<SpinEventArgs> handler = Spin;
if (handler != null)
{
handler(this, e);
}
}
}
/// <summary>
/// Called when valid spin direction changed.
/// </summary>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
protected virtual void OnValidSpinDirectionChanged(ValidSpinDirections oldValue, ValidSpinDirections newValue) { }
}
}
| 39.078947 | 295 | 0.630303 | [
"MIT"
] | weihuajiang/ConfigurationComplete | WPFToolkit.Extended/ButtonSpinner/Implementation/Spinner.cs | 2,972 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RenderContext.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Implements <see cref="IRenderContext" /> for <see cref="Canvas" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Windows
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using global::Windows.Foundation;
using global::Windows.Storage.Streams;
using global::Windows.UI.Text;
using global::Windows.UI.Xaml;
using global::Windows.UI.Xaml.Controls;
using global::Windows.UI.Xaml.Media;
using global::Windows.UI.Xaml.Media.Imaging;
using global::Windows.UI.Xaml.Shapes;
using Path = global::Windows.UI.Xaml.Shapes.Path;
/// <summary>
/// Implements <see cref="IRenderContext" /> for <see cref="Canvas" />.
/// </summary>
public class RenderContext : IRenderContext
{
/// <summary>
/// The brush cache.
/// </summary>
private readonly Dictionary<OxyColor, Brush> brushCache = new Dictionary<OxyColor, Brush>();
/// <summary>
/// The canvas.
/// </summary>
private readonly Canvas canvas;
/// <summary>
/// The images in use
/// </summary>
private readonly HashSet<OxyImage> imagesInUse = new HashSet<OxyImage>();
/// <summary>
/// The image cache
/// </summary>
private readonly Dictionary<OxyImage, BitmapSource> imageCache = new Dictionary<OxyImage, BitmapSource>();
/// <summary>
/// The current tool tip
/// </summary>
private string currentToolTip;
/// <summary>
/// The clip rectangle.
/// </summary>
private Rect clipRect;
/// <summary>
/// The clip flag.
/// </summary>
private bool clip;
/// <summary>
/// Initializes a new instance of the <see cref="RenderContext" /> class.
/// </summary>
/// <param name="canvas">The canvas.</param>
public RenderContext(Canvas canvas)
{
this.canvas = canvas;
this.Width = canvas.ActualWidth;
this.Height = canvas.ActualHeight;
this.RendersToScreen = true;
}
/// <summary>
/// Gets the height.
/// </summary>
/// <value>The height.</value>
public double Height { get; private set; }
/// <summary>
/// Gets a value indicating whether to paint the background.
/// </summary>
/// <value><c>true</c> if the background should be painted; otherwise, <c>false</c>.</value>
public bool PaintBackground
{
get
{
return false;
}
}
/// <summary>
/// Gets the width.
/// </summary>
/// <value>The width.</value>
public double Width { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the context renders to screen.
/// </summary>
/// <value><c>true</c> if the context renders to screen; otherwise, <c>false</c>.</value>
public bool RendersToScreen { get; set; }
/// <summary>
/// Draws an ellipse.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
public void DrawEllipse(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
var el = new Ellipse();
if (stroke.IsVisible())
{
el.Stroke = new SolidColorBrush(stroke.ToColor());
el.StrokeThickness = thickness;
}
if (fill.IsVisible())
{
el.Fill = new SolidColorBrush(fill.ToColor());
}
el.Width = rect.Width;
el.Height = rect.Height;
Canvas.SetLeft(el, rect.Left);
Canvas.SetTop(el, rect.Top);
this.Add(el, rect.Left, rect.Top);
}
/// <summary>
/// Draws the collection of ellipses, where all have the same stroke and fill.
/// This performs better than calling DrawEllipse multiple times.
/// </summary>
/// <param name="rectangles">The rectangles.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public void DrawEllipses(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
{
var path = new Path();
this.SetStroke(path, stroke, thickness);
if (fill.IsVisible())
{
path.Fill = this.GetCachedBrush(fill);
}
var gg = new GeometryGroup { FillRule = FillRule.Nonzero };
foreach (var rect in rectangles)
{
gg.Children.Add(
new EllipseGeometry
{
Center = new Point(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)),
RadiusX = rect.Width / 2,
RadiusY = rect.Height / 2
});
}
path.Data = gg;
this.Add(path);
}
/// <summary>
/// Draws the polyline from the specified points.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public void DrawLine(
IList<ScreenPoint> points,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
var e = new Polyline();
this.SetStroke(e, stroke, thickness, lineJoin, dashArray, aliased);
var pc = new PointCollection();
foreach (var p in points)
{
pc.Add(p.ToPoint(aliased));
}
e.Points = pc;
this.Add(e);
}
/// <summary>
/// Draws the multiple line segments defined by points (0,1) (2,3) (4,5) etc.
/// This should have better performance than calling DrawLine for each segment.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public void DrawLineSegments(
IList<ScreenPoint> points,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
var path = new Path();
this.SetStroke(path, stroke, thickness, lineJoin, dashArray, aliased);
var pg = new PathGeometry();
for (int i = 0; i + 1 < points.Count; i += 2)
{
// if (points[i].Y==points[i+1].Y)
// {
// var line = new Line();
// line.X1 = 0.5+(int)points[i].X;
// line.X2 = 0.5+(int)points[i+1].X;
// line.Y1 = 0.5+(int)points[i].Y;
// line.Y2 = 0.5+(int)points[i+1].Y;
// SetStroke(line, OxyColors.DarkRed, thickness, lineJoin, dashArray, aliased);
// Add(line);
// continue;
// }
var figure = new PathFigure { StartPoint = points[i].ToPoint(aliased), IsClosed = false };
figure.Segments.Add(new LineSegment { Point = points[i + 1].ToPoint(aliased) });
pg.Figures.Add(figure);
}
path.Data = pg;
this.Add(path);
}
/// <summary>
/// Draws the polygon from the specified points. The polygon can have stroke and/or fill.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public void DrawPolygon(
IList<ScreenPoint> points,
OxyColor fill,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
var po = new Polygon();
this.SetStroke(po, stroke, thickness, lineJoin, dashArray, aliased);
if (fill.IsVisible())
{
po.Fill = this.GetCachedBrush(fill);
}
var pc = new PointCollection();
foreach (var p in points)
{
pc.Add(p.ToPoint(aliased));
}
po.Points = pc;
this.Add(po);
}
/// <summary>
/// Draws a collection of polygons, where all polygons have the same stroke and fill.
/// This performs better than calling DrawPolygon multiple times.
/// </summary>
/// <param name="polygons">The polygons.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public void DrawPolygons(
IList<IList<ScreenPoint>> polygons,
OxyColor fill,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
var path = new Path();
this.SetStroke(path, stroke, thickness, lineJoin, dashArray, aliased);
if (fill.IsVisible())
{
path.Fill = this.GetCachedBrush(fill);
}
var pg = new PathGeometry { FillRule = FillRule.Nonzero };
foreach (var polygon in polygons)
{
var figure = new PathFigure { IsClosed = true };
bool first = true;
foreach (var p in polygon)
{
if (first)
{
figure.StartPoint = p.ToPoint(aliased);
first = false;
}
else
{
figure.Segments.Add(new LineSegment { Point = p.ToPoint(aliased) });
}
}
pg.Figures.Add(figure);
}
path.Data = pg;
this.Add(path);
}
/// <summary>
/// Draws the rectangle.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public void DrawRectangle(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
var el = new Rectangle();
if (stroke.IsVisible())
{
el.Stroke = new SolidColorBrush(stroke.ToColor());
el.StrokeThickness = thickness;
}
if (fill.IsVisible())
{
el.Fill = new SolidColorBrush(fill.ToColor());
}
el.Width = rect.Width;
el.Height = rect.Height;
Canvas.SetLeft(el, rect.Left);
Canvas.SetTop(el, rect.Top);
this.Add(el, rect.Left, rect.Top);
}
/// <summary>
/// Draws a collection of rectangles, where all have the same stroke and fill.
/// This performs better than calling DrawRectangle multiple times.
/// </summary>
/// <param name="rectangles">The rectangles.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public void DrawRectangles(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
{
var path = new Path();
this.SetStroke(path, stroke, thickness);
if (fill.IsVisible())
{
path.Fill = this.GetCachedBrush(fill);
}
var gg = new GeometryGroup { FillRule = FillRule.Nonzero };
foreach (var rect in rectangles)
{
gg.Children.Add(new RectangleGeometry { Rect = rect.ToRect(true) });
}
path.Data = gg;
this.Add(path);
}
/// <summary>
/// Draws the text.
/// </summary>
/// <param name="p">The position.</param>
/// <param name="text">The text.</param>
/// <param name="fill">The fill color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="rotate">The rotation angle.</param>
/// <param name="halign">The horizontal alignment.</param>
/// <param name="valign">The vertical alignment.</param>
/// <param name="maxSize">The maximum size of the text.</param>
public void DrawText(
ScreenPoint p,
string text,
OxyColor fill,
string fontFamily,
double fontSize,
double fontWeight,
double rotate,
OxyPlot.HorizontalAlignment halign,
OxyPlot.VerticalAlignment valign,
OxySize? maxSize)
{
var tb = new TextBlock { Text = text, Foreground = new SolidColorBrush(fill.ToColor()) };
// tb.SetValue(TextOptions.TextHintingModeProperty, TextHintingMode.Animated);
if (fontFamily != null)
{
tb.FontFamily = new FontFamily(fontFamily);
}
if (fontSize > 0)
{
tb.FontSize = fontSize;
}
tb.FontWeight = GetFontWeight(fontWeight);
tb.Measure(new Size(1000, 1000));
var size = new Size(tb.ActualWidth, tb.ActualHeight);
if (maxSize != null)
{
if (size.Width > maxSize.Value.Width)
{
size.Width = maxSize.Value.Width;
}
if (size.Height > maxSize.Value.Height)
{
size.Height = maxSize.Value.Height;
}
tb.Clip = new RectangleGeometry { Rect = new Rect(0, 0, size.Width, size.Height) };
}
double dx = 0;
if (halign == OxyPlot.HorizontalAlignment.Center)
{
dx = -size.Width / 2;
}
if (halign == OxyPlot.HorizontalAlignment.Right)
{
dx = -size.Width;
}
double dy = 0;
if (valign == OxyPlot.VerticalAlignment.Middle)
{
dy = -size.Height / 2;
}
if (valign == OxyPlot.VerticalAlignment.Bottom)
{
dy = -size.Height;
}
var transform = new TransformGroup();
transform.Children.Add(new TranslateTransform { X = (int)dx, Y = (int)dy });
if (!rotate.Equals(0))
{
transform.Children.Add(new RotateTransform { Angle = rotate });
}
transform.Children.Add(new TranslateTransform { X = (int)p.X, Y = (int)p.Y });
tb.RenderTransform = transform;
this.ApplyTooltip(tb);
if (this.clip)
{
// add a clipping container that is not rotated
var c = new Canvas();
c.Children.Add(tb);
this.Add(c);
}
else
{
this.Add(tb);
}
}
/// <summary>
/// Measures the text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>The text size.</returns>
public OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight)
{
if (string.IsNullOrEmpty(text))
{
return OxySize.Empty;
}
var tb = new TextBlock { Text = text };
if (fontFamily != null)
{
tb.FontFamily = new FontFamily(fontFamily);
}
if (fontSize > 0)
{
tb.FontSize = fontSize;
}
tb.FontWeight = GetFontWeight(fontWeight);
tb.Measure(new Size(1000, 1000));
return new OxySize(tb.ActualWidth, tb.ActualHeight);
}
/// <summary>
/// Sets the tool tip for the following items.
/// </summary>
/// <param name="text">The text in the tooltip.</param>
public void SetToolTip(string text)
{
this.currentToolTip = text;
}
/// <summary>
/// Draws the specified portion of the specified <see cref="OxyImage" /> at the specified location and with the specified size.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="srcX">The x-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcY">The y-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcWidth">Width of the portion of the source image to draw.</param>
/// <param name="srcHeight">Height of the portion of the source image to draw.</param>
/// <param name="destX">The x-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destY">The y-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destWidth">The width of the drawn image.</param>
/// <param name="destHeight">The height of the drawn image.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolate">interpolate if set to <c>true</c>.</param>
public void DrawImage(
OxyImage source,
double srcX,
double srcY,
double srcWidth,
double srcHeight,
double destX,
double destY,
double destWidth,
double destHeight,
double opacity,
bool interpolate)
{
if (destWidth <= 0 || destHeight <= 0 || srcWidth <= 0 || srcHeight <= 0)
{
return;
}
var image = new Image();
var bmp = this.GetImageSource(source);
if (srcX.Equals(0) && srcY.Equals(0) && srcWidth.Equals(bmp.PixelWidth) && srcHeight.Equals(bmp.PixelHeight))
{
// do not crop
}
else
{
// TODO: cropped image not available in Silverlight??
// bmp = new CroppedBitmap(bmp, new Int32Rect((int)srcX, (int)srcY, (int)srcWidth, (int)srcHeight));
return;
}
image.Opacity = opacity;
image.Width = destWidth;
image.Height = destHeight;
image.Stretch = Stretch.Fill;
// TODO: not available in Silverlight??
// RenderOptions.SetBitmapScalingMode(image, interpolate ? BitmapScalingMode.HighQuality : BitmapScalingMode.NearestNeighbor);
// Canvas.SetLeft(image, x);
// Canvas.SetTop(image, y);
image.RenderTransform = new TranslateTransform { X = destX, Y = destY };
image.Source = bmp;
this.ApplyTooltip(image);
this.Add(image, destX, destY);
}
/// <summary>
/// Sets the clipping rectangle.
/// </summary>
/// <param name="clippingRect">The clipping rectangle.</param>
/// <returns>True if the clipping rectangle was set.</returns>
public bool SetClip(OxyRect clippingRect)
{
this.clipRect = clippingRect.ToRect(false);
this.clip = true;
return true;
}
/// <summary>
/// Resets the clipping rectangle.
/// </summary>
public void ResetClip()
{
this.clip = false;
}
/// <summary>
/// Cleans up resources not in use.
/// </summary>
/// <remarks>This method is called at the end of each rendering.</remarks>
public void CleanUp()
{
// Find the images in the cache that has not been used since last call to this method
var imagesToRelease = this.imageCache.Keys.Where(i => !this.imagesInUse.Contains(i)).ToList();
// Remove the images from the cache
foreach (var i in imagesToRelease)
{
this.imageCache.Remove(i);
}
this.imagesInUse.Clear();
}
/// <summary>
/// Creates the dash array collection.
/// </summary>
/// <param name="dashArray">The dash array.</param>
/// <returns>A DoubleCollection.</returns>
private static DoubleCollection CreateDashArrayCollection(IEnumerable<double> dashArray)
{
var dac = new DoubleCollection();
foreach (double v in dashArray)
{
dac.Add(v);
}
return dac;
}
/// <summary>
/// Gets the font weight.
/// </summary>
/// <param name="fontWeight">The font weight.</param>
/// <returns>A <see cref="FontWeight" /></returns>
private static FontWeight GetFontWeight(double fontWeight)
{
return fontWeight > OxyPlot.FontWeights.Normal ? FontWeights.Bold : FontWeights.Normal;
}
/// <summary>
/// Adds the specified element to the canvas.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="clipOffsetX">The clip offset X.</param>
/// <param name="clipOffsetY">The clip offset Y.</param>
private void Add(UIElement element, double clipOffsetX = 0, double clipOffsetY = 0)
{
if (this.clip)
{
this.ApplyClip(element, clipOffsetX, clipOffsetY);
}
this.canvas.Children.Add(element);
}
/// <summary>
/// Applies the tooltip to the specified element.
/// </summary>
/// <param name="element">The element.</param>
private void ApplyTooltip(DependencyObject element)
{
if (!string.IsNullOrEmpty(this.currentToolTip))
{
ToolTipService.SetToolTip(element, this.currentToolTip);
}
}
/// <summary>
/// Gets the cached brush.
/// </summary>
/// <param name="stroke">The stroke.</param>
/// <returns>The brush.</returns>
private Brush GetCachedBrush(OxyColor stroke)
{
Brush brush;
if (!this.brushCache.TryGetValue(stroke, out brush))
{
brush = new SolidColorBrush(stroke.ToColor());
this.brushCache.Add(stroke, brush);
}
return brush;
}
/// <summary>
/// Sets the stroke of the specified shape.
/// </summary>
/// <param name="shape">The shape.</param>
/// <param name="stroke">The stroke.</param>
/// <param name="thickness">The thickness.</param>
/// <param name="lineJoin">The line join.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="aliased">aliased if set to <c>true</c>.</param>
private void SetStroke(
Shape shape,
OxyColor stroke,
double thickness,
LineJoin lineJoin = LineJoin.Miter,
IEnumerable<double> dashArray = null,
bool aliased = false)
{
if (stroke.IsVisible() && thickness > 0)
{
shape.Stroke = this.GetCachedBrush(stroke);
switch (lineJoin)
{
case LineJoin.Round:
shape.StrokeLineJoin = PenLineJoin.Round;
break;
case LineJoin.Bevel:
shape.StrokeLineJoin = PenLineJoin.Bevel;
break;
// The default StrokeLineJoin is Miter
}
shape.StrokeThickness = thickness;
if (dashArray != null)
{
shape.StrokeDashArray = CreateDashArrayCollection(dashArray);
}
if (aliased)
{
// shape.UseLayoutRounding = aliased;
}
}
}
/// <summary>
/// Applies the clip rectangle.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="x">The x offset of the element.</param>
/// <param name="y">The y offset of the element.</param>
private void ApplyClip(UIElement image, double x, double y)
{
image.Clip = new RectangleGeometry { Rect = new Rect(this.clipRect.X - x, this.clipRect.Y - y, this.clipRect.Width, this.clipRect.Height) };
}
/// <summary>
/// Gets the bitmap source.
/// </summary>
/// <param name="image">The image.</param>
/// <returns>The bitmap source.</returns>
private BitmapSource GetImageSource(OxyImage image)
{
if (image == null)
{
return null;
}
if (!this.imagesInUse.Contains(image))
{
this.imagesInUse.Add(image);
}
BitmapSource src;
if (this.imageCache.TryGetValue(image, out src))
{
return src;
}
var bitmapImage = new BitmapImage();
var imageStream = ConvertToRandomAccessStream(image.GetData()).GetAwaiter().GetResult();
bitmapImage.SetSource(imageStream);
this.imageCache.Add(image, bitmapImage);
return bitmapImage;
}
/// <summary>
/// Converts the specified byte array to a <see cref="IRandomAccessStream" />.
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
private static async Task<IRandomAccessStream> ConvertToRandomAccessStream(byte[] buffer)
{
//https://stackoverflow.com/questions/16397509/how-to-convert-byte-array-to-inmemoryrandomaccessstream-or-irandomaccessstream-i
var randomAccessStream = new InMemoryRandomAccessStream();
await randomAccessStream.WriteAsync(buffer.AsBuffer());
randomAccessStream.Seek(0);
return randomAccessStream;
}
}
} | 35.619753 | 152 | 0.512997 | [
"MIT"
] | GeertvanHorrik/oxyplot | Source/OxyPlot.Windows/RenderContext.cs | 28,854 | C# |
// Copyright (c) KhooverSoft. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
namespace Khooversoft.Toolbox.Security
{
public class HmacConfiguration : IHmacConfiguration
{
private static IEnumerable<string> _standardHeaders = new string[]
{
"Content-MD5",
"Content-Type",
"API-RequestId",
"API-Cv",
"Date"
};
public HmacConfiguration(IEnumerable<string> additionalHeaders = null)
{
var headers = new List<string>(_standardHeaders);
if (additionalHeaders != null && additionalHeaders.Count() > 0)
{
headers.AddRange(additionalHeaders);
}
Headers = headers.Select(x => x.Trim().ToLower()).ToList();
}
public IEnumerable<string> Headers { get; }
}
}
| 29.294118 | 111 | 0.600402 | [
"MIT"
] | khoover768/Toolbox | Src/Dev/Khooversoft.Toolbox/Security/HMAC/HmacConfiguration.cs | 998 | 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("120_UnityContainerDisposalHang")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("120_UnityContainerDisposalHang")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a5bd6a11-9344-4f1d-967e-22858b829f83")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.72973 | 84 | 0.75157 | [
"MIT"
] | IoCHowTo/IoCTasks | 120_UnityContainerDisposalHang/Properties/AssemblyInfo.cs | 1,436 | C# |
using BusLane.Exceptions;
using Microsoft.Extensions.Logging;
using STAN.Client;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace BusLane.Transport.NatsStreaming.Publishing
{
/// <summary>
/// An <see cref="IMessagePublisher"/> that publishes messages to a RabbitMQ broker.
/// </summary>
internal sealed class NatsStreamingMessagePublisher : IMessagePublisher
{
private readonly ILogger<NatsStreamingMessagePublisher> _Logger;
/// <summary>
/// Gets the connection to the message broker.
/// </summary>
private readonly IStanConnection _Connection;
/// <summary>
/// Initializes a new <see cref="NatsStreamingMessagePublisher"/>.
/// </summary>
/// <param name="logger">The logger to write to.</param>
/// <param name="clusterId">The cluster ID of streaming server.</param>
/// <param name="clientId">A unique ID for this connection.</param>
/// <param name="options">Connection options</param>
public NatsStreamingMessagePublisher(
ILogger<NatsStreamingMessagePublisher> logger,
string clusterId,
string clientId,
StanOptions? options = null)
{
_Logger = logger;
_Connection = new StanConnectionFactory().CreateConnection(
clusterId,
clientId,
options ?? StanOptions.GetDefaultOptions());
}
/// <summary>
/// Publishes a new message to the broker, using the stated categories.
/// </summary>
/// <param name="message">The message to publish.</param>
/// <param name="topic">The topic to publish the message to.</param>
/// <param name="cancellationToken">The token to cancel the operation with.</param>
/// <exception cref="T:System.OperationCanceledException">Thrown if the operation was cancelled.</exception>
/// <exception cref="T:Mes.Core.Libraries.Messaging.Exceptions.CommunicationException">
/// Thrown if communication with the message broker failed.
/// </exception>
public async Task PublishAsync(
ReadOnlyMemory<byte> message,
string topic,
CancellationToken cancellationToken = new CancellationToken())
{
_Logger.LogTrace("Publishing message to topic '{Topic}'", topic);
try
{
await _Connection.PublishAsync(topic, message.ToArray());
_Logger.LogDebug("Published to topic '{Topic}'", topic);
}
catch (Exception publishException)
{
throw new MessagingException("Failed to publish message.", publishException);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources
/// asynchronously.
/// </summary>
/// <returns>A task that represents the asynchronous dispose operation.</returns>
public void Dispose()
{
_Connection.Close();
_Connection.Dispose();
}
}
} | 39.506173 | 116 | 0.614375 | [
"Apache-2.0"
] | teian/BusLane | src/BusLane.Transport.NatsStreaming/Publishing/NatsStreamingMessagePublisher.cs | 3,202 | C# |
// ===================================================================
// 项目说明,功能实体类,用CodeSmith自动生成。
// ===================================================================
// 文件名: Advertisement.cs
// 修改时间:2017/12/26 17:33:25
// 修改人: lixiong
// ===================================================================
using System;
namespace JX.Core.Entity
{
/// <summary>
/// 数据库表:Advertisement 的实体类.
/// </summary>
public partial class Advertisement
{
#region Properties
private System.Int32 _adid = 0;
/// <summary>
/// 广告ID (主键)
/// </summary>
public System.Int32 ADID
{
get {return _adid;}
set {_adid = value;}
}
private System.Int32 _userID = 0;
/// <summary>
/// 广告客户ID
/// </summary>
public System.Int32 UserID
{
get {return _userID;}
set {_userID = value;}
}
private System.Int32 _aDType = 0;
/// <summary>
/// 广告类型 图片、动画、文本、代码、页面
/// </summary>
public System.Int32 ADType
{
get {return _aDType;}
set {_aDType = value;}
}
private System.String _aDName = string.Empty;
/// <summary>
/// 广告名称
/// </summary>
public System.String ADName
{
get {return _aDName;}
set {_aDName = value;}
}
private System.String _imgUrl = string.Empty;
/// <summary>
/// 图片地址
/// </summary>
public System.String ImgUrl
{
get {return _imgUrl;}
set {_imgUrl = value;}
}
private System.Int32 _imgWidth = 0;
/// <summary>
/// 图片的宽度
/// </summary>
public System.Int32 ImgWidth
{
get {return _imgWidth;}
set {_imgWidth = value;}
}
private System.Int32 _imgHeight = 0;
/// <summary>
/// 图片的高度
/// </summary>
public System.Int32 ImgHeight
{
get {return _imgHeight;}
set {_imgHeight = value;}
}
private System.Int32 _flashWmode = 0;
/// <summary>
/// Flash是否透明
/// </summary>
public System.Int32 FlashWmode
{
get {return _flashWmode;}
set {_flashWmode = value;}
}
private System.String _aDIntro = string.Empty;
/// <summary>
/// 广告内容
/// </summary>
public System.String ADIntro
{
get {return _aDIntro;}
set {_aDIntro = value;}
}
private System.String _linkUrl = string.Empty;
/// <summary>
/// 链接网址
/// </summary>
public System.String LinkUrl
{
get {return _linkUrl;}
set {_linkUrl = value;}
}
private System.Int32 _linkTarget = 0;
/// <summary>
/// 是否在新窗口打开
/// </summary>
public System.Int32 LinkTarget
{
get {return _linkTarget;}
set {_linkTarget = value;}
}
private System.String _linkAlt = string.Empty;
/// <summary>
/// 链接提示
/// </summary>
public System.String LinkAlt
{
get {return _linkAlt;}
set {_linkAlt = value;}
}
private System.Int32 _priority = 0;
/// <summary>
/// 广告项目的权重
/// </summary>
public System.Int32 Priority
{
get {return _priority;}
set {_priority = value;}
}
private System.String _setting = string.Empty;
/// <summary>
/// 其他设定
/// </summary>
public System.String Setting
{
get {return _setting;}
set {_setting = value;}
}
private System.Boolean _isCountView = false;
/// <summary>
/// 是否统计浏览数
/// </summary>
public System.Boolean IsCountView
{
get {return _isCountView;}
set {_isCountView = value;}
}
private System.Int32 _views = 0;
/// <summary>
/// 浏览数
/// </summary>
public System.Int32 Views
{
get {return _views;}
set {_views = value;}
}
private System.Boolean _isCountClick = false;
/// <summary>
/// 是否统计点击数
/// </summary>
public System.Boolean IsCountClick
{
get {return _isCountClick;}
set {_isCountClick = value;}
}
private System.Int32 _clicks = 0;
/// <summary>
/// 点击数
/// </summary>
public System.Int32 Clicks
{
get {return _clicks;}
set {_clicks = value;}
}
private System.Boolean _isAbsolutePath = false;
/// <summary>
/// 是否绝对路径
/// </summary>
public System.Boolean IsAbsolutePath
{
get {return _isAbsolutePath;}
set {_isAbsolutePath = value;}
}
private System.Boolean _isPassed = false;
/// <summary>
/// 是否通过审核
/// </summary>
public System.Boolean IsPassed
{
get {return _isPassed;}
set {_isPassed = value;}
}
private DateTime? _overdueDate = DateTime.MaxValue;
/// <summary>
/// 广告过期时间
/// </summary>
public DateTime? OverdueDate
{
get {return _overdueDate;}
set {_overdueDate = value;}
}
#endregion
}
}
| 20.852381 | 72 | 0.586664 | [
"Apache-2.0"
] | lixiong24/IPS2.1 | JXIPS/JX.Core/Entity/AdvertisementEntity.cs | 4,685 | C# |
// ----------------------------------------------------------------------
// <copyright file="OAuth2.cs" company="nGenesis, LLC">
// Copyright (c) 2012, nGenesis, LLC.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution (Liscense.htm), and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// Contributors:
// dapug - Initial author, core functionality
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace FSAPI.Identity
{
public class OAuth2 : ServiceBase
{
public event GetAccessTokenCompletedEventHandler GetAccessTokenCompleted;
public delegate void GetAccessTokenCompletedEventHandler(object sender, OAuth2AccessTokenEventArgs e);
Net.SuperWebClient client;
string contentType = "application/x-www-form-urlencoded";
#region Constructors
/// <summary>
/// Instantiates the Service
/// </summary>
public OAuth2()
{
userAgentComplete = userAgentFSAPI;// +";" + this.contributorRef;
client = new Net.SuperWebClient();
client.Headers = new System.Net.WebHeaderCollection();
client.Headers.Add("Content-Type", contentType);
client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
}
/// <summary>
/// Instantiates the Service
/// </summary>
/// <param name="userAgent">Name of the application and version that is accessing FamilySearch. Use this format: "MyApp/v1.0"</param>
/// <param name="server">Indicate which server to use to process all API requests</param>
public OAuth2(string userAgent, FSServer server)
{
this.UserAgent = userAgent;
this.Server = server;
client = new Net.SuperWebClient();
client.Headers = new System.Net.WebHeaderCollection();
client.Headers.Add("Content-Type", contentType);
client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
}
/// <summary>
/// Instantiates the Service and sets the SessionId to use for Authenticated requests to FamilySearch
/// </summary>
/// <param name="accessToken">AccessToken to use for authenticated requests to FamilySearch.</param>
/// <param name="userAgent">Name of the application and version that is accessing FamilySearch. Use this format: "MyApp/v1.0"</param>
/// <param name="server">Indicate which server to use to process all API requests</param>
public OAuth2(string accessToken, string userAgent, FSServer server)
{
this.AccessToken = accessToken;
this.userAgent = userAgent;
this.UserAgent = userAgent; //intentionally using the Public version of this.UserAgent
this.Server = server;
client = new Net.SuperWebClient();
client.Headers = new System.Net.WebHeaderCollection();
client.Headers.Add("Content-Type", contentType);
client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
}
#endregion
#region Public Methods
/// <summary>
/// Gets the authorization Uri to refer the user to in their Browser to complete the Authentication process
/// </summary>
/// <param name="clientID">Client ID (or Dev Key)</param>
/// <param name="redirectUri">Uri that the OAuth system should return the auth code to</param>
/// <param name="userState">Arbitrary value for the client app to track this request (optional)</param>
/// <param name="language">Language that the sign in screen should render in for the user (optional, default "en")</param>
/// <returns></returns>
public string GetAuthUrl(string clientID, string redirectUri, string userState, string language)
{
string authUrl = FSUri.ActiveDomain + FSUri.OAuth2_AuthPath + "?response_type=code&client_id=" + clientID;
if (redirectUri != null && redirectUri.Length > 0)
authUrl += "&redirect_uri=" + redirectUri;
if (userState != null && userState.Length > 0)
authUrl += "&state=" + userState;
if (language != null && language.Length > 0)
authUrl += "&lng=" + language;
return authUrl;
}
/// <summary>
/// Gets an Access Token to use for all subsequent calls to the API's in the system
/// </summary>
/// <param name="clientID">Client ID (or Dev Key)</param>
/// <param name="authCode">Authorization code returned to the client after the user signed in</param>
/// <returns></returns>
public OAuth2AccessTokenEventArgs GetAccessToken(string clientID, string authCode)
{
return GetAccessToken(clientID, authCode, false);
}
/// <summary>
/// Gets an Access Token asynchronously, to use for all subsequent calls to the API's in the system
/// </summary>
/// <param name="clientID">Client ID (or Dev Key)</param>
/// <param name="authCode">Authorization code returned to the client after the user signed in</param>
public void GetAccessTokenAsync(string clientID, string authCode)
{
GetAccessToken(clientID, authCode, true);
}
#endregion
#region Private Methods
private OAuth2AccessTokenEventArgs GetAccessToken(string clientID, string authCode, bool doAsync)
{
string postData = ConstructAccessRequestBody(clientID, authCode);
string uri = FSUri.ActiveDomain + FSUri.OAuth2_TokenPath;
string authResult = string.Empty;
if (doAsync)
client.UploadStringAsync(new Uri(uri), "POST", postData);
else
authResult = client.UploadString(uri, "POST", postData);
return GetArgsFromAuthResponse(client.StatusCode, client.StatusDescription, authResult);
}
private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var info = ParseAccessTokenResponse(e.Result);
if (GetAccessTokenCompleted != null)
GetAccessTokenCompleted(this, new OAuth2AccessTokenEventArgs(client.StatusCode, client.StatusDescription, info));
}
private OAuth2AccessTokenEventArgs GetArgsFromAuthResponse(HttpStatusCode statusCode, string statusDescription, string authResult)
{
Identity.AccessTokenInfo info = null;
//parse the result
info = ParseAccessTokenResponse(authResult);
//create and return args containing the result
return new OAuth2AccessTokenEventArgs(statusCode, statusDescription, info);
}
private string ConstructAccessRequestBody(string clientID, string authCode)
{
if (authCode == null || authCode.Length <= 0 || clientID == null && clientID.Length <= 0)
throw new Exception("Auth Code and ClientID are both required for an Access Token request");
string postData =
"client_id=" + clientID +
//"&client_secret=" + clientSecret +
"&code=" + authCode +
"&grant_type=authorization_code";
return postData;
}
private Identity.AccessTokenInfo ParseAccessTokenResponse(string data)
{
if (data != null && data.Length > 0)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Identity.AccessTokenInfo>(data);
}
else
{
return null;
}
}
#endregion
}
}
| 41.872449 | 142 | 0.617765 | [
"EPL-1.0"
] | dapug/FSAPI.Net | FSAPI.Net/Identity/OAuth2.cs | 8,209 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
/// <summary> A class to add extension methods to ResourceGroup. </summary>
internal partial class ResourceGroupExtensionClient : ArmResource
{
private ClientDiagnostics _longTermRetentionBackupsClientDiagnostics;
private LongTermRetentionBackupsRestOperations _longTermRetentionBackupsRestClient;
private ClientDiagnostics _longTermRetentionManagedInstanceBackupsClientDiagnostics;
private LongTermRetentionManagedInstanceBackupsRestOperations _longTermRetentionManagedInstanceBackupsRestClient;
/// <summary> Initializes a new instance of the <see cref="ResourceGroupExtensionClient"/> class for mocking. </summary>
protected ResourceGroupExtensionClient()
{
}
/// <summary> Initializes a new instance of the <see cref="ResourceGroupExtensionClient"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal ResourceGroupExtensionClient(ArmClient client, ResourceIdentifier id) : base(client, id)
{
}
private ClientDiagnostics LongTermRetentionBackupsClientDiagnostics => _longTermRetentionBackupsClientDiagnostics ??= new ClientDiagnostics("Azure.ResourceManager.Sql", ProviderConstants.DefaultProviderNamespace, Diagnostics);
private LongTermRetentionBackupsRestOperations LongTermRetentionBackupsRestClient => _longTermRetentionBackupsRestClient ??= new LongTermRetentionBackupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint);
private ClientDiagnostics LongTermRetentionManagedInstanceBackupsClientDiagnostics => _longTermRetentionManagedInstanceBackupsClientDiagnostics ??= new ClientDiagnostics("Azure.ResourceManager.Sql", ProviderConstants.DefaultProviderNamespace, Diagnostics);
private LongTermRetentionManagedInstanceBackupsRestOperations LongTermRetentionManagedInstanceBackupsRestClient => _longTermRetentionManagedInstanceBackupsRestClient ??= new LongTermRetentionManagedInstanceBackupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint);
private string GetApiVersionOrNull(ResourceType resourceType)
{
TryGetApiVersion(resourceType, out string apiVersion);
return apiVersion;
}
/// <summary> Gets a collection of InstanceFailoverGroups in the InstanceFailoverGroup. </summary>
/// <param name="locationName"> The name of the region where the resource is located. </param>
/// <returns> An object representing collection of InstanceFailoverGroups and their operations over a InstanceFailoverGroup. </returns>
public virtual InstanceFailoverGroupCollection GetInstanceFailoverGroups(string locationName)
{
return new InstanceFailoverGroupCollection(Client, Id, locationName);
}
/// <summary> Gets a collection of InstancePools in the InstancePool. </summary>
/// <returns> An object representing collection of InstancePools and their operations over a InstancePool. </returns>
public virtual InstancePoolCollection GetInstancePools()
{
return GetCachedClient(Client => new InstancePoolCollection(Client, Id));
}
/// <summary> Gets a collection of ResourceGroupLongTermRetentionBackups in the ResourceGroupLongTermRetentionBackup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <returns> An object representing collection of ResourceGroupLongTermRetentionBackups and their operations over a ResourceGroupLongTermRetentionBackup. </returns>
public virtual ResourceGroupLongTermRetentionBackupCollection GetResourceGroupLongTermRetentionBackups(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName)
{
return new ResourceGroupLongTermRetentionBackupCollection(Client, Id, locationName, longTermRetentionServerName, longTermRetentionDatabaseName);
}
/// <summary> Gets a collection of ResourceGroupLongTermRetentionManagedInstanceBackups in the ResourceGroupLongTermRetentionManagedInstanceBackup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="managedInstanceName"> The name of the managed instance. </param>
/// <param name="databaseName"> The name of the managed database. </param>
/// <returns> An object representing collection of ResourceGroupLongTermRetentionManagedInstanceBackups and their operations over a ResourceGroupLongTermRetentionManagedInstanceBackup. </returns>
public virtual ResourceGroupLongTermRetentionManagedInstanceBackupCollection GetResourceGroupLongTermRetentionManagedInstanceBackups(string locationName, string managedInstanceName, string databaseName)
{
return new ResourceGroupLongTermRetentionManagedInstanceBackupCollection(Client, Id, locationName, managedInstanceName, databaseName);
}
/// <summary> Gets a collection of ManagedInstances in the ManagedInstance. </summary>
/// <returns> An object representing collection of ManagedInstances and their operations over a ManagedInstance. </returns>
public virtual ManagedInstanceCollection GetManagedInstances()
{
return GetCachedClient(Client => new ManagedInstanceCollection(Client, Id));
}
/// <summary> Gets a collection of ServerTrustGroups in the ServerTrustGroup. </summary>
/// <param name="locationName"> The name of the region where the resource is located. </param>
/// <returns> An object representing collection of ServerTrustGroups and their operations over a ServerTrustGroup. </returns>
public virtual ServerTrustGroupCollection GetServerTrustGroups(string locationName)
{
return new ServerTrustGroupCollection(Client, Id, locationName);
}
/// <summary> Gets a collection of VirtualClusters in the VirtualCluster. </summary>
/// <returns> An object representing collection of VirtualClusters and their operations over a VirtualCluster. </returns>
public virtual VirtualClusterCollection GetVirtualClusters()
{
return GetCachedClient(Client => new VirtualClusterCollection(Client, Id));
}
/// <summary> Gets a collection of SqlServers in the SqlServer. </summary>
/// <returns> An object representing collection of SqlServers and their operations over a SqlServer. </returns>
public virtual SqlServerCollection GetSqlServers()
{
return GetCachedClient(Client => new SqlServerCollection(Client, Id));
}
/// <summary>
/// Lists the long term retention backups for a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupLocationAsync(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupLocationAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupLocationNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupLocation(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupLocation(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupLocationNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given server.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionServers/{longTermRetentionServerName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupServer
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupServerAsync(string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupServerAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupServerNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given server.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionServers/{longTermRetentionServerName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupServer
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupServer(string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupServer(Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupServerNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given managed instance.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupInstance
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="managedInstanceName"> The name of the managed instance. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstanceAsync(string locationName, string managedInstanceName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstanceAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstanceNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given managed instance.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupInstance
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="managedInstanceName"> The name of the managed instance. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance(string locationName, string managedInstanceName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionManagedInstanceBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstance(Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionManagedInstanceBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstanceNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for managed databases in a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocationAsync(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocationAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocationNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for managed databases in a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionManagedInstanceBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocation(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionManagedInstanceBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocationNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
}
}
| 73.497917 | 328 | 0.703393 | [
"MIT"
] | nitsi/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Extensions/ResourceGroupExtensionClient.cs | 35,279 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20170901
{
/// <summary>
/// Route table resource.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:network/v20170901:RouteTable")]
public partial class RouteTable : Pulumi.CustomResource
{
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string?> Etag { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Output("provisioningState")]
public Output<string?> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Collection of routes contained within a route table.
/// </summary>
[Output("routes")]
public Output<ImmutableArray<Outputs.RouteResponse>> Routes { get; private set; } = null!;
/// <summary>
/// A collection of references to subnets.
/// </summary>
[Output("subnets")]
public Output<ImmutableArray<Outputs.SubnetResponse>> Subnets { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a RouteTable resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public RouteTable(string name, RouteTableArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20170901:RouteTable", name, args ?? new RouteTableArgs(), MakeResourceOptions(options, ""))
{
}
private RouteTable(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20170901:RouteTable", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/latest:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:RouteTable"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:RouteTable"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing RouteTable resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static RouteTable Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new RouteTable(name, id, options);
}
}
public sealed class RouteTableArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated.
/// </summary>
[Input("etag")]
public Input<string>? Etag { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Input("provisioningState")]
public Input<string>? ProvisioningState { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the route table.
/// </summary>
[Input("routeTableName")]
public Input<string>? RouteTableName { get; set; }
[Input("routes")]
private InputList<Inputs.RouteArgs>? _routes;
/// <summary>
/// Collection of routes contained within a route table.
/// </summary>
public InputList<Inputs.RouteArgs> Routes
{
get => _routes ?? (_routes = new InputList<Inputs.RouteArgs>());
set => _routes = value;
}
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public RouteTableArgs()
{
}
}
}
| 44.888372 | 134 | 0.582012 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20170901/RouteTable.cs | 9,651 | C# |
using Newtonsoft.Json;
namespace Zilon.Core.Schemes
{
/// <inheritdoc cref="ILocationScheme" />
/// <summary>
/// Схема узла на глобальной карте.
/// </summary>
public sealed class LocationScheme : SchemeBase, ILocationScheme
{
/// <summary>
/// Характеристики секторов по уровням.
/// Если null, то в данной локации нет сектора.
/// </summary>
[JsonConverter(typeof(ConcreteTypeConverter<SectorSubScheme[]>))]
[JsonProperty]
public ISectorSubScheme[]? SectorLevels { get; private set; }
}
} | 30.368421 | 73 | 0.627383 | [
"MIT"
] | kreghek/Zilon_Roguelike | Zilon.Core/Zilon.Core/Schemes/LocationScheme.cs | 666 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
/// <summary> A copy activity Teradata source. </summary>
public partial class TeradataSource : TabularSource
{
/// <summary> Initializes a new instance of TeradataSource. </summary>
public TeradataSource()
{
Type = "TeradataSource";
}
/// <summary> Initializes a new instance of TeradataSource. </summary>
/// <param name="type"> Copy source type. </param>
/// <param name="sourceRetryCount"> Source retry count. Type: integer (or Expression with resultType integer). </param>
/// <param name="sourceRetryWait"> Source retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). </param>
/// <param name="maxConcurrentConnections"> The maximum concurrent connection count for the source data store. Type: integer (or Expression with resultType integer). </param>
/// <param name="additionalProperties"> . </param>
/// <param name="queryTimeout"> Query timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). </param>
/// <param name="query"> Teradata query. Type: string (or Expression with resultType string). </param>
/// <param name="partitionOption"> The partition mechanism that will be used for teradata read in parallel. </param>
/// <param name="partitionSettings"> The settings that will be leveraged for teradata source partitioning. </param>
internal TeradataSource(string type, object sourceRetryCount, object sourceRetryWait, object maxConcurrentConnections, IDictionary<string, object> additionalProperties, object queryTimeout, object query, TeradataPartitionOption? partitionOption, TeradataPartitionSettings partitionSettings) : base(type, sourceRetryCount, sourceRetryWait, maxConcurrentConnections, additionalProperties, queryTimeout)
{
Query = query;
PartitionOption = partitionOption;
PartitionSettings = partitionSettings;
Type = type ?? "TeradataSource";
}
/// <summary> Teradata query. Type: string (or Expression with resultType string). </summary>
public object Query { get; set; }
/// <summary> The partition mechanism that will be used for teradata read in parallel. </summary>
public TeradataPartitionOption? PartitionOption { get; set; }
/// <summary> The settings that will be leveraged for teradata source partitioning. </summary>
public TeradataPartitionSettings PartitionSettings { get; set; }
}
}
| 60.808511 | 408 | 0.683345 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/TeradataSource.cs | 2,858 | C# |
//using System.IO;
//using System.Numerics;
//using static GameEstate.EstateDebug;
//namespace GameEstate.Cry.Formats.Models
//{
// /// <summary>
// /// BONETOWORLD contains the world space location/rotation of a bone.
// /// </summary>
// public struct BONETOWORLD
// {
// public float[,] boneToWorld;// 4x3 structure
// public void ReadBoneToWorld(BinaryReader r)
// {
// boneToWorld = new float[3, 4];
// for (var i = 0; i < 3; i++) for (var j = 0; j < 4; j++) boneToWorld[i, j] = r.ReadSingle();
// //Log($"boneToWorld: {boneToWorld[i, j]:F7}");
// return;
// }
// /// <summary>
// /// Returns the world space rotational matrix in a Math.net 3x3 matrix.
// /// </summary>
// /// <returns>Matrix33</returns>
// public Matrix3x3 GetBoneToWorldRotationMatrix() => new Matrix3x3
// {
// M11 = boneToWorld[0, 0],
// M12 = boneToWorld[0, 1],
// M13 = boneToWorld[0, 2],
// M21 = boneToWorld[1, 0],
// M22 = boneToWorld[1, 1],
// M23 = boneToWorld[1, 2],
// M31 = boneToWorld[2, 0],
// M32 = boneToWorld[2, 1],
// M33 = boneToWorld[2, 2]
// };
// public Vector3 GetBoneToWorldTranslationVector() => new Vector3
// {
// X = boneToWorld[0, 3],
// Y = boneToWorld[1, 3],
// Z = boneToWorld[2, 3]
// };
// #region Log
//#if LOG
// public void LogBoneToWorld()
// {
// Log($"*** Bone to World ***");
// Log($"{boneToWorld[0, 0]:F6} {boneToWorld[0, 1]:F6} {boneToWorld[0, 2]:F6} {boneToWorld[0, 3]:F6}");
// Log($"{boneToWorld[1, 0]:F6} {boneToWorld[1, 1]:F6} {boneToWorld[1, 2]:F6} {boneToWorld[1, 3]:F6}");
// Log($"{boneToWorld[2, 0]:F6} {boneToWorld[2, 1]:F6} {boneToWorld[2, 2]:F6} {boneToWorld[2, 3]:F6}");
// }
//#endif
// #endregion
// }
//} | 35.87931 | 117 | 0.483421 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Cry/GameEstate.Cry/Formats/Unused/BONETOWORLD.cs | 2,083 | C# |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace DaleranGames.UI
{
public class FocusPanel : MonoBehaviour, IPointerDownHandler
{
private RectTransform panel;
void Awake()
{
panel = GetComponent<RectTransform>();
}
public void OnPointerDown(PointerEventData data)
{
panel.SetAsLastSibling();
}
}
} | 18.652174 | 64 | 0.620047 | [
"MIT"
] | Daleran-Games/adelaides-ph | Assets/DalLib/UI/Scripts/FocusPanel.cs | 431 | C# |
namespace ClassLib101
{
public class Class020
{
public static string Property => "ClassLib101";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib101/Class020.cs | 120 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using Stride.Core;
namespace Stride.Graphics
{
/// <summary>
/// <p>Determines the fill mode to use when rendering triangles.</p>
/// </summary>
/// <remarks>
/// <p>This enumeration is part of a rasterizer-state object description (see <strong><see cref="RasterizerStateDescription"/></strong>).</p>
/// </remarks>
[DataContract]
public enum FillMode : int
{
/// <summary>
/// <dd> <p>Draw lines connecting the vertices. Adjacent vertices are not drawn.</p> </dd>
/// </summary>
Wireframe = unchecked((int)2),
/// <summary>
/// <dd> <p>Fill the triangles formed by the vertices. Adjacent vertices are not drawn.</p> </dd>
/// </summary>
Solid = unchecked((int)3),
}
}
| 36.466667 | 145 | 0.634369 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Graphics/FillMode.cs | 1,094 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ordering.Application.Contracts.infrastructure;
using Ordering.Application.Contracts.Persistence;
using Ordering.Application.Models;
using Ordering.Infrastructure.Mail;
using Ordering.Infrastructure.Persistence;
using Ordering.Infrastructure.Repositories;
namespace Ordering.Infrastructure
{
public static class InfrastructureServiceRegistration
{
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<OrderContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("OrderingConnectionString")));
services.AddScoped(typeof(IAsyncRepository<>), typeof(RepositoryBase<>));
services.AddScoped<IOrderRepository, OrderRepository>();
services.Configure<EmailSettings>(c => configuration.GetSection("EmailSettings"));
services.AddTransient<IEmailService, EmailService>();
return services;
}
}
}
| 38.6 | 130 | 0.761658 | [
"MIT"
] | agungtri/AspnetMicroservices | src/Services/Ordering/Ordering.Infrastructure/InfrastructureServiceRegistration.cs | 1,160 | C# |
using kevincastejon.unity;
using UnityEngine;
using Event = kevincastejon.Event;
namespace EventManagerExample
{
public class Example : MonoBehaviour
{
public EventDispatcher Dispatcher;
private bool Dispatched = false;
// Start is called before the first frame update
void Start()
{
}
public void MyCallback(Event e)
{
Debug.Log(e.Name + " event has been dispatched by" + e.Target);
}
// Update is called once per frame
void Update()
{
if (!Dispatched)
{
Dispatcher.DispatchEvent(new Event("someEventName"));
Dispatched = true;
}
}
}
} | 23.03125 | 75 | 0.550882 | [
"MIT"
] | kevincastejon/cs-event-manager-for-unity | Assets/EventManagerForUnity/Scripts/Example.cs | 739 | C# |
var greeter = new HelloWorldApp.Common.Greeter();
Console.WriteLine(greeter.Greet());
| 29.666667 | 51 | 0.752809 | [
"MIT"
] | azurevoodoo/NDCOslo2021 | src/HelloWorldApp.Tool/Program.cs | 91 | C# |
#if !(UNITY_WSA_10_0 && NETFX_CORE)
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.Appearance
//
public enum Appearance : int
{
WearingGlasses =0,
}
}
#endif
| 17.529412 | 52 | 0.600671 | [
"Apache-2.0"
] | 0toN/FruitNinja-with-Kinect | Assets/Standard Assets/Windows/Kinect/Appearance.cs | 298 | 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("XmlTextWriter_Demo2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("XmlTextWriter_Demo2")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("aaac783c-fce1-4c3e-9a2f-2f14619479cd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.621622 | 84 | 0.750875 | [
"MIT"
] | JYang17/SampleCode | Samples/XmlTextWriter_Demo2/XmlTextWriter_Demo2/Properties/AssemblyInfo.cs | 1,432 | C# |
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace nanoFramework.Tools.MetadataProcessor.Tests.Core.Tables
{
[TestClass]
public class nanoAssemblyReferenceTableTests
{
[TestMethod]
public void ConstructorTest()
{
var assemblyDefinition = TestObjectHelper.GetTestNFAppAssemblyDefinition();
var mainModule = assemblyDefinition.MainModule;
var context = TestObjectHelper.GetTestNFAppNanoTablesContext();
// test
var iut = new nanoAssemblyReferenceTable(
mainModule.AssemblyReferences,
context);
// no op
Assert.IsNotNull(iut);
}
[TestMethod]
public void ForEachItemsTest()
{
var assemblyDefinition = TestObjectHelper.GetTestNFAppAssemblyDefinition();
var mainModule = assemblyDefinition.MainModule;
var context = TestObjectHelper.GetTestNFAppNanoTablesContext();
var items = assemblyDefinition.MainModule.AssemblyReferences.ToList<object>();
// test
var iut = new nanoAssemblyReferenceTable(
mainModule.AssemblyReferences,
context);
// test
var forEachCalledOnItems = new List<object>();
iut.ForEachItems((idx, item) =>
{
forEachCalledOnItems.Add(item);
Assert.AreEqual(items.IndexOf(item), (int)idx);
});
CollectionAssert.AreEqual(items.ToArray(), forEachCalledOnItems.ToArray());
}
[TestMethod]
public void WriteTest()
{
var assemblyDefinition = TestObjectHelper.GetTestNFAppAssemblyDefinition();
var mainModule = assemblyDefinition.MainModule;
var context = TestObjectHelper.GetTestNFAppNanoTablesContext();
// test
var iut = new nanoAssemblyReferenceTable(
mainModule.AssemblyReferences,
context);
// need to force this property
context.MinimizeComplete = true;
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms, Encoding.Default, true))
{
var writer = nanoBinaryWriter.CreateLittleEndianBinaryWriter(bw);
// test
iut.Write(writer);
bw.Flush();
}
var streamOutput = new MemoryStream();
var writerTestOutput = new BinaryWriter(streamOutput, Encoding.Default, true);
foreach(var a in iut.Items)
{
writerTestOutput.Write(context.StringTable.GetOrCreateStringId(a.Name));
// padding
writerTestOutput.Write((ushort)0x0);
// version
writerTestOutput.Write((ushort)a.Version.Major);
writerTestOutput.Write((ushort)a.Version.Minor);
writerTestOutput.Write((ushort)a.Version.Build);
writerTestOutput.Write((ushort)a.Version.Revision);
}
var expectedByteWritten = streamOutput.ToArray();
var bytesWritten = ms.ToArray();
CollectionAssert.AreEqual(expectedByteWritten, bytesWritten, $"Wrote: {string.Join(", ", bytesWritten.Select(i => i.ToString("X")))}, Expected: {string.Join(", ", expectedByteWritten.Select(i => i.ToString("X")))} ");
}
}
}
}
| 34.4375 | 233 | 0.574281 | [
"MIT"
] | Eclo/metadata-processor | MetadataProcessor.Tests/Core/Tables/nanoAssemblyReferenceTableTests.cs | 3,859 | C# |
// Copyright (c) ServiceStack, Inc. All Rights Reserved.
// License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System.IO;
using ServiceStack.Text;
namespace ServiceStack.ProtoBuf
{
public static class ProtoBufExtensions
{
public static byte[] ToProtoBuf<T>(this T obj)
{
using (var ms = MemoryStreamFactory.GetStream())
{
ProtoBufFormat.Serialize(obj, ms);
var bytes = ms.ToArray();
return bytes;
}
}
public static T FromProtoBuf<T>(this byte[] bytes)
{
using (var ms = MemoryStreamFactory.GetStream(bytes))
{
var obj = (T)ProtoBufFormat.Deserialize(typeof(T), ms);
return obj;
}
}
}
} | 28.733333 | 80 | 0.539443 | [
"Apache-2.0"
] | BruceCowan-AI/ServiceStack | src/ServiceStack.ProtoBuf/ProtoBufExtensions.cs | 835 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// MemberResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.IpMessaging.V1.Service.Channel
{
public class MemberResource : Resource
{
private static Request BuildFetchRequest(FetchMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Fetch(FetchMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(FetchMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Fetch(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Create(CreateMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(CreateMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="roleSid"> The role_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Create(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="roleSid"> The role_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static ResourceSet<MemberResource> Read(ReadMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<MemberResource>.FromJson("members", response.Content);
return new ResourceSet<MemberResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(ReadMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<MemberResource>.FromJson("members", response.Content);
return new ResourceSet<MemberResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static ResourceSet<MemberResource> Read(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<MemberResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("members", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<MemberResource> NextPage(Page<MemberResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("members", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<MemberResource> PreviousPage(Page<MemberResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("members", response.Content);
}
private static Request BuildDeleteRequest(DeleteMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static bool Delete(DeleteMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static bool Delete(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Update(UpdateMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(UpdateMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="roleSid"> The role_sid </param>
/// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Update(string pathServiceSid,
string pathChannelSid,
string pathSid,
string roleSid = null,
int? lastConsumedMessageIndex = null,
ITwilioRestClient client = null)
{
var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="roleSid"> The role_sid </param>
/// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
string roleSid = null,
int? lastConsumedMessageIndex = null,
ITwilioRestClient client = null)
{
var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a MemberResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> MemberResource object represented by the provided JSON </returns>
public static MemberResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<MemberResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The sid
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The account_sid
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The channel_sid
/// </summary>
[JsonProperty("channel_sid")]
public string ChannelSid { get; private set; }
/// <summary>
/// The service_sid
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The identity
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// The date_created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date_updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The role_sid
/// </summary>
[JsonProperty("role_sid")]
public string RoleSid { get; private set; }
/// <summary>
/// The last_consumed_message_index
/// </summary>
[JsonProperty("last_consumed_message_index")]
public int? LastConsumedMessageIndex { get; private set; }
/// <summary>
/// The last_consumption_timestamp
/// </summary>
[JsonProperty("last_consumption_timestamp")]
public DateTime? LastConsumptionTimestamp { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private MemberResource()
{
}
}
} | 45.871429 | 163 | 0.530092 | [
"MIT"
] | BrimmingDev/twilio-csharp | src/Twilio/Rest/IpMessaging/V1/Service/Channel/MemberResource.cs | 25,688 | 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("TestFlask.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestFlask.Models")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("950e37cd-2c68-4b4e-9137-f82e696dc52c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.972973 | 84 | 0.745196 | [
"MIT"
] | FatihSahin/test-flask | TestFlask.Models/Properties/AssemblyInfo.cs | 1,408 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Moq;
using TwitterStats.API.Controllers;
using TwitterStats.API.DTO;
using TwitterStats.API.Models;
using TwitterStats.API.Repository;
using Xunit;
namespace TwitterStats.UnitTest
{
/*
* In the interest of time I'm not actually going to finish these out. You get the idea though.
* This set of tests should simply be a sanity-check for our controller.
* Since the controller is really just a query handler, I would argue that unit tests here are unnecessary.
* Just wanted to show how I'd get these tested in interest of 100% test coverage.
*/
public class InfoApiTest
{
private readonly Mock<ITweetInfoRepository> _repoMock;
public InfoApiTest()
{
_repoMock = new Mock<ITweetInfoRepository>();
}
private InfoController BuildInfoController()
{
return new(_repoMock.Object);
}
[Fact]
public async void Get_count_success()
{
// Arrange
long expectation = 256;
_repoMock.Setup(x => x.GetCount()).Returns(Task.FromResult(expectation));
// Act
var infoController = BuildInfoController();
var result = await infoController.GetCount();
// Assert
var objectResult = Assert.IsType<OkObjectResult>(result.Result);
var dto = Assert.IsType<CountDto>(objectResult.Value);
Assert.Equal(expectation, dto.TotalTweets);
}
[Fact]
public async void Get_rate_success()
{
// Arrange
var expectation = new TweetRate
{
TweetsPerSecond = 60
};
_repoMock.Setup(x => x.GetTweetRate()).Returns(Task.FromResult(expectation));
// Act
var infoController = BuildInfoController();
var result = await infoController.GetTweetRate();
// Assert
var objectResult = Assert.IsType<OkObjectResult>(result.Result);
var dto = Assert.IsType<TweetRateDto>(objectResult.Value);
Assert.Equal(expectation, dto.Rate);
}
[Fact]
public async void Get_emoji_success()
{
// Arrange
var itemMock = new Mock<IEnumerable<KeyValuePair<string, int>>>();
_repoMock.Setup(x => x.GetTopEmoji(1)).Returns(Task.FromResult(itemMock.Object));
// Act
var infoController = BuildInfoController();
var result = await infoController.GetEmojiInfo();
// Assert
var objectResult = Assert.IsType<OkObjectResult>(result.Result);
var dto = Assert.IsType<EmojiDto>(objectResult.Value);
}
}
} | 32.953488 | 111 | 0.609033 | [
"MIT"
] | deinman/TwitterStreamDemo | TwitterStats.UnitTest/InfoApiTest.cs | 2,834 | C# |
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Text;
namespace Library.Business
{
public class ActionResponse<T> where T : class, new()
{
public HttpResponseMessage CreateResponse(BResult<T> result)
{
var response = new HttpResponseMessage();
response.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
if (result.Error.Count == 0)
{
if (result.Result == null || result.Result == default(T))
response.StatusCode = HttpStatusCode.NoContent;
else
response.StatusCode = HttpStatusCode.OK;
}
else
response.StatusCode = HttpStatusCode.BadRequest;
return response;
}
public HttpResponseMessage CreateResponse(BResult result)
{
var response = new HttpResponseMessage();
response.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
if (result.Error.Count == 0)
response.StatusCode = HttpStatusCode.NoContent;
else
response.StatusCode = HttpStatusCode.BadRequest;
return response;
}
}
}
| 32.209302 | 122 | 0.575451 | [
"MIT"
] | bschreder/Calculator | Library/Business/ActionResponse.cs | 1,387 | C# |
using AdaptiveRoads.Manager;
using AdaptiveRoads.Patches.Lane;
using ICities;
using KianCommons;
using System.Diagnostics;
namespace AdaptiveRoads.LifeCycle {
public class ThreadingExtensions : ThreadingExtensionBase {
public override void OnAfterSimulationTick() {
base.OnBeforeSimulationTick();
NetworkExtensionManager.Instance.SimulationStep();
}
#if DEBUG
public static Stopwatch timer;
public override void OnUpdate(float realTimeDelta, float simulationTimeDelta) {
return;
timer ??= Stopwatch.StartNew();
if (timer.ElapsedMilliseconds > 1000) {
Handle(CheckPropFlagsCommons.timer, "propcheck");
Handle(CheckPropFlagsCommons.timer2, "propcheck2");
Handle(CheckPropFlagsCommons.timer3, "propcheck3");
timer.Restart();
}
}
public static void Handle(Stopwatch sw, string name) {
Log.Debug($"{name} = %{100 * sw.ElapsedMilliseconds / timer.ElapsedMilliseconds}", false);
sw.Reset();
}
#endif
}
public static class TimerExtensions {
public static void Restart(this Stopwatch sw) {
sw.Reset();
sw.Start();
}
}
}
| 31.390244 | 102 | 0.620824 | [
"MIT"
] | kianzarrin/AdaptiveNetworks | AdaptiveRoads/LifeCycle/ThreadingExtensions.cs | 1,287 | C# |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.iOS.DOM
{
/// <summary>
/// Marks last undoable state.
/// </summary>
[Command(ProtocolName.DOM.MarkUndoableState)]
[SupportedBy("iOS")]
public class MarkUndoableStateCommand
{
}
}
| 20.3125 | 52 | 0.763077 | [
"MIT"
] | vadik007/ChromeDevTools | source/ChromeDevTools/Protocol/iOS/DOM/MarkUndoableStateCommand.cs | 325 | C# |
using System.Threading.Tasks;
using FluentAssertions;
using NUnit.Framework;
using Vostok.Applications.AspNetCore.Builders;
using Vostok.Applications.AspNetCore.Diagnostics;
using Vostok.Applications.AspNetCore.Tests.Extensions;
using Vostok.Clusterclient.Core.Model;
using Vostok.Hosting.Abstractions;
using Vostok.Logging.Abstractions;
using HeaderNames = Microsoft.Net.Http.Headers.HeaderNames;
namespace Vostok.Applications.AspNetCore.Tests.Tests
{
public class DiagnosticApiMiddlewareTests : TestsBase
{
public DiagnosticApiMiddlewareTests(bool webApplication)
: base(webApplication)
{
}
[Test]
public async Task Root_path_should_return_an_html_page_with_a_list_of_registered_info_providers()
{
var response = (await Client.GetAsync("/_diagnostic")).Response.EnsureSuccessStatusCode();
response.Headers[HeaderNames.ContentType].Should().Be("text/html");
response.HasContent.Should().BeTrue();
Log.Info(response.Content.ToString());
}
[Test]
public async Task Root_path_should_reject_requests_with_prohibited_headers()
{
var request = Request.Get("/_diagnostic").WithHeader("Prohibited", "yep");
var response = (await Client.SendAsync(request)).Response;
response.Code.Should().Be(ResponseCode.Forbidden);
response.HasContent.Should().BeFalse();
}
[Test]
public async Task Info_path_should_return_json_info_for_registered_entries()
{
var response = (await Client.GetAsync($"/_diagnostic/{DiagnosticConstants.Component}/request-throttling")).Response.EnsureSuccessStatusCode();
response.Headers[HeaderNames.ContentType].Should().Be("application/json");
response.HasContent.Should().BeTrue();
Log.Info(response.Content.ToString());
}
[Test]
public async Task Info_path_should_reject_requests_with_prohibited_headers()
{
var request = Request.Get($"/_diagnostic/{DiagnosticConstants.Component}/request-throttling")
.WithHeader("Prohibited", "yep");
var response = (await Client.SendAsync(request)).Response;
response.Code.Should().Be(ResponseCode.Forbidden);
response.HasContent.Should().BeFalse();
}
[Test]
public async Task Info_path_should_not_handle_requests_with_unknown_entries()
{
var request = Request.Get("/_diagnostic/unknown-component/request-throttling");
var response = (await Client.SendAsync(request)).Response;
response.Code.Should().Be(ResponseCode.NotFound);
response.HasContent.Should().BeFalse();
}
protected override void SetupGlobal(IVostokAspNetCoreApplicationBuilder builder, IVostokHostingEnvironment environment)
{
builder.SetupDiagnosticApi(settings => settings.ProhibitedHeaders.Add("Prohibited"));
}
#if NET6_0_OR_GREATER
protected override void SetupGlobal(IVostokAspNetCoreWebApplicationBuilder builder, IVostokHostingEnvironment environment)
{
builder.SetupDiagnosticApi(settings => settings.ProhibitedHeaders.Add("Prohibited"));
}
#endif
}
} | 37.41573 | 154 | 0.685886 | [
"MIT"
] | vostok/hosting.aspnetcore | Vostok.Applications.AspNetCore.Tests/Tests/DiagnosticApiMiddlewareTests.cs | 3,332 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace starsky.foundation.database.Migrations
{
public partial class importdatabase : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ImportIndex",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true)
.Annotation("MySql:ValueGeneratedOnAdd", true),
AddToDatabase = table.Column<DateTime>(nullable: false),
FileHash = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ImportIndex", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ImportIndex");
}
}
}
| 33.030303 | 76 | 0.531193 | [
"MIT"
] | qdraw/starsky | starsky/starsky.foundation.database/Migrations/20180419182654_importdatabase.cs | 1,092 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d2d1effects.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum D2D1_TILE_PROP : uint
{
D2D1_TILE_PROP_RECT = 0,
D2D1_TILE_PROP_FORCE_DWORD = 0xffffffff,
}
}
| 32.285714 | 145 | 0.732301 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/d2d1effects/D2D1_TILE_PROP.cs | 454 | C# |
using System;
namespace lab_02_class
{
class Program
{
static void Main()
{
var dog1 = new Dog(); //This is an instance of a class
dog1.Age = 10;
dog1.Height = 50;
dog1.Name = "Bob";
//Console.WriteLine("Hello World!");
Console.WriteLine($"The dog's name is {dog1.Name}, is {dog1.Age} years old and is {dog1.Height}cm tall.");
Console.ReadLine();
dog1.Grow();
Console.WriteLine($"{dog1.Name} is now {dog1.Age} years old and is {dog1.Height}cm tall.");
}
}
class Dog
{
public string Name;
public int Age, Height;
public void Grow()
{
this.Age++;
this.Height += 10;
}
}
}
| 23.028571 | 118 | 0.485112 | [
"MIT"
] | SamRibes/2019-09-c-sharp-labs | labs/lab_02_class/Program.cs | 808 | C# |
using System;
namespace Mem.Core.Moderator
{
public class WorldHandler : IWorldHandler
{
private readonly IWorldKeeper worldKeeper;
private readonly IAreaLoader areaLoader;
private readonly IMudLogger log;
private bool isInitialResetPerformed;
public WorldHandler(IWorldKeeper worldKeeper, IAreaLoader areaLoader, IMudLogger log)
{
this.worldKeeper = worldKeeper ?? throw new ArgumentNullException(nameof(worldKeeper));
this.areaLoader = areaLoader ?? throw new ArgumentNullException(nameof(areaLoader));
this.log = log ?? throw new ArgumentNullException(nameof(log));
}
public void BuildWorld()
{
this.worldKeeper.World = new World(this.areaLoader.LoadAreas().ReplaceNewLines());
}
public void SpinWorld()
{
var world = this.worldKeeper.World;
if (!this.isInitialResetPerformed)
{
foreach (var area in world.Areas)
{
this.log.Info("Resetting: {Title}", area.Title);
world.Reset(area.Resets);
}
this.isInitialResetPerformed = true;
}
}
}
}
| 29.418605 | 99 | 0.588933 | [
"Unlicense"
] | jurishev/memento | server/Mem.Core.Moderator/WorldHandler.cs | 1,267 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.DotNet.Interactive.Commands;
using Microsoft.DotNet.Interactive.Events;
namespace Microsoft.DotNet.Interactive.Connection
{
public class CommandOrEvent
{
public KernelCommand Command { get; }
public KernelEvent Event { get; }
public bool IsParseError { get; }
public CommandOrEvent(KernelCommand kernelCommand)
{
Command = kernelCommand ?? throw new ArgumentNullException(nameof(kernelCommand));
Event = null;
}
public CommandOrEvent(KernelEvent kernelEvent, bool isParseError = false)
{
Command = null;
Event = kernelEvent ?? throw new ArgumentNullException(nameof(kernelEvent));
IsParseError = isParseError;
}
};
} | 33.413793 | 101 | 0.675955 | [
"MIT"
] | AngleQian/interactive | src/Microsoft.DotNet.Interactive/Connection/CommandOrEvent.cs | 971 | C# |
namespace EA.Weee.Email.Tests.Unit.EventHandlers.OrganisationUserRequest
{
using EA.Weee.Domain.Events;
using EA.Weee.Domain.Organisation;
using EA.Weee.Email.EventHandlers;
using FakeItEasy;
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
public class OrganisationUserRequestCompletedEventHandlerTests
{
private IWeeeEmailService emailService;
private readonly IOrganisationUserRequestEventHandlerDataAccess dataAccess;
private OrganisationUserRequestCompletedEventHandler handler;
public OrganisationUserRequestCompletedEventHandlerTests()
{
this.emailService = A.Fake<IWeeeEmailService>();
this.dataAccess = A.Fake<IOrganisationUserRequestEventHandlerDataAccess>();
this.handler = new OrganisationUserRequestCompletedEventHandler(dataAccess, emailService);
}
[Fact]
public async Task HandleAsync_GivenRequest_DataAccessIsCalled()
{
var request = A.Dummy<OrganisationUserRequestCompletedEvent>();
await handler.HandleAsync(request);
A.CallTo(() => dataAccess.FetchActiveOrganisationUsers(request.OrganisationUser.OrganisationId)).MustHaveHappened(Repeated.Exactly.Once);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task HandleAsync_GivenRequest_SendOrganisationUserRequestCompletedIsCalledWithCorrectParameters(bool activeUsers)
{
var request = A.Dummy<OrganisationUserRequestCompletedEvent>();
var activeOrganisationUsers = new List<OrganisationUser>();
if (activeUsers)
{
activeOrganisationUsers.Add(A.Fake<OrganisationUser>());
}
A.CallTo(() => dataAccess.FetchActiveOrganisationUsers(request.OrganisationUser.OrganisationId)).Returns(activeOrganisationUsers);
await handler.HandleAsync(request);
A.CallTo(() => emailService.SendOrganisationUserRequestCompleted(request.OrganisationUser, activeUsers)).MustHaveHappened(Repeated.Exactly.Once);
}
}
}
| 37.633333 | 157 | 0.706377 | [
"Unlicense"
] | DEFRA/prsd-weee | src/EA.Weee.Email.Tests.Unit/EventHandlers/OrganisationUserRequest/OrganisationUserRequestCompletedEventHandlerTests.cs | 2,260 | C# |
using System;
using Xunit;
using Sample.MergeKSortedLs;
namespace Sample.Tests{
public class UnitTest_MergeKSortedLs{
[Theory]
[InlineData(0,0)]
public void checkResult(int n,int expected){
Assert.Equal(expected,mergeKSortedLs.naive(n));
}
}
}
| 21.214286 | 59 | 0.649832 | [
"MIT"
] | zcemycl/algoTest | cs/sample/Sample.Tests/MergeKSortedLs/testMergeKSortedLs.cs | 297 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SparkBallGame
{
public class DoubleMultiplayer : PowerUp
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
} | 16.666667 | 56 | 0.591429 | [
"MIT"
] | MohamedAtres-Dev/SparkMan | Assets/Scripts/Collectables/PowerUpTypes/DoubleMultiplayer.cs | 350 | C# |
using Microsoft.Bot.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ai.pdm.bot.models
{
public class AIPDMContext : TurnContextWrapper
{
/// <summary>
/// AlarmBot recognized Intents for the incoming activity
/// </summary>
public IRecognizedIntents RecognizedIntents { get { return this.Services.Get<IRecognizedIntents>(); } }
public AIPDMContext(ITurnContext context) : base(context)
{
}
}
}
| 24.818182 | 111 | 0.659341 | [
"MIT"
] | Nepomuceno/ai-pdm | ai.pdm.bot/models/AIPDMContext.cs | 548 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Edgee.Api.VutbuCore.DataLayer
{
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[MaxLength(50)]
[Required]
public string Username { get; set; }
[MaxLength(250)]
[Required]
public string Name { get; set; }
[MaxLength(250)]
public string Surname { get; set; }
[MaxLength(250)]
public string ProfilePhoto { get; set; }
public List<UserContact> UserContacts { get; set; }
public List<UserGroup> UserGroups { get; set; }
public UserFinancial UserFinancial { get; set; }
}
}
| 28.206897 | 61 | 0.629584 | [
"MIT"
] | edgeetech/Edgee-Currency-Api | Edgee.Api.VutbuCore/DataLayer/User.cs | 820 | C# |
// <copyright file="WarpInfo.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.DataModel.Configuration
{
/// <summary>
/// Defines a warp list entry.
/// </summary>
/// <remarks>
/// AFAIK, this is only relevant if we want to host the server for clients of season 5 and below.
/// With season 6 and upwards, gates are used directly. Then I ask myself how the warp price is determined -> TODO.
/// </remarks>
public class WarpInfo
{
/// <summary>
/// Gets or sets the index.
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the warp zen.
/// </summary>
public uint WarpCosts { get; set; }
/// <summary>
/// Gets or sets the warp level req.
/// </summary>
public ushort WarpLvlReq { get; set; }
/// <summary>
/// Gets or sets the gate.
/// </summary>
public virtual ExitGate Gate { get; set; }
}
}
| 29.47619 | 119 | 0.560582 | [
"MIT"
] | sven-n/OpenMU | src/DataModel/Configuration/WarpInfo.cs | 1,240 | C# |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Yu5h1Tools.WPFExtension
{
public static class MouseEventUtility
{
public static Point previouseDragPoint;
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target"></param>
/// <param name="DragStart">boolean confirm start</param>
/// <param name="Draging">Vector draged distance.</param>
/// <param name="DragEnd"></param>
/// <param name="RMBDown">boolean IsCancel</param>
public static void AddMouseDragEvent<T>(T target,
Func<bool> DragStart, Action<Vector> Draging, Action DragEnd, Action<bool> RMBDown)
where T : UIElement
{
target.MouseLeftButtonDown += (s,e) => {
var sender = (UIElement)s;
previouseDragPoint = e.GetPosition(sender);
if (DragStart()) {
sender.CaptureMouse();
}
};
target.MouseMove += (s, e) => {
var sender = (UIElement)s;
if (sender.IsMouseCaptured)
{
var v = e.GetPosition(sender) - previouseDragPoint ;
Draging(v);
}
};
target.MouseLeftButtonUp += (s, e) => {
var sender = (UIElement)s;
if (sender.IsMouseCaptured)
{
DragEnd();
sender.ReleaseMouseCapture();
}
};
//Cancel Drag
target.MouseRightButtonDown += (s, e) => {
var sender = (UIElement)s;
RMBDown(sender.IsMouseCaptured);
if (sender.IsMouseCaptured)
{
sender.ReleaseMouseCapture();
}
};
}
}
}
| 33.033333 | 95 | 0.4778 | [
"MIT"
] | Yu5h1/WPFExtension | Yu5h1Tools.WPFExtension/MouseEventUtility.cs | 1,984 | C# |
using System;
namespace NuGet.Frameworks
{
/// <summary>
/// Internal cache key used to store framework compatibility.
/// </summary>
internal class CompatibilityCacheKey : IEquatable<CompatibilityCacheKey>
{
public NuGetFramework Target { get; }
public NuGetFramework Candidate { get; }
private readonly int _hashCode;
public CompatibilityCacheKey(NuGetFramework target, NuGetFramework candidate)
{
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
if (candidate == null)
{
throw new ArgumentNullException(nameof(candidate));
}
Target = target;
Candidate = candidate;
// This is designed to be cached, just get the hash up front
var combiner = new HashCodeCombiner();
combiner.AddObject(target);
combiner.AddObject(candidate);
_hashCode = combiner.CombinedHash;
}
public override int GetHashCode()
{
return _hashCode;
}
public bool Equals(CompatibilityCacheKey other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Target.Equals(other.Target)
&& Candidate.Equals(other.Candidate);
}
public override bool Equals(object obj)
{
return Equals(obj as CompatibilityCacheKey);
}
public override string ToString()
{
return $"{Target.DotNetFrameworkName} -> {Candidate.DotNetFrameworkName}";
}
}
}
| 26.086957 | 86 | 0.541667 | [
"Apache-2.0"
] | StephenCleary/NuGet.Client | src/NuGet.Core/NuGet.Frameworks/CompatibilityCacheKey.cs | 1,802 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Search.Documents.Indexes;
namespace Azure.Search.Documents.Perf.Infrastructure
{
/// <summary>
/// Address.
/// </summary>
public sealed class Address
{
/// <summary>
/// StreetAddress.
/// </summary>
[SearchableField]
public string StreetAddress { get; set; }
/// <summary>
/// City.
/// </summary>
[SearchableField(IsFilterable = true, IsSortable = true, IsFacetable = true)]
public string City { get; set; }
/// <summary>
/// StateProvince.
/// </summary>
[SearchableField(IsFilterable = true, IsSortable = true, IsFacetable = true)]
public string StateProvince { get; set; }
/// <summary>
/// PostalCode.
/// </summary>
[SearchableField(IsFilterable = true, IsSortable = true, IsFacetable = true)]
public string PostalCode { get; set; }
/// <summary>
/// Country.
/// </summary>
[SearchableField(IsFilterable = true, IsSortable = true, IsFacetable = true)]
public string Country { get; set; }
}
}
| 28.181818 | 85 | 0.569355 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/search/Azure.Search.Documents/perf/Azure.Search.Documents.Perf/Infrastructure/Address.cs | 1,242 | C# |
using Bot.BotLists.Interfaces.Services;
using Bot.BotLists.Services;
using Bot.Discord;
using Bot.Discord.Configurations;
using Bot.Discord.Handlers;
using Bot.Discord.Handlers.CommandHandlers;
using Bot.Discord.Services;
using Bot.Discord.Timers;
using Bot.Interfaces;
using Bot.Interfaces.Discord;
using Bot.Interfaces.Discord.Handlers;
using Bot.Interfaces.Discord.Handlers.CommandHandlers;
using Bot.Interfaces.Discord.Services;
using Bot.Logger.Interfaces;
using Bot.Persistence.EntityFrameWork;
using Bot.Persistence.EntityFrameWork.Repositories;
using Bot.Persistence.EntityFrameWork.UnitOfWorks;
using Bot.Persistence.Repositories;
using Bot.Persistence.UnitOfWorks;
using Discord.Commands;
using Discord.WebSocket;
using Unity;
using Unity.Injection;
using Unity.Lifetime;
namespace Bot
{
public static class Unity
{
private static UnityContainer container;
private static UnityContainer Container
{
get
{
if (container == null)
RegisterTypes();
return container;
}
}
/// <summary>
/// Registers objects to the <see cref="container"/>
/// </summary>
public static void RegisterTypes()
{
container = new UnityContainer();
container.RegisterType<IBot, Bot>(new PerThreadLifetimeManager());
container.RegisterSingleton<IConnection, Connection>();
container.RegisterType<ILogger, Logger.Logger>(new PerThreadLifetimeManager());
// DI for discord
container.RegisterFactory<DiscordSocketConfig>(i => SocketConfig.GetDefault(), new SingletonLifetimeManager());
container.RegisterFactory<CommandService>(i => CommandConfig.GetDefault(), new SingletonLifetimeManager());
container.RegisterSingleton<DiscordShardedClient>(new InjectionConstructor(typeof(DiscordSocketConfig)));
container.RegisterSingleton<IClientLogHandler, ClientLogHandler>();
container.RegisterSingleton<IMiscEventHandler, MiscEventHandler>();
container.RegisterSingleton<IPrefixService, PrefixService>();
container.RegisterSingleton<IBotListUpdater, BotListUpdater>();
container.RegisterSingleton<DiscordBotListsUpdateTimer>();
container.RegisterType<ICommandErrorHandler, CommandErrorHandler>(new PerThreadLifetimeManager());
container.RegisterType<ICommandInputErrorHandler, CommandInputErrorHandler>(new PerThreadLifetimeManager());
container.RegisterType<ICommandHandler, CommandHandler>(new PerThreadLifetimeManager());
container.RegisterType<ISpamFilter, SpamFilter>(new PerThreadLifetimeManager());
// DI for Entity framework
container.RegisterType<BotContext>(new PerResolveLifetimeManager());
container.RegisterType<IUnitOfWork, UnitOfWork>(new PerResolveLifetimeManager());
container.RegisterType<IRequestUnitOfWork, RequestUnitOfWork>(new PerResolveLifetimeManager());
container.RegisterType<IServerUnitOfWork, ServerUnitOfWork>(new PerResolveLifetimeManager());
container.RegisterType<IServerRepository, ServerRepository>(new PerResolveLifetimeManager());
container.RegisterType<IUserRepository, UserRepository>(new PerResolveLifetimeManager());
container.RegisterType<IRequestRepository, RequestRepository>(new PerResolveLifetimeManager());
}
/// <summary>
/// Resolve a objects that is registered in the <see cref="container"/>.
/// </summary>
/// <typeparam name="T">The object you want to resolve</typeparam>
/// <returns>The resolved object.</returns>
public static T Resolve<T>()
{
return (T)Container.Resolve(typeof(T));
}
}
}
| 42.217391 | 123 | 0.705458 | [
"MIT"
] | Baaaliiint/Music-commands | Bot/Unity.cs | 3,886 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Docker.Outputs
{
[OutputType]
public sealed class ServiceTaskSpec
{
/// <summary>
/// The spec for each container
/// </summary>
public readonly Outputs.ServiceTaskSpecContainerSpec ContainerSpec;
/// <summary>
/// A counter that triggers an update even if no relevant parameters have been changed. See the [spec](https://github.com/docker/swarmkit/blob/master/api/specs.proto#L126).
/// </summary>
public readonly int? ForceUpdate;
/// <summary>
/// Specifies the log driver to use for tasks created from this spec. If not present, the default one for the swarm will be used, finally falling back to the engine default if not specified
/// </summary>
public readonly Outputs.ServiceTaskSpecLogDriver? LogDriver;
/// <summary>
/// Ids of the networks in which the container will be put in
/// </summary>
public readonly ImmutableArray<string> Networks;
/// <summary>
/// The placement preferences
/// </summary>
public readonly Outputs.ServiceTaskSpecPlacement? Placement;
/// <summary>
/// Resource requirements which apply to each individual container created as part of the service
/// </summary>
public readonly Outputs.ServiceTaskSpecResources? Resources;
/// <summary>
/// Specification for the restart policy which applies to containers created as part of this service.
/// </summary>
public readonly Outputs.ServiceTaskSpecRestartPolicy? RestartPolicy;
/// <summary>
/// Runtime is the type of runtime specified for the task executor. See the [types](https://github.com/moby/moby/blob/master/api/types/swarm/runtime.go).
/// </summary>
public readonly string? Runtime;
[OutputConstructor]
private ServiceTaskSpec(
Outputs.ServiceTaskSpecContainerSpec containerSpec,
int? forceUpdate,
Outputs.ServiceTaskSpecLogDriver? logDriver,
ImmutableArray<string> networks,
Outputs.ServiceTaskSpecPlacement? placement,
Outputs.ServiceTaskSpecResources? resources,
Outputs.ServiceTaskSpecRestartPolicy? restartPolicy,
string? runtime)
{
ContainerSpec = containerSpec;
ForceUpdate = forceUpdate;
LogDriver = logDriver;
Networks = networks;
Placement = placement;
Resources = resources;
RestartPolicy = restartPolicy;
Runtime = runtime;
}
}
}
| 38.128205 | 197 | 0.64694 | [
"Apache-2.0"
] | stevesloka/pulumi-docker | sdk/dotnet/Outputs/ServiceTaskSpec.cs | 2,974 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using leaderboardAPI.Models;
namespace leaderboardAPI.Migrations
{
[DbContext(typeof(PlayerContext))]
[Migration("20190626110327_adding avatarId for player")]
partial class addingavatarIdforplayer
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
modelBuilder.Entity("BrainPowerApp.Model.Player", b =>
{
b.Property<int>("id")
.ValueGeneratedOnAdd();
b.Property<int>("avatarId");
b.Property<string>("name");
b.Property<string>("recordDate");
b.Property<int>("score");
b.HasKey("id");
b.ToTable("players");
});
#pragma warning restore 612, 618
}
}
}
| 28.878049 | 75 | 0.598818 | [
"MIT"
] | Aimene-BAHRI/Hacktober-2019 | APIs/TodoAPI/TodoAPI/Migrations/20190626110327_adding avatarId for player.Designer.cs | 1,186 | C# |
using System;
namespace EventBus
{
public class Class1
{
}
}
| 8.333333 | 23 | 0.6 | [
"MIT"
] | rodrigoarias12/BlockchainMessageEvent | BuildingBlocks/EventBus/Class1.cs | 77 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Controls
{
#if false || false || false || false || false || false || false
#if false || false || false || false || false || false || false
[global::Uno.NotImplemented]
#endif
public enum SnapPointsType
{
// Skipping already declared field Windows.UI.Xaml.Controls.SnapPointsType.None
// Skipping already declared field Windows.UI.Xaml.Controls.SnapPointsType.Optional
// Skipping already declared field Windows.UI.Xaml.Controls.SnapPointsType.Mandatory
// Skipping already declared field Windows.UI.Xaml.Controls.SnapPointsType.OptionalSingle
// Skipping already declared field Windows.UI.Xaml.Controls.SnapPointsType.MandatorySingle
}
#endif
}
| 41.684211 | 92 | 0.762626 | [
"Apache-2.0"
] | Abhishek-Sharma-Msft/uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/SnapPointsType.cs | 792 | C# |
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace Blade.Util
{
/// <summary>
/// 任务队列
/// </summary>
public class TaskQueue
{
#region 构造函数
/// <summary>
/// 默认队列
/// 注:默认间隔时间1ms
/// </summary>
public TaskQueue()
{
_timeSpan = TimeSpan.Zero;
Start();
}
/// <summary>
/// 间隔任务队列
/// 注:每个任务之间间隔一段时间
/// </summary>
/// <param name="timeSpan">间隔时间</param>
public TaskQueue(TimeSpan timeSpan)
{
_timeSpan = timeSpan;
Start();
}
#endregion
#region 私有成员
Semaphore _semaphore { get; } = new Semaphore(0, int.MaxValue);
private void Start()
{
Task.Factory.StartNew(() =>
{
while (_isRun)
{
try
{
_semaphore.WaitOne();
bool success = _taskList.TryDequeue(out Action task);
if (success)
{
task?.Invoke();
}
if (_timeSpan != TimeSpan.Zero)
Thread.Sleep(_timeSpan);
}
catch (Exception ex)
{
HandleException?.Invoke(ex);
}
}
}, TaskCreationOptions.LongRunning);
}
private bool _isRun { get; set; } = true;
private TimeSpan _timeSpan { get; set; }
private ConcurrentQueue<Action> _taskList { get; } = new ConcurrentQueue<Action>();
#endregion
#region 外部接口
public void Stop()
{
_isRun = false;
}
public void Enqueue(Action task)
{
_taskList.Enqueue(task);
_semaphore.Release();
}
public Action<Exception> HandleException { get; set; }
#endregion
}
}
| 23.898876 | 91 | 0.432534 | [
"MIT"
] | lypcore/Blade.Admin | src/Blade.Util/ClassLibrary/TaskQeury.cs | 2,233 | C# |
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated May 1, 2019. Replaces all prior versions.
*
* Copyright (c) 2013-2019, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS
* INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 UnityEngine;
namespace Spine.Unity {
// To use this example component, add it to your SkeletonAnimation Spine GameObject.
// This component will disable that SkeletonAnimation component to prevent it from calling its own Update and LateUpdate methods.
[DisallowMultipleComponent]
public sealed class SkeletonAnimationFixedTimestep : MonoBehaviour {
#region Inspector
public SkeletonAnimation skeletonAnimation;
[Tooltip("The duration of each frame in seconds. For 12 fps: enter '1/12' in the Unity inspector.")]
public float frameDeltaTime = 1 / 15f;
[Header("Advanced")]
[Tooltip("The maximum number of fixed timesteps. If the game framerate drops below the If the framerate is consistently faster than the limited frames, this does nothing.")]
public int maxFrameSkip = 4;
[Tooltip("If enabled, the Skeleton mesh will be updated only on the same frame when the animation and skeleton are updated. Disable this or call SkeletonAnimation.LateUpdate yourself if you are modifying the Skeleton using other components that don't run in the same fixed timestep.")]
public bool frameskipMeshUpdate = true;
[Tooltip("This is the amount the internal accumulator starts with. Set it to some fraction of your frame delta time if you want to stagger updates between multiple skeletons.")]
public float timeOffset;
#endregion
float accumulatedTime = 0;
bool requiresNewMesh;
void OnValidate () {
skeletonAnimation = GetComponent<SkeletonAnimation>();
if (frameDeltaTime <= 0) frameDeltaTime = 1 / 60f;
if (maxFrameSkip < 1) maxFrameSkip = 1;
}
void Awake () {
requiresNewMesh = true;
accumulatedTime = timeOffset;
}
void Update () {
if (skeletonAnimation.enabled)
skeletonAnimation.enabled = false;
accumulatedTime += Time.deltaTime;
float frames = 0;
while (accumulatedTime >= frameDeltaTime) {
frames++;
if (frames > maxFrameSkip) break;
accumulatedTime -= frameDeltaTime;
}
if (frames > 0) {
skeletonAnimation.Update(frames * frameDeltaTime);
requiresNewMesh = true;
}
}
void LateUpdate () {
if (frameskipMeshUpdate && !requiresNewMesh) return;
skeletonAnimation.LateUpdate();
requiresNewMesh = false;
}
}
}
| 41.515464 | 288 | 0.705488 | [
"MIT"
] | duckbossa/unity-mecanim-spine | spine-mecanim/Assets/Spine Examples/Scripts/Sample Components/SkeletonAnimationFixedTimestep.cs | 4,027 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Sero.Mapper.Tests
{
internal class DestModel
{
public int IdSrc { get; set; }
public string NameSrc { get; set; }
public string DescriptionSrc { get; set; }
public DestModel() { }
public DestModel(int id, string name, string description)
{
IdSrc = id;
NameSrc = name;
DescriptionSrc = description;
}
}
}
| 22.181818 | 65 | 0.579918 | [
"MIT"
] | Agnael/Sero.Mapper | Sero.Mapper.UnitTests/TestInfrastructure/Models/DestModel.cs | 490 | C# |
namespace OctoTorrent.Client.Messages.Standard
{
using System.Text;
public class RequestMessage : PeerMessage
{
private const int MessageLength = 13;
internal const int MaxSize = 65536 + 64;
internal const int MinSize = 4096;
internal const byte MessageId = 6;
#region Public Properties
public override int ByteLength
{
get { return MessageLength + 4; }
}
public int StartOffset { get; private set; }
public int PieceIndex { get; private set; }
public int RequestLength { get; private set; }
#endregion
#region Constructors
public RequestMessage()
{
}
public RequestMessage(int pieceIndex, int startOffset, int requestLength)
{
PieceIndex = pieceIndex;
StartOffset = startOffset;
RequestLength = requestLength;
}
#endregion
#region Methods
public override void Decode(byte[] buffer, int offset, int length)
{
PieceIndex = ReadInt(buffer, ref offset);
StartOffset = ReadInt(buffer, ref offset);
RequestLength = ReadInt(buffer, ref offset);
}
public override int Encode(byte[] buffer, int offset)
{
var written = offset;
written += Write(buffer, written, MessageLength);
written += Write(buffer, written, MessageId);
written += Write(buffer, written, PieceIndex);
written += Write(buffer, written, StartOffset);
written += Write(buffer, written, RequestLength);
return CheckWritten(written - offset);
}
public override bool Equals(object obj)
{
var requestMessage = obj as RequestMessage;
return requestMessage != null &&
PieceIndex == requestMessage.PieceIndex &&
StartOffset == requestMessage.StartOffset &&
RequestLength == requestMessage.RequestLength;
}
public override int GetHashCode()
{
return PieceIndex.GetHashCode() ^ RequestLength.GetHashCode() ^ StartOffset.GetHashCode();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("RequestMessage ");
sb.Append(" Index ");
sb.Append(PieceIndex);
sb.Append(" Offset ");
sb.Append(StartOffset);
sb.Append(" Length ");
sb.Append(RequestLength);
return sb.ToString();
}
#endregion
}
} | 27.760417 | 102 | 0.562852 | [
"BSD-3-Clause"
] | bietiekay/sonos-podcast-service | Libraries/OctoTorrent/OctoTorrent/Client/Messages/StandardMessages/RequestMessage.cs | 2,665 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal abstract partial class SymbolKey
{
private class TypeParameterSymbolKey : AbstractSymbolKey<TypeParameterSymbolKey>
{
private readonly SymbolKey _containerKey;
private readonly string _metadataName;
public TypeParameterSymbolKey(ITypeParameterSymbol symbol, Visitor visitor)
{
_containerKey = GetOrCreate(symbol.ContainingSymbol, visitor);
_metadataName = symbol.MetadataName;
}
public override SymbolKeyResolution Resolve(Compilation compilation, bool ignoreAssemblyKey, CancellationToken cancellationToken)
{
var container = _containerKey.Resolve(compilation, ignoreAssemblyKey, cancellationToken);
var typeParameters = GetAllSymbols<INamedTypeSymbol>(container).SelectMany(s => Resolve(compilation, s));
return CreateSymbolInfo(typeParameters);
}
private IEnumerable<ITypeParameterSymbol> Resolve(Compilation compilation, INamedTypeSymbol container)
{
return container.TypeParameters.Where(t => Equals(compilation, t.MetadataName, _metadataName));
}
internal override bool Equals(TypeParameterSymbolKey other, ComparisonOptions options)
{
return
Equals(options.IgnoreCase, other._metadataName, _metadataName) &&
other._containerKey.Equals(_containerKey, options);
}
internal override int GetHashCode(ComparisonOptions options)
{
return Hash.Combine(
GetHashCode(options.IgnoreCase, _metadataName),
_containerKey.GetHashCode(options));
}
}
}
}
| 40.698113 | 161 | 0.658785 | [
"Apache-2.0"
] | 0x53A/roslyn | src/Workspaces/Core/Portable/SymbolId/SymbolKey.TypeParameterSymbolKey.cs | 2,159 | C# |
using Expressway.Contracts.Repository;
using Expressway.Database.Context;
using Expressway.Infrastructure.GenericRepository;
using Expressway.Model.Domain;
using Expressway.Utility.Enums;
using System;
using System.Collections.Generic;
using System.Text;
namespace Expressway.Repository.Core
{
public class UserRepository : GenericRepository<User>, IUserRepository
{
public UserRepository(ExpresswayContext context) : base(context)
{
}
public ExpresswayContext TenantDbContext => context as ExpresswayContext;
}
}
| 26.714286 | 81 | 0.768271 | [
"MIT"
] | gambheera/expressway | Expressway.Repository/Core/UserRepository.cs | 563 | C# |
using System.Linq;
using Autofac;
using JoinRpg.Common.EmailSending.Impl;
using JoinRpg.Dal.Impl;
using JoinRpg.Services.Email;
using JoinRpg.Services.Export;
using JoinRpg.Services.Impl;
using JoinRpg.Services.Interfaces;
using JoinRpg.Services.Interfaces.Email;
using JoinRpg.Services.Interfaces.Notification;
namespace JoinRpg.DI
{
public class JoinrpgMainModule : Module
{
protected override void Load(ContainerBuilder builder)
{
_ = builder.RegisterTypes(RepositoriesRegistraton.GetTypes().ToArray()).AsImplementedInterfaces();
_ = builder.RegisterTypes(Services.Impl.Services.GetTypes().ToArray()).AsImplementedInterfaces().AsSelf();
_ = builder.RegisterTypes(WebPortal.Managers.Registration.GetTypes().ToArray()).AsSelf().AsImplementedInterfaces();
_ = builder.RegisterType<ExportDataServiceImpl>().As<IExportDataService>();
_ = builder.RegisterType<EmailServiceImpl>().As<IEmailService>();
_ = builder.RegisterType<EmailSendingServiceImpl>().As<IEmailSendingService>();
_ = builder.RegisterType<MyDbContext>()
.AsSelf()
.AsImplementedInterfaces()
.InstancePerDependency()
.UsingConstructor(typeof(IJoinDbContextConfiguration));
_ = builder.RegisterType<VirtualUsersService>().As<IVirtualUsersService>().SingleInstance();
_ = builder.RegisterType<PaymentsService>().As<IPaymentsService>();
base.Load(builder);
}
}
}
| 38.725 | 127 | 0.692705 | [
"MIT"
] | andy-krivtsov/joinrpg-net | src/JoinRpg.DI/JoinrpgMainModule.cs | 1,549 | C# |
using System.Web;
using System.Web.Mvc;
namespace ASPNET.Plugin.Master
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | 20.923077 | 80 | 0.661765 | [
"MIT"
] | Oobert/ASP.NET-MVC-Plugins | ASPNET.Plugin.Master/App_Start/FilterConfig.cs | 274 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.