content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Edit_Retroalimentacion : System.Web.UI.Page
{
private int identificador;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
identificador = Convert.ToInt32(Request.QueryString["id"]);
SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True");
conexion.Open();
SqlCommand cmd = new SqlCommand("SELECT codso, Software.nombre FROM Retroalimentacion "+
"INNER JOIN Software ON "+
"Software.id_software = Retroalimentacion.codso where id_retroalimentacion=" + identificador + "", conexion);
SqlDataReader registro = cmd.ExecuteReader();
if (registro.Read())
{
software_id.Text =Convert.ToString(registro.GetInt32(0));
nombre.Text = registro.GetString(1);
BindData();
RellenarCampos();
}
}
}
private void BindData()
{
SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True");
SqlDataAdapter adaptador = new SqlDataAdapter("SELECT Metricas.id_metricas, Metricas.Nombre FROM Retroalimentacion " +
"INNER JOIN Retro_metricas ON "+
"Retro_metricas.idrealim = Retroalimentacion.id_retroalimentacion "+
"INNER JOIN Metricas ON "+
"Metricas.id_metricas = Retro_metricas.idmetca where id_retroalimentacion=" + identificador + "", conexion);
DataTable dt = new DataTable();
adaptador.Fill(dt);
lv.DataSource = dt;
lv.DataBind();
conexion.Close();
}
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument.ToString());
id--;
if (e.CommandName.ToString() == "imgedit1")
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (e.CommandName.ToString() == "imgedit2")
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (e.CommandName.ToString() == "imgedit3")
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (e.CommandName.ToString() == "imgedit4")
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (e.CommandName.ToString() == "imgedit5")
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-fill-lg.png";
}
}
protected void save_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if(DeleteCustomer() == true)
{
String usuario = Request.Cookies["UserSettings"]["user"];
String ventaja = Ventaja.Text;
String desventaja = Desventaja.Text;
String comentario = Comentario.Text;
int frecuencia = Convert.ToInt32(Frecuencia.SelectedValue);
int software = Convert.ToInt32(software_id.Text);
//----------------------------------------------------------------------Conexion a Base de Datos--------------------------------------------------------------------
SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True;Integrated Security=True;MultipleActiveResultSets=True");
conexion.Open();
int id = 0;
String fecha = DateTime.Now.ToShortDateString();
//------------------------------------------------------------------------Guardar en Retroalimentacion--------------------------------------------------------------------
SqlCommand insert = new SqlCommand("INSERT INTO Retroalimentacion(Ventaja,Desventaja,Comentario,codusuario,fecha,codfrecuencia,codso) VALUES('" + ventaja + "','" + desventaja + "','" + comentario + "','" + usuario + "','" + fecha + "'," + frecuencia + "," + software + ");", conexion);
try
{
//----------------------------------------------------------Verificar Ultimo Guardado------------------------------------------------------
insert.ExecuteNonQuery();
SqlCommand cantidad = new SqlCommand("Select count(*) From Retroalimentacion", conexion);
SqlCommand cmd = new SqlCommand("Select MAX(id_retroalimentacion) from Retroalimentacion", conexion);
int result = Convert.ToInt32(cantidad.ExecuteScalar());
if (result > 0)
{
id = Convert.ToInt32(cmd.ExecuteScalar());
}
//--------------------------------------------------------------------GUARDAR EN INTERMEDIA RETRO-METRICA------------------------------------------------------------------
for (int i = 0; i < lv.Items.Count; i++)
{
ImageButton imgedit1 = (ImageButton)lv.Items[i].FindControl("imgedit1");
ImageButton imgedit2 = (ImageButton)lv.Items[i].FindControl("imgedit2");
ImageButton imgedit3 = (ImageButton)lv.Items[i].FindControl("imgedit3");
ImageButton imgedit4 = (ImageButton)lv.Items[i].FindControl("imgedit4");
ImageButton imgedit5 = (ImageButton)lv.Items[i].FindControl("imgedit5");
Label categoria = (Label)lv.Items[i].FindControl("Label1");
SqlCommand categoriab = new SqlCommand("Select * from Metricas where Nombre='" + categoria.Text + "'", conexion); //Buscamos la Metrica
SqlDataReader registro_busqueda = categoriab.ExecuteReader();
while (registro_busqueda.Read())
{
int puntaje = 0;
if (imgedit5.ImageUrl == "imagenes/star-fill-lg.png")
{
puntaje = 5;
}
else if (imgedit4.ImageUrl == "imagenes/star-fill-lg.png")
{
puntaje = 4;
}
else if (imgedit3.ImageUrl == "imagenes/star-fill-lg.png")
{
puntaje = 3;
}
else if (imgedit2.ImageUrl == "imagenes/star-fill-lg.png")
{
puntaje = 2;
}
else if (imgedit1.ImageUrl == "imagenes/star-fill-lg.png")
{
puntaje = 1;
}
int idcategoria = registro_busqueda.GetInt32(0);
SqlCommand insert_categoria = new SqlCommand("INSERT INTO Retro_metricas(puntaje,idrealim,idmetca) VALUES(" + puntaje + "," + id + "," + idcategoria + ");", conexion);
try
{
insert_categoria.ExecuteNonQuery();
}
catch (SqlException ee)
{
string script2 = "alert(\"Error Al guardar 2\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script2, true);
}
}
}
}
catch (SqlException ee)
{
string script2 = "alert(\"Error Al guardar\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script2, true);
}
Ventaja.Text = "";
Desventaja.Text = "";
Comentario.Text = "";
}
}
}
private Boolean DeleteCustomer()
{
int id = Convert.ToInt32(Request.QueryString["id"]);
String sql1 = "delete from Retro_metricas where idrealim="+id;
String sql2= "delete from Retroalimentacion where id_retroalimentacion=" + id;
SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True;MultipleActiveResultSets=True");
conexion.Open();
SqlCommand cmds = new SqlCommand (sql1, conexion);
SqlCommand cmds2 = new SqlCommand(sql2, conexion);
try
{
if (cmds.ExecuteNonQuery() > 0 && cmds2.ExecuteNonQuery() > 0)
{
return true;
}
else
{
return false;
}
}
catch (SqlException ee)
{
conexion.Close();
return false;
}
}
//----------------------------------------------------------Mostrar Datos Guardados---------------------------------------------------
private void RellenarCampos()
{
//-----------------------------------------Estrellas--------------------------------------------------------------------------------
int retro_int = Convert.ToInt32(Request.QueryString["id"]);
int id = 0;
SqlConnection conexion = new SqlConnection("Data Source=LAPTOP-2V9EL9OT\\SQLEXPRESS;Initial Catalog=Fase2;Integrated Security=True;MultipleActiveResultSets=True");
conexion.Open();
SqlCommand cmd = new SqlCommand("SELECT Retro_metricas.puntaje FROM Retroalimentacion " +
"INNER JOIN Retro_metricas ON " +
"Retro_metricas.idrealim = Retroalimentacion.id_retroalimentacion " +
"INNER JOIN Metricas ON " +
"Metricas.id_metricas = Retro_metricas.idmetca where id_retroalimentacion=" + retro_int + "", conexion);
SqlDataReader registro = cmd.ExecuteReader();
while (registro.Read())
{
int puntuaje = registro.GetInt32(0);
if (puntuaje == 1)
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (puntuaje == 2)
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (puntuaje == 3)
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-empty-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (puntuaje == 4)
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-empty-lg.png";
}
if (puntuaje == 5)
{
ImageButton imgedit1 = (ImageButton)lv.Items[id].FindControl("imgedit1");
imgedit1.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit2 = (ImageButton)lv.Items[id].FindControl("imgedit2");
imgedit2.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit3 = (ImageButton)lv.Items[id].FindControl("imgedit3");
imgedit3.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit4 = (ImageButton)lv.Items[id].FindControl("imgedit4");
imgedit4.ImageUrl = "imagenes/star-fill-lg.png";
ImageButton imgedit5 = (ImageButton)lv.Items[id].FindControl("imgedit5");
imgedit5.ImageUrl = "imagenes/star-fill-lg.png";
}
id++;
}
//-----------------------------------------------------------Resto de Comentarios-----------------------------------------------------------------
SqlCommand cmd2 = new SqlCommand("SELECT * FROM Retroalimentacion where id_retroalimentacion=" + retro_int + ";", conexion);
SqlDataReader registro2 = cmd2.ExecuteReader();
if (registro2.Read())
{
Frecuencia.SelectedIndex = registro2.GetInt32(6);
Comentario.Text = registro2.GetString(3);
Ventaja.Text = registro2.GetString(1);
Desventaja.Text = registro2.GetString(2);
}
}
} | 55.585507 | 301 | 0.528863 | [
"MIT"
] | wolfghost9898/Proyectos | IPC2/IPC FASE II/Edit_Retroalimentacion.aspx.cs | 19,179 | C# |
using System;
namespace Etimo.Cli
{
public class OptionNameAttribute : Attribute
{
public string Name { get; }
public OptionNameAttribute(string name)
{
Name = name.ToLowerInvariant();
}
}
}
| 16.6 | 48 | 0.582329 | [
"MIT"
] | Etimo/etimo-cli | Etimo.Cli/Attributes/OptionNameAttribute.cs | 249 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("CoreWbAPi")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("CoreWbAPi")]
[assembly: System.Reflection.AssemblyTitleAttribute("CoreWbAPi")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.708333 | 80 | 0.645855 | [
"Apache-2.0"
] | nsxr51/CoreWebApi | CoreWbAPi/CoreWbAPi/obj/Debug/netcoreapp2.0/CoreWbAPi.AssemblyInfo.cs | 977 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// <para>
/// Represents a reader that provides <see cref="JsonSchema"/> validation.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public class JsonValidatingReader : JsonReader, IJsonLineInfo
{
private class SchemaScope
{
private readonly JTokenType _tokenType;
private readonly IList<JsonSchemaModel> _schemas;
private readonly Dictionary<string, bool> _requiredProperties;
public string CurrentPropertyName { get; set; }
public int ArrayItemCount { get; set; }
public bool IsUniqueArray { get; set; }
public IList<JToken> UniqueArrayItems { get; set; }
public JTokenWriter CurrentItemWriter { get; set; }
public IList<JsonSchemaModel> Schemas
{
get { return _schemas; }
}
public Dictionary<string, bool> RequiredProperties
{
get { return _requiredProperties; }
}
public JTokenType TokenType
{
get { return _tokenType; }
}
public SchemaScope(JTokenType tokenType, IList<JsonSchemaModel> schemas)
{
_tokenType = tokenType;
_schemas = schemas;
_requiredProperties = schemas.SelectMany<JsonSchemaModel, string>(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false);
if (tokenType == JTokenType.Array && schemas.Any(s => s.UniqueItems))
{
IsUniqueArray = true;
UniqueArrayItems = new List<JToken>();
}
}
private IEnumerable<string> GetRequiredProperties(JsonSchemaModel schema)
{
if (schema == null || schema.Properties == null)
return Enumerable.Empty<string>();
return schema.Properties.Where(p => p.Value.Required).Select(p => p.Key);
}
}
private readonly JsonReader _reader;
private readonly Stack<SchemaScope> _stack;
private JsonSchema _schema;
private JsonSchemaModel _model;
private SchemaScope _currentScope;
/// <summary>
/// Sets an event handler for receiving schema validation errors.
/// </summary>
public event ValidationEventHandler ValidationEventHandler;
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
/// <value></value>
public override object Value
{
get { return _reader.Value; }
}
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public override int Depth
{
get { return _reader.Depth; }
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public override string Path
{
get { return _reader.Path; }
}
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
/// <value></value>
public override char QuoteChar
{
get { return _reader.QuoteChar; }
protected internal set { }
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
/// <value></value>
public override JsonToken TokenType
{
get { return _reader.TokenType; }
}
/// <summary>
/// Gets the Common Language Runtime (CLR) type for the current JSON token.
/// </summary>
/// <value></value>
public override Type ValueType
{
get { return _reader.ValueType; }
}
private void Push(SchemaScope scope)
{
_stack.Push(scope);
_currentScope = scope;
}
private SchemaScope Pop()
{
SchemaScope poppedScope = _stack.Pop();
_currentScope = (_stack.Count != 0)
? _stack.Peek()
: null;
return poppedScope;
}
private IList<JsonSchemaModel> CurrentSchemas
{
get { return _currentScope.Schemas; }
}
private static readonly IList<JsonSchemaModel> EmptySchemaList = new List<JsonSchemaModel>();
private IList<JsonSchemaModel> CurrentMemberSchemas
{
get
{
if (_currentScope == null)
return new List<JsonSchemaModel>(new[] { _model });
if (_currentScope.Schemas == null || _currentScope.Schemas.Count == 0)
return EmptySchemaList;
switch (_currentScope.TokenType)
{
case JTokenType.None:
return _currentScope.Schemas;
case JTokenType.Object:
{
if (_currentScope.CurrentPropertyName == null)
throw new JsonReaderException("CurrentPropertyName has not been set on scope.");
IList<JsonSchemaModel> schemas = new List<JsonSchemaModel>();
foreach (JsonSchemaModel schema in CurrentSchemas)
{
JsonSchemaModel propertySchema;
if (schema.Properties != null && schema.Properties.TryGetValue(_currentScope.CurrentPropertyName, out propertySchema))
{
schemas.Add(propertySchema);
}
if (schema.PatternProperties != null)
{
foreach (KeyValuePair<string, JsonSchemaModel> patternProperty in schema.PatternProperties)
{
if (Regex.IsMatch(_currentScope.CurrentPropertyName, patternProperty.Key))
{
schemas.Add(patternProperty.Value);
}
}
}
if (schemas.Count == 0 && schema.AllowAdditionalProperties && schema.AdditionalProperties != null)
schemas.Add(schema.AdditionalProperties);
}
return schemas;
}
case JTokenType.Array:
{
IList<JsonSchemaModel> schemas = new List<JsonSchemaModel>();
foreach (JsonSchemaModel schema in CurrentSchemas)
{
if (!schema.PositionalItemsValidation)
{
if (schema.Items != null && schema.Items.Count > 0)
schemas.Add(schema.Items[0]);
}
else
{
if (schema.Items != null && schema.Items.Count > 0)
{
if (schema.Items.Count > (_currentScope.ArrayItemCount - 1))
schemas.Add(schema.Items[_currentScope.ArrayItemCount - 1]);
}
if (schema.AllowAdditionalItems && schema.AdditionalItems != null)
schemas.Add(schema.AdditionalItems);
}
}
return schemas;
}
case JTokenType.Constructor:
return EmptySchemaList;
default:
throw new ArgumentOutOfRangeException("TokenType", "Unexpected token type: {0}".FormatWith(CultureInfo.InvariantCulture, _currentScope.TokenType));
}
}
}
private void RaiseError(string message, JsonSchemaModel schema)
{
IJsonLineInfo lineInfo = this;
string exceptionMessage = (lineInfo.HasLineInfo())
? message + " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition)
: message;
OnValidationEvent(new JsonSchemaException(exceptionMessage, null, Path, lineInfo.LineNumber, lineInfo.LinePosition));
}
private void OnValidationEvent(JsonSchemaException exception)
{
ValidationEventHandler handler = ValidationEventHandler;
if (handler != null)
handler(this, new ValidationEventArgs(exception));
else
throw exception;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonValidatingReader"/> class that
/// validates the content returned from the given <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from while validating.</param>
public JsonValidatingReader(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
_reader = reader;
_stack = new Stack<SchemaScope>();
}
/// <summary>
/// Gets or sets the schema.
/// </summary>
/// <value>The schema.</value>
public JsonSchema Schema
{
get { return _schema; }
set
{
if (TokenType != JsonToken.None)
throw new InvalidOperationException("Cannot change schema while validating JSON.");
_schema = value;
_model = null;
}
}
/// <summary>
/// Gets the <see cref="JsonReader"/> used to construct this <see cref="JsonValidatingReader"/>.
/// </summary>
/// <value>The <see cref="JsonReader"/> specified in the constructor.</value>
public JsonReader Reader
{
get { return _reader; }
}
private void ValidateNotDisallowed(JsonSchemaModel schema)
{
if (schema == null)
return;
JsonSchemaType? currentNodeType = GetCurrentNodeSchemaType();
if (currentNodeType != null)
{
if (JsonSchemaGenerator.HasFlag(schema.Disallow, currentNodeType.Value))
RaiseError("Type {0} is disallowed.".FormatWith(CultureInfo.InvariantCulture, currentNodeType), schema);
}
}
private JsonSchemaType? GetCurrentNodeSchemaType()
{
switch (_reader.TokenType)
{
case JsonToken.StartObject:
return JsonSchemaType.Object;
case JsonToken.StartArray:
return JsonSchemaType.Array;
case JsonToken.Integer:
return JsonSchemaType.Integer;
case JsonToken.Float:
return JsonSchemaType.Float;
case JsonToken.String:
return JsonSchemaType.String;
case JsonToken.Boolean:
return JsonSchemaType.Boolean;
case JsonToken.Null:
return JsonSchemaType.Null;
default:
return null;
}
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>.</returns>
public override int? ReadAsInt32()
{
int? i = _reader.ReadAsInt32();
ValidateCurrentToken();
return i;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Byte"/>[].
/// </summary>
/// <returns>
/// A <see cref="Byte"/>[] or a null reference if the next JSON token is null.
/// </returns>
public override byte[] ReadAsBytes()
{
byte[] data = _reader.ReadAsBytes();
ValidateCurrentToken();
return data;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>.</returns>
public override decimal? ReadAsDecimal()
{
decimal? d = _reader.ReadAsDecimal();
ValidateCurrentToken();
return d;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override string ReadAsString()
{
string s = _reader.ReadAsString();
ValidateCurrentToken();
return s;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTime? ReadAsDateTime()
{
DateTime? dateTime = _reader.ReadAsDateTime();
ValidateCurrentToken();
return dateTime;
}
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>.</returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
DateTimeOffset? dateTimeOffset = _reader.ReadAsDateTimeOffset();
ValidateCurrentToken();
return dateTimeOffset;
}
#endif
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
if (!_reader.Read())
return false;
if (_reader.TokenType == JsonToken.Comment)
return true;
ValidateCurrentToken();
return true;
}
private void ValidateCurrentToken()
{
// first time validate has been called. build model
if (_model == null)
{
JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder();
_model = builder.Build(_schema);
if (!JsonTokenUtils.IsStartToken(_reader.TokenType))
Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas));
}
switch (_reader.TokenType)
{
case JsonToken.StartObject:
ProcessValue();
IList<JsonSchemaModel> objectSchemas = CurrentMemberSchemas.Where(ValidateObject).ToList();
Push(new SchemaScope(JTokenType.Object, objectSchemas));
WriteToken(CurrentSchemas);
break;
case JsonToken.StartArray:
ProcessValue();
IList<JsonSchemaModel> arraySchemas = CurrentMemberSchemas.Where(ValidateArray).ToList();
Push(new SchemaScope(JTokenType.Array, arraySchemas));
WriteToken(CurrentSchemas);
break;
case JsonToken.StartConstructor:
ProcessValue();
Push(new SchemaScope(JTokenType.Constructor, null));
WriteToken(CurrentSchemas);
break;
case JsonToken.PropertyName:
WriteToken(CurrentSchemas);
foreach (JsonSchemaModel schema in CurrentSchemas)
{
ValidatePropertyName(schema);
}
break;
case JsonToken.Raw:
ProcessValue();
break;
case JsonToken.Integer:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateInteger(schema);
}
break;
case JsonToken.Float:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateFloat(schema);
}
break;
case JsonToken.String:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateString(schema);
}
break;
case JsonToken.Boolean:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateBoolean(schema);
}
break;
case JsonToken.Null:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateNull(schema);
}
break;
case JsonToken.EndObject:
WriteToken(CurrentSchemas);
foreach (JsonSchemaModel schema in CurrentSchemas)
{
ValidateEndObject(schema);
}
Pop();
break;
case JsonToken.EndArray:
WriteToken(CurrentSchemas);
foreach (JsonSchemaModel schema in CurrentSchemas)
{
ValidateEndArray(schema);
}
Pop();
break;
case JsonToken.EndConstructor:
WriteToken(CurrentSchemas);
Pop();
break;
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
// these have no equivalent in JSON schema
WriteToken(CurrentMemberSchemas);
break;
case JsonToken.None:
// no content, do nothing
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void WriteToken(IList<JsonSchemaModel> schemas)
{
foreach (SchemaScope schemaScope in _stack)
{
bool isInUniqueArray = (schemaScope.TokenType == JTokenType.Array && schemaScope.IsUniqueArray && schemaScope.ArrayItemCount > 0);
if (isInUniqueArray || schemas.Any(s => s.Enum != null))
{
if (schemaScope.CurrentItemWriter == null)
{
if (JsonTokenUtils.IsEndToken(_reader.TokenType))
continue;
schemaScope.CurrentItemWriter = new JTokenWriter();
}
schemaScope.CurrentItemWriter.WriteToken(_reader, false);
// finished writing current item
if (schemaScope.CurrentItemWriter.Top == 0 && _reader.TokenType != JsonToken.PropertyName)
{
JToken finishedItem = schemaScope.CurrentItemWriter.Token;
// start next item with new writer
schemaScope.CurrentItemWriter = null;
if (isInUniqueArray)
{
if (schemaScope.UniqueArrayItems.Contains(finishedItem, JToken.EqualityComparer))
RaiseError("Non-unique array item at index {0}.".FormatWith(CultureInfo.InvariantCulture, schemaScope.ArrayItemCount - 1), schemaScope.Schemas.First(s => s.UniqueItems));
schemaScope.UniqueArrayItems.Add(finishedItem);
}
else if (schemas.Any(s => s.Enum != null))
{
foreach (JsonSchemaModel schema in schemas)
{
if (schema.Enum != null)
{
if (!schema.Enum.ContainsValue(finishedItem, JToken.EqualityComparer))
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
finishedItem.WriteTo(new JsonTextWriter(sw));
RaiseError("Value {0} is not defined in enum.".FormatWith(CultureInfo.InvariantCulture, sw.ToString()), schema);
}
}
}
}
}
}
}
}
private void ValidateEndObject(JsonSchemaModel schema)
{
if (schema == null)
return;
Dictionary<string, bool> requiredProperties = _currentScope.RequiredProperties;
if (requiredProperties != null)
{
List<string> unmatchedRequiredProperties =
requiredProperties.Where(kv => !kv.Value).Select(kv => kv.Key).ToList();
if (unmatchedRequiredProperties.Count > 0)
RaiseError("Required properties are missing from object: {0}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", unmatchedRequiredProperties.ToArray())), schema);
}
}
private void ValidateEndArray(JsonSchemaModel schema)
{
if (schema == null)
return;
int arrayItemCount = _currentScope.ArrayItemCount;
if (schema.MaximumItems != null && arrayItemCount > schema.MaximumItems)
RaiseError("Array item count {0} exceeds maximum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MaximumItems), schema);
if (schema.MinimumItems != null && arrayItemCount < schema.MinimumItems)
RaiseError("Array item count {0} is less than minimum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MinimumItems), schema);
}
private void ValidateNull(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Null))
return;
ValidateNotDisallowed(schema);
}
private void ValidateBoolean(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Boolean))
return;
ValidateNotDisallowed(schema);
}
private void ValidateString(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.String))
return;
ValidateNotDisallowed(schema);
string value = _reader.Value.ToString();
if (schema.MaximumLength != null && value.Length > schema.MaximumLength)
RaiseError("String '{0}' exceeds maximum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MaximumLength), schema);
if (schema.MinimumLength != null && value.Length < schema.MinimumLength)
RaiseError("String '{0}' is less than minimum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MinimumLength), schema);
if (schema.Patterns != null)
{
foreach (string pattern in schema.Patterns)
{
if (!Regex.IsMatch(value, pattern))
RaiseError("String '{0}' does not match regex pattern '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, pattern), schema);
}
}
}
private void ValidateInteger(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Integer))
return;
ValidateNotDisallowed(schema);
object value = _reader.Value;
if (schema.Maximum != null)
{
if (JValue.Compare(JTokenType.Integer, value, schema.Maximum) > 0)
RaiseError("Integer {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema);
if (schema.ExclusiveMaximum && JValue.Compare(JTokenType.Integer, value, schema.Maximum) == 0)
RaiseError("Integer {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema);
}
if (schema.Minimum != null)
{
if (JValue.Compare(JTokenType.Integer, value, schema.Minimum) < 0)
RaiseError("Integer {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema);
if (schema.ExclusiveMinimum && JValue.Compare(JTokenType.Integer, value, schema.Minimum) == 0)
RaiseError("Integer {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema);
}
if (schema.DivisibleBy != null)
{
bool notDivisible;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
if (value is BigInteger)
{
// not that this will lose any decimal point on DivisibleBy
// so manually raise an error if DivisibleBy is not an integer and value is not zero
BigInteger i = (BigInteger)value;
bool divisibleNonInteger = !Math.Abs(schema.DivisibleBy.Value - Math.Truncate(schema.DivisibleBy.Value)).Equals(0);
if (divisibleNonInteger)
notDivisible = i != 0;
else
notDivisible = i % new BigInteger(schema.DivisibleBy.Value) != 0;
}
else
#endif
notDivisible = !IsZero(Convert.ToInt64(value, CultureInfo.InvariantCulture) % schema.DivisibleBy.Value);
if (notDivisible)
RaiseError("Integer {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema);
}
}
private void ProcessValue()
{
if (_currentScope != null && _currentScope.TokenType == JTokenType.Array)
{
_currentScope.ArrayItemCount++;
foreach (JsonSchemaModel currentSchema in CurrentSchemas)
{
// if there is positional validation and the array index is past the number of item validation schemas and there is no additonal items then error
if (currentSchema != null
&& currentSchema.PositionalItemsValidation
&& !currentSchema.AllowAdditionalItems
&& (currentSchema.Items == null || _currentScope.ArrayItemCount - 1 >= currentSchema.Items.Count))
{
RaiseError("Index {0} has not been defined and the schema does not allow additional items.".FormatWith(CultureInfo.InvariantCulture, _currentScope.ArrayItemCount), currentSchema);
}
}
}
}
private void ValidateFloat(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Float))
return;
ValidateNotDisallowed(schema);
double value = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
if (schema.Maximum != null)
{
if (value > schema.Maximum)
RaiseError("Float {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema);
if (schema.ExclusiveMaximum && value == schema.Maximum)
RaiseError("Float {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema);
}
if (schema.Minimum != null)
{
if (value < schema.Minimum)
RaiseError("Float {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema);
if (schema.ExclusiveMinimum && value == schema.Minimum)
RaiseError("Float {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema);
}
if (schema.DivisibleBy != null)
{
double remainder = FloatingPointRemainder(value, schema.DivisibleBy.Value);
if (!IsZero(remainder))
RaiseError("Float {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema);
}
}
private static double FloatingPointRemainder(double dividend, double divisor)
{
return dividend - Math.Floor(dividend / divisor) * divisor;
}
private static bool IsZero(double value)
{
const double epsilon = 2.2204460492503131e-016;
return Math.Abs(value) < 20.0 * epsilon;
}
private void ValidatePropertyName(JsonSchemaModel schema)
{
if (schema == null)
return;
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
if (_currentScope.RequiredProperties.ContainsKey(propertyName))
_currentScope.RequiredProperties[propertyName] = true;
if (!schema.AllowAdditionalProperties)
{
bool propertyDefinied = IsPropertyDefinied(schema, propertyName);
if (!propertyDefinied)
RaiseError("Property '{0}' has not been defined and the schema does not allow additional properties.".FormatWith(CultureInfo.InvariantCulture, propertyName), schema);
}
_currentScope.CurrentPropertyName = propertyName;
}
private bool IsPropertyDefinied(JsonSchemaModel schema, string propertyName)
{
if (schema.Properties != null && schema.Properties.ContainsKey(propertyName))
return true;
if (schema.PatternProperties != null)
{
foreach (string pattern in schema.PatternProperties.Keys)
{
if (Regex.IsMatch(propertyName, pattern))
return true;
}
}
return false;
}
private bool ValidateArray(JsonSchemaModel schema)
{
if (schema == null)
return true;
return (TestType(schema, JsonSchemaType.Array));
}
private bool ValidateObject(JsonSchemaModel schema)
{
if (schema == null)
return true;
return (TestType(schema, JsonSchemaType.Object));
}
private bool TestType(JsonSchemaModel currentSchema, JsonSchemaType currentType)
{
if (!JsonSchemaGenerator.HasFlag(currentSchema.Type, currentType))
{
RaiseError("Invalid type. Expected {0} but got {1}.".FormatWith(CultureInfo.InvariantCulture, currentSchema.Type, currentType), currentSchema);
return false;
}
return true;
}
bool IJsonLineInfo.HasLineInfo()
{
IJsonLineInfo lineInfo = _reader as IJsonLineInfo;
return lineInfo != null && lineInfo.HasLineInfo();
}
int IJsonLineInfo.LineNumber
{
get
{
IJsonLineInfo lineInfo = _reader as IJsonLineInfo;
return (lineInfo != null) ? lineInfo.LineNumber : 0;
}
}
int IJsonLineInfo.LinePosition
{
get
{
IJsonLineInfo lineInfo = _reader as IJsonLineInfo;
return (lineInfo != null) ? lineInfo.LinePosition : 0;
}
}
}
} | 40.044517 | 204 | 0.519482 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | nerai/Nibbler | src/lib/Newtonsoft.Json/JsonValidatingReader.cs | 36,883 | C# |
// <auto-generated />
namespace CarSystem.Data.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class Initial : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(Initial));
string IMigrationMetadata.Id
{
get { return "201703140329083_Initial"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 26.9 | 90 | 0.614622 | [
"MIT"
] | Azonic89/My-ASP.NET-MVC-Project | CarSystem/Data/CarSystem.Data/Migrations/201703140329083_Initial.Designer.cs | 807 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.NAS.Model.V20170626;
namespace Aliyun.Acs.NAS.Transform.V20170626
{
public class CreateRecycleBinRestoreJobResponseUnmarshaller
{
public static CreateRecycleBinRestoreJobResponse Unmarshall(UnmarshallerContext _ctx)
{
CreateRecycleBinRestoreJobResponse createRecycleBinRestoreJobResponse = new CreateRecycleBinRestoreJobResponse();
createRecycleBinRestoreJobResponse.HttpResponse = _ctx.HttpResponse;
createRecycleBinRestoreJobResponse.RequestId = _ctx.StringValue("CreateRecycleBinRestoreJob.RequestId");
createRecycleBinRestoreJobResponse.JobId = _ctx.StringValue("CreateRecycleBinRestoreJob.JobId");
return createRecycleBinRestoreJobResponse;
}
}
}
| 39.707317 | 117 | 0.777027 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-nas/NAS/Transform/V20170626/CreateRecycleBinRestoreJobResponseUnmarshaller.cs | 1,628 | C# |
namespace JenkinsObserver.Test
{
public static class ConstJson
{
public const string NODEJS_SERVER_NORMAL =
#region Json
@"{
""assignedLabels"" : [
{
}
],
""mode"" : ""NORMAL"",
""nodeDescription"" : ""the master Jenkins node"",
""nodeName"" : """",
""numExecutors"" : 1,
""description"" : null,
""jobs"" : [
{
""name"" : ""libuv-julien"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/"",
""color"" : ""red""
},
{
""name"" : ""libuv-julien-windows"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/"",
""color"" : ""red""
},
{
""name"" : ""libuv-master"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/"",
""color"" : ""yellow""
}
],
""overallLoad"" : {
},
""primaryView"" : {
""name"" : ""All"",
""url"" : ""http://jenkins.nodejs.org/""
},
""quietingDown"" : false,
""slaveAgentPort"" : 0,
""unlabeledLoad"" : {
},
""useCrumbs"" : false,
""useSecurity"" : true,
""views"" : [
{
""name"" : ""All"",
""url"" : ""http://jenkins.nodejs.org/""
},
{
""name"" : ""libuv"",
""url"" : ""http://jenkins.nodejs.org/view/libuv/""
},
{
""name"" : ""node"",
""url"" : ""http://jenkins.nodejs.org/view/node/""
}
]
}";
#endregion Json
public const string NODEJS_JOB1_NORMAL =
#region Json
@"{
""actions"" : [
{
},
{
},
{
}
],
""description"" : """",
""displayName"" : ""libuv-julien"",
""displayNameOrNull"" : null,
""name"" : ""libuv-julien"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/"",
""buildable"" : true,
""builds"" : [
{
""number"" : 256,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/256/""
},
{
""number"" : 255,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/255/""
},
{
""number"" : 254,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/254/""
},
{
""number"" : 253,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/253/""
}
],
""color"" : ""red"",
""firstBuild"" : {
""number"" : 1,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/1/""
},
""healthReport"" : [
{
""description"" : ""Build stability: All recent builds failed."",
""iconClassName"" : ""icon-health-00to19"",
""iconUrl"" : ""health-00to19.png"",
""score"" : 0
},
{
""description"" : ""Test Result: 0 tests failing out of a total of 758 tests."",
""iconClassName"" : ""icon-health-80plus"",
""iconUrl"" : ""health-80plus.png"",
""score"" : 100
}
],
""inQueue"" : false,
""keepDependencies"" : false,
""lastBuild"" : {
""number"" : 256,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/256/""
},
""lastCompletedBuild"" : {
""number"" : 256,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/256/""
},
""lastFailedBuild"" : {
""number"" : 256,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/256/""
},
""lastStableBuild"" : null,
""lastSuccessfulBuild"" : {
""number"" : 75,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/75/""
},
""lastUnstableBuild"" : {
""number"" : 75,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/75/""
},
""lastUnsuccessfulBuild"" : {
""number"" : 256,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/256/""
},
""nextBuildNumber"" : 257,
""property"" : [
{
},
{
}
],
""queueItem"" : null,
""concurrentBuild"" : false,
""downstreamProjects"" : [
],
""scm"" : {
},
""upstreamProjects"" : [
],
""activeConfigurations"" : [
{
""name"" : ""label=osx"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/label=osx/"",
""color"" : ""blue""
},
{
""name"" : ""label=smartos"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/label=smartos/"",
""color"" : ""red""
},
{
""name"" : ""label=ubuntu-12.04"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/label=ubuntu-12.04/"",
""color"" : ""blue""
},
{
""name"" : ""label=ubuntu-14.04"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien/label=ubuntu-14.04/"",
""color"" : ""blue""
}
]
}";
#endregion Json
public const string NODEJS_JOB2_NORMAL =
#region Json
@"{
""actions"" : [
{
},
{
},
{
}
],
""description"" : """",
""displayName"" : ""libuv-julien-windows"",
""displayNameOrNull"" : null,
""name"" : ""libuv-julien-windows"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/"",
""buildable"" : true,
""builds"" : [
{
""number"" : 255,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/255/""
},
{
""number"" : 254,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/254/""
},
{
""number"" : 253,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/253/""
}
],
""color"" : ""red"",
""firstBuild"" : {
""number"" : 82,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/82/""
},
""healthReport"" : [
{
""description"" : ""Build stability: All recent builds failed."",
""iconClassName"" : ""icon-health-00to19"",
""iconUrl"" : ""health-00to19.png"",
""score"" : 0
},
{
""description"" : ""Test Result: 0 tests in total."",
""iconClassName"" : ""icon-health-80plus"",
""iconUrl"" : ""health-80plus.png"",
""score"" : 100
}
],
""inQueue"" : false,
""keepDependencies"" : false,
""lastBuild"" : {
""number"" : 255,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/255/""
},
""lastCompletedBuild"" : {
""number"" : 255,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/255/""
},
""lastFailedBuild"" : {
""number"" : 255,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/255/""
},
""lastStableBuild"" : {
""number"" : 82,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/82/""
},
""lastSuccessfulBuild"" : {
""number"" : 131,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/131/""
},
""lastUnstableBuild"" : {
""number"" : 131,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/131/""
},
""lastUnsuccessfulBuild"" : {
""number"" : 255,
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/255/""
},
""nextBuildNumber"" : 256,
""property"" : [
{
},
{
}
],
""queueItem"" : null,
""concurrentBuild"" : false,
""downstreamProjects"" : [
],
""scm"" : {
},
""upstreamProjects"" : [
],
""activeConfigurations"" : [
{
""name"" : ""DESTCPU=ia32,label=windows"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/DESTCPU=ia32,label=windows/"",
""color"" : ""red""
},
{
""name"" : ""DESTCPU=x64,label=windows"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-julien-windows/DESTCPU=x64,label=windows/"",
""color"" : ""red""
}
]
}";
#endregion Json
public const string NODEJS_JOB3_NORMAL =
#region Json
@"{
""actions"" : [
{
},
{
},
{
}
],
""description"" : """",
""displayName"" : ""libuv-master"",
""displayNameOrNull"" : null,
""name"" : ""libuv-master"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/"",
""buildable"" : true,
""builds"" : [
{
""number"" : 1173,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1173/""
},
{
""number"" : 1172,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1172/""
},
{
""number"" : 1171,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1171/""
}
],
""color"" : ""yellow"",
""firstBuild"" : {
""number"" : 1,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1/""
},
""healthReport"" : [
{
""description"" : ""Test Result: 3 tests failing out of a total of 1,026 tests."",
""iconClassName"" : ""icon-health-80plus"",
""iconUrl"" : ""health-80plus.png"",
""score"" : 100
},
{
""description"" : ""Build stability: No recent builds failed."",
""iconClassName"" : ""icon-health-80plus"",
""iconUrl"" : ""health-80plus.png"",
""score"" : 100
}
],
""inQueue"" : false,
""keepDependencies"" : false,
""lastBuild"" : {
""number"" : 1173,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1173/""
},
""lastCompletedBuild"" : {
""number"" : 1173,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1173/""
},
""lastFailedBuild"" : {
""number"" : 1150,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1150/""
},
""lastStableBuild"" : {
""number"" : 2,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/2/""
},
""lastSuccessfulBuild"" : {
""number"" : 1173,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1173/""
},
""lastUnstableBuild"" : {
""number"" : 1173,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1173/""
},
""lastUnsuccessfulBuild"" : {
""number"" : 1173,
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/1173/""
},
""nextBuildNumber"" : 1174,
""property"" : [
{
},
{
}
],
""queueItem"" : null,
""concurrentBuild"" : false,
""downstreamProjects"" : [
],
""scm"" : {
},
""upstreamProjects"" : [
],
""activeConfigurations"" : [
{
""name"" : ""label=smartos"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/label=smartos/"",
""color"" : ""yellow""
},
{
""name"" : ""label=osx-build"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/label=osx-build/"",
""color"" : ""blue""
},
{
""name"" : ""label=ubuntu-12.04"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/label=ubuntu-12.04/"",
""color"" : ""blue""
},
{
""name"" : ""label=ubuntu-14.04"",
""url"" : ""http://jenkins.nodejs.org/job/libuv-master/label=ubuntu-14.04/"",
""color"" : ""blue""
}
]
}";
#endregion Json
}
} | 24.268519 | 99 | 0.502289 | [
"MIT"
] | haroldhues/JenkinsObserver | Test/ConstJson.cs | 10,486 | C# |
#pragma checksum "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\Shared\MainLayout.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "f30d17c414b59cf5f764b5c45dcec884d64c2318"
// <auto-generated/>
#pragma warning disable 1591
namespace BlazorPong3.Client.Shared
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\_Imports.razor"
using BlazorPong3.Client;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\_Imports.razor"
using BlazorPong3.Client.Shared;
#line default
#line hidden
#nullable disable
public partial class MainLayout : LayoutComponentBase
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__builder.OpenElement(0, "div");
__builder.AddAttribute(1, "class", "main");
__builder.AddMarkupContent(2, "\r\n ");
__builder.AddMarkupContent(3, @"<div class=""top-row px-4"">
<div class=""col-4"">
<div>
0 : 0
</div>
</div>
<div class=""col-4"">
<div class=""text-center"">BlazorPong</div>
</div>
<div class=""col-4"">
<div class=""text-right"">
<a href=""/about"" target=""_blank"" class=""ml-md-auto"">About</a>
</div>
</div>
</div>
");
__builder.OpenElement(4, "div");
__builder.AddAttribute(5, "id", "plane");
__builder.AddAttribute(6, "class", "content p-0 pl-0 pr-0 m-0");
__builder.AddMarkupContent(7, "\r\n ");
__builder.AddContent(8,
#nullable restore
#line 21 "C:\Users\Piotrek\source\repos\BlazorPong\BlazorPong3\Client\Shared\MainLayout.razor"
Body
#line default
#line hidden
#nullable disable
);
__builder.AddMarkupContent(9, "\r\n ");
__builder.CloseElement();
__builder.AddMarkupContent(10, "\r\n");
__builder.CloseElement();
}
#pragma warning restore 1998
}
}
#pragma warning restore 1591
| 30.861111 | 186 | 0.680768 | [
"MIT"
] | brzezinol/blazorpong | BlazorPong3/Client/obj/Debug/netstandard2.1/Razor/Shared/MainLayout.razor.g.cs | 3,333 | C# |
using CallManagerPanel.Business.Abstract;
using CallManagerPanel.Business.DependencyResolvers.Ninject;
using CallManagerPanel.Business.ValidationRules.FluentValidation.Abstract;
using CallManagerPanel.Entities.Concrete;
using FluentValidation;
namespace CallManagerPanel.Business.ValidationRules.FluentValidation
{
public class CallValidator : BaseValidator<Call>
{
private static readonly ICallService CallService;
static CallValidator()
{
CallService = InstanceFactory.GetInstance<ICallService>();
}
public CallValidator()
{
RuleFor(x => x.ContactId).GreaterThan(0).WithMessage("'{PropertyName}' is not valid.");
RuleFor(x => x.Date).NotEmpty();
RuleSet("create", () =>
{
RuleFor(x => x)
.Must(x => CallService.GetCountByContactId(x.ContactId) < 10)
.WithMessage("The maximum limit has been reached. No more can be added.");
});
}
}
} | 33.451613 | 99 | 0.639344 | [
"MIT"
] | furkanisitan/call-manager-panel | CallManagerPanel.Business/ValidationRules/FluentValidation/CallValidator.cs | 1,039 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MovieShop.DTOs
{
public class ListRentsDTO
{
public string MovieTitle { get; set; }
public string UserName { get; set; }
public string Genre { get; set; }
}
} | 20.785714 | 46 | 0.656357 | [
"MIT"
] | clubbed/MovieShop | MovieShop/MovieShop/DTOs/ListRentsDTO.cs | 293 | C# |
namespace javax.net.ssl
{
[global::MonoJavaBridge.JavaInterface(typeof(global::javax.net.ssl.SSLSession_))]
public partial interface SSLSession : global::MonoJavaBridge.IJavaObject
{
global::java.lang.Object getValue(java.lang.String arg0);
byte[] getId();
global::java.lang.String getProtocol();
void putValue(java.lang.String arg0, java.lang.Object arg1);
bool isValid();
void invalidate();
global::java.lang.String getCipherSuite();
global::java.security.Principal getPeerPrincipal();
global::java.security.Principal getLocalPrincipal();
global::java.security.cert.Certificate[] getLocalCertificates();
global::java.security.cert.Certificate[] getPeerCertificates();
global::javax.security.cert.X509Certificate[] getPeerCertificateChain();
global::javax.net.ssl.SSLSessionContext getSessionContext();
long getCreationTime();
long getLastAccessedTime();
void removeValue(java.lang.String arg0);
global::java.lang.String[] getValueNames();
global::java.lang.String getPeerHost();
int getPeerPort();
int getPacketBufferSize();
int getApplicationBufferSize();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::javax.net.ssl.SSLSession))]
internal sealed partial class SSLSession_ : java.lang.Object, SSLSession
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal SSLSession_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
global::java.lang.Object javax.net.ssl.SSLSession.getValue(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "getValue", "(Ljava/lang/String;)Ljava/lang/Object;", ref global::javax.net.ssl.SSLSession_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m1;
byte[] javax.net.ssl.SSLSession.getId()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::javax.net.ssl.SSLSession_.staticClass, "getId", "()[B", ref global::javax.net.ssl.SSLSession_._m1) as byte[];
}
private static global::MonoJavaBridge.MethodId _m2;
global::java.lang.String javax.net.ssl.SSLSession.getProtocol()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSession_.staticClass, "getProtocol", "()Ljava/lang/String;", ref global::javax.net.ssl.SSLSession_._m2) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m3;
void javax.net.ssl.SSLSession.putValue(java.lang.String arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "putValue", "(Ljava/lang/String;Ljava/lang/Object;)V", ref global::javax.net.ssl.SSLSession_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
bool javax.net.ssl.SSLSession.isValid()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "isValid", "()Z", ref global::javax.net.ssl.SSLSession_._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
void javax.net.ssl.SSLSession.invalidate()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "invalidate", "()V", ref global::javax.net.ssl.SSLSession_._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
global::java.lang.String javax.net.ssl.SSLSession.getCipherSuite()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSession_.staticClass, "getCipherSuite", "()Ljava/lang/String;", ref global::javax.net.ssl.SSLSession_._m6) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m7;
global::java.security.Principal javax.net.ssl.SSLSession.getPeerPrincipal()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.security.Principal>(this, global::javax.net.ssl.SSLSession_.staticClass, "getPeerPrincipal", "()Ljava/security/Principal;", ref global::javax.net.ssl.SSLSession_._m7) as java.security.Principal;
}
private static global::MonoJavaBridge.MethodId _m8;
global::java.security.Principal javax.net.ssl.SSLSession.getLocalPrincipal()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.security.Principal>(this, global::javax.net.ssl.SSLSession_.staticClass, "getLocalPrincipal", "()Ljava/security/Principal;", ref global::javax.net.ssl.SSLSession_._m8) as java.security.Principal;
}
private static global::MonoJavaBridge.MethodId _m9;
global::java.security.cert.Certificate[] javax.net.ssl.SSLSession.getLocalCertificates()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.security.cert.Certificate>(this, global::javax.net.ssl.SSLSession_.staticClass, "getLocalCertificates", "()[Ljava/security/cert/Certificate;", ref global::javax.net.ssl.SSLSession_._m9) as java.security.cert.Certificate[];
}
private static global::MonoJavaBridge.MethodId _m10;
global::java.security.cert.Certificate[] javax.net.ssl.SSLSession.getPeerCertificates()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.security.cert.Certificate>(this, global::javax.net.ssl.SSLSession_.staticClass, "getPeerCertificates", "()[Ljava/security/cert/Certificate;", ref global::javax.net.ssl.SSLSession_._m10) as java.security.cert.Certificate[];
}
private static global::MonoJavaBridge.MethodId _m11;
global::javax.security.cert.X509Certificate[] javax.net.ssl.SSLSession.getPeerCertificateChain()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<javax.security.cert.X509Certificate>(this, global::javax.net.ssl.SSLSession_.staticClass, "getPeerCertificateChain", "()[Ljavax/security/cert/X509Certificate;", ref global::javax.net.ssl.SSLSession_._m11) as javax.security.cert.X509Certificate[];
}
private static global::MonoJavaBridge.MethodId _m12;
global::javax.net.ssl.SSLSessionContext javax.net.ssl.SSLSession.getSessionContext()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<javax.net.ssl.SSLSessionContext>(this, global::javax.net.ssl.SSLSession_.staticClass, "getSessionContext", "()Ljavax/net/ssl/SSLSessionContext;", ref global::javax.net.ssl.SSLSession_._m12) as javax.net.ssl.SSLSessionContext;
}
private static global::MonoJavaBridge.MethodId _m13;
long javax.net.ssl.SSLSession.getCreationTime()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "getCreationTime", "()J", ref global::javax.net.ssl.SSLSession_._m13);
}
private static global::MonoJavaBridge.MethodId _m14;
long javax.net.ssl.SSLSession.getLastAccessedTime()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "getLastAccessedTime", "()J", ref global::javax.net.ssl.SSLSession_._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
void javax.net.ssl.SSLSession.removeValue(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "removeValue", "(Ljava/lang/String;)V", ref global::javax.net.ssl.SSLSession_._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
global::java.lang.String[] javax.net.ssl.SSLSession.getValueNames()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSession_.staticClass, "getValueNames", "()[Ljava/lang/String;", ref global::javax.net.ssl.SSLSession_._m16) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m17;
global::java.lang.String javax.net.ssl.SSLSession.getPeerHost()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSession_.staticClass, "getPeerHost", "()Ljava/lang/String;", ref global::javax.net.ssl.SSLSession_._m17) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m18;
int javax.net.ssl.SSLSession.getPeerPort()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "getPeerPort", "()I", ref global::javax.net.ssl.SSLSession_._m18);
}
private static global::MonoJavaBridge.MethodId _m19;
int javax.net.ssl.SSLSession.getPacketBufferSize()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "getPacketBufferSize", "()I", ref global::javax.net.ssl.SSLSession_._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
int javax.net.ssl.SSLSession.getApplicationBufferSize()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::javax.net.ssl.SSLSession_.staticClass, "getApplicationBufferSize", "()I", ref global::javax.net.ssl.SSLSession_._m20);
}
static SSLSession_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::javax.net.ssl.SSLSession_.staticClass = @__env.NewGlobalRef(@__env.FindClass("javax/net/ssl/SSLSession"));
}
}
}
| 63.695946 | 315 | 0.781479 | [
"MIT"
] | JeroMiya/androidmono | MonoJavaBridge/android/generated/javax/net/ssl/SSLSession.cs | 9,427 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CAIMonsterDefeated : CAIMonsterDeath
{
[Ordinal(1)] [RED("localDeathTree")] public CHandle<CAIMonsterDeath> LocalDeathTree { get; set;}
[Ordinal(2)] [RED("unconsciousTree")] public CHandle<CAINpcUnconsciousTree> UnconsciousTree { get; set;}
public CAIMonsterDefeated(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIMonsterDefeated(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 35.296296 | 130 | 0.739769 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CAIMonsterDefeated.cs | 953 | C# |
using System;
using System.IO;
using UnaryHeap.Utilities.D2;
namespace UnaryHeap.Utilities.Apps
{
/// <summary>
/// Represents the logic behind a console utility application that can convert
/// JSON-formatted Graph2D objects to SVG.
/// </summary>
public abstract class GraphRendererApp
{
/// <summary>
/// The main method of the application.
/// </summary>
/// <remarks>
/// If run with no arguments, the Graph2D is read from Console.In and the SVG is written
/// to Console.Out.
/// If run with one argument, the Graph2D is read from the filename specified, and
/// the SVG is written to the same filename, only with extension 'svg'.
/// If run with two arguments, the Graph2D is read from the first filename specified,
/// and the SVG is written to the second filename specified.
/// </remarks>
/// <param name="args">The arguments from the command prompt.</param>
/// <returns>
/// 0 if successful; otherwise, a description of the error is written to
/// Console.Error and the method returns 1.
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Catch statement is last-resort exception for writing " +
"an error message before exiting the application.")]
public static int MainMethod(string[] args)
{
if (null == args)
throw new ArgumentNullException("args");
try
{
switch (args.Length)
{
case 0:
new ConsoleGraphRenderApp().Run();
return 0;
case 1:
new FileGraphRenderApp(args[0]).Run();
return 0;
case 2:
new FileGraphRenderApp(args[0], args[1]).Run();
return 0;
}
Console.Error.WriteLine("The syntax of the command is incorrect.");
}
catch (Exception ex)
{
Console.Error.WriteLine("ERROR: " + ex.Message);
}
return 1;
}
/// <summary>
/// Runs the application: a Graph2D object is deserialized from the input stream,
/// and an SVG representation is serialized to the output stream.
/// </summary>
public void Run()
{
var graph = ReadGraph();
var settings = new SvgFormatterSettings(graph);
WriteSvg(graph, settings);
}
void WriteSvg(Graph2D graph, SvgFormatterSettings settings)
{
TextWriter output = null;
try
{
output = AcquireOutput();
SvgGraph2DFormatter.Generate(graph, output, settings);
}
finally
{
if (null != output)
ReleaseOutput(output);
}
}
Graph2D ReadGraph()
{
TextReader input = null;
try
{
input = AcquireInput();
return Graph2D.FromJson(input);
}
finally
{
if (null != input)
ReleaseInput(input);
}
}
/// <summary>
/// Gets a TextReader containing a JSON-formatted Graph2D object.
/// </summary>
/// <returns>A TextReader containing a JSON-formatted Graph2D object.</returns>
protected abstract TextReader AcquireInput();
/// <summary>
/// Releases the TextReader returned from the AcquireInput method.
/// </summary>
/// <param name="reader">The TextReader returned from the AcquireInput method.</param>
protected abstract void ReleaseInput(TextReader reader);
/// <summary>
/// Gets a TextWriter to which the SVG will be written.
/// </summary>
/// <returns>A TextWriter to which the SVG will be written</returns>
protected abstract TextWriter AcquireOutput();
/// <summary>
/// Releases the TextWriter returned from the AcquireOutput method.
/// </summary>
/// <param name="writer">The TextWriter returned from the AcquireOutput method.</param>
protected abstract void ReleaseOutput(TextWriter writer);
}
/// <summary>
/// Implementation of UnaryHeap.Utilities.GraphRenderApp which reads from and writes to
/// arbitrary streams.
/// </summary>
public class StreamGraphRenderApp : GraphRendererApp
{
TextReader input;
TextWriter output;
/// <summary>
/// Initializes a new instance of the StreamGraphRenderApp class.
/// </summary>
/// <param name="input">The input stream from which to read.</param>
/// <param name="output">The output stream to which to write.</param>
/// <exception cref="System.ArgumentNullException">
/// input or output are null.</exception>
public StreamGraphRenderApp(TextReader input, TextWriter output)
{
if (null == input)
throw new ArgumentNullException("input");
if (null == output)
throw new ArgumentNullException("output");
this.input = input;
this.output = output;
}
/// <summary>
/// Gets a TextReader containing a JSON-formatted Graph2D object.
/// </summary>
/// <returns>A TextReader containing a JSON-formatted Graph2D object.</returns>
protected override TextReader AcquireInput()
{
return input;
}
/// <summary>
/// Releases the TextReader returned from the AcquireInput method.
/// </summary>
/// <param name="reader">The TextReader returned from the AcquireInput method.</param>
protected override void ReleaseInput(TextReader reader)
{
}
/// <summary>
/// Gets a TextWriter to which the SVG will be written.
/// </summary>
/// <returns>A TextWriter to which the SVG will be written</returns>
protected override TextWriter AcquireOutput()
{
return output;
}
/// <summary>
/// Releases the TextWriter returned from the AcquireOutput method.
/// </summary>
/// <param name="writer">The TextWriter returned from the AcquireOutput method.</param>
protected override void ReleaseOutput(TextWriter writer)
{
}
}
/// <summary>
/// Implementation of GraphRenderApp which reads from and writes to standard streams.
/// </summary>
class ConsoleGraphRenderApp : StreamGraphRenderApp
{
public ConsoleGraphRenderApp()
: base(Console.In, Console.Out)
{
}
}
/// <summary>
/// Implementation of GraphRenderApp which reads from and writes to files on disk.
/// </summary>
public class FileGraphRenderApp : GraphRendererApp
{
string inputJsonFile;
string outputSvgFile;
/// <summary>
/// Initializes a new instance of the FileGraphReaderApp class using the specified
/// input file name and a default output file name.
/// </summary>
/// <param name="inputJsonFile">The name of the input file.</param>
public FileGraphRenderApp(string inputJsonFile)
{
if (null == inputJsonFile)
throw new ArgumentNullException("inputJsonFile");
if (0 == inputJsonFile.Length)
throw new ArgumentOutOfRangeException("inputJsonFile");
inputJsonFile = Path.GetFullPath(inputJsonFile);
if (false == File.Exists(inputJsonFile))
throw new ArgumentException("Input file not found.", "inputJsonFile");
if (HasSvgExtension(inputJsonFile))
throw new ArgumentException("Input file name has extension 'svg' " +
"and collides with default output file name. Output file name must " +
"be specified.", "inputJsonFile");
this.inputJsonFile = inputJsonFile;
this.outputSvgFile = Path.ChangeExtension(inputJsonFile, "svg");
}
private static bool HasSvgExtension(string inputJsonFile)
{
return string.Equals(".svg",
Path.GetExtension(inputJsonFile), StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Initializes a new instance of the FileGraphReaderApp class using the specified
/// input and output file names.
/// </summary>
/// <param name="inputJsonFile">The name of the input file.</param>
/// <param name="outputSvgFile">The name of the output file.</param>
public FileGraphRenderApp(string inputJsonFile, string outputSvgFile)
{
if (null == inputJsonFile)
throw new ArgumentNullException("inputJsonFile");
if (null == outputSvgFile)
throw new ArgumentNullException("outputSvgFile");
if (0 == inputJsonFile.Length)
throw new ArgumentOutOfRangeException("inputJsonFile");
if (0 == outputSvgFile.Length)
throw new ArgumentOutOfRangeException("outputSvgFile");
inputJsonFile = Path.GetFullPath(inputJsonFile);
outputSvgFile = Path.GetFullPath(outputSvgFile);
if (false == File.Exists(inputJsonFile))
throw new ArgumentException("Input file not found.", "inputJsonFile");
if (string.Equals(inputJsonFile, outputSvgFile, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(
"Input file name cannot be the same as output file name.");
this.inputJsonFile = inputJsonFile;
this.outputSvgFile = outputSvgFile;
}
/// <summary>
/// Gets a TextReader containing a JSON-formatted Graph2D object.
/// </summary>
/// <returns>A TextReader containing a JSON-formatted Graph2D object.</returns>
protected override TextReader AcquireInput()
{
return File.OpenText(inputJsonFile);
}
/// <summary>
/// Releases the TextReader returned from the AcquireInput method.
/// </summary>
/// <param name="reader">The TextReader returned from the AcquireInput method.</param>
protected override void ReleaseInput(TextReader reader)
{
if (null == reader)
throw new ArgumentNullException("reader");
reader.Close();
}
/// <summary>
/// Gets a TextWriter to which the SVG will be written.
/// </summary>
/// <returns>A TextWriter to which the SVG will be written</returns>
protected override TextWriter AcquireOutput()
{
return File.CreateText(outputSvgFile);
}
/// <summary>
/// Releases the TextWriter returned from the AcquireOutput method.
/// </summary>
/// <param name="writer">The TextWriter returned from the AcquireOutput method.</param>
protected override void ReleaseOutput(TextWriter writer)
{
if (null == writer)
throw new ArgumentNullException("writer");
writer.Close();
}
}
} | 37.974603 | 97 | 0.560609 | [
"MIT"
] | SheepNine/UnaryHeap | source/UnaryHeap.Utilities/UnaryHeap.Utilities/Apps/GraphRendererApp.cs | 11,964 | C# |
using System;
using System.Runtime.InteropServices;
namespace Steamworks
{
[global::Steamworks.CallbackIdentity(201)]
[global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 8)]
public struct GSClientApprove_t
{
public const int k_iCallback = 201;
public global::Steamworks.CSteamID m_SteamID;
public global::Steamworks.CSteamID m_OwnerSteamID;
}
}
| 25.294118 | 126 | 0.797674 | [
"CC0-1.0"
] | FreyaFreed/mordheim | Assembly-CSharp/Steamworks/GSClientApprove_t.cs | 432 | C# |
using System.Threading.Tasks;
namespace ApprovalUtilities.Persistence;
public class SaverAsyncWrapper<T> : ISaverAsync<T>
{
readonly ISaver<T> saver;
public SaverAsyncWrapper(ISaver<T> saver)
{
this.saver = saver;
}
public Task<T> Save(T objectToBeSaved)
{
return Task.Factory.StartNew(() => saver.Save(objectToBeSaved));
}
} | 21.722222 | 73 | 0.644501 | [
"Apache-2.0"
] | skalinets/ApprovalTests.Net | src/ApprovalUtilities/Persistence/SaverAsyncWrapper.cs | 376 | C# |
/*
// <copyright>
// dotNetRDF is free and open source software licensed under the MIT License
// -------------------------------------------------------------------------
//
// Copyright (c) 2009-2021 dotNetRDF Project (http://dotnetrdf.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
*/
using System;
using VDS.RDF.Query.Spin.Model;
using VDS.RDF;
using VDS.RDF.Query.Spin;
namespace VDS.RDF.Query.Spin.Core
{
/**
* A singleton that is used to render resources into strings.
* By default this displays qnames (if possible).
* Can be changed, for example, to switch to displaying rdfs:labels
* instead of qnames etc.
*
* @author Holger Knublauch
*/
internal class SPINLabels
{
/**
* Gets a "human-readable" label for a given Resource.
* This checks for any existing rdfs:label, otherwise falls back to
* <code>getLabel()</code>.
* @param resource
* @return the label (never null)
*/
public static String getCustomizedLabel(IResource resource)
{
String label = resource.getString(RDFS.PropertyLabel);
if (label != null)
{
return label;
}
return getLabel(resource);
}
/**
* Gets the label for a given Resource.
* @param resource the Resource to get the label of
* @return the label (never null)
*/
public static String getLabel(INode resource)
{
if (resource is IUriNode)
{
// TODO
return null;
}
else
{
return resource.ToString();
}
}
}
} | 34.146341 | 84 | 0.616786 | [
"MIT"
] | BME-MIT-IET/iet-hf2021-gitgud | Libraries/dotNetRDF.Query.Spin/Core/SPINLabels.cs | 2,800 | C# |
// <copyright file="ListExtensions.cs" company="improvGroup, LLC">
// Copyright © improvGroup, LLC. All Rights Reserved.
// </copyright>
namespace SharedCode.Core.Collections
{
using System.Collections.Generic;
using JetBrains.Annotations;
/// <summary>
/// The list extensions class
/// </summary>
public static class ListExtensions
{
/// <summary>
/// Determines whether a list is not null or empty.
/// </summary>
/// <typeparam name="T">The item type.</typeparam>
/// <param name="items">The list.</param>
/// <returns><c>true</c> if this list is not null or empty; otherwise, <c>false</c>.</returns>
public static bool IsNotNullOrEmpty<T>([CanBeNull][ItemCanBeNull] this IList<T> items) => items?.Count > 0;
/// <summary>
/// Determines whether a list is null or empty.
/// </summary>
/// <typeparam name="T">The item type.</typeparam>
/// <param name="items">The list.</param>
/// <returns><c>true</c> if this list is null or empty; otherwise, <c>false</c>.</returns>
public static bool IsNullOrEmpty<T>([CanBeNull][ItemCanBeNull] this IList<T> items) => items == null || items.Count == 0;
/// <summary>
/// This extension method replaces an item in a collection that implements the IList interface.
/// </summary>
/// <typeparam name="T">The type of the field that we are manipulating</typeparam>
/// <param name="thisList">The input list</param>
/// <param name="position">The position of the old item</param>
/// <param name="item">The item we are goint to put in it's place</param>
/// <returns>True in case of a replace, false if failed</returns>
public static bool Replace<T>([CanBeNull][ItemCanBeNull] this IList<T> thisList, int position, [CanBeNull] T item)
{
// only process if inside the range of this list
if (thisList == null || position > thisList.Count - 1)
{
return false;
}
// remove the old item
thisList?.RemoveAt(position);
// insert the new item at its position
thisList?.Insert(position, item);
// return success
return true;
}
}
} | 40.344828 | 129 | 0.591026 | [
"MIT"
] | JTOne123/SharedCode | SharedCode.Core/Collections/ListExtensions.cs | 2,343 | C# |
#region [License]
// The MIT License (MIT)
//
// Copyright (c) 2017, Unity Technologies
// Copyright (c) 2018, Cristian Alexandru Geambasu
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// https://bitbucket.org/Unity-Technologies/ui
#endregion
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
namespace Luminosity.IO
{
[AddComponentMenu("Luminosity/Input Manager/Standalone Input Module")]
/// <summary>
/// A BaseInputModule designed for mouse / keyboard / controller input.
/// </summary>
/// <remarks>
/// Input module for working with, mouse, keyboard, or controller.
/// </remarks>
public class StandaloneInputModule : PointerInputModule
{
public const string VERSION = "2018.3";
private float m_PrevActionTime;
private Vector2 m_LastMoveVector;
private Vector2 m_LastMousePosition;
private Vector2 m_MousePosition;
private GameObject m_CurrentFocusedGameObject;
private PointerEventData m_InputPointerEvent;
protected StandaloneInputModule()
{
}
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public enum InputMode
{
Mouse,
Buttons
}
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public InputMode inputMode
{
get { return InputMode.Mouse; }
}
[SerializeField]
private string m_UpButton = "UI_Up";
[SerializeField]
private string m_DownButton = "UI_Down";
[SerializeField]
private string m_LeftButton = "UI_Left";
[SerializeField]
private string m_RightButton = "UI_Right";
[SerializeField]
private string m_SubmitButton = "UI_Submit";
[SerializeField]
private string m_CancelButton = "UI_Cancel";
[SerializeField]
[FormerlySerializedAs("m_AllowActivationOnMobileDevice")]
private bool m_ForceModuleActive;
[Obsolete("allowActivationOnMobileDevice has been deprecated. Use forceModuleActive instead (UnityUpgradable) -> forceModuleActive")]
public bool AllowActivationOnMobileDevice
{
get { return m_ForceModuleActive; }
set { m_ForceModuleActive = value; }
}
/// <summary>
/// Force this module to be active.
/// </summary>
/// <remarks>
/// If there is no module active with higher priority (ordered in the inspector) this module will be forced active even if valid enabling conditions are not met.
/// </remarks>
public bool ForceModuleActive
{
get { return m_ForceModuleActive; }
set { m_ForceModuleActive = value; }
}
public string UpButton
{
get { return m_UpButton; }
set { m_UpButton = value; }
}
public string DownButton
{
get { return m_DownButton; }
set { m_DownButton = value; }
}
public string LeftButton
{
get { return m_LeftButton; }
set { m_LeftButton = value; }
}
public string RightButton
{
get { return m_RightButton; }
set { m_RightButton = value; }
}
public string SubmitButton
{
get { return m_SubmitButton; }
set { m_SubmitButton = value; }
}
public string CancelButton
{
get { return m_CancelButton; }
set { m_CancelButton = value; }
}
protected override void Awake()
{
base.Awake();
m_InputOverride = gameObject.AddComponent<UIInputAdapter>();
}
private bool ShouldIgnoreEventsOnNoFocus()
{
switch(SystemInfo.operatingSystemFamily)
{
case OperatingSystemFamily.Windows:
case OperatingSystemFamily.Linux:
case OperatingSystemFamily.MacOSX:
#if UNITY_EDITOR
if(UnityEditor.EditorApplication.isRemoteConnected)
return false;
#endif
return true;
default:
return false;
}
}
public override void UpdateModule()
{
if(!eventSystem.isFocused && ShouldIgnoreEventsOnNoFocus())
{
if(m_InputPointerEvent != null && m_InputPointerEvent.pointerDrag != null && m_InputPointerEvent.dragging)
ExecuteEvents.Execute(m_InputPointerEvent.pointerDrag, m_InputPointerEvent, ExecuteEvents.endDragHandler);
m_InputPointerEvent = null;
return;
}
m_LastMousePosition = m_MousePosition;
m_MousePosition = input.mousePosition;
}
public override bool IsModuleSupported()
{
return m_ForceModuleActive || input.mousePresent || input.touchSupported;
}
public override bool ShouldActivateModule()
{
if(!base.ShouldActivateModule())
return false;
var shouldActivate = m_ForceModuleActive;
shouldActivate |= input.GetButtonDown(m_SubmitButton);
shouldActivate |= input.GetButtonDown(m_CancelButton);
shouldActivate |= input.GetButtonDown(m_UpButton);
shouldActivate |= input.GetButtonDown(m_DownButton);
shouldActivate |= input.GetButtonDown(m_LeftButton);
shouldActivate |= input.GetButtonDown(m_RightButton);
shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
shouldActivate |= input.GetMouseButtonDown(0);
if(input.touchCount > 0)
shouldActivate = true;
return shouldActivate;
}
/// <summary>
/// See BaseInputModule.
/// </summary>
public override void ActivateModule()
{
if(!eventSystem.isFocused && ShouldIgnoreEventsOnNoFocus())
return;
base.ActivateModule();
m_MousePosition = input.mousePosition;
m_LastMousePosition = input.mousePosition;
var toSelect = eventSystem.currentSelectedGameObject;
if(toSelect == null)
toSelect = eventSystem.firstSelectedGameObject;
eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData());
}
/// <summary>
/// See BaseInputModule.
/// </summary>
public override void DeactivateModule()
{
base.DeactivateModule();
ClearSelection();
}
public override void Process()
{
if(!eventSystem.isFocused && ShouldIgnoreEventsOnNoFocus())
return;
bool usedEvent = SendUpdateEventToSelectedObject();
if(eventSystem.sendNavigationEvents)
{
if(!usedEvent)
usedEvent |= SendMoveEventToSelectedObject();
if(!usedEvent)
SendSubmitEventToSelectedObject();
}
// touch needs to take precedence because of the mouse emulation layer
if(!ProcessTouchEvents() && input.mousePresent)
ProcessMouseEvent();
}
private bool ProcessTouchEvents()
{
for(int i = 0; i < input.touchCount; ++i)
{
Touch touch = input.GetTouch(i);
if(touch.type == TouchType.Indirect)
continue;
bool released;
bool pressed;
var pointer = GetTouchPointerEventData(touch, out pressed, out released);
ProcessTouchPress(pointer, pressed, released);
if(!released)
{
ProcessMove(pointer);
ProcessDrag(pointer);
}
else
RemovePointerData(pointer);
}
return input.touchCount > 0;
}
/// <summary>
/// This method is called by Unity whenever a touch event is processed. Override this method with a custom implementation to process touch events yourself.
/// </summary>
/// <param name="pointerEvent">Event data relating to the touch event, such as position and ID to be passed to the touch event destination object.</param>
/// <param name="pressed">This is true for the first frame of a touch event, and false thereafter. This can therefore be used to determine the instant a touch event occurred.</param>
/// <param name="released">This is true only for the last frame of a touch event.</param>
/// <remarks>
/// This method can be overridden in derived classes to change how touch press events are handled.
/// </remarks>
protected void ProcessTouchPress(PointerEventData pointerEvent, bool pressed, bool released)
{
var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
// PointerDown notification
if(pressed)
{
pointerEvent.eligibleForClick = true;
pointerEvent.delta = Vector2.zero;
pointerEvent.dragging = false;
pointerEvent.useDragThreshold = true;
pointerEvent.pressPosition = pointerEvent.position;
pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
DeselectIfSelectionChanged(currentOverGo, pointerEvent);
if(pointerEvent.pointerEnter != currentOverGo)
{
// send a pointer enter to the touched element if it isn't the one to select...
HandlePointerExitAndEnter(pointerEvent, currentOverGo);
pointerEvent.pointerEnter = currentOverGo;
}
// search for the control that will receive the press
// if we can't find a press handler set the press
// handler to be what would receive a click.
var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
// didnt find a press handler... search for a click handler
if(newPressed == null)
newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// Debug.Log("Pressed: " + newPressed);
float time = Time.unscaledTime;
if(newPressed == pointerEvent.lastPress)
{
var diffTime = time - pointerEvent.clickTime;
if(diffTime < 0.3f)
++pointerEvent.clickCount;
else
pointerEvent.clickCount = 1;
pointerEvent.clickTime = time;
}
else
{
pointerEvent.clickCount = 1;
}
pointerEvent.pointerPress = newPressed;
pointerEvent.rawPointerPress = currentOverGo;
pointerEvent.clickTime = time;
// Save the drag handler as well
pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
if(pointerEvent.pointerDrag != null)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
m_InputPointerEvent = pointerEvent;
}
// PointerUp notification
if(released)
{
// Debug.Log("Executing pressup on: " + pointer.pointerPress);
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
// Debug.Log("KeyCode: " + pointer.eventData.keyCode);
// see if we mouse up on the same element that we clicked on...
var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// PointerClick and Drop events
if(pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
}
else if(pointerEvent.pointerDrag != null && pointerEvent.dragging)
{
ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
}
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
if(pointerEvent.pointerDrag != null && pointerEvent.dragging)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
pointerEvent.dragging = false;
pointerEvent.pointerDrag = null;
// send exit events as we need to simulate this on touch up on touch device
ExecuteEvents.ExecuteHierarchy(pointerEvent.pointerEnter, pointerEvent, ExecuteEvents.pointerExitHandler);
pointerEvent.pointerEnter = null;
m_InputPointerEvent = pointerEvent;
}
}
/// <summary>
/// Calculate and send a submit event to the current selected object.
/// </summary>
/// <returns>If the submit event was used by the selected object.</returns>
protected bool SendSubmitEventToSelectedObject()
{
if(eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
if(input.GetButtonDown(m_SubmitButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
if(input.GetButtonDown(m_CancelButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
return data.used;
}
private Vector2 GetRawMoveVector()
{
Vector2 move = Vector2.zero;
if(input.GetButtonDown(m_LeftButton))
move.x = -1.0f;
if(input.GetButtonDown(m_RightButton))
move.x = 1.0f;
if(input.GetButtonDown(m_UpButton))
move.y = 1.0f;
if(input.GetButtonDown(m_DownButton))
move.y = -1.0f;
return move;
}
/// <summary>
/// Calculate and send a move event to the current selected object.
/// </summary>
/// <returns>If the move event was used by the selected object.</returns>
protected bool SendMoveEventToSelectedObject()
{
var movement = GetRawMoveVector();
var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f);
if(axisEventData.moveDir != MoveDirection.None)
{
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
}
return axisEventData.used;
}
protected void ProcessMouseEvent()
{
ProcessMouseEvent(0);
}
[Obsolete("This method is no longer checked, overriding it with return true does nothing!")]
protected virtual bool ForceAutoSelect()
{
return false;
}
/// <summary>
/// Process all mouse events.
/// </summary>
protected void ProcessMouseEvent(int id)
{
var mouseData = GetMousePointerEventData(id);
var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData;
m_CurrentFocusedGameObject = leftButtonData.buttonData.pointerCurrentRaycast.gameObject;
// Process the first mouse button fully
ProcessMousePress(leftButtonData);
ProcessMove(leftButtonData.buttonData);
ProcessDrag(leftButtonData.buttonData);
// Now process right / middle clicks
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData);
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData);
if(!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f))
{
var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject);
ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler);
}
}
protected bool SendUpdateEventToSelectedObject()
{
if(eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
return data.used;
}
/// <summary>
/// Calculate and process any mouse button state changes.
/// </summary>
protected void ProcessMousePress(MouseButtonEventData data)
{
var pointerEvent = data.buttonData;
var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
// PointerDown notification
if(data.PressedThisFrame())
{
pointerEvent.eligibleForClick = true;
pointerEvent.delta = Vector2.zero;
pointerEvent.dragging = false;
pointerEvent.useDragThreshold = true;
pointerEvent.pressPosition = pointerEvent.position;
pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
DeselectIfSelectionChanged(currentOverGo, pointerEvent);
// search for the control that will receive the press
// if we can't find a press handler set the press
// handler to be what would receive a click.
var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
// didnt find a press handler... search for a click handler
if(newPressed == null)
newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// Debug.Log("Pressed: " + newPressed);
float time = Time.unscaledTime;
if(newPressed == pointerEvent.lastPress)
{
var diffTime = time - pointerEvent.clickTime;
if(diffTime < 0.3f)
++pointerEvent.clickCount;
else
pointerEvent.clickCount = 1;
pointerEvent.clickTime = time;
}
else
{
pointerEvent.clickCount = 1;
}
pointerEvent.pointerPress = newPressed;
pointerEvent.rawPointerPress = currentOverGo;
pointerEvent.clickTime = time;
// Save the drag handler as well
pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
if(pointerEvent.pointerDrag != null)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
m_InputPointerEvent = pointerEvent;
}
// PointerUp notification
if(data.ReleasedThisFrame())
{
// Debug.Log("Executing pressup on: " + pointer.pointerPress);
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
// Debug.Log("KeyCode: " + pointer.eventData.keyCode);
// see if we mouse up on the same element that we clicked on...
var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// PointerClick and Drop events
if(pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
}
else if(pointerEvent.pointerDrag != null && pointerEvent.dragging)
{
ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
}
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
if(pointerEvent.pointerDrag != null && pointerEvent.dragging)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
pointerEvent.dragging = false;
pointerEvent.pointerDrag = null;
// redo pointer enter / exit to refresh state
// so that if we moused over somethign that ignored it before
// due to having pressed on something else
// it now gets it.
if(currentOverGo != pointerEvent.pointerEnter)
{
HandlePointerExitAndEnter(pointerEvent, null);
HandlePointerExitAndEnter(pointerEvent, currentOverGo);
}
m_InputPointerEvent = pointerEvent;
}
}
protected GameObject GetCurrentFocusedGameObject()
{
return m_CurrentFocusedGameObject;
}
}
}
| 38.273616 | 190 | 0.6 | [
"MIT-0",
"MIT"
] | Chillu1/InputManager | Assets/InputManager/Addons/UIInputModule/Runtime/StandaloneInputModule.cs | 23,502 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Torshia.Web.App_Start
{
public static class ViewEngineConfig
{
public static void RegisterViewEngines()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
}
}
} | 21.588235 | 59 | 0.66485 | [
"MIT"
] | svetlimladenov/ASP.NET-MVC-5 | Homeworks/TorshiaHomework/Torshia/Web/Torshia.Web/App_Start/ViewEngineConfig.cs | 369 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Certificate create or update details.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class CertificateCreateOrUpdateParameters
{
/// <summary>
/// Initializes a new instance of the
/// CertificateCreateOrUpdateParameters class.
/// </summary>
public CertificateCreateOrUpdateParameters()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// CertificateCreateOrUpdateParameters class.
/// </summary>
/// <param name="data">Base 64 encoded certificate using the
/// application/x-pkcs12 representation.</param>
/// <param name="password">Password for the Certificate</param>
public CertificateCreateOrUpdateParameters(string data, string password)
{
Data = data;
Password = password;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets base 64 encoded certificate using the
/// application/x-pkcs12 representation.
/// </summary>
[JsonProperty(PropertyName = "properties.data")]
public string Data { get; set; }
/// <summary>
/// Gets or sets password for the Certificate
/// </summary>
[JsonProperty(PropertyName = "properties.password")]
public string Password { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Data == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Data");
}
if (Password == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Password");
}
}
}
}
| 32.494118 | 90 | 0.604996 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/ApiManagement/Management.ApiManagement/Generated/Models/CertificateCreateOrUpdateParameters.cs | 2,762 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using StackExchange.Status.Models;
using StackExchange.Status.Models.Dashboard;
using StackExchange.Status.Models.HAProxy;
using StackExchange.Status.Models.SQL;
namespace StackExchange.Status.Helpers
{
public static class AppCache
{
#region Dashboard
private static List<DashboardView> _dashboardViews;
public static List<DashboardView> DashboardViews
{
get { return _dashboardViews ?? (_dashboardViews = Current.Settings.Dashboard.Views.All.Select(v => new DashboardView(v)).ToList()); }
}
public static ServerInfoCache ServerInfo
{
get
{
return Current.LocalCache.GetSet<ServerInfoCache>
("server-cache",
(old, ctx) =>
{
try
{
Dictionary<int, List<string>> nodeToIPs = null;
Dictionary<string, int> ipToNodes = null;
var servers = Models.Dashboard.ServerInfo.GetAll();
try
{
var ips = Models.Dashboard.ServerInfo.GetIPs();
nodeToIPs = ips.GroupBy(m => m.Item1).ToDictionary(g => g.Key, g => g.Select(i => i.Item2).OrderBy(ip => ip).ToList());
var ipGroups = ips.GroupBy(m => m.Item2);
ipToNodes = ipGroups.ToDictionary(g => g.Key, g => g.Max(i => i.Item1));
var dupes = ipGroups.Where(g => g.Count() > 1).ToList();
if (dupes.Any())
{
var dupeEx = new ApplicationException(string.Format("{0} Duplicate IP{1} found", dupes.Count, dupes.Count != 1 ? "s" : ""));
foreach (var dupe in dupes)
{
var dupeNames = dupe.Select(i =>
{
var ipServer = servers != null
? servers.FirstOrDefault(s => s.Id == i.Item1)
: null;
return ipServer != null ? ipServer.PrettyName : "Id: " + i.Item1;
});
dupeEx.AddLoggedData(dupe.Key, string.Join(", ", dupeNames));
}
Current.LogException(dupeEx, key: "Cache.Servers.DuplicateIPs", reLogDelaySeconds: 5*60*60);
}
}
catch (Exception e)
{
Current.LogException(e, key: "Cache.Servers");
return new ServerInfoCache
{
Servers = servers,
NodeIPs = nodeToIPs ?? (old != null ? old.NodeIPs : new Dictionary<int, List<string>>()),
IPToNode = ipToNodes ?? (old != null ? old.IPToNode : new Dictionary<string, int>()),
LastFetch = FetchInfo.Success(),
LastSuccessfulFetch = FetchInfo.Success()
};
}
return new ServerInfoCache
{
Servers = servers,
NodeIPs = nodeToIPs,
IPToNode = ipToNodes,
LastFetch = FetchInfo.Success(),
LastSuccessfulFetch = FetchInfo.Success()
};
}
catch (Exception e)
{
Current.LogException(e, key: "Cache.Servers.Outer");
return new ServerInfoCache
{
Servers = old != null ? old.Servers : new List<ServerInfo>(),
NodeIPs = old != null ? old.NodeIPs : new Dictionary<int, List<string>>(),
IPToNode = old != null ? old.IPToNode : new Dictionary<string, int>(),
LastFetch = FetchInfo.Fail(e.Message, e),
LastSuccessfulFetch = old != null ? old.LastSuccessfulFetch : null
};
}
}, 30, 24*60*60);
}
}
public static List<Interface> Interfaces
{
get { return Current.LocalCache.GetSet<List<Interface>>("interface-cache", (old, ctx) => Interface.GetAll(), 30, 24 * 60 * 60); }
}
public static List<Volume> Volumes
{
get { return Current.LocalCache.GetSet<List<Volume>>("volume-cache", (old, ctx) => Volume.GetAll(), 120, 24 * 60 * 60); }
}
public static List<Application> Applications
{
get { return Current.LocalCache.GetSet<List<Application>>("application-cache", (old, ctx) => Application.GetAll(), 120, 24 * 60 * 60); }
}
public class ServerInfoCache
{
public List<ServerInfo> Servers { get; set; }
public Dictionary<int, List<string>> NodeIPs { get; set; }
public Dictionary<string, int> IPToNode { get; set; }
public FetchInfo LastFetch { get; set; }
public FetchInfo LastSuccessfulFetch { get; set; }
}
#endregion
private static List<SQLCluster> _sqlClusters;
public static List<SQLCluster> SQLClusters
{
get
{
if (_sqlClusters == null)
{
if (Current.Settings.SQL.Enabled)
_sqlClusters = Current.Settings.SQL.Clusters.All.Select(c => new SQLCluster(c)).ToList();
else
_sqlClusters = new List<SQLCluster>();
}
return _sqlClusters;
}
}
private static List<HAProxyInstance> _haProxyInstances;
public static List<HAProxyInstance> HAProxyInstances
{
get
{
if (_haProxyInstances == null)
{
if (Current.Settings.HAProxy.Enabled)
_haProxyInstances = Current.Settings.HAProxy.Instances.All.Select(c => new HAProxyInstance(c)).ToList();
else
_haProxyInstances = new List<HAProxyInstance>();
}
return _haProxyInstances;
}
}
}
} | 49.228758 | 165 | 0.409851 | [
"MIT"
] | ghuntley/Opserver | Opserver/Helpers/Cache.cs | 7,534 | C# |
using System.Xml.Serialization;
namespace OctoAwesome.Model
{
[XmlInclude(typeof(BoxItem))]
[XmlInclude(typeof(TreeItem))]
public abstract class Item
{
public Vector2 Position { get; set; }
}
}
| 17.307692 | 45 | 0.662222 | [
"MIT"
] | Krishnait86/OctoAwesome | OctoAwesome/Model/Item.cs | 227 | C# |
// This file is part of Core WF which is licensed under the MIT license.
// See LICENSE file in the project root for full license information.
namespace System.Activities.XamlIntegration
{
using System;
using System.Text;
using System.Activities;
using System.Activities.Statements;
using System.Activities.Validation;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Collections.Generic;
using Microsoft.VisualBasic.Activities;
using Microsoft.VisualBasic;
using System.Windows.Markup;
using System.Xaml;
using System.IO;
using System.Activities.Expressions;
using System.Activities.Runtime;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Security.Permissions;
using System.Globalization;
using System.Linq.Expressions;
using System.Activities.Internals;
using System.Linq;
public class TextExpressionCompiler
{
static string typedDataContextName = "_TypedDataContext";
static string expressionGetString = "__Expr{0}Get";
static string expressionSetString = "__Expr{0}Set";
static string expressionStatementString = "__Expr{0}Statement";
static string expressionGetTreeString = "__Expr{0}GetTree";
static string getValueTypeValuesString = "GetValueTypeValues";
static string setValueTypeValuesString = "SetValueTypeValues";
static string valueTypeAccessorString = "ValueType_";
static string forReadOnly = "_ForReadOnly";
static string xamlIntegrationNamespace = "System.Activities.XamlIntegration";
static string rootActivityFieldName = "rootActivity";
static string dataContextActivitiesFieldName = "dataContextActivities";
static string forImplementationName = "forImplementation";
static CodeAttributeDeclaration generatedCodeAttribute;
static CodeAttributeDeclaration browsableCodeAttribute;
static CodeAttributeDeclaration editorBrowsableCodeAttribute;
static string csharpLambdaString = "() => ";
static string vbLambdaString = "Function() ";
static string locationsOffsetFieldName = "locationsOffset";
static string expectedLocationsCountFieldName = "expectedLocationsCount";
Dictionary<int, IList<string>> expressionIdToLocationReferences = new Dictionary<int, IList<string>>();
string activityFullName;
int nextContextId;
bool? isCS = null;
bool? isVB = null;
bool generateSource;
TextExpressionCompilerSettings settings;
List<CompiledExpressionDescriptor> expressionDescriptors;
Stack<CompiledDataContextDescriptor> compiledDataContexts;
CodeNamespace codeNamespace;
CodeTypeDeclaration classDeclaration;
CodeCompileUnit compileUnit;
string fileName = null;
// Dictionary of namespace name => [Line#]
Dictionary<string, int> lineNumbersForNSes;
Dictionary<string, int> lineNumbersForNSesForImpl;
public TextExpressionCompiler(TextExpressionCompilerSettings settings)
{
if (settings == null)
{
throw FxTrace.Exception.ArgumentNull(nameof(settings));
}
if (settings.Activity == null)
{
throw FxTrace.Exception.Argument(nameof(settings), SR.TextExpressionCompilerActivityRequired);
}
if (settings.ActivityName == null)
{
throw FxTrace.Exception.Argument(nameof(settings), SR.TextExpressionCompilerActivityNameRequired);
}
if (settings.Language == null)
{
throw FxTrace.Exception.Argument(nameof(settings), SR.TextExpressionCompilerLanguageRequired);
}
this.expressionDescriptors = new List<CompiledExpressionDescriptor>();
this.compiledDataContexts = new Stack<CompiledDataContextDescriptor>();
this.nextContextId = 0;
this.settings = settings;
this.activityFullName = activityFullName = GetActivityFullName(settings);
this.generateSource = this.settings.AlwaysGenerateSource;
this.lineNumbersForNSes = new Dictionary<string, int>();
this.lineNumbersForNSesForImpl = new Dictionary<string, int>();
}
bool IsCS
{
get
{
if (!isCS.HasValue)
{
isCS = TextExpression.LanguagesAreEqual(this.settings.Language, "C#");
}
return isCS.Value;
}
}
bool IsVB
{
get
{
if (!isVB.HasValue)
{
isVB = TextExpression.LanguagesAreEqual(this.settings.Language, "VB");
}
return isVB.Value;
}
}
bool InVariableScopeArgument
{
get;
set;
}
static CodeAttributeDeclaration GeneratedCodeAttribute
{
get
{
if (generatedCodeAttribute == null)
{
AssemblyName currentAssemblyName = new AssemblyName(Assembly.GetExecutingAssembly().FullName);
generatedCodeAttribute = new CodeAttributeDeclaration(
new CodeTypeReference(typeof(GeneratedCodeAttribute)),
new CodeAttributeArgument(new CodePrimitiveExpression(currentAssemblyName.Name)),
new CodeAttributeArgument(new CodePrimitiveExpression(currentAssemblyName.Version.ToString())));
}
return generatedCodeAttribute;
}
}
static CodeAttributeDeclaration BrowsableCodeAttribute
{
get
{
if (browsableCodeAttribute == null)
{
browsableCodeAttribute = new CodeAttributeDeclaration(
new CodeTypeReference(typeof(BrowsableAttribute)),
new CodeAttributeArgument(new CodePrimitiveExpression(false)));
}
return browsableCodeAttribute;
}
}
static CodeAttributeDeclaration EditorBrowsableCodeAttribute
{
get
{
if (editorBrowsableCodeAttribute == null)
{
editorBrowsableCodeAttribute = new CodeAttributeDeclaration(
new CodeTypeReference(typeof(EditorBrowsableAttribute)),
new CodeAttributeArgument(new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(EditorBrowsableState))), "Never")));
}
return editorBrowsableCodeAttribute;
}
}
public bool GenerateSource(TextWriter textWriter)
{
if (textWriter == null)
{
throw FxTrace.Exception.ArgumentNull(nameof(textWriter));
}
Parse();
if (this.generateSource)
{
WriteCode(textWriter);
return true;
}
return false;
}
public TextExpressionCompilerResults Compile()
{
Parse();
if (this.generateSource)
{
return CompileInMemory();
}
return new TextExpressionCompilerResults();
}
void Parse()
{
if (!this.settings.Activity.IsMetadataCached)
{
IList<ValidationError> validationErrors = null;
try
{
ActivityUtilities.CacheRootMetadata(this.settings.Activity, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CompiledExpressionsCacheMetadataException(this.settings.Activity.GetType().AssemblyQualifiedName, e.ToString())));
}
}
this.compileUnit = new CodeCompileUnit();
this.codeNamespace = GenerateCodeNamespace();
this.classDeclaration = GenerateClass();
this.codeNamespace.Types.Add(classDeclaration);
this.compileUnit.Namespaces.Add(this.codeNamespace);
//
// Generate data contexts with properties and expression methods
// Use the shared, public tree walk for expressions routine for consistency.
ExpressionCompilerActivityVisitor visitor = new ExpressionCompilerActivityVisitor(this)
{
NextExpressionId = 0,
};
try
{
visitor.Visit(this.settings.Activity, this.settings.ForImplementation);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
//
// Note that unlike the above where the exception from CacheMetadata is always going to be from the user's code
// an exception here is more likely to be from our code and unexpected. However it could be from user code in some cases.
// Output a message that attempts to normalize this and presents enough info to the user to determine if they can take action.
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CompiledExpressionsActivityException(e.GetType().FullName, this.settings.Activity.GetType().AssemblyQualifiedName, e.ToString())));
}
if (this.generateSource)
{
GenerateInvokeExpressionMethod(true);
GenerateInvokeExpressionMethod(false);
GenerateCanExecuteMethod();
GenerateGetRequiredLocationsMethod();
GenerateGetExpressionTreeForExpressionMethod();
}
}
void OnRootActivity()
{
//
// Always generate a CDC for the root
// This will contain expressions for the default value of the root arguments
// These expressions cannot see other root arguments or variables so they need
// to be at the very root, before we add any properties
PushDataContextDescriptor();
}
void OnAfterRootActivity()
{
//
// First pop the root arguments descriptor pushed in OnAfterRootArguments
PopDataContextDescriptor();
//
// If we are walking the implementation there will be a second root context descriptor
// that holds the member declarations for root arguments.
// This isn't generatedwhen walking the public surface
if (this.settings.ForImplementation)
{
PopDataContextDescriptor();
}
}
void OnAfterRootArguments(Activity activity)
{
//
// Generate the properties for root arguments in a context below the context
// that contains the default expressions for the root arguments
CompiledDataContextDescriptor contextDescriptor = PushDataContextDescriptor();
if (activity.RuntimeArguments != null && activity.RuntimeArguments.Count > 0)
{
//
// Walk the arguments
foreach (RuntimeArgument runtimeArgument in activity.RuntimeArguments)
{
if (runtimeArgument.IsBound)
{
AddMember(runtimeArgument.Name, runtimeArgument.Type, contextDescriptor);
}
}
}
}
void OnActivityDelegateScope()
{
PushDataContextDescriptor();
}
void OnDelegateArgument(RuntimeDelegateArgument delegateArgument)
{
AddMember(delegateArgument.BoundArgument.Name, delegateArgument.BoundArgument.Type, this.compiledDataContexts.Peek());
}
void OnAfterActivityDelegateScope()
{
PopDataContextDescriptor();
}
void OnVariableScope(Activity activity)
{
CompiledDataContextDescriptor contextDescriptor = PushDataContextDescriptor();
//
// Generate the variable accessors
foreach (Variable v in activity.RuntimeVariables)
{
AddMember(v.Name, v.Type, contextDescriptor);
}
}
void OnRootImplementationScope(Activity activity, out CompiledDataContextDescriptor rootArgumentAccessorContext)
{
Fx.Assert(this.compiledDataContexts.Count == 2, "The stack of data contexts should contain the root argument default expression and accessor contexts");
rootArgumentAccessorContext = this.compiledDataContexts.Pop();
if (activity.RuntimeVariables != null && activity.RuntimeVariables.Count > 0)
{
this.OnVariableScope(activity);
}
}
void OnAfterRootImplementationScope(Activity activity, CompiledDataContextDescriptor rootArgumentAccessorContext)
{
if (activity.RuntimeVariables != null && activity.RuntimeVariables.Count > 0)
{
OnAfterVariableScope();
}
this.compiledDataContexts.Push(rootArgumentAccessorContext);
}
void AddMember(string name, Type type, CompiledDataContextDescriptor contextDescriptor)
{
if (IsValidTextIdentifierName(name))
{
//
// These checks will be invariantlowercase if the language is VB
if (contextDescriptor.Fields.ContainsKey(name) || contextDescriptor.Properties.ContainsKey(name))
{
if (!contextDescriptor.Duplicates.Contains(name))
{
contextDescriptor.Duplicates.Add(name.ToUpperInvariant());
}
}
else
{
MemberData memberData = new MemberData();
memberData.Type = type;
memberData.Name = name;
memberData.Index = contextDescriptor.NextMemberIndex;
if (type.IsValueType)
{
contextDescriptor.Fields.Add(name, memberData);
}
else
{
contextDescriptor.Properties.Add(name, memberData);
}
}
}
//
// Regardless of whether or not this member name is an invalid, duplicate, or valid identifier
// always increment the member count so that the indexes we generate always match
// the list that the runtime gives to the ITextExpression
// The exception here is if the name is null
if (name != null)
{
contextDescriptor.NextMemberIndex++;
}
}
void GenerateMembers(CompiledDataContextDescriptor descriptor)
{
foreach (KeyValuePair<string, MemberData> property in descriptor.Properties)
{
GenerateProperty(property.Value, descriptor);
}
if (descriptor.Fields.Count > 0)
{
foreach (KeyValuePair<string, MemberData> field in descriptor.Fields)
{
GenerateField(field.Value, descriptor);
}
CodeMemberMethod getValueTypeValuesMethod = GenerateGetValueTypeValues(descriptor);
descriptor.CodeTypeDeclaration.Members.Add(getValueTypeValuesMethod);
descriptor.CodeTypeDeclaration.Members.Add(GenerateSetValueTypeValues(descriptor));
descriptor.CodeTypeDeclarationForReadOnly.Members.Add(getValueTypeValuesMethod);
}
if (descriptor.Duplicates.Count > 0 && this.IsVB)
{
foreach (string duplicate in descriptor.Duplicates)
{
AddPropertyForDuplicates(duplicate, descriptor);
}
}
}
void GenerateField(MemberData memberData, CompiledDataContextDescriptor contextDescriptor)
{
if (contextDescriptor.Duplicates.Contains(memberData.Name))
{
return;
}
CodeMemberField accessorField = new CodeMemberField();
accessorField.Attributes = MemberAttributes.Family | MemberAttributes.Final;
accessorField.Name = memberData.Name;
accessorField.Type = new CodeTypeReference(memberData.Type);
if (IsRedefinition(memberData.Name))
{
accessorField.Attributes |= MemberAttributes.New;
}
contextDescriptor.CodeTypeDeclaration.Members.Add(accessorField);
contextDescriptor.CodeTypeDeclarationForReadOnly.Members.Add(accessorField);
}
void GenerateProperty(MemberData memberData, CompiledDataContextDescriptor contextDescriptor)
{
if (contextDescriptor.Duplicates.Contains(memberData.Name))
{
return;
}
bool isRedefinition = IsRedefinition(memberData.Name);
CodeMemberProperty accessorProperty = GenerateCodeMemberProperty(memberData, isRedefinition);
//
// Generate a get accessor that looks like this:
// return (Foo) this.GetVariableValue(contextId, locationIndexId)
CodeMethodReturnStatement getterStatement = new CodeMethodReturnStatement(
new CodeCastExpression(memberData.Type, new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
"GetVariableValue"),
new CodeBinaryOperatorExpression(
new CodePrimitiveExpression(memberData.Index),
CodeBinaryOperatorType.Add,
new CodeVariableReferenceExpression("locationsOffset")))));
accessorProperty.GetStatements.Add(getterStatement);
// Generate a set accessor that looks something like this:
// this.SetVariableValue(contextId, locationIndexId, value)
accessorProperty.SetStatements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
"SetVariableValue"),
new CodeBinaryOperatorExpression(
new CodePrimitiveExpression(memberData.Index),
CodeBinaryOperatorType.Add,
new CodeVariableReferenceExpression("locationsOffset")),
new CodePropertySetValueReferenceExpression()));
contextDescriptor.CodeTypeDeclaration.Members.Add(accessorProperty);
//
// Create another property for the read only class.
// This will only have a getter so we can't just re-use the property from above
CodeMemberProperty accessorPropertyForReadOnly = GenerateCodeMemberProperty(memberData, isRedefinition);
//
// OK to share the getter statement from above
accessorPropertyForReadOnly.GetStatements.Add(getterStatement);
contextDescriptor.CodeTypeDeclarationForReadOnly.Members.Add(accessorPropertyForReadOnly);
}
CodeMemberProperty GenerateCodeMemberProperty(MemberData memberData, bool isRedefinition)
{
CodeMemberProperty accessorProperty = new CodeMemberProperty();
accessorProperty.Attributes = MemberAttributes.Family | MemberAttributes.Final;
accessorProperty.Name = memberData.Name;
accessorProperty.Type = new CodeTypeReference(memberData.Type);
if (isRedefinition)
{
accessorProperty.Attributes |= MemberAttributes.New;
}
return accessorProperty;
}
void AddPropertyForDuplicates(string name, CompiledDataContextDescriptor contextDescriptor)
{
CodeMemberProperty accessorProperty = new CodeMemberProperty();
accessorProperty.Attributes = MemberAttributes.Family | MemberAttributes.Final;
accessorProperty.Name = name;
accessorProperty.Type = new CodeTypeReference(typeof(object));
CodeThrowExceptionStatement exception = new CodeThrowExceptionStatement(
new CodeObjectCreateExpression(typeof(InvalidOperationException), new CodePrimitiveExpression(SR.CompiledExpressionsDuplicateName(name))));
accessorProperty.GetStatements.Add(exception);
accessorProperty.SetStatements.Add(exception);
contextDescriptor.CodeTypeDeclaration.Members.Add(accessorProperty);
//
// Create another property for the read only class.
// This will only have a getter so we can't just re-use the property from above
CodeMemberProperty accessorPropertyForReadOnly = new CodeMemberProperty();
accessorPropertyForReadOnly.Attributes = MemberAttributes.Family | MemberAttributes.Final;
accessorPropertyForReadOnly.Name = name;
accessorPropertyForReadOnly.Type = new CodeTypeReference(typeof(object));
//
// OK to share the exception from above
accessorPropertyForReadOnly.GetStatements.Add(exception);
contextDescriptor.CodeTypeDeclarationForReadOnly.Members.Add(accessorPropertyForReadOnly);
}
[Fx.Tag.SecurityNote(Critical = "Critical because we are accessing CodeDom.",
Safe = "Safe because we are demanding FullTrust")]
[SecuritySafeCritical]
////[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
bool IsValidTextIdentifierName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
if (this.settings.LogSourceGenerationMessage != null)
{
this.settings.LogSourceGenerationMessage(SR.CompiledExpressionsIgnoringUnnamedVariable);
}
return false;
}
if (!CodeDomProvider.CreateProvider(this.settings.Language).IsValidIdentifier(name))
{
if (this.settings.LogSourceGenerationMessage != null)
{
this.settings.LogSourceGenerationMessage(SR.CompiledExpressionsIgnoringInvalidIdentifierVariable(name));
}
return false;
}
return true;
}
bool IsRedefinition(string variableName)
{
if (this.compiledDataContexts == null)
{
return false;
}
foreach (CompiledDataContextDescriptor contextDescriptor in this.compiledDataContexts)
{
foreach (KeyValuePair<string, MemberData> field in contextDescriptor.Fields)
{
if (NamesMatch(variableName, field.Key))
{
return true;
}
}
foreach (KeyValuePair<string, MemberData> property in contextDescriptor.Properties)
{
if (NamesMatch(variableName, property.Key))
{
return true;
}
}
}
return false;
}
bool NamesMatch(string toCheck, string current)
{
if (IsVB && string.Compare(toCheck, current, true, CultureInfo.CurrentCulture) == 0)
{
return true;
}
else if (!IsVB && toCheck == current)
{
return true;
}
return false;
}
void OnAfterVariableScope()
{
PopDataContextDescriptor();
}
void OnITextExpressionFound(Activity activity, ExpressionCompilerActivityVisitor visitor)
{
CompiledDataContextDescriptor contextDescriptor = null;
CompiledDataContextDescriptor currentContextDescriptor = this.compiledDataContexts.Peek();
if (this.InVariableScopeArgument)
{
//
// Temporarily popping the stack so don't use PopDataContextDescriptor
// because that is for when the descriptor is done being built
this.compiledDataContexts.Pop();
contextDescriptor = PushDataContextDescriptor();
}
else
{
contextDescriptor = currentContextDescriptor;
}
if (TryGenerateExpressionCode(activity, contextDescriptor, visitor.NextExpressionId, this.settings.Language))
{
expressionIdToLocationReferences.Add(visitor.NextExpressionId, this.FindLocationReferences(activity));
visitor.NextExpressionId++;
this.generateSource = true;
}
if (this.InVariableScopeArgument)
{
PopDataContextDescriptor();
this.compiledDataContexts.Push(currentContextDescriptor);
}
}
IList<string> FindLocationReferences(Activity activity)
{
ActivityWithResult boundExpression;
LocationReference locationReference;
List<string> requiredLocationReferences = new List<string>();
foreach (RuntimeArgument runtimeArgument in activity.RuntimeArguments)
{
boundExpression = runtimeArgument.BoundArgument.Expression;
if (boundExpression != null && boundExpression is ILocationReferenceWrapper)
{
locationReference = ((ILocationReferenceWrapper)boundExpression).LocationReference;
if (locationReference != null)
{
requiredLocationReferences.Add(locationReference.Name);
}
}
}
return requiredLocationReferences;
}
CodeTypeDeclaration GenerateClass()
{
CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(this.settings.ActivityName);
classDeclaration.BaseTypes.Add(new CodeTypeReference(typeof(ICompiledExpressionRoot)));
classDeclaration.IsPartial = this.settings.GenerateAsPartialClass;
CodeMemberField compiledRootField = new CodeMemberField(new CodeTypeReference(typeof(Activity)), rootActivityFieldName);
classDeclaration.Members.Add(compiledRootField);
CodeMemberMethod languageProperty = new CodeMemberMethod();
languageProperty.Attributes = MemberAttributes.Final | MemberAttributes.Public;
languageProperty.Name = "GetLanguage";
languageProperty.ReturnType = new CodeTypeReference(typeof(string));
languageProperty.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(this.settings.Language)));
languageProperty.ImplementationTypes.Add(new CodeTypeReference(typeof(ICompiledExpressionRoot)));
languageProperty.CustomAttributes.Add(GeneratedCodeAttribute);
languageProperty.CustomAttributes.Add(BrowsableCodeAttribute);
languageProperty.CustomAttributes.Add(EditorBrowsableCodeAttribute);
classDeclaration.Members.Add(languageProperty);
CodeMemberField dataContextActivitiesField = new CodeMemberField();
dataContextActivitiesField.Attributes = MemberAttributes.Private;
dataContextActivitiesField.Name = dataContextActivitiesFieldName;
dataContextActivitiesField.Type = new CodeTypeReference(typeof(object));
classDeclaration.Members.Add(dataContextActivitiesField);
CodeMemberField forImplementationField = new CodeMemberField();
forImplementationField.Attributes = MemberAttributes.Private;
forImplementationField.Name = forImplementationName;
forImplementationField.Type = new CodeTypeReference(typeof(bool));
forImplementationField.InitExpression = new CodePrimitiveExpression(this.settings.ForImplementation);
classDeclaration.Members.Add(forImplementationField);
if (!this.settings.GenerateAsPartialClass)
{
classDeclaration.Members.Add(GenerateCompiledExpressionRootConstructor());
}
return classDeclaration;
}
CodeConstructor GenerateCompiledExpressionRootConstructor()
{
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
constructor.Parameters.Add(
new CodeParameterDeclarationExpression(
new CodeTypeReference(typeof(Activity)),
rootActivityFieldName));
CodeBinaryOperatorExpression nullArgumentExpression = new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression(rootActivityFieldName),
CodeBinaryOperatorType.IdentityEquality,
new CodePrimitiveExpression(null));
CodeConditionStatement nullArgumentCondition = new CodeConditionStatement(
nullArgumentExpression,
new CodeThrowExceptionStatement(
new CodeObjectCreateExpression(
new CodeTypeReference(typeof(ArgumentNullException)),
new CodePrimitiveExpression(rootActivityFieldName))));
constructor.Statements.Add(nullArgumentCondition);
constructor.Statements.Add(
new CodeAssignStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
rootActivityFieldName),
new CodeVariableReferenceExpression(rootActivityFieldName)));
return constructor;
}
Dictionary<string, int> GetCacheIndicies()
{
Dictionary<string, int> contexts = new Dictionary<string, int>();
int currentIndex = 0;
foreach (CompiledExpressionDescriptor descriptor in this.expressionDescriptors)
{
string name = descriptor.TypeName;
if (!contexts.ContainsKey(name))
{
contexts.Add(name, currentIndex++);
}
}
return contexts;
}
void GenerateGetRequiredLocationsMethod()
{
CodeMemberMethod getLocationsMethod = new CodeMemberMethod();
getLocationsMethod.Name = "GetRequiredLocations";
getLocationsMethod.Attributes = MemberAttributes.Final | MemberAttributes.Public;
getLocationsMethod.CustomAttributes.Add(GeneratedCodeAttribute);
getLocationsMethod.CustomAttributes.Add(BrowsableCodeAttribute);
getLocationsMethod.CustomAttributes.Add(EditorBrowsableCodeAttribute);
getLocationsMethod.ImplementationTypes.Add(new CodeTypeReference(typeof(ICompiledExpressionRoot)));
getLocationsMethod.ReturnType = new CodeTypeReference(typeof(IList<string>));
getLocationsMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "expressionId"));
if (this.IsVB)
{
GenerateRequiredLocationsBody(getLocationsMethod);
}
else
{
GenerateEmptyRequiredLocationsBody(getLocationsMethod);
}
classDeclaration.Members.Add(getLocationsMethod);
}
void GenerateEmptyRequiredLocationsBody(CodeMemberMethod getLocationsMethod)
{
getLocationsMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
}
void GenerateRequiredLocationsBody(CodeMemberMethod getLocationsMethod)
{
CodeVariableDeclarationStatement returnLocationsVar = new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(List<string>)),
"returnLocations",
new CodeObjectCreateExpression(new CodeTypeReference(typeof(List<string>))));
getLocationsMethod.Statements.Add(returnLocationsVar);
foreach (CompiledExpressionDescriptor descriptor in expressionDescriptors)
{
IList<string> requiredLocations = null;
bool found = expressionIdToLocationReferences.TryGetValue(descriptor.Id, out requiredLocations);
if (!found)
{
return;
}
CodeStatement[] conditionStatements = null;
conditionStatements = GetRequiredLocationsConditionStatements(requiredLocations);
CodeBinaryOperatorExpression idExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("expressionId"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(descriptor.Id));
CodeConditionStatement idCondition = new CodeConditionStatement(idExpression, conditionStatements);
getLocationsMethod.Statements.Add(idCondition);
}
getLocationsMethod.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("returnLocations")));
}
static CodeStatement[] GetRequiredLocationsConditionStatements(IList<string> requiredLocations)
{
CodeStatementCollection statementCollection = new CodeStatementCollection();
foreach (string locationName in requiredLocations)
{
CodeMethodInvokeExpression invokeValidateExpression = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("returnLocations"), "Add"),
new CodePrimitiveExpression(locationName));
statementCollection.Add(invokeValidateExpression);
}
CodeStatement[] returnStatements = new CodeStatement[statementCollection.Count];
statementCollection.CopyTo(returnStatements, 0);
return returnStatements;
}
void GenerateGetExpressionTreeForExpressionMethod()
{
CodeMemberMethod getExpressionTreeForExpressionMethod = new CodeMemberMethod();
getExpressionTreeForExpressionMethod.Name = "GetExpressionTreeForExpression";
getExpressionTreeForExpressionMethod.Attributes = MemberAttributes.Final | MemberAttributes.Public;
getExpressionTreeForExpressionMethod.ReturnType = new CodeTypeReference(typeof(Expression));
getExpressionTreeForExpressionMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "expressionId"));
getExpressionTreeForExpressionMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IList<LocationReference>)), "locationReferences"));
getExpressionTreeForExpressionMethod.ImplementationTypes.Add(new CodeTypeReference(typeof(ICompiledExpressionRoot)));
// Mark this type as tool generated code
getExpressionTreeForExpressionMethod.CustomAttributes.Add(GeneratedCodeAttribute);
// Mark it as Browsable(false)
// Note that this does not prevent intellisense within a single project, just at the metadata level
getExpressionTreeForExpressionMethod.CustomAttributes.Add(BrowsableCodeAttribute);
// Mark it as EditorBrowsable(EditorBrowsableState.Never)
// Note that this does not prevent intellisense within a single project, just at the metadata level
getExpressionTreeForExpressionMethod.CustomAttributes.Add(EditorBrowsableCodeAttribute);
foreach (CompiledExpressionDescriptor descriptor in expressionDescriptors)
{
CodeMethodReturnStatement conditionStatement = new CodeMethodReturnStatement(
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeObjectCreateExpression(new CodeTypeReference(descriptor.TypeName), new CodeExpression[] { new CodeVariableReferenceExpression("locationReferences") }),
descriptor.GetExpressionTreeMethodName)));
CodeBinaryOperatorExpression idExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("expressionId"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(descriptor.Id));
CodeConditionStatement idCondition = new CodeConditionStatement(idExpression, conditionStatement);
getExpressionTreeForExpressionMethod.Statements.Add(idCondition);
}
getExpressionTreeForExpressionMethod.Statements.Add(new CodeMethodReturnStatement(
new CodePrimitiveExpression(null)));
classDeclaration.Members.Add(getExpressionTreeForExpressionMethod);
}
void GenerateInvokeExpressionMethod(bool withLocationReferences)
{
CodeMemberMethod invokeExpressionMethod = new CodeMemberMethod();
invokeExpressionMethod.Name = "InvokeExpression";
invokeExpressionMethod.Attributes = MemberAttributes.Final | MemberAttributes.Public;
invokeExpressionMethod.CustomAttributes.Add(GeneratedCodeAttribute);
invokeExpressionMethod.CustomAttributes.Add(BrowsableCodeAttribute);
invokeExpressionMethod.CustomAttributes.Add(EditorBrowsableCodeAttribute);
invokeExpressionMethod.ImplementationTypes.Add(new CodeTypeReference(typeof(ICompiledExpressionRoot)));
invokeExpressionMethod.ReturnType = new CodeTypeReference(typeof(object));
invokeExpressionMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "expressionId"));
if (withLocationReferences)
{
invokeExpressionMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IList<LocationReference>)), "locations"));
invokeExpressionMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(ActivityContext)), "activityContext"));
}
else
{
invokeExpressionMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IList<Location>)), "locations"));
}
if (this.settings.GenerateAsPartialClass)
{
invokeExpressionMethod.Statements.Add(GenerateInitializeDataContextActivity());
}
if (withLocationReferences)
{
if (this.expressionDescriptors != null && this.expressionDescriptors.Count > 0)
{
//
// We only generate the helper method on the root data context/context 0
// No need to have it on all contexts. This is just a slight of hand
// so that we don't need to make GetDataContextActivities public on CompiledDataContext.
invokeExpressionMethod.Statements.Add(GenerateDataContextActivitiesCheck(this.expressionDescriptors[0]));
}
}
Dictionary<string, int> cacheIndicies = GetCacheIndicies();
foreach (CompiledExpressionDescriptor descriptor in expressionDescriptors)
{
//
// if ((expressionId == [descriptor.Id]))
// {
// if (!CheckExpressionText(expressionId, activityContext)
// {
// throw new Exception();
// }
// System.Activities.XamlIntegration.CompiledDataContext[] cachedCompiledDataContext = Workflow1_TypedDataContext1_ForReadOnly.GetCompiledDataContextCacheHelper(this, activityContext, 1);
// if ((cachedCompiledDataContext[0] == null))
// {
// cachedCompiledDataContext[0] = new Workflow1_TypedDataContext1_ForReadOnly(locations, activityContext);
// }
// Workflow1_TypedDataContext1_ForReadOnly valDataContext0 = ((Workflow1_TypedDataContext1_ForReadOnly)(cachedCompiledDataContext[0]));
// return valDataContext0.ValueType___Expr0Get();
// }
//
CodeStatement[] conditionStatements = null;
if (descriptor.IsReference)
{
conditionStatements = GenerateReferenceExpressionInvocation(descriptor, withLocationReferences, cacheIndicies);
}
else if (descriptor.IsValue)
{
conditionStatements = GenerateValueExpressionInvocation(descriptor, withLocationReferences, cacheIndicies);
}
else if (descriptor.IsStatement)
{
conditionStatements = GenerateStatementInvocation(descriptor, withLocationReferences, cacheIndicies);
}
CodeBinaryOperatorExpression idExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("expressionId"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(descriptor.Id));
CodeConditionStatement idCondition = new CodeConditionStatement(idExpression, conditionStatements);
invokeExpressionMethod.Statements.Add(idCondition);
}
invokeExpressionMethod.Statements.Add(new CodeMethodReturnStatement(
new CodePrimitiveExpression(null)));
classDeclaration.Members.Add(invokeExpressionMethod);
}
CodeConditionStatement GenerateDataContextActivitiesCheck(CompiledExpressionDescriptor descriptor)
{
CodeBinaryOperatorExpression dataContextActivitiesNullExpression = new CodeBinaryOperatorExpression(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), dataContextActivitiesFieldName),
CodeBinaryOperatorType.IdentityEquality,
new CodePrimitiveExpression(null));
CodeConditionStatement dataContextActivitiesNullStatement = new CodeConditionStatement(
dataContextActivitiesNullExpression,
new CodeAssignStatement(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), dataContextActivitiesFieldName),
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(new CodeTypeReference(descriptor.TypeName)),
"GetDataContextActivitiesHelper"),
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
rootActivityFieldName),
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
forImplementationName))));
return dataContextActivitiesNullStatement;
}
CodeStatement GenerateInitializeDataContextActivity()
{
//
// if (this.rootActivity == null)
// {
// this.rootActivity == this;
// }
CodeBinaryOperatorExpression dataContextActivityExpression = new CodeBinaryOperatorExpression(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
rootActivityFieldName),
CodeBinaryOperatorType.IdentityEquality,
new CodePrimitiveExpression(null));
CodeConditionStatement dataContextActivityCheck = new CodeConditionStatement(
dataContextActivityExpression,
new CodeAssignStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
rootActivityFieldName),
new CodeThisReferenceExpression()));
return dataContextActivityCheck;
}
void GenerateGetDataContextVariable(CompiledExpressionDescriptor descriptor, CodeVariableDeclarationStatement dataContextVariable, CodeStatementCollection statements, bool withLocationReferences, Dictionary<string, int> cacheIndicies)
{
CodeObjectCreateExpression dataContext = GenerateDataContextCreateExpression(descriptor.TypeName, withLocationReferences);
if (withLocationReferences)
{
//
// System.Activities.XamlIntegration.CompiledDataContext[] cachedCompiledDataContext = CompiledExpressions_TypedDataContext2.GetCompiledDataContextCacheHelper(this, activityContext, 2);
// if ((cachedCompiledDataContext[1] == null))
// {
// if (!CompiledExpressions_TypedDataContext2.Validate(locations, activityContext))
// {
// return false;
// }
// cachedCompiledDataContext[1] = new CompiledExpressions_TypedDataContext2(locations, activityContext);
// }
//
CodeVariableDeclarationStatement cachedCompiledDataContextArray = new CodeVariableDeclarationStatement(
typeof(CompiledDataContext[]),
"cachedCompiledDataContext",
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(descriptor.TypeName),
"GetCompiledDataContextCacheHelper"),
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
dataContextActivitiesFieldName),
new CodeVariableReferenceExpression("activityContext"),
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
rootActivityFieldName),
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
forImplementationName),
new CodePrimitiveExpression(cacheIndicies.Count)));
CodeIndexerExpression compiledDataContextIndexer = new CodeIndexerExpression(
new CodeVariableReferenceExpression("cachedCompiledDataContext"),
new CodePrimitiveExpression(cacheIndicies[descriptor.TypeName]));
//
// if (cachedCompiledDataContext[index] == null)
// {
// cachedCompiledDataContext[index] = new TCDC(locations, activityContext);
// }
//
CodeBinaryOperatorExpression nullCacheItemExpression = new CodeBinaryOperatorExpression(
compiledDataContextIndexer,
CodeBinaryOperatorType.IdentityEquality,
new CodePrimitiveExpression(null));
CodeAssignStatement cacheIndexInitializer = new CodeAssignStatement(
compiledDataContextIndexer,
dataContext);
CodeConditionStatement conditionStatement = new CodeConditionStatement(
nullCacheItemExpression,
cacheIndexInitializer);
//
// [compiledDataContextVariable] = cachedCompiledDataContext[index]
//
dataContextVariable.InitExpression = new CodeCastExpression(descriptor.TypeName, compiledDataContextIndexer);
statements.Add(cachedCompiledDataContextArray);
statements.Add(conditionStatement);
}
else
{
//
// [compiledDataContextVariable] = new [compiledDataContextType](locations);
//
dataContextVariable.InitExpression = dataContext;
}
}
CodeStatement[] GenerateReferenceExpressionInvocation(CompiledExpressionDescriptor descriptor, bool withLocationReferences, Dictionary<string, int> cacheIndicies)
{
string indexString = descriptor.Id.ToString(CultureInfo.InvariantCulture);
string dataContextVariableName = "refDataContext" + indexString;
CodeVariableDeclarationStatement dataContextVariable = new CodeVariableDeclarationStatement(
new CodeTypeReference(descriptor.TypeName), dataContextVariableName);
CodeStatementCollection compiledDataContextStatements = new CodeStatementCollection();
GenerateGetDataContextVariable(descriptor, dataContextVariable, compiledDataContextStatements, withLocationReferences, cacheIndicies);
compiledDataContextStatements.Add(dataContextVariable);
CodeExpression getExpression = null;
CodeExpression setExpression = null;
if (this.IsVB)
{
getExpression = new CodeDelegateCreateExpression(
new CodeTypeReference(descriptor.TypeName),
new CodeVariableReferenceExpression(dataContextVariableName),
descriptor.GetMethodName);
setExpression = new CodeDelegateCreateExpression(
new CodeTypeReference(descriptor.TypeName),
new CodeVariableReferenceExpression(dataContextVariableName),
descriptor.SetMethodName);
}
else
{
getExpression = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dataContextVariableName), descriptor.GetMethodName);
setExpression = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dataContextVariableName), descriptor.SetMethodName);
}
CodeMethodReferenceExpression getLocationMethod = new CodeMethodReferenceExpression(
new CodeVariableReferenceExpression(dataContextVariableName),
"GetLocation",
new CodeTypeReference[] { new CodeTypeReference(descriptor.ResultType) });
CodeExpression[] getLocationParameters = null;
if (withLocationReferences)
{
getLocationParameters = new CodeExpression[] {
getExpression,
setExpression,
new CodeVariableReferenceExpression("expressionId"),
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
rootActivityFieldName),
new CodeVariableReferenceExpression("activityContext") };
}
else
{
getLocationParameters = new CodeExpression[] {
getExpression,
setExpression };
}
CodeMethodInvokeExpression getLocationExpression = new CodeMethodInvokeExpression(
getLocationMethod,
getLocationParameters);
CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(getLocationExpression);
compiledDataContextStatements.Add(returnStatement);
CodeStatement[] returnStatements = new CodeStatement[compiledDataContextStatements.Count];
compiledDataContextStatements.CopyTo(returnStatements, 0);
return returnStatements;
}
CodeStatement[] GenerateValueExpressionInvocation(CompiledExpressionDescriptor descriptor, bool withLocationReferences, Dictionary<string, int> cacheIndicies)
{
CodeStatementCollection compiledDataContextStatements = new CodeStatementCollection();
string indexString = descriptor.Id.ToString(CultureInfo.InvariantCulture);
string dataContextVariableName = "valDataContext" + indexString;
CodeVariableDeclarationStatement dataContextVariable = new CodeVariableDeclarationStatement(
new CodeTypeReference(descriptor.TypeName), dataContextVariableName);
GenerateGetDataContextVariable(descriptor, dataContextVariable, compiledDataContextStatements, withLocationReferences, cacheIndicies);
compiledDataContextStatements.Add(dataContextVariable);
CodeMethodInvokeExpression expressionInvoke = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeVariableReferenceExpression(dataContextVariableName), descriptor.GetMethodName));
CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(expressionInvoke);
compiledDataContextStatements.Add(returnStatement);
CodeStatement[] returnStatements = new CodeStatement[compiledDataContextStatements.Count];
compiledDataContextStatements.CopyTo(returnStatements, 0);
return returnStatements;
}
CodeStatement[] GenerateStatementInvocation(CompiledExpressionDescriptor descriptor, bool withLocationReferences, Dictionary<string, int> cacheIndicies)
{
string indexString = descriptor.Id.ToString(CultureInfo.InvariantCulture);
string dataContextVariableName = "valDataContext" + indexString;
CodeVariableDeclarationStatement dataContextVariable = new CodeVariableDeclarationStatement(
new CodeTypeReference(descriptor.TypeName), dataContextVariableName);
CodeStatementCollection compiledDataContextStatements = new CodeStatementCollection();
GenerateGetDataContextVariable(descriptor, dataContextVariable, compiledDataContextStatements, withLocationReferences, cacheIndicies);
compiledDataContextStatements.Add(dataContextVariable);
CodeMethodInvokeExpression expressionInvoke = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeVariableReferenceExpression(dataContextVariableName), descriptor.StatementMethodName));
CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(new CodePrimitiveExpression(null));
compiledDataContextStatements.Add(expressionInvoke);
compiledDataContextStatements.Add(returnStatement);
CodeStatement[] returnStatements = new CodeStatement[compiledDataContextStatements.Count];
compiledDataContextStatements.CopyTo(returnStatements, 0);
return returnStatements;
}
void GenerateCanExecuteMethod()
{
CodeMemberMethod isValidMethod = new CodeMemberMethod();
isValidMethod.Name = "CanExecuteExpression";
isValidMethod.ReturnType = new CodeTypeReference(typeof(bool));
isValidMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
isValidMethod.CustomAttributes.Add(GeneratedCodeAttribute);
isValidMethod.CustomAttributes.Add(BrowsableCodeAttribute);
isValidMethod.CustomAttributes.Add(EditorBrowsableCodeAttribute);
isValidMethod.ImplementationTypes.Add(new CodeTypeReference(typeof(ICompiledExpressionRoot)));
isValidMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(string)), "expressionText"));
isValidMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(bool)), "isReference"));
isValidMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IList<LocationReference>)), "locations"));
CodeParameterDeclarationExpression expressionIdParam = new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "expressionId");
expressionIdParam.Direction = FieldDirection.Out;
isValidMethod.Parameters.Add(expressionIdParam);
//
// if (((isReference == false)
// && ((expressionText == [expression text])
// && ([data context type name].Validate(locations, true) == true))))
// {
// expressionId = [id for expression text and data context];
// return true;
// }
//
foreach (CompiledExpressionDescriptor descriptor in expressionDescriptors)
{
CodeBinaryOperatorExpression checkIsReferenceExpression = new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("isReference"),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(descriptor.IsReference));
CodeBinaryOperatorExpression checkTextExpression = new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("expressionText"),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(descriptor.ExpressionText));
CodeMethodInvokeExpression invokeValidateExpression = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(descriptor.TypeName),
"Validate"),
new CodeVariableReferenceExpression("locations"),
new CodePrimitiveExpression(true),
new CodePrimitiveExpression(0));
CodeBinaryOperatorExpression checkValidateExpression = new CodeBinaryOperatorExpression(
invokeValidateExpression,
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(true));
CodeBinaryOperatorExpression checkTextAndValidateExpression = new CodeBinaryOperatorExpression(
checkTextExpression,
CodeBinaryOperatorType.BooleanAnd,
checkValidateExpression);
CodeBinaryOperatorExpression checkIsReferenceAndTextAndValidateExpression = new CodeBinaryOperatorExpression(
checkIsReferenceExpression,
CodeBinaryOperatorType.BooleanAnd,
checkTextAndValidateExpression);
CodeAssignStatement assignId = new CodeAssignStatement(
new CodeVariableReferenceExpression("expressionId"),
new CodePrimitiveExpression(descriptor.Id));
CodeConditionStatement matchCondition = new CodeConditionStatement(
checkIsReferenceAndTextAndValidateExpression);
matchCondition.TrueStatements.Add(assignId);
matchCondition.TrueStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true)));
isValidMethod.Statements.Add(matchCondition);
}
isValidMethod.Statements.Add(
new CodeAssignStatement(
new CodeVariableReferenceExpression("expressionId"),
new CodePrimitiveExpression(-1)));
isValidMethod.Statements.Add(
new CodeMethodReturnStatement(
new CodePrimitiveExpression(false)));
classDeclaration.Members.Add(isValidMethod);
}
CodeObjectCreateExpression GenerateDataContextCreateExpression(string typeName, bool withLocationReferences)
{
if (withLocationReferences)
{
return new CodeObjectCreateExpression(
new CodeTypeReference(typeName),
new CodeVariableReferenceExpression("locations"),
new CodeVariableReferenceExpression("activityContext"),
new CodePrimitiveExpression(true));
}
else
{
return new CodeObjectCreateExpression(
new CodeTypeReference(typeName),
new CodeExpression[] { new CodeVariableReferenceExpression("locations"),
new CodePrimitiveExpression(true) });
}
}
bool TryGenerateExpressionCode(Activity activity, CompiledDataContextDescriptor dataContextDescriptor, int nextExpressionId, string language)
{
ITextExpression textExpression = (ITextExpression)activity;
if (!TextExpression.LanguagesAreEqual(textExpression.Language, language)
|| string.IsNullOrWhiteSpace(textExpression.ExpressionText))
{
//
// We can only compile expressions that match the project's flavor
// and expression activities with no expressions don't need anything generated.
return false;
}
Type resultType = (activity is ActivityWithResult) ? ((ActivityWithResult)activity).ResultType : null;
string expressionText = textExpression.ExpressionText;
bool isReference = false;
bool isValue = false;
bool isStatement = false;
if (resultType == null)
{
isStatement = true;
}
else
{
isReference = TypeHelper.AreTypesCompatible(resultType, typeof(Location));
isValue = !isReference;
}
CodeTypeDeclaration typeDeclaration;
if (isValue)
{
typeDeclaration = dataContextDescriptor.CodeTypeDeclarationForReadOnly;
}
else
{
//
// Statement and reference get read/write context
typeDeclaration = dataContextDescriptor.CodeTypeDeclaration;
}
CompiledExpressionDescriptor descriptor = new CompiledExpressionDescriptor();
descriptor.TypeName = typeDeclaration.Name;
descriptor.Id = nextExpressionId;
descriptor.ExpressionText = textExpression.ExpressionText;
if (isReference)
{
if (resultType.IsGenericType)
{
resultType = resultType.GetGenericArguments()[0];
}
else
{
resultType = typeof(object);
}
}
descriptor.ResultType = resultType;
GenerateExpressionGetTreeMethod(activity, descriptor, dataContextDescriptor, isValue, isStatement, nextExpressionId);
if (isValue || isReference)
{
CodeMemberMethod expressionGetMethod = GenerateGetMethod(activity, resultType, expressionText, nextExpressionId);
typeDeclaration.Members.Add(expressionGetMethod);
CodeMemberMethod expressionGetValueTypeAccessorMethod = GenerateGetMethodWrapper(expressionGetMethod);
typeDeclaration.Members.Add(expressionGetValueTypeAccessorMethod);
descriptor.GetMethodName = expressionGetValueTypeAccessorMethod.Name;
}
if (isReference)
{
CodeMemberMethod expressionSetMethod = GenerateSetMethod(activity, resultType, expressionText, nextExpressionId);
dataContextDescriptor.CodeTypeDeclaration.Members.Add(expressionSetMethod);
CodeMemberMethod expressionSetValueTypeAccessorMethod = GenerateSetMethodWrapper(expressionSetMethod);
dataContextDescriptor.CodeTypeDeclaration.Members.Add(expressionSetValueTypeAccessorMethod);
descriptor.SetMethodName = expressionSetValueTypeAccessorMethod.Name;
}
if (isStatement)
{
CodeMemberMethod statementMethod = GenerateStatementMethod(activity, expressionText, nextExpressionId);
dataContextDescriptor.CodeTypeDeclaration.Members.Add(statementMethod);
CodeMemberMethod expressionSetValueTypeAccessorMethod = GenerateStatementMethodWrapper(statementMethod);
dataContextDescriptor.CodeTypeDeclaration.Members.Add(expressionSetValueTypeAccessorMethod);
descriptor.StatementMethodName = expressionSetValueTypeAccessorMethod.Name;
}
expressionDescriptors.Add(descriptor);
return true;
}
void GenerateExpressionGetTreeMethod(Activity activity, CompiledExpressionDescriptor expressionDescriptor, CompiledDataContextDescriptor dataContextDescriptor, bool isValue, bool isStatement, int nextExpressionId)
{
CodeMemberMethod expressionMethod = new CodeMemberMethod();
expressionMethod.Attributes = MemberAttributes.Assembly | MemberAttributes.Final;
expressionMethod.Name = string.Format(CultureInfo.InvariantCulture, expressionGetTreeString, nextExpressionId);
expressionMethod.ReturnType = new CodeTypeReference(typeof(Expression));
expressionDescriptor.GetExpressionTreeMethodName = expressionMethod.Name;
if (isStatement)
{
// Can't generate expression tree for a statement
expressionMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
dataContextDescriptor.CodeTypeDeclaration.Members.Add(expressionMethod);
return;
}
string coreExpressionText = expressionDescriptor.ExpressionText;
CodeLinePragma pragma;
AlignText(activity, ref coreExpressionText, out pragma);
Type returnType = typeof(Expression<>).MakeGenericType(typeof(Func<>).MakeGenericType(expressionDescriptor.ResultType));
string expressionText = null;
if (IsVB)
{
expressionText = string.Concat(vbLambdaString, coreExpressionText);
}
else if (IsCS)
{
expressionText = string.Concat(csharpLambdaString, coreExpressionText);
}
if (expressionText != null)
{
CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(returnType, "expression", new CodeSnippetExpression(expressionText));
statement.LinePragma = pragma;
expressionMethod.Statements.Add(statement);
CodeMethodInvokeExpression invokeExpression = new CodeMethodInvokeExpression(
new CodeBaseReferenceExpression(),
"RewriteExpressionTree",
new CodeExpression[] { new CodeVariableReferenceExpression("expression") });
expressionMethod.Statements.Add(new CodeMethodReturnStatement(invokeExpression));
}
else
{
expressionMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
}
if (isValue)
{
dataContextDescriptor.CodeTypeDeclarationForReadOnly.Members.Add(expressionMethod);
}
else
{
dataContextDescriptor.CodeTypeDeclaration.Members.Add(expressionMethod);
}
}
CodeMemberMethod GenerateGetMethod(Activity activity, Type resultType, string expressionText, int nextExpressionId)
{
CodeMemberMethod expressionMethod = new CodeMemberMethod();
expressionMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
expressionMethod.Name = string.Format(CultureInfo.InvariantCulture, expressionGetString, nextExpressionId);
expressionMethod.ReturnType = new CodeTypeReference(resultType);
expressionMethod.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(Diagnostics.DebuggerHiddenAttribute))));
CodeLinePragma pragma;
AlignText(activity, ref expressionText, out pragma);
CodeStatement statement = new CodeMethodReturnStatement(new CodeSnippetExpression(expressionText));
statement.LinePragma = pragma;
expressionMethod.Statements.Add(statement);
return expressionMethod;
}
CodeMemberMethod GenerateGetMethodWrapper(CodeMemberMethod expressionMethod)
{
CodeMemberMethod wrapperMethod = new CodeMemberMethod();
wrapperMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
wrapperMethod.Name = valueTypeAccessorString + expressionMethod.Name;
wrapperMethod.ReturnType = expressionMethod.ReturnType;
wrapperMethod.Statements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
getValueTypeValuesString)));
wrapperMethod.Statements.Add(new CodeMethodReturnStatement(
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
expressionMethod.Name))));
return wrapperMethod;
}
CodeMemberMethod GenerateSetMethod(Activity activity, Type resultType, string expressionText, int nextExpressionId)
{
string paramName = "value";
if (string.Compare(expressionText, paramName, true, System.Globalization.CultureInfo.CurrentCulture) == 0)
{
paramName += "1";
}
CodeMemberMethod expressionMethod = new CodeMemberMethod();
expressionMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
expressionMethod.Name = string.Format(CultureInfo.InvariantCulture, expressionSetString, nextExpressionId);
expressionMethod.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(Diagnostics.DebuggerHiddenAttribute))));
var exprValueParam = new CodeParameterDeclarationExpression(resultType, paramName);
expressionMethod.Parameters.Add(exprValueParam);
CodeLinePragma pragma;
AlignText(activity, ref expressionText, out pragma);
CodeAssignStatement statement = new CodeAssignStatement(new CodeSnippetExpression(expressionText), new CodeArgumentReferenceExpression(paramName));
statement.LinePragma = pragma;
expressionMethod.Statements.Add(statement);
return expressionMethod;
}
CodeMemberMethod GenerateSetMethodWrapper(CodeMemberMethod expressionMethod)
{
CodeMemberMethod wrapperMethod = new CodeMemberMethod();
wrapperMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
wrapperMethod.Name = valueTypeAccessorString + expressionMethod.Name;
CodeParameterDeclarationExpression exprValueParam = new CodeParameterDeclarationExpression(expressionMethod.Parameters[0].Type, expressionMethod.Parameters[0].Name);
wrapperMethod.Parameters.Add(exprValueParam);
wrapperMethod.Statements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
getValueTypeValuesString)));
CodeMethodInvokeExpression setExpression = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
expressionMethod.Name));
setExpression.Parameters.Add(new CodeVariableReferenceExpression(expressionMethod.Parameters[0].Name));
wrapperMethod.Statements.Add(setExpression);
wrapperMethod.Statements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
setValueTypeValuesString)));
return wrapperMethod;
}
CodeMemberMethod GenerateStatementMethod(Activity activity, string expressionText, int nextExpressionId)
{
CodeMemberMethod expressionMethod = new CodeMemberMethod();
expressionMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
expressionMethod.Name = string.Format(CultureInfo.InvariantCulture, expressionStatementString, nextExpressionId);
expressionMethod.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(Diagnostics.DebuggerHiddenAttribute))));
CodeLinePragma pragma;
AlignText(activity, ref expressionText, out pragma);
CodeStatement statement = new CodeSnippetStatement(expressionText);
statement.LinePragma = pragma;
expressionMethod.Statements.Add(statement);
return expressionMethod;
}
CodeMemberMethod GenerateStatementMethodWrapper(CodeMemberMethod expressionMethod)
{
CodeMemberMethod wrapperMethod = new CodeMemberMethod();
wrapperMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
wrapperMethod.Name = valueTypeAccessorString + expressionMethod.Name;
wrapperMethod.Statements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
getValueTypeValuesString)));
CodeMethodInvokeExpression setExpression = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
expressionMethod.Name));
wrapperMethod.Statements.Add(setExpression);
wrapperMethod.Statements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
setValueTypeValuesString)));
return wrapperMethod;
}
CodeMemberMethod GenerateGetValueTypeValues(CompiledDataContextDescriptor descriptor)
{
CodeMemberMethod fetchMethod = new CodeMemberMethod();
fetchMethod.Name = getValueTypeValuesString;
fetchMethod.Attributes = MemberAttributes.Override | MemberAttributes.Family;
foreach (KeyValuePair<string, MemberData> valueField in descriptor.Fields)
{
if (descriptor.Duplicates.Contains(valueField.Key))
{
continue;
}
CodeExpression getValue = new CodeCastExpression(
valueField.Value.Type,
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
"GetVariableValue"),
new CodeBinaryOperatorExpression(
new CodePrimitiveExpression(valueField.Value.Index),
CodeBinaryOperatorType.Add,
new CodeVariableReferenceExpression("locationsOffset"))));
CodeFieldReferenceExpression fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), valueField.Key);
fetchMethod.Statements.Add(
new CodeAssignStatement(fieldReference, getValue));
}
fetchMethod.Statements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeBaseReferenceExpression(),
fetchMethod.Name)));
return fetchMethod;
}
CodeMemberMethod GenerateSetValueTypeValues(CompiledDataContextDescriptor descriptor)
{
CodeMemberMethod pushMethod = new CodeMemberMethod();
pushMethod.Name = setValueTypeValuesString;
pushMethod.Attributes = MemberAttributes.Override | MemberAttributes.Family;
foreach (KeyValuePair<string, MemberData> valueField in descriptor.Fields)
{
if (descriptor.Duplicates.Contains(valueField.Key))
{
continue;
}
CodeMethodInvokeExpression setValue = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeThisReferenceExpression(),
"SetVariableValue"),
new CodeBinaryOperatorExpression(
new CodePrimitiveExpression(valueField.Value.Index),
CodeBinaryOperatorType.Add,
new CodeVariableReferenceExpression("locationsOffset")),
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), valueField.Key));
pushMethod.Statements.Add(setValue);
}
pushMethod.Statements.Add(new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeBaseReferenceExpression(),
pushMethod.Name)));
return pushMethod;
}
CodeTypeDeclaration GenerateCompiledDataContext(bool forReadOnly)
{
string forReadOnlyString = forReadOnly ? TextExpressionCompiler.forReadOnly : string.Empty;
string contextName = string.Concat(this.settings.ActivityName, TextExpressionCompiler.typedDataContextName, this.nextContextId, forReadOnlyString);
CodeTypeDeclaration typedDataContext = new CodeTypeDeclaration(contextName);
typedDataContext.TypeAttributes = TypeAttributes.NestedPrivate;
//
// data context classes are declared inside of the main class via the partial class to reduce visibility/surface area.
this.classDeclaration.Members.Add(typedDataContext);
if (this.compiledDataContexts != null && this.compiledDataContexts.Count > 0)
{
string baseTypeName = null;
if (forReadOnly)
{
baseTypeName = this.compiledDataContexts.Peek().CodeTypeDeclarationForReadOnly.Name;
}
else
{
baseTypeName = this.compiledDataContexts.Peek().CodeTypeDeclaration.Name;
}
typedDataContext.BaseTypes.Add(baseTypeName);
}
else
{
typedDataContext.BaseTypes.Add(typeof(CompiledDataContext));
//
// We only generate the helper method on the root data context/context 0
// No need to have it on all contexts. This is just a slight of hand
// so that we don't need to make GetDataContextActivities public on CompiledDataContext.
typedDataContext.Members.Add(GenerateDataContextActivitiesHelper());
}
CodeMemberField offsetField = new CodeMemberField();
offsetField.Attributes = MemberAttributes.Private;
offsetField.Name = locationsOffsetFieldName;
offsetField.Type = new CodeTypeReference(typeof(int));
typedDataContext.Members.Add(offsetField);
CodeMemberField expectedLocationsCountField = new CodeMemberField();
expectedLocationsCountField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
expectedLocationsCountField.Name = expectedLocationsCountFieldName;
expectedLocationsCountField.Type = new CodeTypeReference(typeof(int));
typedDataContext.Members.Add(expectedLocationsCountField);
typedDataContext.Members.Add(GenerateLocationReferenceActivityContextConstructor());
typedDataContext.Members.Add(GenerateLocationConstructor());
typedDataContext.Members.Add(GenerateLocationReferenceConstructor());
typedDataContext.Members.Add(GenerateCacheHelper());
typedDataContext.Members.Add(GenerateSetLocationsOffsetMethod());
//
// Mark this type as tool generated code
typedDataContext.CustomAttributes.Add(GeneratedCodeAttribute);
//
// Mark it as Browsable(false)
// Note that this does not prevent intellisense within a single project, just at the metadata level
typedDataContext.CustomAttributes.Add(BrowsableCodeAttribute);
//
// Mark it as EditorBrowsable(EditorBrowsableState.Never)
// Note that this does not prevent intellisense within a single project, just at the metadata level
typedDataContext.CustomAttributes.Add(EditorBrowsableCodeAttribute);
return typedDataContext;
}
CodeMemberMethod GenerateDataContextActivitiesHelper()
{
CodeMemberMethod dataContextActivitiesHelper = new CodeMemberMethod();
dataContextActivitiesHelper.Name = "GetDataContextActivitiesHelper";
dataContextActivitiesHelper.Attributes = MemberAttributes.Assembly | MemberAttributes.Final | MemberAttributes.Static;
if (this.compiledDataContexts != null && this.compiledDataContexts.Count > 0)
{
dataContextActivitiesHelper.Attributes |= MemberAttributes.New;
}
dataContextActivitiesHelper.ReturnType = new CodeTypeReference(typeof(object));
dataContextActivitiesHelper.Parameters.Add(
new CodeParameterDeclarationExpression(
new CodeTypeReference(typeof(Activity)),
"compiledRoot"));
dataContextActivitiesHelper.Parameters.Add(
new CodeParameterDeclarationExpression(
new CodeTypeReference(typeof(bool)),
forImplementationName));
dataContextActivitiesHelper.Statements.Add(
new CodeMethodReturnStatement(
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(typeof(CompiledDataContext)),
"GetDataContextActivities"),
new CodeVariableReferenceExpression("compiledRoot"),
new CodeVariableReferenceExpression(forImplementationName))));
return dataContextActivitiesHelper;
}
CodeMemberMethod GenerateSetLocationsOffsetMethod()
{
CodeMemberMethod setLocationsOffsetMethod = new CodeMemberMethod();
setLocationsOffsetMethod.Name = "SetLocationsOffset";
setLocationsOffsetMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)),
"locationsOffsetValue"));
setLocationsOffsetMethod.Attributes = MemberAttributes.Public;
if (this.compiledDataContexts.Count > 0)
{
setLocationsOffsetMethod.Attributes |= MemberAttributes.New;
}
CodeAssignStatement assignLocationsOffsetStatement = new CodeAssignStatement(
new CodeVariableReferenceExpression("locationsOffset"),
new CodeVariableReferenceExpression("locationsOffsetValue"));
setLocationsOffsetMethod.Statements.Add(assignLocationsOffsetStatement);
if (this.nextContextId > 0)
{
CodeMethodInvokeExpression baseSetLocationsOffsetMethod = new CodeMethodInvokeExpression(
new CodeBaseReferenceExpression(), "SetLocationsOffset", new CodeVariableReferenceExpression("locationsOffset"));
setLocationsOffsetMethod.Statements.Add(baseSetLocationsOffsetMethod);
}
return setLocationsOffsetMethod;
}
CodeMemberMethod GenerateCacheHelper()
{
CodeMemberMethod cacheHelper = new CodeMemberMethod();
cacheHelper.Name = "GetCompiledDataContextCacheHelper";
cacheHelper.Attributes = MemberAttributes.Assembly | MemberAttributes.Final | MemberAttributes.Static;
if (this.compiledDataContexts != null && this.compiledDataContexts.Count > 0)
{
cacheHelper.Attributes |= MemberAttributes.New;
}
cacheHelper.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), dataContextActivitiesFieldName));
cacheHelper.Parameters.Add(new CodeParameterDeclarationExpression(typeof(ActivityContext), "activityContext"));
cacheHelper.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Activity), "compiledRoot"));
cacheHelper.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), forImplementationName));
cacheHelper.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "compiledDataContextCount"));
cacheHelper.ReturnType = new CodeTypeReference(typeof(CompiledDataContext[]));
cacheHelper.Statements.Add(
new CodeMethodReturnStatement(
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(typeof(CompiledDataContext)),
"GetCompiledDataContextCache"),
new CodeVariableReferenceExpression(dataContextActivitiesFieldName),
new CodeVariableReferenceExpression("activityContext"),
new CodeVariableReferenceExpression("compiledRoot"),
new CodeVariableReferenceExpression(forImplementationName),
new CodeVariableReferenceExpression("compiledDataContextCount"))));
return cacheHelper;
}
CodeConstructor GenerateLocationReferenceActivityContextConstructor()
{
//
// public [typename](IList<LocationReference> locations, ActivityContext activityContext)
// : base(locations, activityContext)
//
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression constructorLocationsParam =
new CodeParameterDeclarationExpression(typeof(IList<LocationReference>), "locations");
constructor.Parameters.Add(constructorLocationsParam);
constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("locations"));
CodeParameterDeclarationExpression constructorActivityContextParam =
new CodeParameterDeclarationExpression(typeof(ActivityContext), "activityContext");
constructor.Parameters.Add(constructorActivityContextParam);
constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("activityContext"));
CodeParameterDeclarationExpression computelocationsOffsetParam =
new CodeParameterDeclarationExpression(typeof(bool), "computelocationsOffset");
constructor.Parameters.Add(computelocationsOffsetParam);
if (this.nextContextId > 0)
{
constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(false));
}
InvokeSetLocationsOffsetMethod(constructor);
return constructor;
}
CodeConstructor GenerateLocationConstructor()
{
//
// public [typename](IList<Location> locations, ActivityContext activityContext)
// : base(locations)
//
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression constructorLocationsParam =
new CodeParameterDeclarationExpression(typeof(IList<Location>), "locations");
constructor.Parameters.Add(constructorLocationsParam);
constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("locations"));
CodeParameterDeclarationExpression computelocationsOffsetParam =
new CodeParameterDeclarationExpression(typeof(bool), "computelocationsOffset");
constructor.Parameters.Add(computelocationsOffsetParam);
if (this.nextContextId > 0)
{
constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(false));
}
InvokeSetLocationsOffsetMethod(constructor);
return constructor;
}
CodeConstructor GenerateLocationReferenceConstructor()
{
//
// public [typename](IList<LocationReference> locationReferences)
// : base(locationReferences)
//
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression constructorLocationsParam = new CodeParameterDeclarationExpression(typeof(IList<LocationReference>), "locationReferences");
constructor.Parameters.Add(constructorLocationsParam);
constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("locationReferences"));
return constructor;
}
void InvokeSetLocationsOffsetMethod(CodeConstructor constructor)
{
CodeExpressionStatement setLocationsOffsetMethod = new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),
"SetLocationsOffset",
new CodeBinaryOperatorExpression(
new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("locations"), "Count"),
CodeBinaryOperatorType.Subtract,
new CodeVariableReferenceExpression("expectedLocationsCount"))));
CodeConditionStatement offsetCheckStatement = new CodeConditionStatement(new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("computelocationsOffset"),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(true)),
new CodeStatement[] { setLocationsOffsetMethod });
constructor.Statements.Add(offsetCheckStatement);
}
CodeNamespace GenerateCodeNamespace()
{
CodeNamespace codeNamespace = new CodeNamespace(this.settings.ActivityNamespace);
bool seenXamlIntegration = false;
foreach (string nsReference in GetNamespaceReferences())
{
if (!seenXamlIntegration && nsReference == xamlIntegrationNamespace)
{
seenXamlIntegration = true;
}
codeNamespace.Imports.Add(new CodeNamespaceImport(nsReference)
{
LinePragma = GenerateLinePragmaForNamespace(nsReference),
});
}
if (!seenXamlIntegration)
{
codeNamespace.Imports.Add(new CodeNamespaceImport(xamlIntegrationNamespace)
{
LinePragma = GenerateLinePragmaForNamespace(xamlIntegrationNamespace),
});
}
return codeNamespace;
}
bool AssemblyContainsTypeWithActivityNamespace()
{
// We need to include the ActivityNamespace in the imports if there are any types in
// the Activity's assembly that are contained in that namespace.
Type[] types;
try
{
types = this.settings.Activity.GetType().Assembly.GetTypes();
}
catch (ReflectionTypeLoadException)
{
// We had a problem loading all the types. Take the safe route and assume we need to include the ActivityNamespace.
return true;
}
if (types != null)
{
foreach (Type type in types)
{
if (type.Namespace == this.settings.ActivityNamespace)
{
return true;
}
}
}
return false;
}
IEnumerable<string> GetNamespaceReferences()
{
HashSet<string> nsReferences = new HashSet<string>();
// Add some namespace imports, use the same base set for C# as for VB, they aren't lang specific
foreach (string nsReference in TextExpression.DefaultNamespaces)
{
nsReferences.Add(nsReference);
}
VisualBasicSettings vbSettings = null;
if (IsVB)
{
vbSettings = VisualBasic.GetSettings(this.settings.Activity);
}
if (vbSettings != null)
{
foreach (VisualBasicImportReference nsReference in vbSettings.ImportReferences)
{
if (!string.IsNullOrWhiteSpace(nsReference.Import))
{
// For VB, the ActivityNamespace has the RootNamespace stripped off. We don't need an Imports reference
// to ActivityNamespace, if this reference is in the same assembly and there is a RootNamespace specified.
// We check both Assembly.FullName and
// Assembly.GetName().Name because testing has shown that nsReference.Assembly sometimes gives fully qualified
// names and sometimes not.
if (
(nsReference.Import == this.settings.ActivityNamespace)
&&
((nsReference.Assembly == this.settings.Activity.GetType().Assembly.FullName) ||
(nsReference.Assembly == this.settings.Activity.GetType().Assembly.GetName().Name))
&&
!string.IsNullOrWhiteSpace(this.settings.RootNamespace)
&&
!AssemblyContainsTypeWithActivityNamespace()
)
{
continue;
}
nsReferences.Add(nsReference.Import);
}
}
}
else
{
IList<string> references = this.settings.ForImplementation ?
TextExpression.GetNamespacesForImplementation(this.settings.Activity) :
TextExpression.GetNamespaces(this.settings.Activity);
foreach (string nsReference in references)
{
if (!string.IsNullOrWhiteSpace(nsReference))
{
nsReferences.Add(nsReference);
}
}
}
return nsReferences;
}
CompiledDataContextDescriptor PushDataContextDescriptor()
{
CompiledDataContextDescriptor contextDescriptor = new CompiledDataContextDescriptor(() => this.IsVB)
{
CodeTypeDeclaration = GenerateCompiledDataContext(false),
CodeTypeDeclarationForReadOnly = GenerateCompiledDataContext(true),
NextMemberIndex = GetStartMemberIndex()
};
this.compiledDataContexts.Push(contextDescriptor);
this.nextContextId++;
return contextDescriptor;
}
void PopDataContextDescriptor()
{
CompiledDataContextDescriptor descriptor = this.compiledDataContexts.Pop();
if (descriptor != null)
{
GenerateMembers(descriptor);
GenerateValidate(descriptor, true);
GenerateValidate(descriptor, false);
}
}
int GetStartMemberIndex()
{
if (this.compiledDataContexts == null || this.compiledDataContexts.Count == 0)
{
return 0;
}
else
{
return this.compiledDataContexts.Peek().NextMemberIndex;
}
}
void GenerateValidate(CompiledDataContextDescriptor descriptor, bool forReadOnly)
{
//
//
// Validate the locations at runtime match the set at compile time
//
// protected override bool Validate(IList<LocationReference> locationReferences)
// {
// if (validateLocationCount && locationReferences.Count != [generated count of location references])
// {
// return false;
// }
// if (locationReferences[0].Name != [generated name for index] ||
// locationReferences[0].Type != typeof([generated type for index]))
// {
// return false;
// }
//
// ...
//
// }
CodeMemberMethod validateMethod = new CodeMemberMethod();
validateMethod.Name = "Validate";
validateMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
if (this.compiledDataContexts.Count > 0)
{
validateMethod.Attributes |= MemberAttributes.New;
}
validateMethod.ReturnType = new CodeTypeReference(typeof(bool));
validateMethod.Parameters.Add(
new CodeParameterDeclarationExpression(
new CodeTypeReference(typeof(IList<LocationReference>)),
"locationReferences"));
validateMethod.Parameters.Add(
new CodeParameterDeclarationExpression(
new CodeTypeReference(typeof(bool)),
"validateLocationCount"));
validateMethod.Parameters.Add(
new CodeParameterDeclarationExpression(
new CodeTypeReference(typeof(int)),
"offset") );
CodeBinaryOperatorExpression shouldCheckLocationCountExpression = new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("validateLocationCount"),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(true));
CodeBinaryOperatorExpression compareLocationCountExpression = new CodeBinaryOperatorExpression(
new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("locationReferences"),
"Count"),
CodeBinaryOperatorType.LessThan,
new CodePrimitiveExpression(descriptor.NextMemberIndex)
);
CodeBinaryOperatorExpression checkLocationCountExpression = new CodeBinaryOperatorExpression(
shouldCheckLocationCountExpression,
CodeBinaryOperatorType.BooleanAnd,
compareLocationCountExpression);
CodeConditionStatement checkLocationCountStatement = new CodeConditionStatement(
checkLocationCountExpression,
new CodeMethodReturnStatement(
new CodePrimitiveExpression(false)));
validateMethod.Statements.Add(checkLocationCountStatement);
if (descriptor.NextMemberIndex > 0)
{
CodeConditionStatement generateNewOffset = new CodeConditionStatement(shouldCheckLocationCountExpression,
new CodeStatement[]
{
new CodeAssignStatement(new CodeVariableReferenceExpression("offset"),
new CodeBinaryOperatorExpression(
new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("locationReferences"), "Count"),
CodeBinaryOperatorType.Subtract,
new CodePrimitiveExpression(descriptor.NextMemberIndex)))
});
validateMethod.Statements.Add(generateNewOffset);
}
CodeAssignStatement setexpectedLocationsCountStatement = new CodeAssignStatement(
new CodeVariableReferenceExpression("expectedLocationsCount"),
new CodePrimitiveExpression(descriptor.NextMemberIndex));
validateMethod.Statements.Add(setexpectedLocationsCountStatement);
foreach (KeyValuePair<string, MemberData> kvp in descriptor.Properties)
{
validateMethod.Statements.Add(GenerateLocationReferenceCheck(kvp.Value));
}
foreach (KeyValuePair<string, MemberData> kvp in descriptor.Fields)
{
validateMethod.Statements.Add(GenerateLocationReferenceCheck(kvp.Value));
}
if (this.compiledDataContexts.Count >= 1)
{
CompiledDataContextDescriptor baseDescriptor = this.compiledDataContexts.Peek();
CodeTypeDeclaration baseType = forReadOnly ? baseDescriptor.CodeTypeDeclarationForReadOnly : baseDescriptor.CodeTypeDeclaration;
CodeMethodInvokeExpression invokeBase = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(baseType.Name),
"Validate"),
new CodeVariableReferenceExpression("locationReferences"),
new CodePrimitiveExpression(false),
new CodeVariableReferenceExpression("offset"));
validateMethod.Statements.Add(
new CodeMethodReturnStatement(invokeBase));
}
else
{
validateMethod.Statements.Add(
new CodeMethodReturnStatement(
new CodePrimitiveExpression(true)));
}
if (forReadOnly)
{
descriptor.CodeTypeDeclarationForReadOnly.Members.Add(validateMethod);
}
else
{
descriptor.CodeTypeDeclaration.Members.Add(validateMethod);
}
}
CodeConditionStatement GenerateLocationReferenceCheck(MemberData memberData)
{
CodeIndexerExpression indexer = new CodeIndexerExpression(
new CodeVariableReferenceExpression("locationReferences"),
new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("offset"),
CodeBinaryOperatorType.Add,
new CodePrimitiveExpression(memberData.Index)));
CodeBinaryOperatorExpression locationNameExpression = new CodeBinaryOperatorExpression(
new CodePropertyReferenceExpression(indexer, "Name"),
CodeBinaryOperatorType.IdentityInequality,
new CodePrimitiveExpression(memberData.Name));
CodeBinaryOperatorExpression locationTypeExpression = new CodeBinaryOperatorExpression(
new CodePropertyReferenceExpression(indexer, "Type"),
CodeBinaryOperatorType.IdentityInequality,
new CodeTypeOfExpression(memberData.Type));
CodeBinaryOperatorExpression locationExpression = new CodeBinaryOperatorExpression(
locationNameExpression,
CodeBinaryOperatorType.BooleanOr,
locationTypeExpression);
CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement();
returnStatement.Expression = new CodePrimitiveExpression(false);
CodeConditionStatement locationStatement = new CodeConditionStatement(
locationExpression,
returnStatement);
return locationStatement;
}
[Fx.Tag.SecurityNote(Critical = "Critical because we are accessing CodeDom.",
Safe = "Safe because we are demanding FullTrust")]
[SecuritySafeCritical]
////[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
void WriteCode(TextWriter textWriter)
{
using (CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider(this.settings.Language))
{
using (IndentedTextWriter indentedTextWriter = new IndentedTextWriter(textWriter))
{
codeDomProvider.GenerateCodeFromNamespace(this.codeNamespace, indentedTextWriter, new CodeGeneratorOptions());
}
}
}
[Fx.Tag.SecurityNote(Critical = "Critical because we are using the CodeDomProvider class, which has a link demand for Full Trust.",
Safe = "Safe because we are demanding FullTrust")]
[SecuritySafeCritical]
////[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
TextExpressionCompilerResults CompileInMemory()
{
var messages = new List<TextExpressionCompilerError>();
var compilerParameters = GetCompilerParameters(messages);
var classToCompile = new ClassToCompile(settings.ActivityName, compilerParameters, compileUnit);
return settings.Compiler.Compile(classToCompile);
}
[Fx.Tag.SecurityNote(Critical = "Critical because we are using the CompilerParameters class, which has a link demand for Full Trust.",
Safe = "Safe because we are demanding FullTrust")]
[SecuritySafeCritical]
////[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
CompilerParameters GetCompilerParameters(IList<TextExpressionCompilerError> messages)
{
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateExecutable = false;
compilerParameters.GenerateInMemory = false;
if (this.IsVB && !string.IsNullOrWhiteSpace(this.settings.RootNamespace))
{
compilerParameters.CompilerOptions = string.Concat("/rootnamespace:", this.settings.RootNamespace);
}
List<AssemblyReference> assemblies = this.settings.ForImplementation ?
new List<AssemblyReference>(TextExpression.GetReferencesForImplementation(this.settings.Activity)) :
new List<AssemblyReference>(TextExpression.GetReferences(this.settings.Activity));
assemblies.AddRange(TextExpression.DefaultReferences);
foreach (AssemblyReference assemblyReference in assemblies)
{
if (assemblyReference == null)
{
continue;
}
assemblyReference.LoadAssembly();
if (assemblyReference.Assembly == null)
{
TextExpressionCompilerError warning = new TextExpressionCompilerError();
warning.IsWarning = true;
warning.Message = SR.TextExpressionCompilerUnableToLoadAssembly(assemblyReference.AssemblyName);
messages.Add(warning);
continue;
}
if (assemblyReference.Assembly.CodeBase == null)
{
TextExpressionCompilerError warning = new TextExpressionCompilerError();
warning.IsWarning = true;
warning.Message = SR.TextExpressionCompilerNoCodebase(assemblyReference.AssemblyName);
messages.Add(warning);
continue;
}
string fileName = new Uri(assemblyReference.Assembly.CodeBase).LocalPath;
compilerParameters.ReferencedAssemblies.Add(fileName);
}
return compilerParameters;
}
void AlignText(Activity activity, ref string expressionText, out CodeLinePragma pragma)
{
pragma = null;
}
CodeLinePragma GenerateLinePragmaForNamespace(string namespaceName)
{
if (this.fileName != null)
{
// if source xaml file doesn't exist or it doesn't contain TextExpression
// it defaults to line number 1
int lineNumber = 1;
Dictionary<string, int> lineNumberDictionary = this.settings.ForImplementation ? this.lineNumbersForNSesForImpl : this.lineNumbersForNSes;
int lineNumReturend;
if (lineNumberDictionary.TryGetValue(namespaceName, out lineNumReturend))
{
lineNumber = lineNumReturend;
}
return new CodeLinePragma(this.fileName, lineNumber);
}
return null;
}
string GetActivityFullName(TextExpressionCompilerSettings settings)
{
string rootNamespacePrefix = null;
string namespacePrefix = null;
string activityFullName = "";
if (this.IsVB && !String.IsNullOrWhiteSpace(this.settings.RootNamespace))
{
rootNamespacePrefix = this.settings.RootNamespace + ".";
}
if (!String.IsNullOrWhiteSpace(this.settings.ActivityNamespace))
{
namespacePrefix = this.settings.ActivityNamespace + ".";
}
if (rootNamespacePrefix != null)
{
if (namespacePrefix != null)
{
activityFullName = rootNamespacePrefix + namespacePrefix + settings.ActivityName;
}
else
{
activityFullName = rootNamespacePrefix + settings.ActivityName;
}
}
else
{
if (namespacePrefix != null)
{
activityFullName = namespacePrefix + settings.ActivityName;
}
else
{
activityFullName = settings.ActivityName;
}
}
return activityFullName;
}
class ExpressionCompilerActivityVisitor : CompiledExpressionActivityVisitor
{
TextExpressionCompiler compiler;
public ExpressionCompilerActivityVisitor(TextExpressionCompiler compiler)
{
this.compiler = compiler;
}
public int NextExpressionId
{
get;
set;
}
protected override void Visit(Activity activity, out bool exit)
{
base.Visit(activity, out exit);
}
protected override void VisitRoot(Activity activity, out bool exit)
{
this.compiler.OnRootActivity();
base.VisitRoot(activity, out exit);
this.compiler.OnAfterRootActivity();
}
protected override void VisitRootImplementationArguments(Activity activity, out bool exit)
{
base.VisitRootImplementationArguments(activity, out exit);
if (this.ForImplementation)
{
this.compiler.OnAfterRootArguments(activity);
}
}
protected override void VisitVariableScope(Activity activity, out bool exit)
{
this.compiler.OnVariableScope(activity);
base.VisitVariableScope(activity, out exit);
this.compiler.OnAfterVariableScope();
}
protected override void VisitRootImplementationScope(Activity activity, out bool exit)
{
CompiledDataContextDescriptor rootArgumentAccessorContext = null;
this.compiler.OnRootImplementationScope(activity, out rootArgumentAccessorContext);
base.VisitRootImplementationScope(activity, out exit);
this.compiler.OnAfterRootImplementationScope(activity, rootArgumentAccessorContext);
}
protected override void VisitVariableScopeArgument(RuntimeArgument runtimeArgument, out bool exit)
{
this.compiler.InVariableScopeArgument = true;
base.VisitVariableScopeArgument(runtimeArgument, out exit);
this.compiler.InVariableScopeArgument = false;
}
protected override void VisitITextExpression(Activity activity, out bool exit)
{
this.compiler.OnITextExpressionFound(activity, this);
exit = false;
}
protected override void VisitDelegate(ActivityDelegate activityDelegate, out bool exit)
{
this.compiler.OnActivityDelegateScope();
base.VisitDelegate(activityDelegate, out exit);
this.compiler.OnAfterActivityDelegateScope();
exit = false;
}
protected override void VisitDelegateArgument(RuntimeDelegateArgument delegateArgument, out bool exit)
{
this.compiler.OnDelegateArgument(delegateArgument);
base.VisitDelegateArgument(delegateArgument, out exit);
}
}
class CompiledExpressionDescriptor
{
internal bool IsValue
{
get
{
return !string.IsNullOrWhiteSpace(this.GetMethodName) &&
string.IsNullOrWhiteSpace(this.SetMethodName) &&
string.IsNullOrWhiteSpace(this.StatementMethodName);
}
}
internal bool IsReference
{
get
{
return !string.IsNullOrWhiteSpace(this.SetMethodName);
}
}
internal bool IsStatement
{
get
{
return !string.IsNullOrWhiteSpace(this.StatementMethodName);
}
}
internal string TypeName
{
get;
set;
}
internal Type ResultType
{
get;
set;
}
internal string GetMethodName
{
get;
set;
}
internal string SetMethodName
{
get;
set;
}
internal string StatementMethodName
{
get;
set;
}
internal int Id
{
get;
set;
}
internal string ExpressionText
{
get;
set;
}
internal string GetExpressionTreeMethodName
{
get;
set;
}
}
class CompiledDataContextDescriptor
{
IDictionary<string, MemberData> fields;
IDictionary<string, MemberData> properties;
ISet<string> duplicates;
Func<bool> isVb;
public CompiledDataContextDescriptor(Func<bool> isVb)
{
this.isVb = isVb;
}
public IDictionary<string, MemberData> Fields
{
get
{
if (this.fields == null)
{
if (this.isVb())
{
this.fields = new Dictionary<string, MemberData>(StringComparer.OrdinalIgnoreCase);
}
else
{
this.fields = new Dictionary<string, MemberData>();
}
}
return this.fields;
}
}
public IDictionary<string, MemberData> Properties
{
get
{
if (this.properties == null)
{
if (this.isVb())
{
this.properties = new Dictionary<string, MemberData>(StringComparer.OrdinalIgnoreCase);
}
else
{
this.properties = new Dictionary<string, MemberData>();
}
}
return this.properties;
}
}
public ISet<string> Duplicates
{
get
{
if (this.duplicates == null)
{
if (this.isVb())
{
this.duplicates = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
else
{
this.duplicates = new HashSet<string>();
}
}
return this.duplicates;
}
}
public CodeTypeDeclaration CodeTypeDeclaration
{
get;
set;
}
public CodeTypeDeclaration CodeTypeDeclarationForReadOnly
{
get;
set;
}
public int NextMemberIndex
{
get;
set;
}
}
struct MemberData
{
public int Index;
public string Name;
public Type Type;
}
}
} | 44.096786 | 242 | 0.611138 | [
"MIT"
] | lvama/corewf | src/UiPath.Workflow/XamlIntegration/TextExpressionCompiler.cs | 120,737 | C# |
namespace EF_Test.Migrations
{
using System.Data.Entity.Migrations;
public partial class CarObject : DbMigration
{
public override void Up()
{
CreateTable(
"Cars",
c => new
{
Id = c.Int(nullable: false, identity: true),
Mfg = c.String(),
Model = c.String(),
Year = c.Int(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("Cars");
}
}
}
| 23.464286 | 68 | 0.371385 | [
"MIT"
] | Jorriss/Demo.EFDataProfessionals | EF Test/EF Test/Migrations/201309120209095_Car Object.cs | 657 | C# |
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.Events;
namespace Michsky.UI.ModernUIPack
{
public class ModalWindowManager : MonoBehaviour
{
// Resources
public Image windowIcon;
public TextMeshProUGUI windowTitle;
public TextMeshProUGUI windowDescription;
public Button confirmButton;
public Button cancelButton;
public Animator mwAnimator;
// Content
public Sprite icon;
public string titleText = "Title";
[TextArea] public string descriptionText = "Description here";
// Events
public UnityEvent onConfirm;
public UnityEvent onCancel;
// Settings
public bool sharpAnimations = false;
public bool useCustomValues = false;
public bool destroyOnClose = false;
public bool isOn = false;
void Start()
{
if (mwAnimator == null)
mwAnimator = gameObject.GetComponent<Animator>();
if (confirmButton != null)
confirmButton.onClick.AddListener(onConfirm.Invoke);
if (cancelButton != null)
cancelButton.onClick.AddListener(onCancel.Invoke);
if (useCustomValues == false)
UpdateUI();
}
public void UpdateUI()
{
try
{
windowIcon.sprite = icon;
windowTitle.text = titleText;
windowDescription.text = descriptionText;
}
catch
{
Debug.LogWarning("Modal Window - Cannot update the content due to missing variables.", this);
}
}
public void OpenWindow()
{
if (isOn == false)
{
if (sharpAnimations == false)
mwAnimator.CrossFade("Fade-in", 0.1f);
else
mwAnimator.Play("Fade-in");
isOn = true;
}
}
public void CloseWindow()
{
if (isOn == true)
{
if (sharpAnimations == false)
mwAnimator.CrossFade("Fade-out", 0.1f);
else
mwAnimator.Play("Fade-out");
isOn = false;
if (destroyOnClose == true)
StartCoroutine("DestroyModal");
}
}
public void AnimateWindow()
{
if (isOn == false)
{
if (sharpAnimations == false)
mwAnimator.CrossFade("Fade-in", 0.1f);
else
mwAnimator.Play("Fade-in");
isOn = true;
}
else
{
if (sharpAnimations == false)
mwAnimator.CrossFade("Fade-out", 0.1f);
else
mwAnimator.Play("Fade-out");
isOn = false;
if (destroyOnClose == true)
StartCoroutine("DestroyModal");
}
}
IEnumerator DestroyModal()
{
yield return new WaitForSeconds(1f);
Destroy(gameObject);
}
}
} | 26.039683 | 109 | 0.487656 | [
"CC0-1.0"
] | 00010023/waifu.run | assets/Modern UI Pack/Scripts/Modal Window/ModalWindowManager.cs | 3,283 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Acn.Rdm.Packets.Power
{
/// <summary>
/// This parameter is used to retrieve or change the current operating state of the lamp.
/// </summary>
public class LampState
{
public enum LampStates
{
Off = 0,
On = 1,
Strike = 2,
Standby = 3,
NotPresent = 4,
Error = 0x7F
}
public class Get : RdmRequestPacket
{
public Get()
: base(RdmCommands.Get, RdmParameters.LampState )
{
}
#region Read and Write
protected override void ReadData(RdmBinaryReader data)
{
}
protected override void WriteData(RdmBinaryWriter data)
{
}
#endregion
}
public class GetReply : RdmResponsePacket
{
public GetReply()
: base(RdmCommands.GetResponse, RdmParameters.LampState)
{
}
public LampStates LampState { get; set; }
#region Read and Write
protected override void ReadData(RdmBinaryReader data)
{
LampState = (LampStates) data.ReadByte();
}
protected override void WriteData(RdmBinaryWriter data)
{
data.Write((byte)LampState);
}
#endregion
}
public class Set : RdmRequestPacket
{
public Set()
: base(RdmCommands.Set, RdmParameters.LampState)
{
}
#region Read and Write
protected override void ReadData(RdmBinaryReader data)
{
}
protected override void WriteData(RdmBinaryWriter data)
{
}
#endregion
}
public class SetReply : RdmResponsePacket
{
public SetReply()
: base(RdmCommands.SetResponse, RdmParameters.LampState)
{
}
#region Read and Write
protected override void ReadData(RdmBinaryReader data)
{
}
protected override void WriteData(RdmBinaryWriter data)
{
}
#endregion
}
}
}
| 22.490741 | 93 | 0.492795 | [
"MIT"
] | HakanL/ACN | Acn/Rdm/Packets/Power/LampState.cs | 2,431 | C# |
// Released under the MIT License.
//
// Copyright (c) 2018 Ntreev Soft co., Ltd.
// Copyright (c) 2020 Jeesu Choi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Forked from https://github.com/NtreevSoft/Crema
// Namespaces and files starting with "Ntreev" have been renamed to "JSSoft".
using JSSoft.Library.Commands;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
namespace JSSoft.Crema.Commands.Consoles
{
[Export(typeof(IConsoleCommand))]
[ResourceUsageDescription("Resources")]
class KickCommand : UserCommandBase, IConsoleCommand
{
public KickCommand()
{
}
[CommandPropertyRequired]
[CommandCompletion(nameof(GetUserListAsync))]
public string UserID
{
get; set;
}
[CommandPropertyRequired('m', AllowName = true, IsExplicit = true)]
public string Message
{
get; set;
}
protected override async Task OnExecuteAsync(CancellationToken cancellationToken)
{
var authentication = this.CommandContext.GetAuthentication(this);
var user = await this.GetUserAsync(authentication, this.UserID);
await user.KickAsync(authentication, this.Message);
}
}
}
| 39.423729 | 121 | 0.711522 | [
"MIT"
] | s2quake/JSSoft.Crema | share/JSSoft.Crema.Commands/Consoles/KickCommand.cs | 2,328 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using Microsoft.Extensions.Logging;
using Steeltoe.Messaging.RabbitMQ.Connection;
using Steeltoe.Messaging.RabbitMQ.Core;
using Steeltoe.Messaging.RabbitMQ.Extensions;
using Steeltoe.Messaging.RabbitMQ.Support;
using System;
using System.Collections.Generic;
namespace Steeltoe.Messaging.RabbitMQ.Retry;
public class RepublishMessageRecoverer : IMessageRecoverer
{
public const string X_EXCEPTION_STACKTRACE = "x-exception-stacktrace";
public const string X_EXCEPTION_MESSAGE = "x-exception-message";
public const string X_ORIGINAL_EXCHANGE = "x-original-exchange";
public const string X_ORIGINAL_ROUTING_KEY = "x-original-routingKey";
public const int DEFAULT_FRAME_MAX_HEADROOM = 20_000;
private const int ELLIPSIS_LENGTH = 3;
private const int MAX_EXCEPTION_MESSAGE_SIZE_IN_TRACE = 100 - ELLIPSIS_LENGTH;
private ILogger _logger;
public RepublishMessageRecoverer(RabbitTemplate errorTemplate, ILogger logger = null)
: this(errorTemplate, null, null, logger)
{
}
public RepublishMessageRecoverer(RabbitTemplate errorTemplate, string errorExchange, ILogger logger = null)
: this(errorTemplate, errorExchange, null, logger)
{
}
public RepublishMessageRecoverer(RabbitTemplate errorTemplate, string errorExchange, string errorRoutingKey, ILogger logger = null)
{
ErrorTemplate = errorTemplate ?? throw new ArgumentNullException(nameof(errorTemplate));
ErrorExchangeName = errorExchange;
ErrorRoutingKey = errorRoutingKey;
MaxStackTraceLength = int.MaxValue;
_logger = logger;
}
public RabbitTemplate ErrorTemplate { get; }
public string ErrorExchangeName { get; }
public string ErrorRoutingKey { get; }
public int MaxStackTraceLength { get; set; }
public string ErrorRoutingKeyPrefix { get; set; }
public MessageDeliveryMode DeliveryMode { get; set; }
public int FrameMaxHeadroom { get; set; } = DEFAULT_FRAME_MAX_HEADROOM;
public void Recover(IMessage message, Exception exception)
{
var headers = RabbitHeaderAccessor.GetMutableAccessor(message);
var exceptionMessage = exception.InnerException != null ? exception.InnerException.Message : exception.Message;
var processed = ProcessStackTrace(exception, exceptionMessage);
var stackTraceAsString = processed[0];
var truncatedExceptionMessage = processed[1];
if (truncatedExceptionMessage != null)
{
exceptionMessage = truncatedExceptionMessage;
}
headers.SetHeader(X_EXCEPTION_STACKTRACE, stackTraceAsString);
headers.SetHeader(X_EXCEPTION_MESSAGE, exceptionMessage);
headers.SetHeader(X_ORIGINAL_EXCHANGE, headers.ReceivedExchange);
headers.SetHeader(X_ORIGINAL_ROUTING_KEY, headers.ReceivedRoutingKey);
var additionalHeaders = AddAdditionalHeaders(message, exception);
if (additionalHeaders != null)
{
foreach (var h in additionalHeaders)
{
headers.SetHeader(h.Key, h.Value);
}
}
headers.DeliveryMode ??= DeliveryMode;
if (ErrorExchangeName != null)
{
var routingKey = ErrorRoutingKey ?? PrefixedOriginalRoutingKey(message);
ErrorTemplate.Send(ErrorExchangeName, routingKey, message);
_logger?.LogWarning("Republishing failed message to exchange '{exchange}' with routing key '{routingKey}'", ErrorExchangeName, routingKey);
}
else
{
var routingKey = PrefixedOriginalRoutingKey(message);
ErrorTemplate.Send(routingKey, message);
_logger?.LogWarning("Republishing failed message to the template's default exchange with routing key {key}", routingKey);
}
}
protected virtual Dictionary<string, object> AddAdditionalHeaders(IMessage message, Exception cause) => null;
private string PrefixedOriginalRoutingKey(IMessage message) => ErrorRoutingKeyPrefix + message.Headers.ReceivedRoutingKey();
private List<string> ProcessStackTrace(Exception cause, string exceptionMessage)
{
var stackTraceAsString = cause.StackTrace;
if (MaxStackTraceLength < 0)
{
var maxStackTraceLen = RabbitUtils.GetMaxFrame(ErrorTemplate.ConnectionFactory);
if (maxStackTraceLen > 0)
{
maxStackTraceLen -= FrameMaxHeadroom;
MaxStackTraceLength = maxStackTraceLen;
}
}
return TruncateIfNecessary(cause, exceptionMessage, stackTraceAsString);
}
private List<string> TruncateIfNecessary(Exception cause, string exception, string stackTrace)
{
var truncated = false;
var stackTraceAsString = stackTrace;
var exceptionMessage = exception;
var truncatedExceptionMessage = exceptionMessage.Length <= MAX_EXCEPTION_MESSAGE_SIZE_IN_TRACE ? exceptionMessage : exceptionMessage.Substring(0, MAX_EXCEPTION_MESSAGE_SIZE_IN_TRACE) + "...";
if (MaxStackTraceLength > 0 && stackTraceAsString.Length + exceptionMessage.Length > MaxStackTraceLength)
{
if (!exceptionMessage.Equals(truncatedExceptionMessage))
{
var start = stackTraceAsString.IndexOf(exceptionMessage);
stackTraceAsString = stackTraceAsString.Substring(0, start)
+ truncatedExceptionMessage
+ stackTraceAsString.Substring(start + exceptionMessage.Length);
}
var adjustedStackTraceLen = MaxStackTraceLength - truncatedExceptionMessage.Length;
if (adjustedStackTraceLen > 0)
{
if (stackTraceAsString.Length > adjustedStackTraceLen)
{
stackTraceAsString = stackTraceAsString.Substring(0, adjustedStackTraceLen);
_logger?.LogWarning(cause, "Stack trace in republished message header truncated due to frame_max limitations; consider increasing frame_max on the broker or reduce the stack trace depth");
truncated = true;
}
else if (stackTraceAsString.Length + exceptionMessage.Length > MaxStackTraceLength)
{
_logger?.LogWarning(cause, "Exception message in republished message header truncated due to frame_max limitations; consider increasing frame_max on the broker or reduce the exception message size");
truncatedExceptionMessage = $"{exceptionMessage.Substring(0, MaxStackTraceLength - stackTraceAsString.Length - ELLIPSIS_LENGTH)}...";
truncated = true;
}
}
}
return new List<string> { stackTraceAsString, truncated ? truncatedExceptionMessage : null };
}
}
| 43.417178 | 219 | 0.689275 | [
"Apache-2.0"
] | SteeltoeOSS/steeltoe | src/Messaging/src/RabbitMQ/Retry/RepublishMessageRecoverer.cs | 7,077 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Lightsail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lightsail.Model.Internal.MarshallTransformations
{
/// <summary>
/// ReleaseStaticIp Request Marshaller
/// </summary>
public class ReleaseStaticIpRequestMarshaller : IMarshaller<IRequest, ReleaseStaticIpRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ReleaseStaticIpRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ReleaseStaticIpRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Lightsail");
string target = "Lightsail_20161128.ReleaseStaticIp";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetStaticIpName())
{
context.Writer.WritePropertyName("staticIpName");
context.Writer.Write(publicRequest.StaticIpName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static ReleaseStaticIpRequestMarshaller _instance = new ReleaseStaticIpRequestMarshaller();
internal static ReleaseStaticIpRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ReleaseStaticIpRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.209524 | 145 | 0.630782 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/ReleaseStaticIpRequestMarshaller.cs | 3,697 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using SimplCommerce.Module.Core.Data;
namespace SimplCommerce.WebHost.Migrations
{
[DbContext(typeof(SimplDbContext))]
[Migration("20170217035116_AddedVendor")]
partial class AddedVendor
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.0-rtm-22752")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<long>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<long>("RoleId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("Core_RoleClaim");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<long>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Core_UserClaim");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<long>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<long>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("Core_UserLogin");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<long>", b =>
{
b.Property<long>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("Core_UserToken");
});
modelBuilder.Entity("SimplCommerce.Module.ActivityLog.Models.Activity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("ActivityTypeId");
b.Property<DateTimeOffset>("CreatedOn");
b.Property<long>("EntityId");
b.Property<long>("EntityTypeId");
b.HasKey("Id");
b.HasIndex("ActivityTypeId");
b.ToTable("ActivityLog_Activity");
});
modelBuilder.Entity("SimplCommerce.Module.ActivityLog.Models.ActivityType", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("ActivityLog_ActivityType");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.Brand", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description")
.HasMaxLength(5000);
b.Property<bool>("IsDeleted");
b.Property<bool>("IsPublished");
b.Property<string>("Name");
b.Property<string>("SeoTitle");
b.HasKey("Id");
b.ToTable("Catalog_Brand");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.Category", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description")
.HasMaxLength(5000);
b.Property<int>("DisplayOrder");
b.Property<string>("Image");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsPublished");
b.Property<string>("Name");
b.Property<long?>("ParentId");
b.Property<string>("SeoTitle");
b.HasKey("Id");
b.HasIndex("ParentId");
b.ToTable("Catalog_Category");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.Product", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("BrandId");
b.Property<long?>("CreatedById");
b.Property<DateTimeOffset>("CreatedOn");
b.Property<string>("Description");
b.Property<int>("DisplayOrder");
b.Property<bool>("HasOptions");
b.Property<bool>("IsAllowToOrder");
b.Property<bool>("IsCallForPricing");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsFeatured");
b.Property<bool>("IsPublished");
b.Property<bool>("IsVisibleIndividually");
b.Property<string>("MetaDescription");
b.Property<string>("MetaKeywords");
b.Property<string>("MetaTitle");
b.Property<string>("Name");
b.Property<string>("NormalizedName");
b.Property<decimal?>("OldPrice");
b.Property<decimal>("Price");
b.Property<DateTimeOffset?>("PublishedOn");
b.Property<double?>("RatingAverage");
b.Property<int>("ReviewsCount");
b.Property<string>("SeoTitle");
b.Property<string>("ShortDescription");
b.Property<string>("Sku");
b.Property<decimal?>("SpecialPrice");
b.Property<DateTimeOffset?>("SpecialPriceEnd");
b.Property<DateTimeOffset?>("SpecialPriceStart");
b.Property<string>("Specification");
b.Property<int?>("StockQuantity");
b.Property<long?>("ThumbnailImageId");
b.Property<long?>("UpdatedById");
b.Property<DateTimeOffset>("UpdatedOn");
b.Property<bool?>("VendorId");
b.HasKey("Id");
b.HasIndex("BrandId");
b.HasIndex("CreatedById");
b.HasIndex("ThumbnailImageId");
b.HasIndex("UpdatedById");
b.ToTable("Catalog_Product");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductAttribute", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("GroupId");
b.Property<string>("Name");
b.HasKey("Id");
b.HasIndex("GroupId");
b.ToTable("Catalog_ProductAttribute");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductAttributeGroup", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Catalog_ProductAttributeGroup");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductAttributeValue", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("AttributeId");
b.Property<long>("ProductId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("AttributeId");
b.HasIndex("ProductId");
b.ToTable("Catalog_ProductAttributeValue");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductCategory", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("CategoryId");
b.Property<int>("DisplayOrder");
b.Property<bool>("IsFeaturedProduct");
b.Property<long>("ProductId");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("ProductId");
b.ToTable("Catalog_ProductCategory");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductLink", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("LinkType");
b.Property<long>("LinkedProductId");
b.Property<long>("ProductId");
b.HasKey("Id");
b.HasIndex("LinkedProductId");
b.HasIndex("ProductId");
b.ToTable("Catalog_ProductLink");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductMedia", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("DisplayOrder");
b.Property<long>("MediaId");
b.Property<long>("ProductId");
b.HasKey("Id");
b.HasIndex("MediaId");
b.HasIndex("ProductId");
b.ToTable("Catalog_ProductMedia");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductOption", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Catalog_ProductOption");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductOptionCombination", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("OptionId");
b.Property<long>("ProductId");
b.Property<int>("SortIndex");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("OptionId");
b.HasIndex("ProductId");
b.ToTable("Catalog_ProductOptionCombination");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductOptionValue", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("OptionId");
b.Property<long>("ProductId");
b.Property<int>("SortIndex");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("OptionId");
b.HasIndex("ProductId");
b.ToTable("Catalog_ProductOptionValue");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductTemplate", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired();
b.HasKey("Id");
b.ToTable("Catalog_ProductTemplate");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductTemplateProductAttribute", b =>
{
b.Property<long>("ProductTemplateId");
b.Property<long>("ProductAttributeId");
b.HasKey("ProductTemplateId", "ProductAttributeId");
b.HasIndex("ProductAttributeId");
b.ToTable("Catalog_ProductTemplateProductAttribute");
});
modelBuilder.Entity("SimplCommerce.Module.Cms.Models.Page", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Body");
b.Property<long?>("CreatedById");
b.Property<DateTimeOffset>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsPublished");
b.Property<string>("MetaDescription");
b.Property<string>("MetaKeywords");
b.Property<string>("MetaTitle");
b.Property<string>("Name");
b.Property<DateTimeOffset?>("PublishedOn");
b.Property<string>("SeoTitle");
b.Property<long?>("UpdatedById");
b.Property<DateTimeOffset>("UpdatedOn");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("UpdatedById");
b.ToTable("Cms_Page");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Address", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AddressLine1");
b.Property<string>("AddressLine2");
b.Property<string>("ContactName");
b.Property<long>("CountryId");
b.Property<long>("DistrictId");
b.Property<string>("Phone");
b.Property<long>("StateOrProvinceId");
b.HasKey("Id");
b.HasIndex("CountryId");
b.HasIndex("DistrictId");
b.HasIndex("StateOrProvinceId");
b.ToTable("Core_Address");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.AppSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Key");
b.Property<string>("Value");
b.HasKey("Id");
b.ToTable("Core_AppSetting");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Country", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Core_Country");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.District", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Location");
b.Property<string>("Name");
b.Property<long>("StateOrProvinceId");
b.Property<string>("Type");
b.HasKey("Id");
b.HasIndex("StateOrProvinceId");
b.ToTable("Core_District");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Entity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("EntityId");
b.Property<long>("EntityTypeId");
b.Property<string>("Name");
b.Property<string>("Slug");
b.HasKey("Id");
b.HasIndex("EntityTypeId");
b.ToTable("Core_Entity");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.EntityType", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<string>("RoutingAction");
b.Property<string>("RoutingController");
b.HasKey("Id");
b.ToTable("Core_EntityType");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Media", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Caption");
b.Property<string>("FileName");
b.Property<int>("FileSize");
b.Property<int>("MediaType");
b.HasKey("Id");
b.ToTable("Core_Media");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Role", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("Core_Role");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.StateOrProvince", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("CountryId");
b.Property<string>("Name");
b.Property<string>("Type");
b.HasKey("Id");
b.HasIndex("CountryId");
b.ToTable("Core_StateOrProvince");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTimeOffset>("CreatedOn");
b.Property<long?>("DefaultBillingAddressId");
b.Property<long?>("DefaultShippingAddressId");
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<string>("FullName");
b.Property<bool>("IsDeleted");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<DateTimeOffset>("UpdatedOn");
b.Property<Guid>("UserGuid");
b.Property<string>("UserName")
.HasMaxLength(256);
b.Property<bool?>("VendorId");
b.HasKey("Id");
b.HasIndex("DefaultBillingAddressId");
b.HasIndex("DefaultShippingAddressId");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("Core_User");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.UserAddress", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("AddressId");
b.Property<int>("AddressType");
b.Property<DateTimeOffset?>("LastUsedOn");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("AddressId");
b.HasIndex("UserId");
b.ToTable("Core_UserAddress");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.UserRole", b =>
{
b.Property<long>("UserId");
b.Property<long>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("Core_UserRole");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Vendor", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Email");
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<string>("Name");
b.Property<string>("SeoTitle");
b.HasKey("Id");
b.ToTable("Core_Vendor");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Widget", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code");
b.Property<string>("CreateUrl");
b.Property<DateTimeOffset>("CreatedOn");
b.Property<string>("EditUrl");
b.Property<bool>("IsPublished");
b.Property<string>("Name");
b.Property<string>("ViewComponentName");
b.HasKey("Id");
b.ToTable("Core_Widget");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.WidgetInstance", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTimeOffset>("CreatedOn");
b.Property<string>("Data");
b.Property<int>("DisplayOrder");
b.Property<string>("HtmlData");
b.Property<string>("Name");
b.Property<DateTimeOffset?>("PublishEnd");
b.Property<DateTimeOffset?>("PublishStart");
b.Property<DateTimeOffset>("UpdatedOn");
b.Property<long>("WidgetId");
b.Property<long>("WidgetZoneId");
b.HasKey("Id");
b.HasIndex("WidgetId");
b.HasIndex("WidgetZoneId");
b.ToTable("Core_WidgetInstance");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.WidgetZone", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Core_WidgetZone");
});
modelBuilder.Entity("SimplCommerce.Module.Localization.Models.Culture", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Localization_Culture");
});
modelBuilder.Entity("SimplCommerce.Module.Localization.Models.Resource", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("CultureId");
b.Property<string>("Key");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("CultureId");
b.ToTable("Localization_Resource");
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.CartItem", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTimeOffset>("CreatedOn");
b.Property<long>("ProductId");
b.Property<int>("Quantity");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserId");
b.ToTable("Orders_CartItem");
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.Order", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("BillingAddressId");
b.Property<long>("CreatedById");
b.Property<DateTimeOffset>("CreatedOn");
b.Property<int>("OrderStatus");
b.Property<long?>("ParentId");
b.Property<long>("ShippingAddressId");
b.Property<decimal>("SubTotal");
b.Property<DateTimeOffset?>("UpdatedOn");
b.Property<bool?>("VendorId");
b.HasKey("Id");
b.HasIndex("BillingAddressId");
b.HasIndex("CreatedById");
b.HasIndex("ParentId");
b.HasIndex("ShippingAddressId");
b.ToTable("Orders_Order");
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.OrderAddress", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AddressLine1");
b.Property<string>("AddressLine2");
b.Property<string>("ContactName");
b.Property<long>("CountryId");
b.Property<long>("DistrictId");
b.Property<string>("Phone");
b.Property<long>("StateOrProvinceId");
b.HasKey("Id");
b.HasIndex("CountryId");
b.HasIndex("DistrictId");
b.HasIndex("StateOrProvinceId");
b.ToTable("Orders_OrderAddress");
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.OrderItem", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long?>("OrderId");
b.Property<long>("ProductId");
b.Property<decimal>("ProductPrice");
b.Property<int>("Quantity");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("ProductId");
b.ToTable("Orders_OrderItem");
});
modelBuilder.Entity("SimplCommerce.Module.Reviews.Models.Review", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Comment");
b.Property<DateTimeOffset>("CreatedOn");
b.Property<long>("EntityId");
b.Property<long>("EntityTypeId");
b.Property<int>("Rating");
b.Property<string>("ReviewerName");
b.Property<int>("Status");
b.Property<string>("Title");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Reviews_Review");
});
modelBuilder.Entity("SimplCommerce.Module.Search.Models.Query", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTimeOffset>("CreatedOn");
b.Property<string>("QueryText");
b.Property<int>("ResultsCount");
b.HasKey("Id");
b.ToTable("Search_Query");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<long>", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<long>", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<long>", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.ActivityLog.Models.Activity", b =>
{
b.HasOne("SimplCommerce.Module.ActivityLog.Models.ActivityType", "ActivityType")
.WithMany()
.HasForeignKey("ActivityTypeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.Category", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.Category", "Parent")
.WithMany("Child")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.Product", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.Brand", "Brand")
.WithMany()
.HasForeignKey("BrandId");
b.HasOne("SimplCommerce.Module.Core.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById");
b.HasOne("SimplCommerce.Module.Core.Models.Media", "ThumbnailImage")
.WithMany()
.HasForeignKey("ThumbnailImageId");
b.HasOne("SimplCommerce.Module.Core.Models.User", "UpdatedBy")
.WithMany()
.HasForeignKey("UpdatedById");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductAttribute", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.ProductAttributeGroup", "Group")
.WithMany("Attributes")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductAttributeValue", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.ProductAttribute", "Attribute")
.WithMany()
.HasForeignKey("AttributeId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany("AttributeValues")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductCategory", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany("Categories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductLink", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "LinkedProduct")
.WithMany("LinkedProductLinks")
.HasForeignKey("LinkedProductId");
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany("ProductLinks")
.HasForeignKey("ProductId");
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductMedia", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Media", "Media")
.WithMany()
.HasForeignKey("MediaId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany("Medias")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductOptionCombination", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.ProductOption", "Option")
.WithMany()
.HasForeignKey("OptionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany("OptionCombinations")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductOptionValue", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.ProductOption", "Option")
.WithMany()
.HasForeignKey("OptionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany("OptionValues")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Catalog.Models.ProductTemplateProductAttribute", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.ProductAttribute", "ProductAttribute")
.WithMany("ProductTemplates")
.HasForeignKey("ProductAttributeId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Catalog.Models.ProductTemplate", "ProductTemplate")
.WithMany("ProductAttributes")
.HasForeignKey("ProductTemplateId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Cms.Models.Page", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById");
b.HasOne("SimplCommerce.Module.Core.Models.User", "UpdatedBy")
.WithMany()
.HasForeignKey("UpdatedById");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Address", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Country", "Country")
.WithMany()
.HasForeignKey("CountryId");
b.HasOne("SimplCommerce.Module.Core.Models.District", "District")
.WithMany()
.HasForeignKey("DistrictId");
b.HasOne("SimplCommerce.Module.Core.Models.StateOrProvince", "StateOrProvince")
.WithMany()
.HasForeignKey("StateOrProvinceId");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.District", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.StateOrProvince", "StateOrProvince")
.WithMany()
.HasForeignKey("StateOrProvinceId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.Entity", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.EntityType", "EntityType")
.WithMany()
.HasForeignKey("EntityTypeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.StateOrProvince", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Country", "Country")
.WithMany()
.HasForeignKey("CountryId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.User", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.UserAddress", "DefaultBillingAddress")
.WithMany()
.HasForeignKey("DefaultBillingAddressId");
b.HasOne("SimplCommerce.Module.Core.Models.UserAddress", "DefaultShippingAddress")
.WithMany()
.HasForeignKey("DefaultShippingAddressId");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.UserAddress", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Address", "Address")
.WithMany("UserAddresses")
.HasForeignKey("AddressId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Core.Models.User", "User")
.WithMany("UserAddresses")
.HasForeignKey("UserId");
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.UserRole", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Role", "Role")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Core.Models.User", "User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Core.Models.WidgetInstance", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Widget", "Widget")
.WithMany()
.HasForeignKey("WidgetId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Core.Models.WidgetZone", "WidgetZone")
.WithMany()
.HasForeignKey("WidgetZoneId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Localization.Models.Resource", b =>
{
b.HasOne("SimplCommerce.Module.Localization.Models.Culture", "Culture")
.WithMany("Resources")
.HasForeignKey("CultureId");
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.CartItem", b =>
{
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Core.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.Order", b =>
{
b.HasOne("SimplCommerce.Module.Orders.Models.OrderAddress", "BillingAddress")
.WithMany()
.HasForeignKey("BillingAddressId");
b.HasOne("SimplCommerce.Module.Core.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SimplCommerce.Module.Orders.Models.Order", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
b.HasOne("SimplCommerce.Module.Orders.Models.OrderAddress", "ShippingAddress")
.WithMany()
.HasForeignKey("ShippingAddressId");
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.OrderAddress", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.Country", "Country")
.WithMany()
.HasForeignKey("CountryId");
b.HasOne("SimplCommerce.Module.Core.Models.District", "District")
.WithMany()
.HasForeignKey("DistrictId");
b.HasOne("SimplCommerce.Module.Core.Models.StateOrProvince", "StateOrProvince")
.WithMany()
.HasForeignKey("StateOrProvinceId");
});
modelBuilder.Entity("SimplCommerce.Module.Orders.Models.OrderItem", b =>
{
b.HasOne("SimplCommerce.Module.Orders.Models.Order", "Order")
.WithMany("OrderItems")
.HasForeignKey("OrderId");
b.HasOne("SimplCommerce.Module.Catalog.Models.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SimplCommerce.Module.Reviews.Models.Review", b =>
{
b.HasOne("SimplCommerce.Module.Core.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 33.079273 | 117 | 0.457875 | [
"Apache-2.0"
] | ChauHoe/SimplCommerce | src/SimplCommerce.WebHost/Migrations/20170217035116_AddedVendor.Designer.cs | 45,486 | C# |
////css_dbg /t:winexe, /args:/prj "e:\cs-script\Dev\Dictionary\Dictionary\dictionary.cs";
////css_args /dbg;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using csscript;
using CSScriptLibrary;
using Microsoft.Win32;
/* TODO
* WWF - this project type is yet to be supported by VS2008 Express
*/
namespace VS100
{
class Script
{
static string usage = "Usage: cscscript debugVS10.0 [/e] [[/prj] scriptFile]|[[/r] projectFile] ...\nLoads C# script file into temporary VS 10.0 C# project and opens it.\n\n" +
"</e> - Express edition of Visual Studio 2010\n" +
"</prj> - command switch to create project without opening it\n" +
"</print> - prints into STDOUT all files (dependant scripts and assemblies).\n Not to be used with any other argument.\n" +
"</noide> - prepares the project file and exits (used only from VSX).\n Not to be used with any other argument.\n" +
"</r> - command switch to refresh project content of a .csproj file.\n\n" +
"use //css_dbg directive in code to set on-fly project settings.\n" +
"Example: //css_dbg /t:winexe, /args:\"Test argument\", /platform:x86;\n";
public enum IDEEditions
{
normal,
express,
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool SetEnvironmentVariable(string lpName, string lpValue);
static string GetTempCSSDir()
{
return Path.Combine(Path.GetTempPath(), "CSSCRIPT");
}
static public void Main(string[] args)
{
SetEnvironmentVariable("CSScriptDebugging", "VS10.0");
if (args.Length == 0 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
{
Console.WriteLine(usage);
}
else if (args[0].Trim().ToLower() == "/prj")
{
scriptFile = ResolveScriptFile(args[1]);
try
{
VS100IDE.IsolateProject(scriptFile, Path.Combine(Path.GetDirectoryName(scriptFile), Path.GetFileNameWithoutExtension(scriptFile)));
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message);
}
}
else if (args[0].Trim().ToLower() == "/r")
{
string projFile = args[1];
try
{
VS100IDE.RefreshProject(projFile);
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message);
}
}
else if (args[0].Trim().ToLower() == "/print")
{
try
{
// Note "/print" is to be only invoked from VSX, which can only be hosted by full VS. Thus "/print" and "/e" cannot come together.
scriptFile = args[1];
ScriptParser parser = new ScriptParser(scriptFile, Script.SearchDirs, false);
foreach (string dir in parser.SearchDirs)
AddSearchDir(dir);
Console.WriteLine("Src:{0}", scriptFile);
foreach (string file in parser.SaveImportedScripts())
Console.WriteLine("Src:{0}", file);
string[] defaultAsms = (CSScript.GlobalSettings.DefaultRefAssemblies ?? "")
.Replace(" ", "")
.Split(";,".ToCharArray());
List<string> referencedAssemblies = new List<string>();
List<string> referencedNamespaces = new List<string>();
referencedNamespaces.AddRange(parser.ReferencedNamespaces);
referencedNamespaces.AddRange(defaultAsms);
foreach (string name in referencedNamespaces)
if (!parser.IgnoreNamespaces.Contains(name))
referencedAssemblies.AddRange(AssemblyResolver.FindAssembly(name, SearchDirs));
foreach (string asm in parser.ReferencedAssemblies) //some assemblies were referenced from code
referencedAssemblies.AddRange(AssemblyResolver.FindAssembly(asm, SearchDirs));
foreach (string asm in parser.ResolvePackages())
referencedAssemblies.Add(asm);
foreach (string file in referencedAssemblies.Distinct())
Console.WriteLine("Asm:{0}", file);
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message);
}
}
else
{
try
{
bool doNotOpenIDE = false;
IDEEditions edition = IDEEditions.normal;
scriptFile = args[0];
if (args[0].Trim().ToLower() == "/e")
{
edition = IDEEditions.express;
scriptFile = args[1];
}
// Note "/noide" is to be only invoked from VSX, which can only be hosted by full VS. Thus "/noide" and "/e" cannot come together.
if (args[0].Trim().ToLower() == "/noide")
{
doNotOpenIDE = true;
scriptFile = args[1];
}
scriptFile = ResolveScriptFile(scriptFile);
RunPreScripts(scriptFile);
string tempDir = Path.Combine(GetTempCSSDir(), Environment.TickCount.ToString());
string solutionFile = VS100IDE.CreateProject(scriptFile, tempDir);
string projFile = Path.ChangeExtension(solutionFile, ".csproj");
//"lock" the directory to indicate that it is in use
File.WriteAllText(Path.Combine(tempDir, "host.pid"), Process.GetCurrentProcess().Id.ToString());
//open project
Environment.CurrentDirectory = Path.GetDirectoryName(scriptFile);
Process myProcess = new Process();
myProcess.StartInfo.FileName = VS100IDE.GetIDEFile(edition);
if (myProcess.StartInfo.FileName == "<not defined>")
{
if (edition == IDEEditions.express)
myProcess.StartInfo.FileName = VS100IDE.GetIDEFile(IDEEditions.normal);
else
myProcess.StartInfo.FileName = VS100IDE.GetIDEFile(IDEEditions.express);
}
AddToRecentScripts(scriptFile);
if (!doNotOpenIDE)
{
myProcess.StartInfo.Arguments = "\"" + solutionFile + "\" " + " /command Edit.OpenFile " + "\"" + scriptFile + "\"";
//MessageBox.Show("About to start the VS2010");
myProcess.Start();
myProcess.WaitForExit();
}
else
{
Console.WriteLine("Solution File: " + solutionFile);
}
if (doNotOpenIDE)
{
//calling party is responsible for cleanup
}
else
{
//do clean up
foreach (string file in VS100IDE.GetImportedScripts(projFile))
{
DeleteSatelliteFiles(file);
if (Path.GetFileName(file).StartsWith("i_")) //imported modified files have name "i_file_XXXXXX.cs>"
{
DeleteSatelliteFiles(file);
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
}
try
{
Directory.Delete(tempDir, true);
}
catch { }
RunPostScripts(scriptFile);
}
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be linked to the temp project:\n" + e);
}
}
}
static void AddToRecentScripts(string file)
{
try
{
//Debug.Assert(false);
string historyFile = Path.Combine(GetTempCSSDir(), "VS2010_recent.txt");
int maxHistoryCount = 5;
List<string> lines = new List<string>();
try
{
lines.AddRange(File.ReadAllLines(historyFile));
}
catch { }
using (var writer = new StreamWriter(historyFile + ".pending"))
{
List<string> matchingEntries = new List<string>();
foreach (string line in lines)
if (line.EndsWith(file))
matchingEntries.Add(line);
/*
var matchingEntries1 = (from line in lines
where line.EndsWith(file)
select line)
.ToArray(); //important to call ToArray() in order to create a disconnected copy of the "lines" subset
*/
foreach (string entry in matchingEntries)
lines.Remove(entry);
int countEccess = lines.Count - maxHistoryCount - 1;
if (countEccess > 0)
foreach (string entry in lines.ToArray().Reverse())
{
if (!entry.StartsWith("<pinned>"))
{
countEccess--;
lines.Remove(entry);
}
if (countEccess == 0)
break;
}
if (matchingEntries.Count() != 0)
lines.Insert(0, matchingEntries.First());
else
lines.Insert(0, file);
foreach (var line in lines)
writer.WriteLine(line);
}
File.Copy(historyFile + ".pending", historyFile, true);
File.Delete(historyFile + ".pending");
}
catch { }
}
static void DeleteSatelliteFiles(string file)
{
try
{
if (File.Exists(Path.ChangeExtension(file, ".resx")))
File.Delete(Path.ChangeExtension(file, ".resx"));
else if (File.Exists(Path.ChangeExtension(file, ".layout")))
File.Delete(Path.ChangeExtension(file, ".layout"));
}
catch { }
}
static string ResolveScriptFile(string file)
{
if (Path.GetExtension(file) == "")
return Path.GetFullPath(file + ".cs");
else
return Path.GetFullPath(file);
}
static Settings GetSystemWideSettings()
{
string defaultConfig = Path.GetFullPath(Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\css_config.xml"));
if (File.Exists(defaultConfig))
return Settings.Load(defaultConfig);
else
return null;
}
static string scriptFile;
static List<string> searchDirsList = CreateSearchDirs();
static void AddSearchDir(string newDir)
{
foreach (string dir in searchDirsList)
{
if (string.Compare(newDir, dir, true) == 0)
return;
}
searchDirsList.Add(newDir);
}
static List<string> CreateSearchDirs()
{
var retval = new List<string>();
if (scriptFile != null)
retval.Add(Path.GetDirectoryName(Path.GetFullPath(scriptFile)));
retval.Add(Path.GetFullPath(Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib")));
Settings settings = GetSystemWideSettings();
if (settings != null)
{
foreach (string dirItem in settings.SearchDirs.Split(';'))
if (dirItem != "")
{
string dir = Path.GetFullPath(Environment.ExpandEnvironmentVariables(dirItem));
bool alreadyAdded = false;
foreach (string item in retval)
{
if (string.Compare(item, dir, true) == 0)
{
alreadyAdded = true;
break;
}
}
if (!alreadyAdded)
retval.Add(dir);
}
}
if (CSScript.GlobalSettings != null && CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)
searchDirsList.Add(Path.GetFullPath(CSSEnvironment.GetCacheDirectory(Path.GetFullPath(scriptFile))));
return retval;
}
static string[] SearchDirs
{
get
{
return searchDirsList.ToArray();
}
}
public class VS100IDE
{
static public bool isolating = false;
public delegate string ProcessSourceFile(string srcFile, string projDir);
static public void IsolateProject(string scriptFile, string tempDir)
{
if (Directory.Exists(tempDir))
{
try
{
Directory.Delete(tempDir, true);
}
catch (Exception e)
{
throw new Exception("Cannot clean destination folder " + tempDir + "\n" + e.Message);
}
}
RunPreScripts(scriptFile);
VS100IDE.isolating = true;
string solutionFile = CreateProject(scriptFile, tempDir, new ProcessSourceFile(IsolateSourceFile), true);
//rename project files
string newSolutionFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(scriptFile) + ".sln");
string newProjectFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(scriptFile) + ".csproj");
using (StreamReader sr = new StreamReader(Path.ChangeExtension(solutionFile, ".csproj")))
using (StreamWriter sw = new StreamWriter(newProjectFile))
sw.Write(sr.ReadToEnd().Replace(Path.GetFileNameWithoutExtension(solutionFile), Path.GetFileNameWithoutExtension(newProjectFile)));
File.Delete(Path.ChangeExtension(solutionFile, ".csproj"));
using (StreamReader sr = new StreamReader(solutionFile)) //repoint solution to the right project file
{
using (FileStream fs = new FileStream(newSolutionFile, FileMode.CreateNew))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
//bw.Write((byte)0xEF); //VS2005 binary header
//bw.Write((byte)0xBB);
//bw.Write((byte)0xBF);
string text = sr.ReadToEnd().Replace(Path.GetFileNameWithoutExtension(solutionFile), Path.GetFileNameWithoutExtension(newProjectFile));
char[] buf = text.ToCharArray();
bw.Write(buf, 0, buf.Length);
}
}
}
using (StreamReader sr = new StreamReader(newProjectFile))
if (sr.ReadToEnd().IndexOf(".layout\"") == -1) //is not WWF StateMachine project
foreach (string file in Directory.GetFiles(Path.GetDirectoryName(newProjectFile), "*.layout"))
File.Delete(file);
File.Delete(Path.ChangeExtension(solutionFile, ".csproj.user"));
File.Delete(Path.Combine(Path.GetDirectoryName(solutionFile), "wwf.layout"));
File.Delete(solutionFile);
RunPostScripts(scriptFile);
Console.WriteLine("Script " + Path.GetFileName(scriptFile) + " is isolated to folder: " + new DirectoryInfo(tempDir).FullName);
}
static public string IsolateSourceFile(string srcFile, string projDir)
{
string newName = Path.Combine(projDir, Path.GetFileName(srcFile));
if (Path.GetFileName(newName).StartsWith("i_")) //rename imported files to their original names
{
int end = newName.LastIndexOf("_");
if (end != -1)
{
string newFile = Path.GetFileName(newName.Substring(0, end).Replace("i_", "") + Path.GetExtension(newName));
newFile = Path.Combine(projDir, newFile);
if (File.Exists(newFile))
{
newFile = GetCopyName(newFile);
}
newName = newFile;
}
}
File.Copy(srcFile, newName);
File.SetAttributes(newName, FileAttributes.Normal);
try
{
if (Path.GetFileName(srcFile).StartsWith("i_"))
File.Delete(srcFile);
}
catch { }
return newName;
}
static public string IgnoreSourceFile(string srcFile, string projDir)
{
return srcFile;
}
public static bool IsResxRequired(string scriptFile)
{
if (!File.Exists(scriptFile))
return false;
using (StreamReader sr = new StreamReader(scriptFile))
{
//Form class containing InitializeComponent call require resx dependant designer
//SequentialWorkflowActivity class contains InitializeComponent call but it does not require resx dependant designer
string text = sr.ReadToEnd();
return text.IndexOf("InitializeComponent();") != -1 &&
text.IndexOf("SequentialWorkflowActivity") == -1 &&
text.IndexOf("StateMachineWorkflowActivity") == -1;
}
}
static public string CreateProject(string scriptFile, string tempDir)
{
return CreateProject(scriptFile, tempDir, new ProcessSourceFile(IgnoreSourceFile), false);
}
static string FindAssociatedXml(string srcFile, string[] srcFiles)
{
string retval = "";
if (srcFile.EndsWith(".cs"))
{
if (Path.GetFileNameWithoutExtension(srcFile).ToLower().EndsWith(".xaml")) //Window1.xaml.cs + Window1.xaml
{
retval = Path.Combine(Path.GetDirectoryName(srcFile), Path.GetFileNameWithoutExtension(srcFile));
}
else
{
string expectedXAML = (Path.GetFileNameWithoutExtension(srcFile) + ".xaml").ToLower();
foreach (string file in srcFiles)
if (Path.GetFileName(file).ToLower() == expectedXAML)
retval = file;
}
}
return retval;
}
static private bool UsesPreprocessor(string file, out string precompiler)
{
precompiler = "";
if (!File.Exists(file))
return false;
if (!Path.GetFileName(file).ToLower().StartsWith("debugvs") &&
!Path.GetFileName(file).ToLower().StartsWith("i_debugvs".ToLower())) //do not parse itself
{
using (StreamReader sr = new StreamReader(file))
{
string code = sr.ReadToEnd();
if (code != null)
{
int start = code.IndexOf("//css_pre precompile");
if (start != -1)
{
start += "//css_pre".Length;
int end = code.IndexOf("(", start);
precompiler = code.Substring(start, end - start).Trim();
precompiler = FileResolver.ResolveFile(precompiler, SearchDirs, ".cs");
return true;
}
else
return false;
}
else
return false;
}
}
return false;
}
static private string CreateProject(string scriptFile, string tempDir, ProcessSourceFile fileHandler, bool copyLocalAsm)
{
string srcProjDir = @"Lib\Debug\VS10.0"; //relative to CSSCRIPT_DIR
string scHomeDir = VS100IDE.GetEnvironmentVariable("CSSCRIPT_DIR");
string scriptShortName = Path.GetFileName(scriptFile);
string projFile = Path.Combine(tempDir, "DebugScript.csproj");
string solutionFile = Path.Combine(tempDir, "DebugScript.sln");
//copy project template
if (!Directory.Exists(tempDir))
Directory.CreateDirectory(tempDir);
foreach (string file in Directory.GetFiles(Path.Combine(scHomeDir, srcProjDir)))
{
if (Path.GetExtension(file) != ".resx")
{
if (string.Compare(Path.GetFileName(file), "AssemblyInfo.cs", true) == 0)
{
using (StreamReader sr = new StreamReader(file))
using (StreamWriter sw = new StreamWriter(Path.Combine(tempDir, Path.GetFileName(file))))
{
string code = sr.ReadToEnd().Replace("ScriptDebugger", Path.GetFileNameWithoutExtension(scriptFile))
.Replace("ScriptFullPath", scriptFile);
sw.Write(code);
}
}
else
{
File.Copy(file, Path.Combine(tempDir, Path.GetFileName(file)), true);
}
}
}
//update project template with script specific data
VS100IDE ide = new VS100IDE();
ScriptParser parser = new ScriptParser(scriptFile, Script.SearchDirs, VS100IDE.isolating);
AssemblyResolver asmResolver = new AssemblyResolver();
foreach (string dir in parser.SearchDirs)
AddSearchDir(dir);
string resxSrcFile = Path.Combine(Path.Combine(scHomeDir, srcProjDir), "Form1.resx");
bool XAML = false;
bool WWF = false;
ArrayList importerdScripts = new ArrayList();
ArrayList precompilibleScripts = new ArrayList();
importerdScripts.AddRange(parser.SaveImportedScripts());
string srcFile = fileHandler(scriptFile, tempDir);
XAML = srcFile.ToLower().EndsWith(".xaml");
string associatedXml = FindAssociatedXml(srcFile, (string[])importerdScripts.ToArray(typeof(string)));
string precompiler = "";
if (UsesPreprocessor(srcFile, out precompiler))
precompilibleScripts.Add(new string[] { srcFile, precompiler });
if (VS100IDE.IsResxRequired(srcFile) && associatedXml == "")
ide.InsertFile(srcFile, projFile, resxSrcFile, "");
else
{
if (associatedXml != "")
ide.InsertXamlCSFile(srcFile, projFile, associatedXml);
else
ide.InsertFile(srcFile, projFile, "", "");
}
foreach (string file in importerdScripts)
{
if (UsesPreprocessor(file, out precompiler))
precompilibleScripts.Add(new string[] { file, precompiler });
srcFile = fileHandler(file, tempDir);
associatedXml = FindAssociatedXml(srcFile, (string[])importerdScripts.ToArray(typeof(string)));
XAML = srcFile.ToLower().EndsWith(".xaml");
if (!Path.GetFileName(srcFile).StartsWith("i_") && VS100IDE.IsResxRequired(srcFile) && associatedXml == "")
{
ide.InsertFile(srcFile, projFile, resxSrcFile, "");
}
else
{
if (associatedXml != "")
ide.InsertXamlCSFile(srcFile, projFile, associatedXml);
else
ide.InsertFile(srcFile, projFile, "", "");
}
}
if (XAML)
ide.InsertImport(@"$(MSBuildBinPath)\Microsoft.WinFX.targets", projFile);
ArrayList referencedNamespaces = new ArrayList(parser.ReferencedNamespaces);
string[] defaultAsms = (CSScript.GlobalSettings.DefaultRefAssemblies ?? "")
.Replace(" ", "")
.Split(";,".ToCharArray());
referencedNamespaces.AddRange(defaultAsms);
if (precompilibleScripts.Count > 0)
{
referencedNamespaces.Add("CSScriptLibrary");
Hashtable ht = new Hashtable();
foreach (string[] info in precompilibleScripts)
{
if (!ht.ContainsKey(info[1])) //to avoid duplication
{
ht[info[1]] = true;
string t = Path.GetDirectoryName(scriptFile);
ide.InsertFile(Path.Combine(Path.GetDirectoryName(scriptFile), info[1]), projFile, "", "");
}
}
string commands = "";
foreach (string[] info in precompilibleScripts)
commands += "cscs.exe \"" + Path.Combine(Path.GetDirectoryName(scriptFile), info[1]) + "\" \"" + info[0] + "\" \"/primary:" + scriptFile + "\"" + "\r\n";
string firstPrecompiler = (precompilibleScripts[0] as string[])[1];
ide.InsertFile(Path.Combine(scHomeDir, "Lib\\precompile.part.cs"), projFile, "", firstPrecompiler);
ide.InsertPreBuildEvent(commands, projFile);
//<PropertyGroup>
//<PreBuildEvent>cscs.exe "C:\cs-script\Dev\Macros C#\precompile.cs" "C:\cs-script\Dev\Macros C#\code.cs"</PreBuildEvent>
//</PropertyGroup>
}
foreach (string name in referencedNamespaces)
{
bool ignore = false;
foreach (string ignoreName in parser.IgnoreNamespaces)
if (ignore = (name == ignoreName))
break;
if (ignore)
continue;
string[] asmFiles = AssemblyResolver.FindAssembly(name, SearchDirs);
foreach (string file in asmFiles)
{
if (!WWF && file.ToLower().IndexOf("system.workflow.runtime") != -1)
WWF = true;
if (!copyLocalAsm || file.IndexOf("assembly\\GAC") != -1 || file.IndexOf("assembly/GAC") != -1)
ide.InsertReference(file, projFile);
else
{
string asmCopy = Path.Combine(tempDir, Path.GetFileName(file));
File.Copy(file, asmCopy, true);
ide.InsertReference(Path.GetFileName(asmCopy), projFile);
}
}
}
List<string> refAssemblies = new List<string>(parser.ReferencedAssemblies);
//process referenced assemblies from the compiler options:
// /r:LibA=LibA.dll /r:LibB=LibB.dll
foreach (string optionsDef in parser.CompilerOptions)
foreach (string optionArg in ParseArguments(optionsDef))
{
string[] keyValue = optionArg.Split(new char[] { ':' }, 2);
if (keyValue[0] == "/r" || keyValue[0] == "/reference")
{
refAssemblies.Add(keyValue.Last());
}
}
foreach (string assemblyDef in refAssemblies) //some assemblies were referenced from code
{
string[] tokens = assemblyDef.Split(new char[] { '=' }, 2);
string asm = tokens.Last();
string aliase = null;
if (tokens.Length > 1)
aliase = tokens.First();
foreach (string file in AssemblyResolver.FindAssembly(asm, SearchDirs))
{
if (!WWF && file.ToLower().IndexOf("system.workflow.runtime") != -1)
WWF = true;
if (!copyLocalAsm || file.IndexOf("assembly\\GAC") != -1 || file.IndexOf("assembly\\GAC") != -1)
ide.InsertReference(file, projFile, aliase);
else
{
string asmCopy = Path.Combine(tempDir, Path.GetFileName(file));
if (Path.IsPathRooted(file) || File.Exists(file))
File.Copy(file, asmCopy, true);
ide.InsertReference(Path.GetFileName(asmCopy), projFile, aliase);
}
}
}
//adjust project settings
if (WWF)
{
ide.InsertProjectTypeGuids("{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", projFile);
ide.InsertImport(@"$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\v3.0\Workflow.Targets", projFile);
foreach (string file in importerdScripts)
if (file.ToLower().IndexOf("designer.cs") != -1)
{
string className = Path.GetFileNameWithoutExtension(file.ToLower()).Replace(".designer", "");
string template = Path.Combine(tempDir, "wwf.layout");
string layoutFile = file.Replace("designer.cs", "layout");
if (copyLocalAsm) //isolating
layoutFile = Path.Combine(Path.GetDirectoryName(projFile), Path.GetFileName(layoutFile));
File.Copy(template, layoutFile, true);
ReplaceInFile(layoutFile, "WFInitialState", className + "InitialState");
ide.InsertResource(layoutFile, projFile);
}
}
CSharpParser fileParser = new CSharpParser(scriptFile, true, new string[] { "//css_dbg", "//css_args", "//css_co" });
//foreach (string statement in fileParser.CustomDirectives["//css_dbg"] as List<string>)//should be reenabled when CS-Script is compiled for .NET 2.0
foreach (string statement in fileParser.CustomDirectives["//css_dbg"] as IEnumerable)
foreach (string directive in statement.Split(','))
{
string d = directive.Trim();
if (d.StartsWith("/t:"))
ide.SetOutputType(d.Substring("/t:".Length), projFile);
else if (d.StartsWith("/platform:"))
ide.SetPlatformType(d.Substring("/platform:".Length), projFile, solutionFile);
else if (d.Trim().StartsWith("/args:"))
ide.SetArguments(d.Substring("/args:".Length), projFile + ".user");
}
//foreach (string statement in fileParser.CustomDirectives["//css_args"] as List<string>) //should be reenabled when CS-Script is compiled for .NET 2.0
foreach (string statement in fileParser.CustomDirectives["//css_args"] as IEnumerable)
foreach (string directive in statement.Split(','))
{
string d = directive.Trim();
if (d.StartsWith("/co"))
{
string[] compilerOptions = d.Substring(4).Split(',');
foreach (string option in compilerOptions)
{
string o = option.Trim();
if (o.StartsWith("/unsafe"))
ide.SetAllowUnsafe(projFile);
else if (o.StartsWith("/platform:"))
ide.SetPlatformType(o.Substring("/platform:".Length), projFile, solutionFile);
}
}
}
foreach (string statement in fileParser.CustomDirectives["//css_co"] as IEnumerable)
foreach (string directive in statement.Split(','))
{
string d = directive.Trim();
if (d.StartsWith("/platform:"))
ide.SetPlatformType(d.Substring("/platform:".Length), projFile, solutionFile);
}
Settings settings = GetSystemWideSettings();
if (settings != null)
ide.SetTargetFramework(settings.TargetFramework, projFile);
ide.SetWorkingDir(Path.GetDirectoryName(scriptFile), projFile + ".user");
if (Environment.GetEnvironmentVariable("CSSCRIPT_VS_DROPASMINFO") != null && !VS100IDE.isolating)
ide.RemoveFile("AssemblyInfo.cs", projFile);
string appConfigFile = "";
if (File.Exists(Path.ChangeExtension(scriptFile, ".cs.config")))
appConfigFile = Path.ChangeExtension(scriptFile, ".cs.config");
else if (File.Exists(Path.ChangeExtension(scriptFile, ".exe.config")))
appConfigFile = Path.ChangeExtension(scriptFile, ".exe.config");
if (appConfigFile != "")
ide.InsertAppConfig(appConfigFile, projFile);
///////////////////////////////////
//rename project files
//'#' is an illegal character for the project/solution file name
string newSolutionFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(scriptFile).Replace("#", "Sharp") + " (script).sln");
string newProjectFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(newSolutionFile).Replace("#", "Sharp") + ".csproj");
FileMove(solutionFile, newSolutionFile);
FileMove(projFile, newProjectFile);
FileMove(projFile + ".user", newProjectFile + ".user");
ReplaceInFile(newSolutionFile, Path.GetFileNameWithoutExtension(projFile), Path.GetFileNameWithoutExtension(newProjectFile));
ReplaceInFile(newProjectFile, "DebugScript", Path.GetFileNameWithoutExtension(scriptFile));
//remove xmlns=""
VSProjectDoc.FixFile(newProjectFile);
VSProjectDoc.FixFile(newProjectFile + ".user");
///////////////////////
return newSolutionFile;
}
//very primitive command-line parser
static string[] ParseArguments(string commandLine)
{
var parmChars = commandLine.ToCharArray();
var inSingleQuote = false;
var inDoubleQuote = false;
for (var index = 0; index < parmChars.Length; index++)
{
if (parmChars[index] == '"' && !inSingleQuote)
{
inDoubleQuote = !inDoubleQuote;
parmChars[index] = '\n';
}
if (parmChars[index] == '\'' && !inDoubleQuote)
{
inSingleQuote = !inSingleQuote;
parmChars[index] = '\n';
}
if (!inSingleQuote && !inDoubleQuote && parmChars[index] == ' ')
parmChars[index] = '\n';
}
return (new string(parmChars)).Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
static void FileMove(string src, string dest)
{
if (File.Exists(dest))
File.Delete(dest);
File.Move(src, dest);
}
static void ReplaceInFile(string file, string oldValue, string newValue)
{
ReplaceInFile(file, new string[] { oldValue }, new string[] { newValue });
}
static void ReplaceInFile(string file, string[] oldValue, string[] newValue)
{
string content = "";
using (StreamReader sr = new StreamReader(file))
content = sr.ReadToEnd();
for (int i = 0; i < oldValue.Length; i++)
content = content.Replace(oldValue[i], newValue[i]);
using (StreamWriter sw = new StreamWriter(file))
sw.Write(content);
}
public void InsertImport(string importStr, string projFile)
{
//<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />
VSProjectDoc doc = new VSProjectDoc(projFile);
XmlElement elem = doc.CreateElement("Import");
XmlAttribute newAttr;
newAttr = doc.CreateAttribute("Project");
newAttr.Value = importStr;
elem.Attributes.Append(newAttr);
XmlNode node = doc.SelectFirstNode("//Project");
node.AppendChild(elem);
doc.Save(projFile);
}
public void InsertResource(string file, string projFile)
{
//<EmbeddedResource Include="Workflow1.layout">
// <DependentUpon>Workflow1.cs</DependentUpon>
//</EmbeddedResource>
VSProjectDoc doc = new VSProjectDoc(projFile);
XmlElement group = doc.CreateElement("ItemGroup");
XmlElement res = doc.CreateElement("EmbeddedResource");
XmlAttribute newAttr;
newAttr = doc.CreateAttribute("Include");
newAttr.Value = file;
res.Attributes.Append(newAttr);
XmlElement dependency = doc.CreateElement("DependentUpon");
dependency.InnerText = Path.ChangeExtension(Path.GetFileName(file), ".cs");
res.AppendChild(dependency);
group.AppendChild(res);
doc.SelectFirstNode("//Project").AppendChild(group);
doc.Save(projFile);
}
public void InsertPreBuildEvent(string commands, string projFile)
{
//<PropertyGroup>
//<PreBuildEvent>
//cscs.exe "C:\cs-script\Dev\Macros C#\precompile.cs" "C:\cs-script\Dev\Macros C#\code.cs"
//</PreBuildEvent>
//</PropertyGroup>
VSProjectDoc doc = new VSProjectDoc(projFile);
XmlElement elem = doc.CreateElement("PropertyGroup");
XmlElement elem1 = doc.CreateElement("PreBuildEvent");
elem1.InnerXml = commands;
elem.AppendChild(elem1);
doc.SelectFirstNode("//Project").AppendChild(elem);
doc.Save(projFile);
}
public void InsertProjectTypeGuids(string guids, string projFile)
{
//<ProjectTypeGuids>{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
VSProjectDoc doc = new VSProjectDoc(projFile);
XmlElement elem = doc.CreateElement("ProjectTypeGuids");
elem.InnerXml = guids;
doc.SelectFirstNode("//Project/PropertyGroup/Configuration").ParentNode.AppendChild(elem);
doc.Save(projFile);
}
public void RemoveFile(string file, string projFile)
{
try
{
VSProjectDoc doc = new VSProjectDoc(projFile);
XmlNode node = doc.SelectFirstNode("//Project/ItemGroup/Compile[@Include='" + file + "']");
node.ParentNode.RemoveChild(node);
doc.Save(projFile);
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be inserted to the temp project:\n" + e.Message);
}
}
public void InsertFile(string scriptFile, string projFile, string resxSrcFile, string parentFile)
{
string srcFile = scriptFile;
if (VS100IDE.isolating)
srcFile = Path.GetFileName(srcFile); //remove absolute path
try
{
string parent = "";
if (srcFile.ToLower().EndsWith(".designer.cs")) //needs to be dependent on 'base include'
{
parent = Path.GetFileName(srcFile);
parent = parent.Substring(0, parent.Length - ".designer.cs".Length) + ".cs";
}
if (srcFile.ToLower().EndsWith(".g.cs")) //needs to be dependent on 'base include'
{
parent = Path.GetFileName(srcFile);
parent = parent.Substring(0, parent.Length - ".g.cs".Length) + ".cs";
}
if (srcFile.ToLower().EndsWith(".part.cs")) //needs to be dependent on 'base include'
{
parent = Path.GetFileName(srcFile);
parent = parent.Substring(0, parent.Length - ".part.cs".Length) + ".cs";
}
if (parentFile != null && parentFile != "")
parent = parentFile;
//<Compile Include="C:\cs-script\Samples\tick.cs" />
//NOTE: VS7.1 is able to create .resx file for linked (not in the .proj directory) .cs files correctly. However VS9.0 can do this only for
//non-linked source files. Yes this is a new VS bug. Thus I have to create .resex in case if the file contains
//the class inherited from System.Windows.Form.
VSProjectDoc doc = new VSProjectDoc(projFile);
//Create a new node.
XmlElement elem = doc.CreateElement(srcFile.EndsWith(".xaml") ? "Page" : "Compile");
XmlAttribute newAttr;
newAttr = doc.CreateAttribute("Include");
newAttr.Value = srcFile;
elem.Attributes.Append(newAttr);
if (parent != "")
{
//<DependentUpon>Form1.cs</DependentUpon>
XmlElement nestedElem = doc.CreateElement("DependentUpon");
nestedElem.InnerText = Path.GetFileName(parent);
elem.AppendChild(nestedElem);
}
else if (srcFile.ToLower().EndsWith(".includes.cs"))
{
XmlElement nestedElem = doc.CreateElement("Link");
nestedElem.InnerText = "Includes\\" + Path.GetFileName(srcFile);
elem.AppendChild(nestedElem);
}
XmlNode contentsNode = doc.SelectNodes("//Project/ItemGroup")[1];
contentsNode.AppendChild(elem);
if (resxSrcFile != "")
{
//<EmbeddedResource Include="G:\Dev\WindowsApplication1\Form1.resx">
//<DependentUpon>Form1.cs</DependentUpon>
//</EmbeddedResource>
string resxFile = Path.ChangeExtension(srcFile, ".resx");
File.Copy(resxSrcFile, Path.Combine(Path.GetDirectoryName(scriptFile), resxFile), true);
elem = doc.CreateElement("EmbeddedResource");
newAttr = doc.CreateAttribute("Include");
newAttr.Value = resxFile;
elem.Attributes.Append(newAttr);
XmlElement nestedElem = doc.CreateElement("DependentUpon");
nestedElem.InnerText = Path.GetFileName(srcFile);
elem.AppendChild(nestedElem);
contentsNode.AppendChild(elem);
}
doc.Save(projFile);
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be inserted to the temp project:\n" + e.Message);
}
}
public void InsertAppConfig(string appConfigFile, string projFile)
{
string destFile = Path.Combine(Path.GetDirectoryName(projFile), "app.config");
if (File.Exists(destFile))
{
File.SetAttributes(destFile, FileAttributes.Normal);
File.Delete(destFile);
}
using (StreamReader sr = new StreamReader(appConfigFile))
using (StreamWriter sw = new StreamWriter(destFile))
{
sw.Write(sr.ReadToEnd());
sw.WriteLine("<!-- read-only copy of " + appConfigFile + " -->");
}
File.SetAttributes(destFile, FileAttributes.ReadOnly);
try
{
VSProjectDoc doc = new VSProjectDoc(projFile);
XmlElement group = doc.CreateElement("ItemGroup");
XmlElement none = doc.CreateElement("None");
XmlAttribute attr = doc.CreateAttribute("Include");
attr.Value = "app.config";
group.AppendChild(none);
none.Attributes.Append(attr);
doc.SelectFirstNode("//Project").AppendChild(group);
doc.Save(projFile);
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be inserted to the temp project:\n" + e.Message);
}
}
public void InsertXamlCSFile(string scriptFile, string projFile, string xamlSrcFile)
{
string srcFile = scriptFile;
if (VS100IDE.isolating)
srcFile = Path.GetFileName(srcFile); //remove absolute path
try
{
VSProjectDoc doc = new VSProjectDoc(projFile);
//Create a new node.
XmlElement elem = doc.CreateElement(srcFile.EndsWith(".xaml") ? "Page" : "Compile");
XmlAttribute newAttr;
newAttr = doc.CreateAttribute("Include");
newAttr.Value = srcFile;
elem.Attributes.Append(newAttr);
//<DependentUpon>Window1.xaml</DependentUpon>
XmlElement nestedElem = doc.CreateElement("DependentUpon");
nestedElem.InnerText = Path.GetFileName(xamlSrcFile);
elem.AppendChild(nestedElem);
doc.SelectNodes("//Project/ItemGroup")[1].AppendChild(elem);
doc.Save(projFile);
}
catch (Exception e)
{
MessageBox.Show("Specified file could not be inserted to the temp project:\n" + e.Message);
}
}
public void InsertReference(string asmFile, string projFile, string aliase = null)
{
string refFile = asmFile;
if (VS100IDE.isolating || asmFile.IndexOf("assembly\\GAC") != -1 || asmFile.IndexOf("assembly/GAC") != -1)
refFile = Path.GetFileName(refFile); //remove absolute path
try
{
//<Reference Include="CSScriptLibrary">
// <SpecificVersion>False</SpecificVersion>
// <HintPath>..\VS9.0\CSScriptLibrary.dll</HintPath>
// <Aliases>CSScript</Aliases>
//</Reference>
VSProjectDoc doc = new VSProjectDoc(projFile);
//Create a new node.
XmlElement elem = doc.CreateElement("Reference");
XmlAttribute newAttr;
newAttr = doc.CreateAttribute("Include");
newAttr.Value = Path.GetFileNameWithoutExtension(refFile);
elem.Attributes.Append(newAttr);
XmlElement elemSpecVer = doc.CreateElement("SpecificVersion");
elemSpecVer.InnerText = "False";
elem.AppendChild(elemSpecVer);
XmlElement elemPath = doc.CreateElement("HintPath");
elemPath.InnerText = refFile;
elem.AppendChild(elemPath);
if (aliase != null)
{
XmlElement elemAliase = doc.CreateElement("Aliases");
elemAliase.InnerText = aliase;
elem.AppendChild(elemAliase);
}
doc.SelectFirstNode("//Project/ItemGroup").AppendChild(elem);
doc.Save(projFile);
}
catch (Exception e)
{
MessageBox.Show("Specified reference could not be inserted into the temp project:\n" + e.Message);
}
}
public void SetWorkingDir(string dir, string file)
{
try
{
//<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
// <StartWorkingDirectory>C:\Program Files\Google\</StartWorkingDirectory>
//</PropertyGroup>
VSProjectDoc doc = new VSProjectDoc(file);
XmlElement elem = doc.CreateElement("StartWorkingDirectory");
elem.InnerText = dir;
XmlNodeList nodes = doc.SelectNodes("//Project/PropertyGroup");
nodes[0].AppendChild(elem);
nodes[1].AppendChild(elem.Clone());
doc.Save(file);
}
catch (Exception e)
{
MessageBox.Show("Specified 'working directory' could not be set for the temp project:\n" + e.Message);
}
}
public void SetArguments(string args, string file)
{
try
{
//<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
// <StartArguments>test</StartArguments>
//</PropertyGroup>
VSProjectDoc doc = new VSProjectDoc(file);
XmlElement elem = doc.CreateElement("StartArguments");
elem.InnerText = args;
XmlNodeList nodes = doc.SelectNodes("//Project/PropertyGroup");
nodes[0].AppendChild(elem);
nodes[1].AppendChild(elem.Clone());
doc.Save(file);
}
catch (Exception e)
{
MessageBox.Show("Specified 'working directory' could not be set for the temp project:\n" + e.Message);
}
}
public void SetAllowUnsafe(string file)
{
try
{
//<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
// <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
//</PropertyGroup>
VSProjectDoc doc = new VSProjectDoc(file);
//Create a new node.
XmlElement elem = doc.CreateElement("AllowUnsafeBlocks");
elem.InnerText = "true";
XmlNodeList nodes = doc.SelectNodes("//Project/PropertyGroup");
nodes[1].AppendChild(elem);
nodes[2].AppendChild(elem.Clone());
doc.Save(file);
}
catch (Exception e)
{
MessageBox.Show("Specified 'unsafe' could not be set for the temp project:\n" + e.Message);
}
}
public void SetOutputType(string type, string file)
{
try
{
//<OutputType>Exe</OutputType>
ReplaceInFile(file, "<OutputType>Exe</OutputType>", "<OutputType>" + type + "</OutputType>");
}
catch (Exception e)
{
MessageBox.Show("Specified 'working directory' could not be set for the temp project:\n" + e.Message);
}
}
public void SetTargetFramework(string target, string file)
{
try
{
//<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
ReplaceInFile(file, "<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>", "<TargetFrameworkVersion>" + target + "</TargetFrameworkVersion>");
}
catch (Exception e)
{
MessageBox.Show("Specified 'working directory' could not be set for the temp project:\n" + e.Message);
}
}
public void SetPlatformType(string type, string file, string solutionFile)
{
try
{
//<PlatformTarget>x86</PlatformTarget>
VSProjectDoc doc = new VSProjectDoc(file);
//Create a new node.
XmlNodeList existingElement = doc.SelectNodes("//Project/PropertyGroup/PlatformTarget");
XmlElement elem;
if (existingElement.Count > 0)
elem = (XmlElement)existingElement[0];
else
elem = doc.CreateElement("PlatformTarget");
elem.InnerText = type;
XmlNodeList nodes = doc.SelectNodes("//Project/PropertyGroup");
nodes[1].AppendChild(elem);
nodes[2].AppendChild(elem.Clone());
doc.Save(file);
ReplaceInFile(file, "AnyCPU", "x86");
ReplaceInFile(solutionFile, "AnyCPU", "x86");
ReplaceInFile(solutionFile, "Any CPU", "x86");
}
catch (Exception e)
{
MessageBox.Show("Specified '" + type + "' could not be set for the temp project:\n" + e.Message);
}
}
public void SetProjectTypeGuids(string type, string file)
{
try
{
//<ProjectTypeGuids></ProjectTypeGuids>
if (type != null && type != "")
ReplaceInFile(file, "<ProjectTypeGuids></ProjectTypeGuids>", "");
else
ReplaceInFile(file, "<ProjectTypeGuids></ProjectTypeGuids>", "<ProjectTypeGuids>" + type + "</ProjectTypeGuids>");
}
catch (Exception e)
{
MessageBox.Show("Specified 'working directory' could not be set for the temp project:\n" + e.Message);
}
}
static public string[][] GetAvailableIDE()
{
ArrayList retval = new ArrayList();
string name = "";
string hint = "";
string command = "";
string scHomeDir = GetEnvironmentVariable("CSSCRIPT_DIR");
if (GetIDEFile(IDEEditions.express) != "<not defined>")
{
name = "Open with VS2010E";
hint = "\t- Open with MS Visual Studio 2010 Express";
command = "\"" + scHomeDir + "\\csws.exe\" /c \"" + scHomeDir + "\\lib\\DebugVS10.0.cs\" /e \"%1\"";
retval.Add(new string[] { name, hint, command });
}
if (GetIDEFile(IDEEditions.normal) != "<not defined>")
{
name = "Open with VS2010";
hint = "\t- Open with MS Visual Studio 2010";
command = "\"" + scHomeDir + "\\csws.exe\" /c \"" + scHomeDir + "\\lib\\DebugVS10.0.cs\" \"%1\"";
retval.Add(new string[] { name, hint, command });
}
return (string[][])retval.ToArray(typeof(string[]));
}
static public string GetIDEFile(IDEEditions edition)
{
string retval = "<not defined>";
try
{
string keyname = (edition == IDEEditions.express) ? @"VCSExpress.cs.10.0\shell\Open\Command" : @"VisualStudio.cs.10.0\shell\Open\Command";
RegistryKey IDE = Registry.ClassesRoot.OpenSubKey(keyname);
if (IDE != null)
{
if (IDE.GetValue("") != null)
retval = IDE.GetValue("").ToString().TrimStart("\"".ToCharArray()).Split("\"".ToCharArray())[0];
}
}
catch { }
return retval;
}
static public string GetEnvironmentVariable(string name)
{
//It is important in the all "installation" scripts to have reliable GetEnvironmentVariable().
//Under some circumstances freshly set environment variable CSSCRIPT_DIR cannot be obtained with
//Environment.GetEnvironmentVariable(). For example when running under Total Commander or similar
//shell utility. Even SendMessageTimeout does not help in all cases. That is why GetEnvironmentVariable
//is reimplemented here.
object value = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment").GetValue(name);
return value == null ? null : value.ToString();
}
static private string GetCopyName(string file)
{
string retval = file;
int i = 1;
while (File.Exists(retval))
{
retval = Path.Combine(Path.GetDirectoryName(file), "Copy" + (i == 1 ? " of " : " (" + i.ToString() + ") ") + Path.GetFileName(file));
i++;
}
return retval;
}
static public string[] GetImportedScripts(string projFile)
{
ArrayList retval = new ArrayList();
XmlDocument doc = new XmlDocument();
doc.Load(projFile);
foreach (XmlNode child in doc.GetElementsByTagName("Compile"))
{
foreach (XmlAttribute attribute in child.Attributes)
{
if (attribute != null && attribute.Name == "Include")
retval.Add(attribute.Value.ToString().ToString());
}
}
return (string[])retval.ToArray(typeof(string));
}
internal static void RefreshProject(string projFile)
{
string[] content = VS100IDE.GetImportedScripts(projFile);
foreach (string file in content) //remove original imported files
{
if (Path.GetFileName(file).StartsWith("i_")) //imported modified files have name "i_file_XXXXXX.cs>"
{
try
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
catch { }
}
}
//regenerate project
scriptFile = ResolveScriptFile(content[0]);
RunPreScripts(scriptFile);
string newSolution = VS100IDE.CreateProject(content[0], Path.GetDirectoryName(projFile));
string[] newContent = VS100IDE.GetImportedScripts(Path.ChangeExtension(newSolution, ".csproj"));
//remove not needed .resx files from includes (not imported) files
for (int i = 1; i < content.Length; i++)
{
string file = content[i];
bool used = false;
if (!Path.GetFileName(file).StartsWith("i_")) //not imported script file
{
foreach (string newFile in newContent)
if (used = (String.Compare(newFile, file, true) == 0))
break;
try
{
if (!used)
{
if (File.Exists(Path.ChangeExtension(file, ".resx")))
File.Delete(Path.ChangeExtension(file, ".resx"));
else if (File.Exists(Path.ChangeExtension(file, ".layout")))
File.Delete(Path.ChangeExtension(file, ".layout"));
}
}
catch { }
}
}
RunPostScripts(scriptFile);
}
}
static void RunScript(string scriptFileCmd)
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cscs.exe";
myProcess.StartInfo.Arguments = scriptFileCmd;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
string line = null;
while (null != (line = myProcess.StandardOutput.ReadLine()))
{
Console.WriteLine(line);
}
myProcess.WaitForExit();
}
static string CompileScript(string scriptFile)
{
string retval = "";
StringBuilder sb = new StringBuilder();
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cscs.exe";
myProcess.StartInfo.Arguments = "/nl /ca \"" + scriptFile + "\"";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
string line = null;
while (null != (line = myProcess.StandardOutput.ReadLine()))
{
sb.Append(line);
sb.Append("\n");
}
myProcess.WaitForExit();
retval = sb.ToString();
string compiledFile = Path.ChangeExtension(scriptFile, ".csc");
if (retval == "" && File.Exists(compiledFile))
File.Delete(compiledFile);
return retval;
}
static void RunPreScripts(string scriptFile)
{
RunPrePostScripts(scriptFile, true);
}
static void RunPostScripts(string scriptFile)
{
RunPrePostScripts(scriptFile, false);
}
static void RunPrePostScripts(string scriptFile, bool prescript)
{
// Compile the script in order to proper execute all pre- and post-scripts.
// The RunScript(cmd) approach is attractive but not sutable as some pre-scripts must be run only from the primary script
// but not as a stand alone scripts. That is why it is disabled for now by "return;"
if (prescript)
{
CompileScript(scriptFile);
}
else
{
//do nothing
//yes this is a limitation of the debugVS9.0.cs
}
return;
//run pre- and post-scripts as an external process to ensure using the same css_config.xml file
string currDir = Environment.CurrentDirectory;
Environment.CurrentDirectory = Path.GetDirectoryName(scriptFile);
foreach (csscript.CSharpParser.CmdScriptInfo cmdScript in new csscript.CSharpParser(scriptFile, true).CmdScripts)
{
if (cmdScript.preScript == prescript)
{
string cmd = "";
foreach (string arg in cmdScript.args)
cmd += "\"" + arg + "\" ";
//The problem with RunScript(cmd) is that all pre- and post-script are executed as stand alone but not as a pre-/post-script of the primary script
RunScript(cmd);
//CSExecutor hard should be used here but it is hard as it is not esposed
//originalOptions.ScriptFilePrimary = scriptFile;
//CSExecutor exec = new CSExecutor(false, originalOptions);
//exec.Execute(cmdScript.args, null, scriptFile);
}
}
Environment.CurrentDirectory = currDir;
}
}
class FileResolver
{
static public string ResolveFile(string file, string[] extraDirs, string extension)
{
string fileName = file;
if (Path.GetExtension(fileName) == "")
fileName += extension;
//arbitrary directories
if (extraDirs != null)
{
foreach (string extraDir in extraDirs)
{
string dir = extraDir;
if (File.Exists(Path.Combine(dir, fileName)))
{
return Path.GetFullPath(Path.Combine(dir, fileName));
}
}
}
//PATH
string[] pathDirs = Environment.GetEnvironmentVariable("PATH").Replace("\"", "").Split(';');
foreach (string pathDir in pathDirs)
{
string dir = pathDir;
if (File.Exists(Path.Combine(dir, fileName)))
{
return Path.GetFullPath(Path.Combine(dir, fileName));
}
}
return "";
}
}
class VSProjectDoc : XmlDocument
{
public VSProjectDoc(string projFile)
{
Load(projFile);
}
static public void FixFile(string projFile)
{
//remove xmlns=""
//using (FileStream fs = new FileStream(projFile, FileMode.OpenOrCreate))
//using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode))
// sw.Write(FormatXml(this.InnerXml.Replace("xmlns=\"\"", "")));
string content = "";
using (StreamReader sr = new StreamReader(projFile))
content = sr.ReadToEnd();
content = content.Replace("xmlns=\"\"", "");
using (StreamWriter sw = new StreamWriter(projFile))
sw.Write(content);
}
public new XmlNodeList SelectNodes(string path)
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(NameTable);
nsmgr.AddNamespace("ab", "http://schemas.microsoft.com/developer/msbuild/2003");
if (path.StartsWith("//"))
{
path = path.Substring(1);
path = "/" + path.Replace("/", "/ab:");
}
else
{
path = path.Replace("/", "/ab:");
}
return SelectNodes(path, nsmgr);
}
public XmlNode SelectFirstNode(string path)
{
XmlNodeList nodes = SelectNodes(path);
if (nodes != null && nodes.Count != 0)
return nodes[0];
else
return null;
}
//static string FormatXml(string xml)
//{
// StringReader sr = new StringReader(xml);
// XmlReader reader = XmlReader.Create(sr);
// reader.MoveToContent();
// StringBuilder sb = new StringBuilder();
// XmlWriterSettings settings = new XmlWriterSettings();
// settings.Indent = true;
// settings.IndentChars = ("\t");
// settings.Encoding = System.Text.Encoding.Unicode;
// using (XmlWriter writer = XmlWriter.Create(sb, settings))
// writer.WriteNode(reader, true);
// return sb.ToString();
//}
}
} | 43.052226 | 184 | 0.48414 | [
"Apache-2.0"
] | findlayit/base-project | libraries/buildsupport/cs-script/lib/debugVS10.0.cs | 72,543 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SagaImpl.OrderService.Entities;
namespace SagaImpl.OrderService.Database.EntityConfiguration
{
public class OrderConfiguration : IEntityTypeConfiguration<OrderEntity>
{
public void Configure(EntityTypeBuilder<OrderEntity> builder)
{
builder.ToTable("Orders", Consents.SchemaNames.ORDER_SCHEMA);
builder.HasKey(o => o.Id);
builder.Property(o => o.Id)
.ValueGeneratedOnAdd();
builder.Property(o => o.UserId)
.IsRequired();
builder.Property(o => o.CreatedDate)
.IsRequired();
builder.Property(o => o.TotalPrice)
.IsRequired();
builder.HasOne(a => a.Status)
.WithMany()
.OnDelete(DeleteBehavior.Cascade)
.HasForeignKey(a => a.StatusId)
.IsRequired();
}
}
public class OrderStatusConfiguration : IEntityTypeConfiguration<OrderStatus>
{
public void Configure(EntityTypeBuilder<OrderStatus> builder)
{
builder.ToTable("OrderStatuses", Consents.SchemaNames.ORDER_SCHEMA);
builder.HasKey(a => a.Id);
builder.Property(a => a.Id)
.ValueGeneratedNever();
builder.Property(a => a.Name)
.HasMaxLength(20)
.IsRequired();
}
}
}
| 29.519231 | 81 | 0.570684 | [
"MIT"
] | IvanJevtic9/SagaPatternImpl | src/SagaImpl.OrderService/Database/EntityConfiguration/OrderConfiguration.cs | 1,537 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace LetsEncrypt.ACME.Simple
{
public class Target
{
public static Dictionary<string, Plugin> Plugins = new Dictionary<string, Plugin>();
static Target()
{
foreach (
var pluginType in
(from t in Assembly.GetExecutingAssembly().GetTypes() where t.BaseType == typeof (Plugin) select t))
{
AddPlugin(pluginType);
}
}
static void AddPlugin(Type type)
{
var plugin = type.GetConstructor(new Type[] {}).Invoke(null) as Plugin;
Plugins.Add(plugin.Name, plugin);
}
public string Host { get; set; }
public string WebRootPath { get; set; }
public long SiteId { get; set; }
public List<string> AlternativeNames { get; set; }
public string PluginName { get; set; } = "IIS";
public Plugin Plugin => Plugins[PluginName];
public override string ToString() => $"{PluginName} {Host} ({WebRootPath})";
}
} | 30.432432 | 120 | 0.579929 | [
"Apache-2.0"
] | etiifa/letsencrypt-win-simple | letsencrypt-win-simple/Target.cs | 1,128 | C# |
using Newtonsoft.Json;
namespace MdsLibrary.Model
{
/// <summary>
/// Response object for subscription to periodic 6-axis (with magnetometer) IMU measurements.
/// </summary>
public class IMU6Data
{
/// <summary>
/// Response object for subscription to periodic 6-axis (with magnetometer) IMU measurements.
/// </summary>
[JsonProperty("Body")]
public Data body;
/// <summary>
/// Creates an IMU6Data object
/// </summary>
/// <param name="body"></param>
public IMU6Data(Data body)
{
this.body = body;
}
/// <summary>
/// Container for IMU6 readings
/// </summary>
public class Data
{
/// <summary>
/// Local timestamp of first measurement.
/// </summary>
[JsonProperty("Timestamp")]
public long Timestamp;
/// <summary>
/// Measured acceleration values (3D) in array.
/// </summary>
[JsonProperty("ArrayAcc")]
public Values3D[] ArrayAcc;
/// <summary>
/// Measured angular velocity values (3D) in array.
/// </summary>
[JsonProperty("ArrayGyro")]
public Values3D[] ArrayGyro;
/// <summary>
/// Headers
/// </summary>
[JsonProperty("Headers")]
public Headers Header;
}
/// <summary>
/// 3D values
/// </summary>
public class Values3D
{
/// <summary>
/// X reading
/// </summary>
[JsonProperty("x")]
public double X;
/// <summary>
/// Y reading
/// </summary>
[JsonProperty("y")]
public double Y;
/// <summary>
/// Z reading
/// </summary>
[JsonProperty("z")]
public double Z;
/// <summary>
/// Constructs Values3D
/// </summary>
/// <param name="x">X value</param>
/// <param name="y">Y value</param>
/// <param name="z">Z value</param>
public Values3D(double x, double y, double z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
}
/// <summary>
/// Headers
/// </summary>
public class Headers
{
/// <summary>
/// parameter
/// </summary>
[JsonProperty("Param0")]
public int Param0;
/// <summary>
/// constructor
/// </summary>
/// <param name="param0"></param>
public Headers(int param0)
{
this.Param0 = param0;
}
}
}
}
| 25.77193 | 101 | 0.427161 | [
"MIT"
] | AndyCW/MovesenseDotNet | src/Movesensedotnet/Movesense/Shared/Model/IMU6Data.cs | 2,938 | C# |
using UnityEngine;
public class StreamSpell : Spell
{
[SerializeField] public float thrustAcceleration = 12f;
[SerializeField] public float minTakeoffFactor = 0.7f;
public ParticleSystem streamParticleSystem;
public ParticleSystem indicatorParticleSystem;
public Quaternion rotationOffset;
private CharacterBody bodyReceivingRecoil;
private bool autoplay = false;
private bool thrusting;
public override void Begin(SpellCaster caster, Transform target)
{
base.Begin(caster, target);
bodyReceivingRecoil = caster.recoilRecipient;
indicatorParticleSystem.Play();
streamParticleSystem.Stop();
if (autoplay)
{
thrusting = true;
streamParticleSystem.Play();
indicatorParticleSystem.Stop();
}
}
public override void Hold()
{
base.Hold();
transform.Rotate(rotationOffset.eulerAngles);
if (thrusting) {
//Apply Recoil
float height = transform.position.y;
Vector3 thrustVector = -transform.forward * thrustAcceleration;
bodyReceivingRecoil?.AddForce(thrustVector, ForceMode.Acceleration);
}
}
public void Activate()
{
thrusting = true;
streamParticleSystem.Play();
indicatorParticleSystem.Stop();
}
public void Deactivate()
{
thrusting = false;
streamParticleSystem.Stop();
indicatorParticleSystem.Play();
}
public override void Punch(Vector3 velocity)
{
Activate();
}
public override void Pull(Vector3 velocity)
{
Deactivate();
}
public override void Release(Vector3 velocity)
{
Deactivate();
target = null;
Object.Destroy(gameObject, destroyTime);
}
}
| 24.233766 | 88 | 0.620579 | [
"Apache-2.0"
] | LevyMatthew/vrmagic | _Spells/StreamSpell.cs | 1,866 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http.Headers;
using System.Web;
namespace StagPj
{
public class In : Action
{
private string cvalue;
private Source source;
public string cValue
{
get { return cvalue; }
set { cvalue = value; }
}
public In()
{
con = new Connexion();
}
public void Add()
{
Add_Money(Montant);
// -- Add Category
con.showDataTable("insert into dbo.Categorie(Designation,A_id) values('" + cvalue + "','" + ID + "')");
}
////////////// ----- InMoney ----- //////////////
public string Add_Money(float prix)
{
u = new Utilisateur();
c = new Compte();
con.Con.Open();
cmd = new SqlCommand("dbo.Add_Money", con.Con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id_C", SqlDbType.UniqueIdentifier);
cmd.Parameters.Add("@id_U", SqlDbType.UniqueIdentifier);
cmd.Parameters.Add("@Montant", SqlDbType.Float);
cmd.Parameters.Add("@responseMessage", SqlDbType.Char, 256);
cmd.Parameters["@responseMessage"].Direction = ParameterDirection.Output;
cmd.Parameters["@id_C"].Value = Guid.Parse(c.ID);
cmd.Parameters["@id_U"].Value = Guid.Parse(u.ID);
cmd.Parameters["@Montant"].Value = prix;
cmd.ExecuteNonQuery();
con.Con.Close();
return cmd.Parameters["@responseMessage"].Value.ToString();
}
}
} | 25.573529 | 115 | 0.53824 | [
"BSD-3-Clause"
] | AninossII/StagPJ | StagPj/In.cs | 1,741 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Kms.V1.Snippets
{
// [START cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async_flattened_resourceNames]
using Google.Cloud.Kms.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedKeyManagementServiceClientSnippets
{
/// <summary>Snippet for GetCryptoKeyAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetCryptoKeyResourceNamesAsync()
{
// Create client
KeyManagementServiceClient keyManagementServiceClient = await KeyManagementServiceClient.CreateAsync();
// Initialize request argument(s)
CryptoKeyName name = CryptoKeyName.FromProjectLocationKeyRingCryptoKey("[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]");
// Make the request
CryptoKey response = await keyManagementServiceClient.GetCryptoKeyAsync(name);
}
}
// [END cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async_flattened_resourceNames]
}
| 43.309524 | 140 | 0.721825 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Kms.V1/Google.Cloud.Kms.V1.GeneratedSnippets/KeyManagementServiceClient.GetCryptoKeyResourceNamesAsyncSnippet.g.cs | 1,819 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace iBlog.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 26.15625 | 89 | 0.654719 | [
"MIT"
] | invoteco/iBlog | Pages/Error.cshtml.cs | 837 | 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.
#nullable disable
using System;
using System.Reflection;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class AssemblyIdentityDisplayNameTests : AssemblyIdentityTestBase
{
private const AssemblyIdentityParts N = AssemblyIdentityParts.Name;
private const AssemblyIdentityParts NV = N | AssemblyIdentityParts.Version;
private const AssemblyIdentityParts NVK = NV | AssemblyIdentityParts.PublicKey;
private const AssemblyIdentityParts NVT = NV | AssemblyIdentityParts.PublicKeyToken;
private const AssemblyIdentityParts NVC = NV | AssemblyIdentityParts.Culture;
private const AssemblyIdentityParts NVCT = NVC | AssemblyIdentityParts.PublicKeyToken;
private void TestParseVersionInvalid(string value)
{
AssemblyIdentityParts actualParts;
ulong actual;
Assert.False(AssemblyIdentity.TryParseVersion(value, out actual, out actualParts));
// compare with fusion
var fusionName = FusionAssemblyIdentity.ToAssemblyNameObject("Name, Version=" + value);
if (fusionName != null)
{
AssemblyIdentityParts fusionParts = 0;
var fusionVersion = FusionAssemblyIdentity.GetVersion(fusionName, out fusionParts);
// name parsing succeeds but there is no version:
Assert.Equal((AssemblyIdentityParts)0, fusionParts);
}
}
private void TestParseVersion(string value, int major, int minor, int build, int revision, AssemblyIdentityParts expectedParts)
{
AssemblyIdentityParts actualParts;
ulong actual;
Assert.True(AssemblyIdentity.TryParseVersion(value, out actual, out actualParts));
Assert.Equal(expectedParts, actualParts);
Version actualVersion = AssemblyIdentity.ToVersion(actual);
Assert.Equal(new Version(major, minor, build, revision), actualVersion);
// compare with fusion
var fusionName = FusionAssemblyIdentity.ToAssemblyNameObject("Name, Version=" + value);
Assert.NotNull(fusionName);
AssemblyIdentityParts fusionParts = 0;
var fusionVersion = FusionAssemblyIdentity.GetVersion(fusionName, out fusionParts);
Assert.Equal(fusionVersion, actualVersion);
// Test limitation:
// When constructing INameObject with CANOF.PARSE_DISPLAY_NAME option,
// the Version=* is treated as unspecified version. That's also done by TryParseDisplayName,
// but outside of TryParseVersion, which we are testing here.
if (value == "*")
{
Assert.Equal((AssemblyIdentityParts)0, fusionParts);
}
else
{
Assert.Equal(expectedParts, fusionParts);
}
}
private void TestParseVersion(string value)
{
string displayName = "Goo, Version=" + value;
var fusion = FusionAssemblyIdentity.ToAssemblyIdentity(FusionAssemblyIdentity.ToAssemblyNameObject(displayName));
AssemblyIdentity id = null;
bool success = AssemblyIdentity.TryParseDisplayName(displayName, out id);
Assert.Equal(fusion != null, success);
if (success)
{
Assert.Equal(fusion.Version, id.Version);
}
}
private void TestParseSimpleName(string displayName, string expected)
{
TestParseSimpleName(displayName, expected, expected);
}
private void TestParseSimpleName(string displayName, string expected, string expectedFusion)
{
var fusionName = FusionAssemblyIdentity.ToAssemblyNameObject(displayName);
var actual = (fusionName != null) ? FusionAssemblyIdentity.GetName(fusionName) : null;
Assert.Equal(expectedFusion, actual);
AssemblyIdentity id;
actual = AssemblyIdentity.TryParseDisplayName(displayName, out id) ? id.Name : null;
Assert.Equal(expected, actual);
}
private void TestParseDisplayName(string displayName, AssemblyIdentity expected, AssemblyIdentityParts expectedParts = 0)
{
TestParseDisplayName(displayName, expected, expectedParts, expected);
}
private void TestParseDisplayName(string displayName, AssemblyIdentity expected, AssemblyIdentityParts expectedParts, AssemblyIdentity expectedFusion)
{
var fusion = FusionAssemblyIdentity.ToAssemblyIdentity(FusionAssemblyIdentity.ToAssemblyNameObject(displayName));
Assert.Equal(expectedFusion, fusion);
AssemblyIdentity id = null;
AssemblyIdentityParts actualParts;
bool success = AssemblyIdentity.TryParseDisplayName(displayName, out id, out actualParts);
Assert.Equal(expected, id);
Assert.Equal(success, id != null);
Assert.Equal(expectedParts, actualParts);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void GetDisplayName()
{
var id = new AssemblyIdentity("goo");
Assert.Equal("goo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", id.GetDisplayName());
id = new AssemblyIdentity("goo", new Version(1, 2, 3, 4));
Assert.Equal("goo, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", id.GetDisplayName());
id = new AssemblyIdentity("goo", cultureName: "en-US");
Assert.Equal("goo, Version=0.0.0.0, Culture=en-US, PublicKeyToken=null", id.GetDisplayName());
id = new AssemblyIdentity("goo", publicKeyOrToken: new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }.AsImmutableOrNull());
Assert.Equal("goo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef", id.GetDisplayName(), StringComparer.OrdinalIgnoreCase);
id = new AssemblyIdentity("goo", isRetargetable: true);
Assert.Equal("goo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null, Retargetable=Yes", id.GetDisplayName());
id = new AssemblyIdentity("goo", contentType: AssemblyContentType.WindowsRuntime);
Assert.Equal("goo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", id.GetDisplayName());
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true);
string dn1 = id.GetDisplayName();
string dn2 = id.GetDisplayName(fullKey: false);
Assert.True(ReferenceEquals(dn1, dn2), "cached full name expected");
Assert.Equal("Goo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=" + StrPublicKeyToken1, dn1);
string dnFull = id.GetDisplayName(fullKey: true);
Assert.Equal("Goo, Version=0.0.0.0, Culture=neutral, PublicKey=" + StrPublicKey1, dnFull);
id = new AssemblyIdentity("Goo", cultureName: "neutral");
Assert.Equal("Goo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", id.GetDisplayName());
id = new AssemblyIdentity("Goo", cultureName: " '\t\r\n\\=, ");
Assert.Equal(@"Goo, Version=0.0.0.0, Culture="" \'\t\r\n\\\=\, "", PublicKeyToken=null", id.GetDisplayName());
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TryParseDisplayName_QuotingAndEscaping()
{
// escapes:
TestParseSimpleName("/, Version=1.0.0.0", expected: "/");
TestParseSimpleName("\\\\, Version=1.0.0.0", expected: "\\");
TestParseSimpleName("\\,\\=, Version=1.0.0.0", expected: ",=");
TestParseSimpleName("\\\\, Version=1.0.0.0", expected: "\\");
TestParseSimpleName("\\/, Version=1.0.0.0", expected: "/");
TestParseSimpleName("\\\", Version=1.0.0.0", expected: "\"");
TestParseSimpleName("\\\', Version=1.0.0.0", expected: "\'");
TestParseSimpleName("a\\tb, Version=1.0.0.0", expected: "a\tb");
TestParseSimpleName("a\\rb, Version=1.0.0.0", expected: "a\rb");
TestParseSimpleName("a\\nb, Version=1.0.0.0", expected: "a\nb");
TestParseSimpleName("a\\vb, Version=1.0.0.0", expected: null);
TestParseSimpleName("a\\fb, Version=1.0.0.0", expected: null);
TestParseSimpleName("a , Version=1.0.0.0", expected: "a");
TestParseSimpleName("a\\a, Version=1.0.0.0", expected: null);
TestParseSimpleName("a\\ , Version=1.0.0.0", expected: null);
TestParseSimpleName("a\\ b, Version=1.0.0.0", expected: null);
TestParseSimpleName("a\\\tb, Version=1.0.0.0", expected: null);
TestParseSimpleName("a\\\rb, Version=1.0.0.0", expected: null);
TestParseSimpleName("a\\\nb, Version=1.0.0.0", expected: null);
TestParseSimpleName("a\\u0;b, Version=1.0.0.0", expected: null, expectedFusion: "a"); // fusion bug
TestParseSimpleName("a\\u20;b, Version=1.0.0.0", expected: "a b");
TestParseSimpleName("a\\u020;b, Version=1.0.0.0", expected: "a b");
TestParseSimpleName("a\\u0020;b, Version=1.0.0.0", expected: "a b");
TestParseSimpleName("a\\u1234", expected: null);
TestParseSimpleName("\\u12345;", expected: "\U00012345");
TestParseSimpleName("\\u100000;", expected: "\U00100000");
TestParseSimpleName("\\u10fFfF;", expected: "\U0010ffff");
TestParseSimpleName("\\u110000;", expected: null);
TestParseSimpleName("\\u1000000;", expected: null);
TestParseSimpleName("\\taa, Version=1.0.0.0", expected: "\taa");
TestParseSimpleName("a\\", expected: null);
// double quotes (unescaped can't be in the middle):
TestParseSimpleName("\"a\"", expected: "a");
TestParseSimpleName("\"a'a\", Version=1.0.0.0", expected: "a'a");
TestParseSimpleName("\\\"aa\\\", Version=1.0.0.0", expected: "\"aa\"");
TestParseSimpleName("\\\"a'a\\\", Version=1.0.0.0", expected: null);
TestParseSimpleName("\\\"a, Version=1.0.0.0", expected: "\"a");
TestParseSimpleName("\", Version=1.0.0.0\", Version=1.0.0.0", expected: ", Version=1.0.0.0");
TestParseSimpleName("\", Version=1.0.0.0", expected: ", Version=1.0.0.0");
TestParseSimpleName("\\\", Version=1.0.0.0", expected: "\"");
TestParseSimpleName("xx\\\"abc\\\"xx", expected: "xx\"abc\"xx");
TestParseSimpleName("aaa\\\"bbb, Version=1.0.0.0", expected: "aaa\"bbb");
TestParseSimpleName("\"b\", Version=1.0.0.0", expected: "b");
TestParseSimpleName(" \"b\" , Version=1.0.0.0", expected: "b");
TestParseSimpleName("\"abc', Version=1.0.0.0", expected: "abc', Version=1.0.0.0");
TestParseSimpleName("'\"a\"', Version=1.0.0.0", expected: "\"a\"");
TestParseSimpleName("'xxx\"xxx\"xxx', Version=1.0.0.0", expected: "xxx\"xxx\"xxx");
TestParseSimpleName("'xxx\\\"xxx\\'xxx', Version=1.0.0.0", expected: "xxx\"xxx'xxx");
TestParseSimpleName("b\", Version=1.0.0.0", expected: null);
TestParseSimpleName("aaa\"b\"bb, Version=1.0.0.0", expected: null);
TestParseSimpleName("a\"b, Version=1.0.0.0", expected: null);
TestParseSimpleName("\"\", Version=1.0.0.0", expected: null);
TestParseSimpleName("\"\"a\"\", Version=1.0.0.0", expected: null);
// single quotes (unescaped can't be in the middle):
TestParseSimpleName("'a'", expected: "a");
TestParseSimpleName("'a\"a', Version=1.0.0.0", expected: "a\"a");
TestParseSimpleName("\\'aa\\', Version=1.0.0.0", expected: "'aa'");
TestParseSimpleName("\\'a\"a\\', Version=1.0.0.0", expected: null);
TestParseSimpleName("\\'a,Version=1.0.0.0", expected: "'a");
TestParseSimpleName("', Version=1.0.0.0', Version=1.0.0.0", expected: ", Version=1.0.0.0");
TestParseSimpleName("', Version=1.0.0.0", expected: ", Version=1.0.0.0");
TestParseSimpleName("\\', Version=1.0.0.0", expected: "'");
TestParseSimpleName("xx\\'abc\\'xx", expected: "xx'abc'xx");
TestParseSimpleName("aaa\\'bbb, Version=1.0.0.0", expected: "aaa'bbb");
TestParseSimpleName("'b', Version=1.0.0.0", expected: "b");
TestParseSimpleName(" 'b' , Version=1.0.0.0", expected: "b");
TestParseSimpleName("'abc\", Version=1.0.0.0", expected: "abc\", Version=1.0.0.0");
TestParseSimpleName("\"'a'\", Version=1.0.0.0", expected: "'a'");
TestParseSimpleName("\"xxx'xxx'xxx\", Version=1.0.0.0", expected: "xxx'xxx'xxx");
TestParseSimpleName("\"xxx\\\"xxx\\'xxx\", Version=1.0.0.0", expected: "xxx\"xxx'xxx");
TestParseSimpleName("b', Version=1.0.0.0", expected: null);
TestParseSimpleName("aaa'b'bb, Version=1.0.0.0", expected: null);
TestParseSimpleName("a'b, Version=1.0.0.0", expected: null);
TestParseSimpleName("'', Version=1.0.0.0", expected: null);
TestParseSimpleName("''a'', Version=1.0.0.0", expected: null);
// Unicode quotes
TestParseSimpleName("\u201ca\u201d", expected: "\u201ca\u201d");
TestParseSimpleName("\\u201c;a\\u201d;", expected: "\u201ca\u201d");
TestParseSimpleName("\u201ca", expected: "\u201ca");
TestParseSimpleName("\\u201c;a", expected: "\u201ca");
TestParseSimpleName("a\u201d", expected: "a\u201d");
TestParseSimpleName("a\\u201d;", expected: "a\u201d");
TestParseSimpleName("\u201ca\u201d ", expected: "\u201ca\u201d");
TestParseSimpleName("\\u201c;a\\u201d; ", expected: "\u201ca\u201d");
TestParseSimpleName("\u2018a\u2019", expected: "\u2018a\u2019");
TestParseSimpleName("\\u2018;a\\u2019;", expected: "\u2018a\u2019");
TestParseSimpleName("\u2018a", expected: "\u2018a");
TestParseSimpleName("\\u2018;a", expected: "\u2018a");
TestParseSimpleName("a\u2019", expected: "a\u2019");
TestParseSimpleName("a\\u2019;", expected: "a\u2019");
TestParseSimpleName("\u2018a\u2019 ", expected: "\u2018a\u2019");
TestParseSimpleName("\\u2018;a\\u2019; ", expected: "\u2018a\u2019");
// NUL characters in the name:
TestParseSimpleName(" \0 , Version=1.0.0.0", expected: null);
TestParseSimpleName("zzz, Version=1.0.0\0.0", null);
TestParseSimpleName("\0", expected: null);
// can't be whitespace only
TestParseSimpleName("\t, Version=1.0.0.0", expected: null);
TestParseSimpleName("\r, Version=1.0.0.0", expected: null);
TestParseSimpleName("\n, Version=1.0.0.0", expected: null);
TestParseSimpleName(" , Version=1.0.0.0", expected: null);
// single or double quote if name starts or ends with whitespace:
TestParseSimpleName("\" a \"", expected: " a ");
TestParseSimpleName("' a '", expected: " a ");
TestParseSimpleName("'\r\t\n', Version=1.0.0.0", expected: "\r\t\n");
TestParseSimpleName("\"\r\t\n\", Version=1.0.0.0", expected: "\r\t\n");
TestParseSimpleName("x\n\t\nx, Version=1.0.0.0", expected: "x\n\t\nx");
// Missing parts
TestParseSimpleName("=", null);
TestParseSimpleName(",", null);
TestParseSimpleName("a,", null);
TestParseSimpleName("a ,", null);
TestParseSimpleName("\"a\"=", expected: null);
TestParseSimpleName("\"a\" =", expected: null);
TestParseSimpleName("\"a\",", expected: null);
TestParseSimpleName("\"a\" ,", expected: null);
TestParseSimpleName("'a'=", expected: null);
TestParseSimpleName("'a' =", expected: null);
TestParseSimpleName("'a',", expected: null);
TestParseSimpleName("'a' ,", expected: null);
// skips initial and trailing whitespace characters (' ', \t, \r, \n):
TestParseSimpleName(" \"a\" ", expected: "a");
TestParseSimpleName(" 'a' ", expected: "a");
TestParseSimpleName(" x, Version=1.0.0.0", expected: "x");
TestParseSimpleName(" x\t\r\n , Version=1.0.0.0", expected: "x");
TestParseSimpleName("\u0008x, Version=1.0.0.0", expected: "\u0008x");
TestParseSimpleName("\u0085x, Version=1.0.0.0", expected: "\u0085x");
TestParseSimpleName("\u00A0x, Version=1.0.0.0", expected: "\u00A0x");
TestParseSimpleName("\u2000x, Version=1.0.0.0", expected: "\u2000x");
TestParseSimpleName("x x, Version=1.0.0.0", expected: "x x");
TestParseSimpleName(" \"a'a\" , Version=1.0.0.0", expected: "a'a");
TestParseSimpleName(" \"aa\" x , Version=1.0.0.0", expected: null);
TestParseSimpleName(" \"aa\" \"\" , Version=1.0.0.0", expected: null);
TestParseSimpleName(" \"aa\" \'\' , Version=1.0.0.0", expected: null);
TestParseSimpleName(" A", "A");
TestParseSimpleName("A ", "A");
TestParseSimpleName(" A ", "A");
TestParseSimpleName(" A, Version=1.0.0.0", "A");
TestParseSimpleName("A , Version=1.0.0.0", "A");
TestParseSimpleName("A , Version=1.0.0.0", "A");
// invalid characters:
foreach (var c in ClrInvalidCharacters)
{
TestParseSimpleName("goo" + c, "goo" + c);
}
TestParseSimpleName("'*', Version=1.0.0.0", expected: "*", expectedFusion: null);
TestParseSimpleName("*, Version=1.0.0.0", expected: "*", expectedFusion: null);
TestParseSimpleName("hello 'xxx', Version=1.0.0.0", expected: null);
}
private void TestQuotingAndEscaping(string simpleName, string expectedSimpleName)
{
var ai = new AssemblyIdentity(simpleName);
var dn = ai.GetDisplayName();
Assert.Equal(expectedSimpleName + ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", dn);
TestParseSimpleName(dn, simpleName);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void GetDisplayName_QuotingAndEscaping()
{
TestQuotingAndEscaping(",", "\\,");
TestQuotingAndEscaping("'", "\\'");
TestQuotingAndEscaping("\"", "\\\"");
TestQuotingAndEscaping("/", "/");
TestQuotingAndEscaping("\\", "\\\\");
TestQuotingAndEscaping("x\rx", "x\\rx");
TestQuotingAndEscaping("x\nx", "x\\nx");
TestQuotingAndEscaping("x\tx", "x\\tx");
TestQuotingAndEscaping("\rx", "\"\\rx\"");
TestQuotingAndEscaping("\nx", "\"\\nx\"");
TestQuotingAndEscaping("\tx", "\"\\tx\"");
TestQuotingAndEscaping(" ", "\" \"");
TestQuotingAndEscaping(" x", "\" x\"");
TestQuotingAndEscaping("x ", "\"x \"");
TestQuotingAndEscaping("\u0008", "\u0008");
TestQuotingAndEscaping("\u0085", "\u0085");
TestQuotingAndEscaping("\u00A0", "\u00A0");
TestQuotingAndEscaping("\u2000", "\u2000");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TryParseDisplayName()
{
string V = "\\u" + ((int)'V').ToString("X4") + ";";
TestParseDisplayName(" \"fo'o\" , " + V + "ersion=1.0.0.0\t, \rCulture=zz-ZZ\n, PublicKeyToken=" + StrPublicKeyToken1,
new AssemblyIdentity("fo'o", new Version(1, 0, 0, 0), "zz-ZZ", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default),
NVCT);
// invalid:
AssemblyIdentity id;
Assert.Throws<ArgumentNullException>(() => AssemblyIdentity.TryParseDisplayName(null, out id));
TestParseDisplayName("", null);
TestParseDisplayName("fo=o, Culture=neutral, Version=1.0.0.0", null);
TestParseDisplayName("goo, Culture=neutral, Version,1.0.0.0", null);
// custom properties:
TestParseDisplayName("goo, A=B",
new AssemblyIdentity("goo"), N | AssemblyIdentityParts.Unknown);
// we don't allow CT=WinRT + Retargetable, fusion does.
Assert.False(
AssemblyIdentity.TryParseDisplayName("goo, Version=1.0.0.0, Culture=en-US, Retargetable=Yes, ContentType=WindowsRuntime, PublicKeyToken=" + StrPublicKeyToken1, out id));
// order
TestParseDisplayName("goo, Culture=neutral, Version=1.0.0.0",
new AssemblyIdentity("goo", new Version(1, 0, 0, 0)), NVC);
TestParseDisplayName("goo, Version=1.0.0.0, Culture=en-US, Retargetable=Yes, PublicKeyToken=" + StrPublicKeyToken1,
new AssemblyIdentity("goo", new Version(1, 0, 0, 0), "en-US", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: true),
NVCT | AssemblyIdentityParts.Retargetability);
TestParseDisplayName("goo, PublicKey=" + StrPublicKey1 + ", Version=1.0.0.1",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1), publicKeyOrToken: RoPublicKey1, hasPublicKey: true),
NVK);
TestParseDisplayName(@"Goo, Version=0.0.0.0, Culture="" \'\t\r\n\\\=\, "", PublicKeyToken=null",
new AssemblyIdentity("Goo", cultureName: " '\t\r\n\\=, "),
NVCT);
// duplicates
TestParseDisplayName("goo, Version=1.0.0.0, Version=1.0.0.0", null);
TestParseDisplayName("goo, Version=1.0.0.0, Version=2.0.0.0", null);
TestParseDisplayName("goo, Culture=neutral, Version=1.0.0.0, Culture=en-US", null);
}
[Fact]
[WorkItem(39647, "https://github.com/dotnet/roslyn/issues/39647")]
public void AssemblyIdentity_EmptyName()
{
var identity = new AssemblyIdentity(noThrow: true, name: "");
var name = identity.GetDisplayName();
Assert.Equal(", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", name);
Assert.False(AssemblyIdentity.TryParseDisplayName(name, out _));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TryParseDisplayName_Version()
{
TestParseDisplayName("Version=1.2.3.4, goo", null);
TestParseDisplayName("Version=1.2.3.4", null);
TestParseDisplayName("Version=", null);
TestParseDisplayName("goo, Version=", null);
TestParseDisplayName("goo, Version", null);
TestParseDisplayName("goo, Version=1",
new AssemblyIdentity("goo", new Version(1, 0, 0, 0)), N | AssemblyIdentityParts.VersionMajor);
TestParseDisplayName("goo, Version=.", new AssemblyIdentity("goo"), N);
TestParseDisplayName("goo, Version=..", new AssemblyIdentity("goo"), N);
TestParseDisplayName("goo, Version=...", new AssemblyIdentity("goo"), N);
TestParseDisplayName("goo, Version=*, Culture=en-US",
new AssemblyIdentity("goo", cultureName: "en-US"),
AssemblyIdentityParts.Name | AssemblyIdentityParts.Culture);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TestParseVersion_Parts()
{
TestParseVersionInvalid("a");
TestParseVersionInvalid("-1");
TestParseVersionInvalid("2*");
TestParseVersionInvalid("2.1*");
TestParseVersionInvalid("2.0*.0.0");
TestParseVersionInvalid("2.*0.0.0");
TestParseVersion("1", 1, 0, 0, 0, AssemblyIdentityParts.VersionMajor);
TestParseVersion("65535", 65535, 0, 0, 0, AssemblyIdentityParts.VersionMajor);
TestParseVersionInvalid("65536");
TestParseVersion(".", 0, 0, 0, 0, 0);
TestParseVersion("1.", 1, 0, 0, 0, AssemblyIdentityParts.VersionMajor);
TestParseVersion("0.1", 0, 1, 0, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor);
TestParseVersion("1.2", 1, 2, 0, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor);
TestParseVersionInvalid("1. 2");
TestParseVersionInvalid("1 . 2");
TestParseVersion("1..", 1, 0, 0, 0, AssemblyIdentityParts.VersionMajor);
TestParseVersion("1.2.", 1, 2, 0, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor);
TestParseVersion("1.2.3", 1, 2, 3, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor | AssemblyIdentityParts.VersionBuild);
TestParseVersion(".2.3", 0, 2, 3, 0, AssemblyIdentityParts.VersionMinor | AssemblyIdentityParts.VersionBuild);
TestParseVersion("1..3", 1, 0, 3, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionBuild);
TestParseVersion("1.2.3.", 1, 2, 3, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor | AssemblyIdentityParts.VersionBuild);
TestParseVersion("1.2..4", 1, 2, 0, 4, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor | AssemblyIdentityParts.VersionRevision);
TestParseVersion("1.2..", 1, 2, 0, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor);
TestParseVersion("1.2.3.4", 1, 2, 3, 4, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor | AssemblyIdentityParts.VersionBuild | AssemblyIdentityParts.VersionRevision);
TestParseVersionInvalid("1. 2.3.4");
TestParseVersionInvalid("1.2.3. 4");
TestParseVersion("65535.65535.65535.65535", 65535, 65535, 65535, 65535,
AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor | AssemblyIdentityParts.VersionBuild | AssemblyIdentityParts.VersionRevision);
TestParseVersionInvalid("65535.65535.65535.65536");
TestParseVersion("*", 0, 0, 0, 0, AssemblyIdentityParts.VersionMajor);
TestParseVersion("1.*", 1, 0, 0, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor);
TestParseVersion("1.2.*", 1, 2, 0, 0, AssemblyIdentityParts.VersionMajor | AssemblyIdentityParts.VersionMinor | AssemblyIdentityParts.VersionBuild);
TestParseVersion("1.2.3.*", 1, 2, 3, 0, AssemblyIdentityParts.Version);
TestParseVersion("1.*.2.*", 1, 0, 2, 0, AssemblyIdentityParts.Version);
TestParseVersionInvalid("1.2.3.4.");
TestParseVersionInvalid("1.2.3.4.5");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TestParseVersionAll()
{
// all combinations:
var possibleParts = new[] { "0", "3", ".", "", "*", null };
foreach (var part1 in possibleParts)
{
foreach (var part2 in possibleParts)
{
foreach (var part3 in possibleParts)
{
foreach (var part4 in possibleParts)
{
TestParseVersion(
(part1 ?? "") +
(part2 != null ? "." + part2 : "") +
(part3 != null ? "." + part3 : "") +
(part4 != null ? "." + part4 : ""));
}
}
}
}
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TryParseDisplayName_Culture()
{
TestParseDisplayName("goo, Version=1.0.0.1, Culture=null",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1), cultureName: "null"), NVC);
TestParseDisplayName("goo, Version=1.0.0.1, cULture=en-US",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1), cultureName: "en-US"), NVC);
TestParseDisplayName("goo, Version=1.0.0.1, Language=en-US",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1), cultureName: "en-US"), NVC);
TestParseDisplayName("goo, Version=1.0.0.1, languagE=en-US",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1), cultureName: "en-US"), NVC);
TestParseDisplayName("goo, Culture=*, Version=1.0.0.1",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NV);
TestParseDisplayName("goo, Culture=*", new AssemblyIdentity("goo"), N);
TestParseDisplayName("goo, Culture=*, Culture=en-US, Version=1.0.0.1", null);
TestParseDisplayName("Goo, Version=1.0.0.0, Culture='neutral', PublicKeyToken=null",
new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), cultureName: null), NVCT);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TryParseDisplayName_Keys()
{
// empty keys:
TestParseDisplayName("goo, PublicKeyToken=null, Version=1.0.0.1",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NVT);
TestParseDisplayName("goo, PublicKeyToken=neutral, Version=1.0.0.1",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NVT);
TestParseDisplayName("goo, PublicKeyToken=*, Version=1.0.0.1",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NV);
TestParseDisplayName("goo, PublicKey=null, Version=1.0.0.1", null);
TestParseDisplayName("goo, PublicKey=neutral, Version=1.0.0.1", null);
TestParseDisplayName("goo, PublicKey=*, Version=1.0.0.1",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NV);
// keys
TestParseDisplayName("goo, PublicKeyToken=, Version=1.0.0.1", null);
TestParseDisplayName("goo, PublicKeyToken=1, Version=1.0.0.1", null);
TestParseDisplayName("goo, PublicKeyToken=111111111111111, Version=1.0.0.1", null);
TestParseDisplayName("goo, PublicKeyToken=1111111111111111111, Version=1.0.0.1", null);
TestParseDisplayName("goo, PublicKey=1, Version=1.0.0.1", null);
TestParseDisplayName("goo, PublicKey=1000000040000000", null);
TestParseDisplayName("goo, PublicKey=11, Version=1.0.0.1", null);
// TODO: need to calculate the correct token for the ECMA key.
// TestParseDisplayName("goo, PublicKey=0000000040000000",
// expectedParts: 0,
// expectedFusion: null, // Fusion rejects the ECMA key.
// expected: new AssemblyIdentity("goo", hasPublicKey: true, publicKeyOrToken: new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0 }.AsImmutable()));
// if public key token calculated from public key matches, then it's ok to specify both
TestParseDisplayName("goo, Culture=neutral, Version=1.0.0.0, PublicKey=" + StrPublicKey1 + ", PublicKeyToken=" + StrPublicKeyToken1,
new AssemblyIdentity("goo", new Version(1, 0, 0, 0), publicKeyOrToken: RoPublicKey1, hasPublicKey: true), NVC | AssemblyIdentityParts.PublicKeyOrToken);
TestParseDisplayName("goo, Culture=neutral, Version=1.0.0.0, PublicKey=" + StrPublicKey1 + ", PublicKeyToken=1111111111111111", null);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TryParseDisplayName_ContentType()
{
TestParseDisplayName("goo, Version=1.0.0.1, ContentType=WindowsRuntime",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1), contentType: AssemblyContentType.WindowsRuntime), NV | AssemblyIdentityParts.ContentType);
TestParseDisplayName("goo, Version=1.0.0.1, ContentType=*",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NV);
TestParseDisplayName("goo, Version=1.0.0.1, ContentType=Default", null);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void TryParseDisplayName_Retargetable()
{
// for some reason the Fusion rejects to parse Retargetable if they are not full names
TestParseDisplayName("goo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=" + StrPublicKeyToken1 + ", Retargetable=yEs",
new AssemblyIdentity("goo", new Version(1, 0, 0, 0), publicKeyOrToken: RoPublicKeyToken1, isRetargetable: true),
NVCT | AssemblyIdentityParts.Retargetability);
TestParseDisplayName("goo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=" + StrPublicKeyToken1 + ", Retargetable=*",
new AssemblyIdentity("goo", new Version(1, 0, 0, 0), publicKeyOrToken: RoPublicKeyToken1),
NVCT);
TestParseDisplayName("goo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=" + StrPublicKeyToken1 + ", retargetable=NO",
new AssemblyIdentity("goo", new Version(1, 0, 0, 0), publicKeyOrToken: RoPublicKeyToken1),
NVCT | AssemblyIdentityParts.Retargetability);
TestParseDisplayName("goo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=" + StrPublicKeyToken1 + ", Retargetable=Bar",
null);
TestParseDisplayName("goo, Version=1.0.0.1, Retargetable=*",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NV);
TestParseDisplayName("goo, Version=1.0.0.1, Retargetable=No",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1)), NV | AssemblyIdentityParts.Retargetability,
expectedFusion: null);
TestParseDisplayName("goo, Version=1.0.0.1, retargetable=YEs",
new AssemblyIdentity("goo", new Version(1, 0, 0, 1), isRetargetable: true), NV | AssemblyIdentityParts.Retargetability,
expectedFusion: null);
}
}
}
| 56.890145 | 202 | 0.607809 | [
"MIT"
] | FPCSharpUnity/roslyn | src/Compilers/Core/CodeAnalysisTest/MetadataReferences/AssemblyIdentityDisplayNameTests.cs | 35,217 | C# |
namespace advisor.Persistence {
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using HotChocolate;
[GraphQLName("Alliance")]
public class DbAlliance : InGameContext {
[GraphQLIgnore]
[Key]
public long Id { get; set; }
[GraphQLIgnore]
public long GameId { get; set; }
[Required]
[MaxLength(256)]
public string Name { get; set; }
public List<DbAllianceMember> Members { get; set; } = new ();
[GraphQLIgnore]
public DbGame Game { get; set; }
}
}
| 23.68 | 69 | 0.597973 | [
"MIT"
] | valdisz/atlantis-economy-advisor | server/Persistence/DbAlliance.cs | 592 | C# |
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TinyIoC;
namespace InMemoryMongoDb
{
class InMemoryDatabase : IMongoDatabase
{
private readonly string name;
private readonly TinyIoCContainer iocContainer;
private readonly ConcurrentDictionary<string, VanillaCollection> collections = new ConcurrentDictionary<string, VanillaCollection>();
public InMemoryDatabase(IMongoClient client, string name, TinyIoCContainer iocContainer)
{
Client = client ?? throw new ArgumentNullException(nameof(client));
this.name = name ?? throw new ArgumentNullException(nameof(name));
this.iocContainer = iocContainer ?? throw new ArgumentNullException(nameof(iocContainer));
}
public IMongoClient Client { get; private set; }
public DatabaseNamespace DatabaseNamespace => new DatabaseNamespace(name);
public MongoDatabaseSettings Settings => new MongoDatabaseSettings();
public void CreateCollection(string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default)
{
collections.TryAdd(name, null);
}
public void CreateCollection(IClientSessionHandle session, string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default)
{
CreateCollection(name);
}
public Task CreateCollectionAsync(string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default)
{
CreateCollection(name);
return Task.CompletedTask;
}
public Task CreateCollectionAsync(IClientSessionHandle session, string name, CreateCollectionOptions options = null, CancellationToken cancellationToken = default)
{
CreateCollection(name);
return Task.CompletedTask;
}
public void CreateView<TDocument, TResult>(string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public void CreateView<TDocument, TResult>(IClientSessionHandle session, string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public Task CreateViewAsync<TDocument, TResult>(string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public Task CreateViewAsync<TDocument, TResult>(IClientSessionHandle session, string viewName, string viewOn, PipelineDefinition<TDocument, TResult> pipeline, CreateViewOptions<TDocument> options = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public void DropCollection(string name, CancellationToken cancellationToken = default)
{
collections.TryRemove(name, out var col);
}
public void DropCollection(IClientSessionHandle session, string name, CancellationToken cancellationToken = default)
{
DropCollection(name);
}
public Task DropCollectionAsync(string name, CancellationToken cancellationToken = default)
{
DropCollection(name);
return Task.CompletedTask;
}
public Task DropCollectionAsync(IClientSessionHandle session, string name, CancellationToken cancellationToken = default)
{
DropCollection(name);
return Task.CompletedTask;
}
public IMongoCollection<TDocument> GetCollection<TDocument>(string name, MongoCollectionSettings settings = null)
{
InMemoryCollection<TDocument> NewCollection(VanillaCollection vCol)
{
return new InMemoryCollection<TDocument>(this, vCol, iocContainer.Resolve<IFilter>(), iocContainer.Resolve<IUpdater>());
}
return NewCollection(collections.GetOrAdd(name, n => new VanillaCollection(n)));// as IMongoCollection<TDocument>;//, (n, c) => c ?? NewCollection(n)) as IMongoCollection<TDocument>;
}
public IAsyncCursor<BsonDocument> ListCollections(ListCollectionsOptions options = null, CancellationToken cancellationToken = default)
{
return INMAsyncCursor.Create(collections.Keys.Select(n => (new { name = n }).ToBsonDocument()));
}
public IAsyncCursor<BsonDocument> ListCollections(IClientSessionHandle session, ListCollectionsOptions options = null, CancellationToken cancellationToken = default)
{
return ListCollections();
}
public Task<IAsyncCursor<BsonDocument>> ListCollectionsAsync(ListCollectionsOptions options = null, CancellationToken cancellationToken = default)
{
return Task.FromResult(ListCollections());
}
public Task<IAsyncCursor<BsonDocument>> ListCollectionsAsync(IClientSessionHandle session, ListCollectionsOptions options = null, CancellationToken cancellationToken = default)
{
return Task.FromResult(ListCollections());
}
public void RenameCollection(string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default)
{
if (collections.TryGetValue(oldName, out var col))
if (collections.TryAdd(newName, col))
return;
else
throw new InMemoryDatabaseException($"A collection already exists named '{newName}'");
else
throw new InMemoryDatabaseException($"Could not find collection '{oldName}'");
}
public void RenameCollection(IClientSessionHandle session, string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default)
{
RenameCollection(oldName, newName);
}
public Task RenameCollectionAsync(string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default)
{
RenameCollection(oldName, newName);
return Task.CompletedTask;
}
public Task RenameCollectionAsync(IClientSessionHandle session, string oldName, string newName, RenameCollectionOptions options = null, CancellationToken cancellationToken = default)
{
RenameCollection(oldName, newName);
return Task.CompletedTask;
}
public TResult RunCommand<TResult>(Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public TResult RunCommand<TResult>(IClientSessionHandle session, Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public Task<TResult> RunCommandAsync<TResult>(Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public Task<TResult> RunCommandAsync<TResult>(IClientSessionHandle session, Command<TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public IMongoDatabase WithReadConcern(ReadConcern readConcern) => this;
public IMongoDatabase WithReadPreference(ReadPreference readPreference) => this;
public IMongoDatabase WithWriteConcern(WriteConcern writeConcern) => this;
}
[Serializable]
public class InMemoryDatabaseException : Exception
{
public InMemoryDatabaseException() { }
public InMemoryDatabaseException(string message) : base(message) { }
public InMemoryDatabaseException(string message, Exception inner) : base(message, inner) { }
protected InMemoryDatabaseException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
}
| 45.225641 | 258 | 0.700193 | [
"MIT"
] | BinaryWorrier/InMemoryMongoDb | src/InMemoryMongoDb/InMemoryDatabase.cs | 8,821 | C# |
using GroupDocs.Merger.Cloud.Sdk.Api;
using GroupDocs.Merger.Cloud.Sdk.Client;
using GroupDocs.Merger.Cloud.Sdk.Model.Requests;
using System;
using GroupDocs.Merger.Cloud.Sdk.Model;
using FileInfo = GroupDocs.Merger.Cloud.Sdk.Model.FileInfo;
namespace GroupDocs.Merger.Cloud.Examples.CSharp
{
/// <summary>
/// This example demonstrates how to update document password.
/// </summary>
public class UpdateDocumentPassword
{
public static void Run()
{
var configuration = Common.GetConfig();
var apiInstance = new SecurityApi(configuration);
try
{
var fileInfo = new FileInfo
{
FilePath = "WordProcessing/password-protected.docx",
Password = "password"
};
var options = new UpdatePasswordOptions
{
FileInfo = fileInfo,
OutputPath = "output/update-password.docx",
NewPassword = "NewPassword"
};
var request = new UpdatePasswordRequest(options);
var response = apiInstance.UpdatePassword(request);
Console.WriteLine("Output file path: " + response.Path);
}
catch (Exception e)
{
Console.WriteLine("Exception while calling api: " + e.Message);
}
}
}
} | 29.130435 | 67 | 0.603731 | [
"MIT"
] | groupdocs-merger-cloud/groupdocs-merger-cloud-dotnet-samples | Examples/GroupDocs.Merger.Cloud.Examples.CSharp/SecurityOperations/UpdateDocumentPassword.cs | 1,340 | 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.Solutions.V20190701.Outputs
{
[OutputType]
public sealed class ApplicationBillingDetailsDefinitionResponse
{
/// <summary>
/// The managed application resource usage Id.
/// </summary>
public readonly string? ResourceUsageId;
[OutputConstructor]
private ApplicationBillingDetailsDefinitionResponse(string? resourceUsageId)
{
ResourceUsageId = resourceUsageId;
}
}
}
| 28.178571 | 84 | 0.697085 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Solutions/V20190701/Outputs/ApplicationBillingDetailsDefinitionResponse.cs | 789 | C# |
using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text.Encodings.Web;
using Action.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace Action.Controllers
{
[Route("api/relationship-factors")]
[EnableCors("Default")]
[AllowAnonymous]
public class RelationshipController : BaseController
{
private readonly ApplicationDbContext _dbContext;
private readonly HtmlEncoder _htmlEncoder;
public RelationshipController(HtmlEncoder htmlEncoder, ApplicationDbContext dbContext = null)
{
_dbContext = dbContext;
_htmlEncoder = htmlEncoder;
}
[HttpGet("")]
public IActionResult Get([FromRoute] int id)
{
return ValidateUser(() =>
{
try
{
if (_dbContext == null)
return NotFound("No database connection");
var items = _dbContext.RelationTypes.OrderBy(x => x.Name).ToList();
return Ok(items);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
});
}
}
} | 29.06383 | 101 | 0.560761 | [
"Apache-2.0"
] | luizhmcarvalho/influencers-api | src/Action/Controllers/RelationshipController.cs | 1,368 | C# |
using System;
namespace IntComSys.Computing
{
public abstract class Vec<T> where T : struct
{
public readonly int size;
public readonly T[] elements;
private Vec() { }
public Vec(int size)
{
this.size = size;
elements = new T[size];
}
public abstract Vec<T> Copy();
public override string ToString()
{
return $"V({size})";
}
public T[] ToArray()
{
T[] result = new T[size];
for (int i = 0; i < size; i++)
{
result[i] = elements[i];
}
return result;
}
public virtual Vec<T> SubVec(int start)
{
return SubVec(start, size - start);
}
public abstract Vec<T> SubVec(int start, int length);
public abstract T Dot(Vec<T> v1, Vec<T> v2);
#region Set
public void Set(T[] arr)
{
for (int i = 0; i < size; i++)
{
elements[i] = arr[i];
}
}
public void Set(Vec<T> v)
{
for (int i = 0; i < size; i++)
{
elements[i] = v.elements[i];
}
}
#endregion
#region Mapping
public void Map(Func<T> fn)
{
Map(0, size, fn);
}
public void Map(int start, Func<T> fn)
{
Map(start, size - start, fn);
}
public void Map(int start, int length, Func<T> fn)
{
int end = start + length;
for (int i = 0; i < end; i++)
{
elements[i] = fn();
}
}
public void Map(Func<T, T> fn)
{
Map(0, size, fn);
}
public void Map(int start, Func<T, T> fn)
{
Map(start, size - start, fn);
}
public void Map(int start, int length, Func<T, T> fn)
{
int end = start + length;
for (int i = start; i < end; i++)
{
elements[i] = fn(elements[i]);
}
}
#endregion
}
}
| 15.158879 | 55 | 0.549938 | [
"Apache-2.0"
] | cutzsc/IntComSys | Computing/Vec.cs | 1,624 | C# |
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Monowallet.Android
{
[Activity(Label = "Monowallet", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new FormsApp());
}
}
}
| 32.714286 | 187 | 0.715284 | [
"MIT"
] | eruptiq/monowallet | Monowallet.UI.Android/MainActivity.cs | 1,145 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
namespace InControl
{
public class InputManager
{
public static readonly VersionInfo Version = VersionInfo.InControlVersion();
public static event Action OnSetup;
public static event Action<ulong,float> OnUpdate;
public static event Action OnReset;
public static event Action<InputDevice> OnDeviceAttached;
public static event Action<InputDevice> OnDeviceDetached;
public static event Action<InputDevice> OnActiveDeviceChanged;
internal static event Action<ulong,float> OnUpdateDevices;
internal static event Action<ulong,float> OnCommitDevices;
static List<InputDeviceManager> deviceManagers = new List<InputDeviceManager>();
static Dictionary<Type,InputDeviceManager> deviceManagerTable = new Dictionary<Type, InputDeviceManager>();
static InputDevice activeDevice = InputDevice.Null;
static List<InputDevice> devices = new List<InputDevice>();
/// <summary>
/// A readonly collection of devices.
/// Not every device in this list is guaranteed to be attached or even a controller.
/// This collection should be treated as a pool from which devices may be selected.
/// The collection is in no particular order and the order may change at any time.
/// Do not treat this collection as a list of players.
/// </summary>
public static ReadOnlyCollection<InputDevice> Devices;
/// <summary>
/// Query whether a command button was pressed on any device during the last frame of input.
/// </summary>
public static bool MenuWasPressed { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether this the Y axis should be inverted for
/// two-axis (directional) controls. When false (default), the Y axis will be positive up,
/// the same as Unity.
/// </summary>
public static bool InvertYAxis { get; set; }
internal static string Platform { get; private set; }
static bool isSetup;
static float initialTime;
static float currentTime;
static float lastUpdateTime;
static ulong currentTick;
static VersionInfo? unityVersion;
/// <summary>
/// DEPRECATED: Use the InControlManager component instead.
/// </summary>
/// @deprecated
/// Calling this method directly is no longer supported. Use the InControlManager component to
/// manage the lifecycle of the input manager instead.
[Obsolete( "Calling InputManager.Setup() directly is no longer supported. Use the InControlManager component to manage the lifecycle of the input manager instead.", true )]
public static void Setup()
{
SetupInternal();
}
internal static void SetupInternal()
{
if (isSetup)
{
return;
}
Platform = (SystemInfo.operatingSystem + " " + SystemInfo.deviceModel).ToUpper();
initialTime = 0.0f;
currentTime = 0.0f;
lastUpdateTime = 0.0f;
currentTick = 0;
deviceManagers.Clear();
deviceManagerTable.Clear();
devices.Clear();
Devices = new ReadOnlyCollection<InputDevice>( devices );
activeDevice = InputDevice.Null;
isSetup = true;
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
if (EnableXInput)
{
XInputDeviceManager.Enable();
}
#endif
if (OnSetup != null)
{
OnSetup.Invoke();
OnSetup = null;
}
var addUnityInputDeviceManager = true;
#if UNITY_ANDROID && INCONTROL_OUYA && !UNITY_EDITOR
addUnityInputDeviceManager = false;
#endif
if (addUnityInputDeviceManager)
{
AddDeviceManager<UnityInputDeviceManager>();
}
}
/// <summary>
/// DEPRECATED: Use the InControlManager component instead.
/// </summary>
/// @deprecated
/// Calling this method directly is no longer supported. Use the InControlManager component to
/// manage the lifecycle of the input manager instead.
[Obsolete( "Calling InputManager.Reset() method directly is no longer supported. Use the InControlManager component to manage the lifecycle of the input manager instead.", true )]
public static void Reset()
{
ResetInternal();
}
internal static void ResetInternal()
{
if (OnReset != null)
{
OnReset.Invoke();
}
OnSetup = null;
OnUpdate = null;
OnReset = null;
OnActiveDeviceChanged = null;
OnDeviceAttached = null;
OnDeviceDetached = null;
OnUpdateDevices = null;
OnCommitDevices = null;
DestroyDeviceManagers();
devices.Clear();
activeDevice = InputDevice.Null;
isSetup = false;
}
/// <summary>
/// DEPRECATED: Use the InControlManager component instead.
/// </summary>
/// @deprecated
/// Calling this method directly is no longer supported. Use the InControlManager component to
/// manage the lifecycle of the input manager instead.
[Obsolete( "Calling InputManager.Update() directly is no longer supported. Use the InControlManager component to manage the lifecycle of the input manager instead.", true )]
public static void Update()
{
UpdateInternal();
}
internal static void UpdateInternal()
{
AssertIsSetup();
if (OnSetup != null)
{
OnSetup.Invoke();
OnSetup = null;
}
currentTick++;
UpdateCurrentTime();
var deltaTime = currentTime - lastUpdateTime;
UpdateDeviceManagers( deltaTime );
MenuWasPressed = false;
UpdateDevices( deltaTime );
CommitDevices( deltaTime );
UpdateActiveDevice();
if (OnUpdate != null)
{
OnUpdate.Invoke( currentTick, deltaTime );
}
lastUpdateTime = currentTime;
}
/// <summary>
/// Force the input manager to reset and setup.
/// </summary>
public static void Reload()
{
ResetInternal();
SetupInternal();
}
static void AssertIsSetup()
{
if (!isSetup)
{
throw new Exception( "InputManager is not initialized. Call InputManager.Setup() first." );
}
}
static void SetZeroTickOnAllControls()
{
int deviceCount = devices.Count;
for (int i = 0; i < deviceCount; i++)
{
var inputControls = devices[i].Controls;
var inputControlCount = inputControls.Length;
for (int j = 0; j < inputControlCount; j++)
{
var inputControl = inputControls[j];
if (inputControl != null)
{
inputControl.SetZeroTick();
}
}
}
}
internal static void OnApplicationFocus( bool focusState )
{
if (!focusState)
{
SetZeroTickOnAllControls();
}
}
internal static void OnApplicationPause( bool pauseState )
{
}
internal static void OnApplicationQuit()
{
ResetInternal();
}
internal static void OnLevelWasLoaded()
{
SetZeroTickOnAllControls();
}
/// <summary>
/// Adds a device manager.
/// Only one instance of a given type can be added. An error will be raised if
/// you try to add more than one.
/// </summary>
/// <param name="inputDeviceManager">The device manager to add.</param>
public static void AddDeviceManager( InputDeviceManager deviceManager )
{
AssertIsSetup();
var type = deviceManager.GetType();
if (deviceManagerTable.ContainsKey( type ))
{
Logger.LogError( "A device manager of type '" + type.Name + "' already exists; cannot add another." );
return;
}
deviceManagers.Add( deviceManager );
deviceManagerTable.Add( type, deviceManager );
deviceManager.Update( currentTick, currentTime - lastUpdateTime );
}
/// <summary>
/// Adds a device manager by type.
/// </summary>
/// <typeparam name="T">A subclass of InputDeviceManager.</typeparam>
public static void AddDeviceManager<T>() where T : InputDeviceManager, new()
{
AddDeviceManager( new T() );
}
/// <summary>
/// Get a device manager from the input manager by type if it one is present.
/// </summary>
/// <typeparam name="T">A subclass of InputDeviceManager.</typeparam>
public static T GetDeviceManager<T>() where T : InputDeviceManager
{
InputDeviceManager deviceManager;
if (deviceManagerTable.TryGetValue( typeof(T), out deviceManager ))
{
return deviceManager as T;
}
return null;
}
/// <summary>
/// Query whether a device manager is present by type.
/// </summary>
/// <typeparam name="T">A subclass of InputDeviceManager.</typeparam>
public static bool HasDeviceManager<T>() where T : InputDeviceManager
{
return deviceManagerTable.ContainsKey( typeof(T) );
}
static void UpdateCurrentTime()
{
// Have to do this hack since Time.realtimeSinceStartup is not set until AFTER Awake().
if (initialTime < float.Epsilon)
{
initialTime = Time.realtimeSinceStartup;
}
currentTime = Mathf.Max( 0.0f, Time.realtimeSinceStartup - initialTime );
}
static void UpdateDeviceManagers( float deltaTime )
{
int inputDeviceManagerCount = deviceManagers.Count;
for (int i = 0; i < inputDeviceManagerCount; i++)
{
deviceManagers[i].Update( currentTick, deltaTime );
}
}
static void DestroyDeviceManagers()
{
int inputDeviceManagerCount = deviceManagers.Count;
for (int i = 0; i < inputDeviceManagerCount; i++)
{
deviceManagers[i].Destroy();
}
deviceManagers.Clear();
deviceManagerTable.Clear();
}
static void UpdateDevices( float deltaTime )
{
int deviceCount = devices.Count;
for (int i = 0; i < deviceCount; i++)
{
var device = devices[i];
device.Update( currentTick, deltaTime );
}
if (OnUpdateDevices != null)
{
OnUpdateDevices.Invoke( currentTick, deltaTime );
}
}
static void CommitDevices( float deltaTime )
{
int deviceCount = devices.Count;
for (int i = 0; i < deviceCount; i++)
{
var device = devices[i];
device.Commit( currentTick, deltaTime );
if (device.MenuWasPressed)
{
MenuWasPressed = true;
}
}
if (OnCommitDevices != null)
{
OnCommitDevices.Invoke( currentTick, deltaTime );
}
}
static void UpdateActiveDevice()
{
var lastActiveDevice = ActiveDevice;
int deviceCount = devices.Count;
for (int i = 0; i < deviceCount; i++)
{
var inputDevice = devices[i];
if (inputDevice.LastChangedAfter( ActiveDevice ))
{
ActiveDevice = inputDevice;
}
}
if (lastActiveDevice != ActiveDevice)
{
if (OnActiveDeviceChanged != null)
{
OnActiveDeviceChanged( ActiveDevice );
}
}
}
/// <summary>
/// Attach a device to the input manager.
/// </summary>
/// <param name="inputDevice">The input device to attach.</param>
public static void AttachDevice( InputDevice inputDevice )
{
AssertIsSetup();
if (!inputDevice.IsSupportedOnThisPlatform)
{
return;
}
devices.Add( inputDevice );
devices.Sort( ( d1, d2 ) => d1.SortOrder.CompareTo( d2.SortOrder ) );
inputDevice.IsAttached = true;
if (OnDeviceAttached != null)
{
OnDeviceAttached( inputDevice );
}
}
/// <summary>
/// Detach a device from the input manager.
/// </summary>
/// <param name="inputDevice">The input device to attach.</param>
public static void DetachDevice( InputDevice inputDevice )
{
AssertIsSetup();
devices.Remove( inputDevice );
inputDevice.IsAttached = false;
if (ActiveDevice == inputDevice)
{
ActiveDevice = InputDevice.Null;
}
if (OnDeviceDetached != null)
{
OnDeviceDetached( inputDevice );
}
}
/// <summary>
/// Hides the devices with a given profile.
/// This must be called before the input manager is initialized.
/// </summary>
/// <param name="type">Type.</param>
public static void HideDevicesWithProfile( Type type )
{
#if !UNITY_EDITOR && UNITY_METRO
if (type.GetTypeInfo().IsAssignableFrom( typeof( UnityInputDeviceProfile ).GetTypeInfo() ))
#else
if (type.IsSubclassOf( typeof(UnityInputDeviceProfile) ))
#endif
{
UnityInputDeviceProfile.Hide( type );
}
}
/// <summary>
/// Detects whether any (keyboard) key is currently pressed.
/// For more flexibility, see <see cref="KeyCombo.Detect()"/>
/// </summary>
public static bool AnyKeyIsPressed
{
get
{
return KeyCombo.Detect( true ).Count > 0;
}
}
/// <summary>
/// Gets the currently active device if present, otherwise returns a null device which does nothing.
/// The currently active device is defined as the last device that provided input events. This is
/// a good way to query for a device in single player applications.
/// </summary>
public static InputDevice ActiveDevice
{
get
{
return (activeDevice == null) ? InputDevice.Null : activeDevice;
}
private set
{
activeDevice = (value == null) ? InputDevice.Null : value;
}
}
/// <summary>
/// Enable XInput support.
/// When enabled on initialization, the input manager will first check
/// whether XInput is supported on this platform and if so, it will add
/// an XInputDeviceManager.
/// </summary>
public static bool EnableXInput { get; internal set; }
/// <summary>
/// Set the XInput background thread polling rate.
/// When set to zero (default) it will equal the projects fixed updated rate.
/// </summary>
public static uint XInputUpdateRate { get; internal set; }
/// <summary>
/// Set the XInput buffer size. (Experimental)
/// Usually you want this to be zero (default). Setting it higher will introduce
/// latency, but may smooth out input if querying input on FixedUpdate, which
/// tends to cluster calls at the end of a frame.
/// </summary>
public static uint XInputBufferSize { get; internal set; }
internal static VersionInfo UnityVersion
{
get
{
if (!unityVersion.HasValue)
{
unityVersion = VersionInfo.UnityVersion();
}
return unityVersion.Value;
}
}
internal static ulong CurrentTick
{
get
{
return currentTick;
}
}
}
}
| 24.108014 | 181 | 0.679867 | [
"MIT"
] | KeikakuB/experiments | 2015/08/dark-dash-and-bash/Assets/InControl/Source/InputManager.cs | 13,838 | C# |
using System;
namespace NSim
{
public class ScheduleEmptyException : Exception
{
}
} | 12.25 | 51 | 0.673469 | [
"BSD-2-Clause"
] | youknowjack0/nsim | NSim/ScheduleEmptyException.cs | 100 | C# |
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V251.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V251.Segment{
///<summary>
/// Represents an HL7 APR message segment.
/// This segment has the following fields:<ol>
///<li>APR-1: Time Selection Criteria (SCV)</li>
///<li>APR-2: Resource Selection Criteria (SCV)</li>
///<li>APR-3: Location Selection Criteria (SCV)</li>
///<li>APR-4: Slot Spacing Criteria (NM)</li>
///<li>APR-5: Filler Override Criteria (SCV)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class APR : AbstractSegment {
/**
* Creates a APR (Appointment Preferences) segment object that belongs to the given
* message.
*/
public APR(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(SCV), false, 0, 80, new System.Object[]{message}, "Time Selection Criteria");
this.add(typeof(SCV), false, 0, 80, new System.Object[]{message}, "Resource Selection Criteria");
this.add(typeof(SCV), false, 0, 80, new System.Object[]{message}, "Location Selection Criteria");
this.add(typeof(NM), false, 1, 5, new System.Object[]{message}, "Slot Spacing Criteria");
this.add(typeof(SCV), false, 0, 80, new System.Object[]{message}, "Filler Override Criteria");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns a single repetition of Time Selection Criteria(APR-1).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public SCV GetTimeSelectionCriteria(int rep)
{
SCV ret = null;
try
{
IType t = this.GetField(1, rep);
ret = (SCV)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Time Selection Criteria (APR-1).
///</summary>
public SCV[] GetTimeSelectionCriteria() {
SCV[] ret = null;
try {
IType[] t = this.GetField(1);
ret = new SCV[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (SCV)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Time Selection Criteria (APR-1).
///</summary>
public int TimeSelectionCriteriaRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(1);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Resource Selection Criteria(APR-2).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public SCV GetResourceSelectionCriteria(int rep)
{
SCV ret = null;
try
{
IType t = this.GetField(2, rep);
ret = (SCV)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Resource Selection Criteria (APR-2).
///</summary>
public SCV[] GetResourceSelectionCriteria() {
SCV[] ret = null;
try {
IType[] t = this.GetField(2);
ret = new SCV[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (SCV)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Resource Selection Criteria (APR-2).
///</summary>
public int ResourceSelectionCriteriaRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(2);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Location Selection Criteria(APR-3).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public SCV GetLocationSelectionCriteria(int rep)
{
SCV ret = null;
try
{
IType t = this.GetField(3, rep);
ret = (SCV)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Location Selection Criteria (APR-3).
///</summary>
public SCV[] GetLocationSelectionCriteria() {
SCV[] ret = null;
try {
IType[] t = this.GetField(3);
ret = new SCV[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (SCV)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Location Selection Criteria (APR-3).
///</summary>
public int LocationSelectionCriteriaRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(3);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Slot Spacing Criteria(APR-4).
///</summary>
public NM SlotSpacingCriteria
{
get{
NM ret = null;
try
{
IType t = this.GetField(4, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Filler Override Criteria(APR-5).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public SCV GetFillerOverrideCriteria(int rep)
{
SCV ret = null;
try
{
IType t = this.GetField(5, rep);
ret = (SCV)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Filler Override Criteria (APR-5).
///</summary>
public SCV[] GetFillerOverrideCriteria() {
SCV[] ret = null;
try {
IType[] t = this.GetField(5);
ret = new SCV[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (SCV)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Filler Override Criteria (APR-5).
///</summary>
public int FillerOverrideCriteriaRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(5);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
}} | 36.352159 | 121 | 0.666423 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V251/Segment/APR.cs | 10,942 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace HybridDb.Queue
{
public class HybridDbMessageQueue : IDisposable
{
// This implementation misses a few pieces:
// [ ] Handling of messages could be idempotent too, by soft deleting them when done, but still keeping it around to guard against
// subsequent redelivery with the same id.
// [ ] Allow faster handling of messages by handling multiple messages (a given max batch size) in one transaction
readonly CancellationTokenSource cts;
readonly ConcurrentDictionary<string, int> retries = new();
readonly ConcurrentDictionary<DocumentTransaction, int> txs = new();
readonly Subject<IHybridDbQueueEvent> events = new();
readonly IDocumentStore store;
readonly ILogger logger;
readonly QueueTable table;
readonly MessageQueueOptions options;
readonly IDisposable eventsSubscription;
readonly Func<IDocumentSession, HybridDbMessage, Task> handler;
public Task MainLoop { get; }
public IObservable<IHybridDbQueueEvent> Events { get; }
public HybridDbMessageQueue(
IDocumentStore store,
Func<IDocumentSession, HybridDbMessage, Task> handler,
MessageQueueOptions options = null)
{
this.store = store;
this.handler = handler;
this.options = options ?? new MessageQueueOptions();
Events = this.options.ObserveEvents(events);
eventsSubscription = this.options.SubscribeEvents(Events);
logger = store.Configuration.Logger;
table = store.Configuration.Tables.Values.OfType<QueueTable>().Single();
cts = this.options.GetCancellationTokenSource();
MainLoop = Task.Factory.StartNew(async () =>
{
events.OnNext(new QueueStarting());
logger.LogInformation("Queue started.");
using var semaphore = new SemaphoreSlim(this.options.MaxConcurrency);
while (!cts.Token.IsCancellationRequested)
{
try
{
var release = await WaitAsync(semaphore);
var tx = BeginTransaction();
try
{
var message = await NextMessage(tx);
await Task.Factory.StartNew(async () =>
{
try { await HandleMessage(tx, message); }
finally
{
release();
DisposeTransaction(tx);
}
}, cts.Token);
}
catch
{
release();
DisposeTransaction(tx);
throw;
}
}
catch (TaskCanceledException) { }
catch (Exception exception)
{
events.OnNext(new QueueFailed(exception));
logger.LogError(exception, $"{nameof(HybridDbMessageQueue)} failed. Will retry.");
}
}
foreach (var tx in txs) DisposeTransaction(tx.Key);
logger.LogInformation("Queue stopped.");
},
cts.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default
).Unwrap();
}
DocumentTransaction BeginTransaction()
{
var tx = store.BeginTransaction();
if (!txs.TryAdd(tx, 0))
throw new InvalidOperationException("Transaction could not be tracked.");
return tx;
}
void DisposeTransaction(DocumentTransaction tx)
{
if (!txs.TryRemove(tx, out _))
throw new InvalidOperationException("Transaction was not tracked.");
try
{
tx.Dispose();
}
catch(Exception ex)
{
logger.LogWarning(ex, "Dispose transaction failed.");
}
}
async Task<Action> WaitAsync(SemaphoreSlim semaphore)
{
await semaphore.WaitAsync();
var released = 0;
return () =>
{
if (Interlocked.Exchange(ref released, 1) == 1) return;
semaphore.Release();
};
}
async Task<HybridDbMessage> NextMessage(DocumentTransaction tx)
{
while (!cts.IsCancellationRequested)
{
// querying on the queue is done in same transaction as the subsequent write, and the message is temporarily removed
// from the queue while handling it, so other machines/workers won't try to handle it too.
var message = tx.Execute(new DequeueCommand(table, options.InboxTopics));
if (message != null) return message;
events.OnNext(new QueueIdle());
await Task.Delay(options.IdleDelay, cts.Token).ConfigureAwait(false);
}
return await Task.FromCanceled<HybridDbMessage>(cts.Token).ConfigureAwait(false);
}
async Task HandleMessage(DocumentTransaction tx, HybridDbMessage message)
{
var context = new MessageContext();
try
{
events.OnNext(new MessageHandling(context, message));
using var session = options.CreateSession(store);
session.Advanced.Enlist(tx);
await handler(session, message);
session.SaveChanges();
events.OnNext(new MessageHandled(context, message));
}
catch (Exception exception)
{
events.OnNext(new MessageFailed(context, message, exception));
var failures = retries.AddOrUpdate(message.Id, key => 1, (key, current) => current + 1);
if (failures < 5)
{
logger.LogWarning(exception, "Dispatch of command {commandId} failed. Will retry.", message.Id);
return;
}
logger.LogError(exception, "Dispatch of command {commandId} failed 5 times. Marks command as failed. Will not retry.", message.Id);
tx.Execute(new EnqueueCommand(table, message, $"errors/{message.Topic}"));
events.OnNext(new PoisonMessage(context, message, exception));
retries.TryRemove(message.Id, out _);
}
tx.Complete();
}
public void Dispose()
{
cts.Cancel();
try { MainLoop.Wait(); }
catch (TaskCanceledException) { }
catch (AggregateException ex) when (ex.InnerException is TaskCanceledException) { }
catch (Exception ex) { logger.LogWarning(ex, $"{nameof(HybridDbMessageQueue)} threw an exception during dispose."); }
eventsSubscription.Dispose();
}
}
public abstract record HybridDbMessage(string Id, string Topic = null);
public interface IHybridDbQueueEvent { }
public record MessageHandling(MessageContext Context, HybridDbMessage Message) : IHybridDbQueueEvent;
public record MessageHandled(MessageContext Context, HybridDbMessage Message) : IHybridDbQueueEvent;
public record MessageFailed(MessageContext Context, HybridDbMessage Message, Exception Exception) : IHybridDbQueueEvent;
public record PoisonMessage(MessageContext Context, HybridDbMessage Message, Exception Exception) : IHybridDbQueueEvent;
public record QueueStarting : IHybridDbQueueEvent;
public record QueueIdle : IHybridDbQueueEvent;
public record QueueFailed(Exception Exception) : IHybridDbQueueEvent;
public class MessageContext : Dictionary<string, object> { }
} | 37.334746 | 148 | 0.533311 | [
"Unlicense"
] | asgerhallas/HybridDb | src/HybridDb/Queue/HybridDbMessageQueue.cs | 8,811 | C# |
using System.Collections.ObjectModel;
namespace BandoMIA.Api.Areas.HelpPage.ModelDescriptions
{
public class ComplexTypeModelDescription : ModelDescription
{
public ComplexTypeModelDescription()
{
Properties = new Collection<ParameterDescription>();
}
public Collection<ParameterDescription> Properties { get; private set; }
}
} | 27.571429 | 80 | 0.704663 | [
"MIT"
] | smetly/BandoMIA | BandoMIA.Api/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs | 386 | C# |
// ***********************************************************************
// Assembly : BI.Interface
// Author : Anugoon Leelaphattarakij
// Created : 04-20-2015
//
// Last Modified By : Anugoon Leelaphattarakij
// Last Modified On : 04-27-2015
// ***********************************************************************
// <copyright file="NullablesToNormal.cs" company="Beyond Inspira">
// Copyright © Anugoon L. 2015
// </copyright>
// <summary>Data model mapper for nullable type to standard data type (int, datetime, float, etc,.).</summary>
// ***********************************************************************
using System;
using System.Diagnostics.CodeAnalysis;
using Omu.ValueInjecter;
namespace BI.Interface.Infrastructure.Mappers
{
/// <summary>
/// Map nullable type to standard data type (int, datetime, float, etc,.).
/// </summary>
[ExcludeFromCodeCoverage]
public class NullablesToNormal : ConventionInjection
{
/// <summary>
/// Matching standard datatype (int, datetime) for mapping
/// </summary>
/// <param name="c">ConventionInfo</param>
/// <returns>Match or not</returns>
protected override bool Match(ConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name &&
Nullable.GetUnderlyingType(c.SourceProp.Type) == c.TargetProp.Type;
}
}
} | 39.567568 | 111 | 0.527322 | [
"MIT"
] | anugoon1374/WVEF | MM-WebUI/BI.Interface/Infrastructure/Mappers/NullablesToNormal.cs | 1,467 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Fakultet.Models;
namespace Fakultet.Controllers
{
public class StudsController : Controller
{
private readonly faksContext _context;
public StudsController(faksContext context)
{
_context = context;
}
// GET: Studs
public async Task<IActionResult> Index()
{
var faksContext = _context.Studs.Include(s => s.PbrRodNavigation).Include(s => s.PbrStanNavigation);
return View(await faksContext.ToListAsync());
}
// GET: Studs/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var stud = await _context.Studs
.Include(s => s.PbrRodNavigation)
.Include(s => s.PbrStanNavigation)
.FirstOrDefaultAsync(m => m.MbrStud == id);
if (stud == null)
{
return NotFound();
}
return View(stud);
}
// GET: Studs/Create
public IActionResult Create()
{
ViewData["PbrRod"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto");
ViewData["PbrStan"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto");
return View();
}
// POST: Studs/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("MbrStud,ImeStud,PrezStud,PbrRod,PbrStan,DatRodStud,JmbgStud")] Stud stud)
{
if (ModelState.IsValid)
{
_context.Add(stud);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["PbrRod"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto", stud.PbrRod);
ViewData["PbrStan"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto", stud.PbrStan);
return View(stud);
}
// GET: Studs/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var stud = await _context.Studs.FindAsync(id);
if (stud == null)
{
return NotFound();
}
ViewData["PbrRod"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto", stud.PbrRod);
ViewData["PbrStan"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto", stud.PbrStan);
return View(stud);
}
// POST: Studs/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("MbrStud,ImeStud,PrezStud,PbrRod,PbrStan,DatRodStud,JmbgStud")] Stud stud)
{
if (id != stud.MbrStud)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(stud);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!StudExists(stud.MbrStud))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["PbrRod"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto", stud.PbrRod);
ViewData["PbrStan"] = new SelectList(_context.Mjestos, "Pbr", "NazMjesto", stud.PbrStan);
return View(stud);
}
// GET: Studs/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var stud = await _context.Studs
.Include(s => s.PbrRodNavigation)
.Include(s => s.PbrStanNavigation)
.FirstOrDefaultAsync(m => m.MbrStud == id);
if (stud == null)
{
return NotFound();
}
return View(stud);
}
// POST: Studs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var stud = await _context.Studs.FindAsync(id);
_context.Studs.Remove(stud);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool StudExists(int id)
{
return _context.Studs.Any(e => e.MbrStud == id);
}
}
}
| 32.53012 | 134 | 0.520556 | [
"MIT"
] | AlgebraC-2020/AlgebraC-2020 | Fakultet/Controllers/StudsController.cs | 5,402 | C# |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Markup.Xaml.Templates;
using System;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests.Templates
{
public class MemberSelectorTests
{
[Fact]
public void Should_Select_Child_Property_Value()
{
var selector = new MemberSelector() { MemberName = "Child.StringValue" };
var data = new Item()
{
Child = new Item() { StringValue = "Value1" }
};
Assert.Same("Value1", selector.Select(data));
}
[Fact]
public void Should_Select_Child_Property_Value_In_Multiple_Items()
{
var selector = new MemberSelector() { MemberName = "Child.StringValue" };
var data = new Item[]
{
new Item() { Child = new Item() { StringValue = "Value1" } },
new Item() { Child = new Item() { StringValue = "Value2" } },
new Item() { Child = new Item() { StringValue = "Value3" } }
};
Assert.Same("Value1", selector.Select(data[0]));
Assert.Same("Value2", selector.Select(data[1]));
Assert.Same("Value3", selector.Select(data[2]));
}
[Fact]
public void Should_Select_MoreComplex_Property_Value()
{
var selector = new MemberSelector() { MemberName = "Child.Child.Child.StringValue" };
var data = new Item()
{
Child = new Item()
{
Child = new Item()
{
Child = new Item() { StringValue = "Value1" }
}
}
};
Assert.Same("Value1", selector.Select(data));
}
[Fact]
public void Should_Select_Null_Value_On_Null_Object()
{
var selector = new MemberSelector() { MemberName = "StringValue" };
Assert.Equal(null, selector.Select(null));
}
[Fact]
public void Should_Select_Null_Value_On_Wrong_MemberName()
{
var selector = new MemberSelector() { MemberName = "WrongProperty" };
var data = new Item() { StringValue = "Value1" };
Assert.Same(null, selector.Select(data));
}
[Fact]
public void Should_Select_Simple_Property_Value()
{
var selector = new MemberSelector() { MemberName = "StringValue" };
var data = new Item() { StringValue = "Value1" };
Assert.Same("Value1", selector.Select(data));
}
[Fact]
public void Should_Select_Simple_Property_Value_In_Multiple_Items()
{
var selector = new MemberSelector() { MemberName = "StringValue" };
var data = new Item[]
{
new Item() { StringValue = "Value1" },
new Item() { StringValue = "Value2" },
new Item() { StringValue = "Value3" }
};
Assert.Same("Value1", selector.Select(data[0]));
Assert.Same("Value2", selector.Select(data[1]));
Assert.Same("Value3", selector.Select(data[2]));
}
[Fact]
public void Should_Select_Target_On_Empty_MemberName()
{
var selector = new MemberSelector();
var data = new Item() { StringValue = "Value1" };
Assert.Same(data, selector.Select(data));
}
[Fact]
public void Should_Support_Change_Of_MemberName()
{
var selector = new MemberSelector() { MemberName = "StringValue" };
var data = new Item()
{
StringValue = "Value1",
IntValue = 1
};
Assert.Same("Value1", selector.Select(data));
selector.MemberName = "IntValue";
Assert.Equal(1, selector.Select(data));
}
[Fact]
public void Should_Support_Change_Of_Target_Value()
{
var selector = new MemberSelector() { MemberName = "StringValue" };
var data = new Item()
{
StringValue = "Value1"
};
Assert.Same("Value1", selector.Select(data));
data.StringValue = "Value2";
Assert.Same("Value2", selector.Select(data));
}
private class Item
{
public Item Child { get; set; }
public int IntValue { get; set; }
public string StringValue { get; set; }
}
}
} | 29.679245 | 104 | 0.521297 | [
"MIT"
] | Beffyman/Avalonia | tests/Avalonia.Markup.Xaml.UnitTests/Templates/MemberSelectorTests.cs | 4,719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> nums = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
int index = 0;
int counter = 0;
int tempIndex = 0;
int tempCounter = 1;
//4 4 2 5 5 5
for (int i = 0; i < nums.Count - 1; i++)
{
if (nums[i] == nums[i + 1]) { tempCounter++; }
else
{
if (tempCounter > counter)
{
counter = tempCounter;
index = tempIndex;
}
tempCounter = 1;
tempIndex = i + 1;
}
}
if (tempCounter > counter)
{
counter = tempCounter;
index = tempIndex;
}
for (int i = index; i < index + counter; i++)
{
Console.WriteLine(nums[i]);
}
}
}
| 21.510638 | 58 | 0.403561 | [
"MIT"
] | aalishov/School | IT-Career-V4/M04-ASDBasics/S01-DataStructures/P17-LongestSequence/Program.cs | 1,013 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IWorkbookRangeBorderRequest.
/// </summary>
public partial interface IWorkbookRangeBorderRequest : IBaseRequest
{
/// <summary>
/// Creates the specified WorkbookRangeBorder using PUT.
/// </summary>
/// <param name="workbookRangeBorderToCreate">The WorkbookRangeBorder to create.</param>
/// <returns>The created WorkbookRangeBorder.</returns>
System.Threading.Tasks.Task<WorkbookRangeBorder> CreateAsync(WorkbookRangeBorder workbookRangeBorderToCreate); /// <summary>
/// Creates the specified WorkbookRangeBorder using PUT.
/// </summary>
/// <param name="workbookRangeBorderToCreate">The WorkbookRangeBorder to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookRangeBorder.</returns>
System.Threading.Tasks.Task<WorkbookRangeBorder> CreateAsync(WorkbookRangeBorder workbookRangeBorderToCreate, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified WorkbookRangeBorder.
/// </summary>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync();
/// <summary>
/// Deletes the specified WorkbookRangeBorder.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the specified WorkbookRangeBorder.
/// </summary>
/// <returns>The WorkbookRangeBorder.</returns>
System.Threading.Tasks.Task<WorkbookRangeBorder> GetAsync();
/// <summary>
/// Gets the specified WorkbookRangeBorder.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookRangeBorder.</returns>
System.Threading.Tasks.Task<WorkbookRangeBorder> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Updates the specified WorkbookRangeBorder using PATCH.
/// </summary>
/// <param name="workbookRangeBorderToUpdate">The WorkbookRangeBorder to update.</param>
/// <returns>The updated WorkbookRangeBorder.</returns>
System.Threading.Tasks.Task<WorkbookRangeBorder> UpdateAsync(WorkbookRangeBorder workbookRangeBorderToUpdate);
/// <summary>
/// Updates the specified WorkbookRangeBorder using PATCH.
/// </summary>
/// <param name="workbookRangeBorderToUpdate">The WorkbookRangeBorder to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookRangeBorder.</returns>
System.Threading.Tasks.Task<WorkbookRangeBorder> UpdateAsync(WorkbookRangeBorder workbookRangeBorderToUpdate, CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookRangeBorderRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookRangeBorderRequest Expand(Expression<Func<WorkbookRangeBorder, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookRangeBorderRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookRangeBorderRequest Select(Expression<Func<WorkbookRangeBorder, object>> selectExpression);
}
}
| 48.179245 | 155 | 0.650676 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookRangeBorderRequest.cs | 5,107 | C# |
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.Ubigia.Infrastructure.Transport.Rest
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using EtAlii.Ubigia.Serialization;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json.Bson;
public class PayloadMediaTypeOutputFormatter : OutputFormatter
{
private static readonly MediaTypeHeaderValue _mediaType = new("application/bson");
private readonly ISerializer _serializer;
public PayloadMediaTypeOutputFormatter()
{
// Set default supported media type
SupportedMediaTypes.Add(_mediaType);
_serializer = new SerializerFactory().Create();
}
protected override bool CanWriteType(Type type)
{
return true;
}
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
// Fix for: https://github.com/aspnet/AspNetCore/issues/7644
var bodyControlFeature = context.HttpContext.Features.Get<IHttpBodyControlFeature>();
if (bodyControlFeature != null)
{
bodyControlFeature.AllowSynchronousIO = true;
}
var response = context.HttpContext.Response;
await WriteToStream(context.ObjectType, context.Object, response.Body).ConfigureAwait(false);
}
private Task WriteToStream(Type type, object value, Stream writeStream)
{
if (writeStream == null)
{
throw new ArgumentNullException(nameof(writeStream));
}
if (value == null)
{
// Cannot serialize null at the top level. Json.Net throws Newtonsoft.Json.JsonWriterException : Error
// writing Null value. BSON must start with an Object or Array. Path ''. Fortunately
// BaseJsonMediaTypeFormatter.ReadFromStream(Type, Stream, HttpContent, IFormatterLogger) treats zero-
// length content as null or the default value of a struct.
return Task.CompletedTask;
}
// See comments in ReadFromStream() above about this special case and the need to include byte[] in it.
// Using runtime type here because Json.Net will throw during serialization whenever it cannot handle the
// runtime type at the top level. For e.g. passed type may be typeof(object) and value may be a string.
var runtimeType = type;
if (IsSimpleType(runtimeType) || runtimeType == typeof(byte[]))
{
// Wrap value in a Dictionary with a single property named "Value" to provide BSON with an Object. Is
// written out as binary equivalent of [ "Value": value ] JSON.
var temporaryDictionary = new Dictionary<string, object>
{
{ "Value", value },
};
return WriteToStreamInternal(temporaryDictionary, writeStream);
}
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return WriteToStreamInternal(value, writeStream);
}
private async Task WriteToStreamInternal(object value, Stream writeStream)
{
using var writer = new BsonDataWriter(writeStream) { CloseOutput = false };
_serializer.Serialize(writer, value);
await writer.FlushAsync().ConfigureAwait(false);
}
// Return true if Json.Net will likely convert value of given type to a Json primitive, not JsonArray nor
// JsonObject.
// To do: https://aspnetwebstack.codeplex.com/workitem/1467
private static bool IsSimpleType(Type type)
{
var isSimpleType = type.GetTypeInfo().IsValueType || type == typeof(string);
return isSimpleType;
}
}
}
| 38.883495 | 119 | 0.65618 | [
"MIT"
] | vrenken/EtAlii.Ubigia | Source/Infrastructure/EtAlii.Ubigia.Infrastructure.Transport.Rest/Serialization/PayloadMediaTypeOutputFormatter.cs | 4,007 | C# |
// Copyright (c) 2021 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT license. See License.txt in the project root for license information.
using BookApp.Books.Domain;
using Microsoft.EntityFrameworkCore;
namespace BookApp.Books.Persistence.CosmosDb
{
public class CosmosDbContext : DbContext //#A
{
public CosmosDbContext(
DbContextOptions<CosmosDbContext> options)
: base(options)
{ }
public DbSet<CosmosBook> Books { get; set; } //#B
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<CosmosBook>()
.HasKey(x => x.BookId); //#C
modelBuilder.Entity<CosmosBook>() //#D
.OwnsMany(p => p.Tags); //#D
}
}
/*****************************************************************
#A The Cosmos DB DbContext has the same structure as any other DbContext
#B For this usage you only need read/write the CosmosBooks
#C BookId doesn't match the By Convention rules, so you need to configure it manually
#D The collection of CosmosTags are owned by the CosmosBook
*****************************************************************/
}
| 37.057143 | 97 | 0.578258 | [
"MIT"
] | JonPSmith/BookApp.All | BookApp.Books.Persistence.CosmosDb/CosmosDbContext.cs | 1,299 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using NUnit.Framework;
[TestFixture]
public class PerfTests03
{
[Test]
public void GetAtIndex_With100000Elements_ShouldWorkFast()
{
// Arrange
IOrganization org = new Organization();
const int count = 100_000;
List<Person> people = new List<Person>();
for (int i = 0; i < count; i++)
{
people.Add(new Person(i.ToString(), i));
org.Add(people[i]);
}
// Act & Assert
Stopwatch sw = Stopwatch.StartNew();
Random rand = new Random();
for (int i = 0; i < 50_000; i++)
{
int rnd = rand.Next(0, count - 1);
Assert.AreEqual(people[rnd], org.GetAtIndex(rnd));
}
sw.Stop();
Assert.Less(sw.ElapsedMilliseconds, 150);
}
} | 24.914286 | 62 | 0.558486 | [
"MIT"
] | IvanBerov/C-DataStructuresFundamentals | DataStructuresExam02July2017/Organization.Tests/Performance/PerfTests03.cs | 874 | C# |
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
namespace Unity.LEGO.Tutorials
{
/// <summary>
/// Contains all the callbacks needed for checking if a user has saved a scene.
/// </summary>
[CreateAssetMenu(fileName = "SaveSceneCriteria", menuName = "Tutorials/Microgame/SaveSceneCriteria")]
class SaveSceneCriteria : ScriptableObject
{
bool currentSceneHasBeenSaved;
Scene activeScene;
public void ResetSceneSavedStatus()
{
currentSceneHasBeenSaved = false;
activeScene = SceneManager.GetActiveScene();
EditorSceneManager.sceneSaved -= OnSceneSaved;
EditorSceneManager.sceneSaved += OnSceneSaved;
}
void OnSceneSaved(Scene scene)
{
currentSceneHasBeenSaved = true;
EditorSceneManager.sceneSaved -= OnSceneSaved;
}
public bool SceneHasBeenSaved()
{
return activeScene.isDirty ? currentSceneHasBeenSaved : true;
}
public bool AutoCompleteSceneSaved()
{
currentSceneHasBeenSaved = true;
EditorSceneManager.sceneSaved -= OnSceneSaved;
return currentSceneHasBeenSaved;
}
}
}
| 31.093023 | 106 | 0.62902 | [
"MIT"
] | TermiSenpai/MicroLego | Assets/LEGO/Tutorials/Criteria/SaveSceneCriteria.cs | 1,337 | C# |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using NSubstitute.Core;
namespace Affecto.Logging.Tests
{
[TestClass]
public class LoggerTests
{
private ILogWriter logWriter;
private ICorrelation correlation;
private Logger sut;
private static readonly string CallerId = "TestCaller";
private static readonly string CorrelationId = "TestCorrelation";
private static readonly Exception Exception = new Exception("Test");
private static readonly string Message = "Test message";
private static readonly object[] MessageParams = { "param1", "param2" };
[TestInitialize]
public void Setup()
{
logWriter = Substitute.For<ILogWriter>();
correlation = Substitute.For<ICorrelation>();
sut = new Logger(logWriter);
}
[TestMethod]
public void VerboseEventIsWrittenToLog()
{
sut.LogVerbose(Message, MessageParams);
AssertCall(null, LogEventLevel.Verbose, null, Message, MessageParams);
}
[TestMethod]
public void VerboseEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogVerbose(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Verbose, null, Message, MessageParams);
}
[TestMethod]
public void VerboseEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogVerbose(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Verbose, null, Message, MessageParams);
}
[TestMethod]
public void InformationEventIsWrittenToLog()
{
sut.LogInformation(Message, MessageParams);
AssertCall(null, LogEventLevel.Information, null, Message, MessageParams);
}
[TestMethod]
public void InformationEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogInformation(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Information, null, Message, MessageParams);
}
[TestMethod]
public void InformationEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogInformation(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Information, null, Message, MessageParams);
}
[TestMethod]
public void WarningEventIsWrittenToLog()
{
sut.LogWarning(Message, MessageParams);
AssertCall(null, LogEventLevel.Warning, null, Message, MessageParams);
}
[TestMethod]
public void WarningEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogWarning(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Warning, null, Message, MessageParams);
}
[TestMethod]
public void WarningEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogWarning(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Warning, null, Message, MessageParams);
}
[TestMethod]
public void WarningExceptionEventIsWrittenToLog()
{
sut.LogWarning(Exception, Message, MessageParams);
AssertCall(null, LogEventLevel.Warning, Exception, Message, MessageParams);
}
[TestMethod]
public void WarningExceptionEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogWarning(correlation, Exception, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Warning, Exception, Message, MessageParams);
}
[TestMethod]
public void WarningExceptionEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogWarning(correlation, Exception, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Warning, Exception, Message, MessageParams);
}
[TestMethod]
public void ErrorEventIsWrittenToLog()
{
sut.LogError(Message, MessageParams);
AssertCall(null, LogEventLevel.Error, null, Message, MessageParams);
}
[TestMethod]
public void ErrorEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogError(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Error, null, Message, MessageParams);
}
[TestMethod]
public void ErrorEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogError(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Error, null, Message, MessageParams);
}
[TestMethod]
public void ErrorExceptionEventIsWrittenToLog()
{
sut.LogError(Exception, Message, MessageParams);
AssertCall(null, LogEventLevel.Error, Exception, Message, MessageParams);
}
[TestMethod]
public void ErrorExceptionEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogError(correlation, Exception, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Error, Exception, Message, MessageParams);
}
[TestMethod]
public void ErrorExceptionEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogError(correlation, Exception, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Error, Exception, Message, MessageParams);
}
[TestMethod]
public void CriticalEventIsWrittenToLog()
{
sut.LogCritical(Message, MessageParams);
AssertCall(null, LogEventLevel.Critical, null, Message, MessageParams);
}
[TestMethod]
public void CriticalEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogCritical(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Critical, null, Message, MessageParams);
}
[TestMethod]
public void CriticalEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogCritical(correlation, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Critical, null, Message, MessageParams);
}
[TestMethod]
public void CriticalExceptionEventIsWrittenToLog()
{
sut.LogCritical(Exception, Message, MessageParams);
AssertCall(null, LogEventLevel.Critical, Exception, Message, MessageParams);
}
[TestMethod]
public void CriticalExceptionEventWithCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
sut.LogCritical(correlation, Exception, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Critical, Exception, Message, MessageParams);
}
[TestMethod]
public void CriticalExceptionEventWithCallerIdAndCorrelationIdIsWrittenToLog()
{
correlation.CorrelationId.Returns(CorrelationId);
correlation.CallerId.Returns(CallerId);
sut.LogCritical(correlation, Exception, Message, MessageParams);
AssertCall(correlation, LogEventLevel.Critical, Exception, Message, MessageParams);
}
private void AssertCall(ICorrelation expectedCorrelation, LogEventLevel eventLevel, Exception exception, string formatMessage,
object[] args)
{
Assert.AreEqual(1, logWriter.ReceivedCalls().Count());
ICall call = logWriter.ReceivedCalls().First();
object[] arguments = call.GetArguments();
Assert.AreEqual(5, arguments.Length);
if (expectedCorrelation == null)
{
Assert.IsNull(arguments[0]);
}
else
{
ICorrelation actualCorrelation = arguments[0] as ICorrelation;
Assert.IsNotNull(actualCorrelation);
if (!string.IsNullOrEmpty(expectedCorrelation.CallerId))
{
Assert.AreEqual(expectedCorrelation.CallerId, actualCorrelation.CallerId);
}
if (!string.IsNullOrEmpty(expectedCorrelation.CorrelationId))
{
Assert.AreEqual(expectedCorrelation.CorrelationId, actualCorrelation.CorrelationId);
}
}
Assert.AreEqual(eventLevel, arguments[1]);
Assert.AreEqual(exception, arguments[2]);
Assert.AreEqual(formatMessage, arguments[3]);
object[] messageParams = arguments[4] as object[];
Assert.IsNotNull(messageParams);
Assert.AreEqual(args.Length, messageParams.Length);
for (int i = 0; i < messageParams.Length; i++)
{
Assert.AreEqual(args[i], messageParams[i]);
}
}
}
} | 36.498233 | 134 | 0.644787 | [
"MIT"
] | gregorypilipenko/dotnet-Logging-nlog-support | Logging.Tests/LoggerTests.cs | 10,331 | C# |
using System;
namespace GrocerySupplyManagementApp.Entities
{
public class CompanyInfo
{
public string Name { get; set; }
public string ShortName { get; set; }
public string Type { get; set; }
public string Address { get; set; }
public long ContactNo { get; set; }
public string EmailId { get; set; }
public string Website { get; set; }
public string FacebookPage { get; set; }
public string RegistrationNo { get; set; }
public string RegistrationDate { get; set; }
public string PanVatNo { get; set; }
public string LogoPath { get; set; }
public string AddedBy { get; set; }
public DateTime AddedDate { get; set; }
public string UpdatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
}
}
| 33.72 | 52 | 0.601423 | [
"MIT"
] | amanandhar/SamyuktaManabSoftwares | SamyuktaManabSoftwares/GrocerySupplyManagementApp/Entities/CompanyInfo.cs | 845 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// As informações gerais sobre um assembly são controladas por
// conjunto de atributos. Altere estes valores de atributo para modificar as informações
// associada a um assembly.
[assembly: AssemblyTitle("PixSnapshot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PixSnapshot")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Definir ComVisible como false torna os tipos neste assembly invisíveis
// para componentes COM. Caso precise acessar um tipo neste assembly de
// COM, defina o atributo ComVisible como true nesse tipo.
[assembly: ComVisible(false)]
// O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM
[assembly: Guid("eb5d6dea-6ae2-4545-a708-6f0f2b1f5c50")]
// As informações da versão de um assembly consistem nos quatro valores a seguir:
//
// Versão Principal
// Versão Secundária
// Número da Versão
// Revisão
//
// É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão
// usando o '*' como mostrado abaixo:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.108108 | 95 | 0.752482 | [
"MIT"
] | LuizZak/PixSnapshot | PixSnapshot/Properties/AssemblyInfo.cs | 1,435 | C# |
using MeshyDB.SDK.Attributes;
using MeshyDB.SDK.Models;
using System;
namespace MeshyForums.Models
{
[MeshName("BlogPost")]
public class Item : MeshData
{
public string Text { get; set; }
public string Description { get; set; }
public string CreatedById { get; set; }
public DateTimeOffset DateCreated { get; set; }
public string CreatedByName { get; set; }
}
} | 26.1875 | 55 | 0.644391 | [
"MIT"
] | yetisoftworks/MeshyDB.Samples | Xamarin/Blog/MeshyForums/MeshyForums/Models/Item.cs | 421 | C# |
using Ryujinx.Graphics.Shader.Decoders;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using System.Collections.Generic;
using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
namespace Ryujinx.Graphics.Shader.Translation
{
class EmitterContext
{
public Block CurrBlock { get; set; }
public OpCode CurrOp { get; set; }
public ShaderConfig Config { get; }
public bool IsNonMain { get; }
private readonly IReadOnlyDictionary<ulong, int> _funcs;
private readonly List<Operation> _operations;
private readonly Dictionary<ulong, Operand> _labels;
public EmitterContext(ShaderConfig config, bool isNonMain, IReadOnlyDictionary<ulong, int> funcs)
{
Config = config;
IsNonMain = isNonMain;
_funcs = funcs;
_operations = new List<Operation>();
_labels = new Dictionary<ulong, Operand>();
}
public Operand Add(Instruction inst, Operand dest = null, params Operand[] sources)
{
Operation operation = new Operation(inst, dest, sources);
Add(operation);
return dest;
}
public (Operand, Operand) Add(Instruction inst, (Operand, Operand) dest, params Operand[] sources)
{
Operand[] dests = new[] { dest.Item1, dest.Item2 };
Operation operation = new Operation(inst, 0, dests, sources);
Add(operation);
return dest;
}
public void Add(Operation operation)
{
_operations.Add(operation);
}
public TextureOperation CreateTextureOperation(
Instruction inst,
SamplerType type,
TextureFlags flags,
int handle,
int compIndex,
Operand dest,
params Operand[] sources)
{
return CreateTextureOperation(inst, type, TextureFormat.Unknown, flags, handle, compIndex, dest, sources);
}
public TextureOperation CreateTextureOperation(
Instruction inst,
SamplerType type,
TextureFormat format,
TextureFlags flags,
int handle,
int compIndex,
Operand dest,
params Operand[] sources)
{
if (!flags.HasFlag(TextureFlags.Bindless))
{
Config.SetUsedTexture(inst, type, format, flags, TextureOperation.DefaultCbufSlot, handle);
}
return new TextureOperation(inst, type, format, flags, handle, compIndex, dest, sources);
}
public void FlagAttributeRead(int attribute)
{
if (Config.Stage == ShaderStage.Vertex && attribute == AttributeConsts.InstanceId)
{
Config.SetUsedFeature(FeatureFlags.InstanceId);
}
else if (Config.Stage == ShaderStage.Fragment)
{
switch (attribute)
{
case AttributeConsts.PositionX:
case AttributeConsts.PositionY:
Config.SetUsedFeature(FeatureFlags.FragCoordXY);
break;
}
}
}
public void FlagAttributeWritten(int attribute)
{
if (Config.Stage == ShaderStage.Vertex)
{
switch (attribute)
{
case AttributeConsts.ClipDistance0:
case AttributeConsts.ClipDistance1:
case AttributeConsts.ClipDistance2:
case AttributeConsts.ClipDistance3:
case AttributeConsts.ClipDistance4:
case AttributeConsts.ClipDistance5:
case AttributeConsts.ClipDistance6:
case AttributeConsts.ClipDistance7:
Config.SetClipDistanceWritten((attribute - AttributeConsts.ClipDistance0) / 4);
break;
}
}
}
public void MarkLabel(Operand label)
{
Add(Instruction.MarkLabel, label);
}
public Operand GetLabel(ulong address)
{
if (!_labels.TryGetValue(address, out Operand label))
{
label = Label();
_labels.Add(address, label);
}
return label;
}
public int GetFunctionId(ulong address)
{
return _funcs[address];
}
public void PrepareForReturn()
{
if (!IsNonMain && Config.Stage == ShaderStage.Fragment)
{
if (Config.OmapDepth)
{
Operand dest = Attribute(AttributeConsts.FragmentOutputDepth);
Operand src = Register(Config.GetDepthRegister(), RegisterType.Gpr);
this.Copy(dest, src);
}
int regIndexBase = 0;
for (int rtIndex = 0; rtIndex < 8; rtIndex++)
{
OmapTarget target = Config.OmapTargets[rtIndex];
for (int component = 0; component < 4; component++)
{
if (!target.ComponentEnabled(component))
{
continue;
}
int fragmentOutputColorAttr = AttributeConsts.FragmentOutputColorBase + rtIndex * 16;
Operand src = Register(regIndexBase + component, RegisterType.Gpr);
// Perform B <-> R swap if needed, for BGRA formats (not supported on OpenGL).
if (component == 0 || component == 2)
{
Operand isBgra = Attribute(AttributeConsts.FragmentOutputIsBgraBase + rtIndex * 4);
Operand lblIsBgra = Label();
Operand lblEnd = Label();
this.BranchIfTrue(lblIsBgra, isBgra);
this.Copy(Attribute(fragmentOutputColorAttr + component * 4), src);
this.Branch(lblEnd);
MarkLabel(lblIsBgra);
this.Copy(Attribute(fragmentOutputColorAttr + (2 - component) * 4), src);
MarkLabel(lblEnd);
}
else
{
this.Copy(Attribute(fragmentOutputColorAttr + component * 4), src);
}
}
if (target.Enabled)
{
regIndexBase += 4;
}
}
}
}
public Operation[] GetOperations()
{
return _operations.ToArray();
}
}
} | 32.64486 | 118 | 0.507443 | [
"MIT"
] | 6Fer6/Ryujinx | Ryujinx.Graphics.Shader/Translation/EmitterContext.cs | 6,986 | 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("Corex.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Corex.Web")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("4b6aadde-9fd3-4af8-8760-6157c7a7c109")]
// 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.567568 | 85 | 0.723896 | [
"Apache-2.0"
] | SharpKit/corex | src/Corex.Web/Properties/AssemblyInfo.cs | 1,430 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using BuildXL.Cache.ContentStore.Distributed.Redis;
using BuildXL.Cache.ContentStore.Interfaces.Distributed;
using BuildXL.Cache.ContentStore.Interfaces.Tracing;
using ContentStoreTest.Test;
using FluentAssertions;
using StackExchange.Redis;
using Xunit;
namespace ContentStoreTest.Distributed.Redis
{
public class RedisConnectionMultiplexerTests
{
[Fact]
public void CreateWithFailingProvider()
{
var context = new Context(TestGlobal.Logger);
var errorMessage = "error";
var failingProvider = CreateFailingProvider(errorMessage);
Func<Task<IConnectionMultiplexer>> createFunc =
() => RedisConnectionMultiplexer.CreateAsync(context, failingProvider, logSeverity: BuildXL.Cache.ContentStore.Interfaces.Logging.Severity.Unknown, usePreventThreadTheft: false);
createFunc.Should().Throw<ArgumentException>().Where(e => e.Message.Contains(
$"Failed to get connection string from provider {failingProvider.GetType().Name}. {errorMessage}."));
}
private IConnectionStringProvider CreateFailingProvider(string errorMessage)
{
var mockProvider = new TestConnectionStringProvider(errorMessage);
return mockProvider;
}
private class TestConnectionStringProvider : IConnectionStringProvider
{
private readonly string _errorMessage;
public TestConnectionStringProvider(string errorMessage)
{
_errorMessage = errorMessage;
}
public Task<ConnectionStringResult> GetConnectionString()
{
return Task.FromResult(ConnectionStringResult.CreateFailure(_errorMessage));
}
}
}
}
| 37.634615 | 195 | 0.670414 | [
"MIT"
] | Microsoft-Android/BuildXL | Public/Src/Cache/ContentStore/DistributedTest/Redis/RedisConnectionMultiplexerTests.cs | 1,957 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Web.Management.PHP.Setup.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.6.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.962963 | 151 | 0.583874 | [
"MIT"
] | RonaldCarter/PHPManager | Setup/PHPManagerSetupHelper/Properties/Settings.Designer.cs | 1,081 | C# |
using NUnit.Framework;
namespace Twitterizer2.TestCases
{
[TestFixture]
public class NUnitSampleTests
{
[Test]
public void SomeFailingTest()
{
Assert.Greater(5, 7);
}
[Test]
public void SomePassingTest()
{
Assert.AreEqual(5, 5);
}
}
} | 17.95 | 38 | 0.490251 | [
"MIT",
"BSD-3-Clause"
] | HemantNegi/Twitterizer | Twitterizer2.TestCases/NUnitSampleTests.cs | 359 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XData.Data.Objects.Oracle
{
internal static class OracleExtensions
{
public static string DecorateDateTimeValue(this DateTime value, string sqlDbType)
{
if (sqlDbType == "date")
{
string sValue = value.ToString("yyyy-MM-dd HH:mm:ss");
return string.Format("TO_DATE('{0}', 'YYYY-MM-DD HH24:MI:SS')", sValue);
}
if (sqlDbType.StartsWith("timestamp"))
{
string sValue = value.ToString("yyyy-MM-dd HH:mm:ss.FFFFFFF");
return string.Format("TO_TIMESTAMP('{0}', 'YYYY-MM-DD HH24:MI:SS.FF9')", sValue);
}
throw new NotSupportedException(sqlDbType);
}
}
}
| 28.83871 | 98 | 0.563758 | [
"MIT"
] | sundy39/xf | ElementFramework.Oracle/OracleExtensions.cs | 896 | C# |
using System;
/*
* Quick Sort : Quick sort is Divide and Conquer algorithm.
* It picks an element as pivot and partitions the given array around the piked pivot.
*
*/
namespace ConsoleApp169
{
internal static class Program
{
public static void Main()
{
var arr = new int[] { 2, 5, -4, 11, 0, 18, 22, 67, 51, 6 };
foreach (var variable in arr)
{
Console.WriteLine(variable);
}
Console.WriteLine(" Sorted Array ");
Quick_Sort(arr, 0, arr.Length - 1);
foreach (var variable in arr)
{
Console.WriteLine(variable);
}
}
private static void Quick_Sort(int[] arr, int i, int arrLength)
{
while (true)
{
if (i < arrLength)
{
var pivot = Partition(arr, i, arrLength);
if (pivot > 1)
{
Quick_Sort(arr, i, pivot - 1);
}
if (pivot + 1 < arrLength)
{
i = pivot + 1;
continue;
}
}
break;
}
}
private static int Partition(int[] arr, int i, int arrLength)
{
var pivot = arr[i];
while (true)
{
while (arr[i] < pivot)
{
i++;
}
while (arr[arrLength] > pivot)
{
arrLength--;
}
if (i < arrLength)
{
if (arr[i] == arr[arrLength]) return arrLength;
var temp = arr[i];
arr[i] = arr[arrLength];
arr[arrLength] = temp;
}
else
{
return arrLength;
}
}
}
}
}
| 19.536585 | 87 | 0.468165 | [
"MIT"
] | hraverkar/DSA | CSharp/QuickSort.cs | 1,602 | C# |
using Aragas.Extensions.Options.FluentValidation.Extensions;
using FluentValidation;
using System.Net.Http;
namespace P3D.Legacy.Server.Infrastructure.Options
{
public sealed class PokeAPIOptionsValidator : AbstractValidator<PokeAPIOptions>
{
public PokeAPIOptionsValidator(HttpClient httpClient)
{
RuleFor(static x => x.GraphQLEndpoint).IsUri().IsUriAvailable(httpClient).When(static x => !string.IsNullOrEmpty(x.GraphQLEndpoint));
}
}
public record PokeAPIOptions
{
public string GraphQLEndpoint { get; init; } = default!;
}
} | 28.619048 | 145 | 0.715474 | [
"MIT"
] | P3D-Legacy/P3D-Legacy-Server | src/P3D.Legacy.Server.Infrastructure/Options/PokeAPIOptions.cs | 603 | C# |
using System;
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
using System.Collections;
using Handelabra.Sentinels.Engine.Controller.TheSentinels;
using System.Collections.Generic;
using Handelabra;
namespace Workshopping.TheSentinels
{
public class WrattleCharacterCardController : SentinelHeroCharacterCardController
{
public WrattleCharacterCardController(Card card, TurnTakerController turnTakerController)
: base(card, turnTakerController)
{
}
public override IEnumerator UsePower(int index = 0)
{
HeroTurnTaker hero = null;
string turnTakerName;
if (this.TurnTaker.IsHero)
{
hero = this.TurnTaker.ToHero();
turnTakerName = this.TurnTaker.Name;
}
else
{
turnTakerName = this.Card.Title;
}
// The next time a hero target is destroyed, you may move it to the owner's hand.
WhenCardIsDestroyedStatusEffect effect = new WhenCardIsDestroyedStatusEffect(this.CardWithoutReplacements, "MoveItToTheBottomOfItsDeckResponse", "The next time a hero target is destroyed, " + turnTakerName + " may move it to its owner's hand.", new TriggerType[] { TriggerType.MoveCard, TriggerType.ChangePostDestroyDestination }, hero, this.Card);
effect.CardDestroyedCriteria.IsHero = true;
effect.CardDestroyedCriteria.IsTarget = true;
effect.CanEffectStack = false;
effect.Priority = StatusEffectPriority.Medium;
effect.PostDestroyDestinationMustBeChangeable = true;
effect.NumberOfUses = 1;
return AddStatusEffect(effect);
}
public IEnumerator MoveItToTheBottomOfItsDeckResponse(DestroyCardAction d, HeroTurnTaker hero, StatusEffect effect, int[] powerNumerals = null)
{
//...you may move it to the bottom of its deck.
if (d.PostDestroyDestinationCanBeChanged)
{
var storedResults = new List<YesNoCardDecision>();
HeroTurnTakerController httc = null;
if (hero != null)
{
httc = FindHeroTurnTakerController(hero);
}
var e = this.GameController.MakeYesNoCardDecision(httc, SelectionType.MoveCardToHand, d.CardToDestroy.Card, storedResults: storedResults, cardSource: GetCardSource());
if (UseUnityCoroutines)
{
yield return this.GameController.StartCoroutine(e);
}
else
{
this.GameController.ExhaustCoroutine(e);
}
if (DidPlayerAnswerYes(storedResults))
{
var nativeDeck = d.CardToDestroy.Card.NativeDeck;
var hand = nativeDeck.OwnerTurnTaker.ToHero().Hand;
d.SetPostDestroyDestination(hand, false, storedResults.CastEnumerable<YesNoCardDecision, IDecision>(), cardSource: GetCardSource());
}
}
}
}
}
| 35.306667 | 351 | 0.743202 | [
"MIT"
] | Handelabra/WorkshopSample | MyMod/TheSentinels/WrattleCharacterCardController.cs | 2,650 | C# |
using System.Collections.Generic;
using System.Linq;
using NML.Parser.Contexts;
using NML.Parser.Objects.Options;
using NML.Parser.Objects.Values;
using NML.Parser.Visitors;
namespace NML.Parser.Objects.Elements
{
public class ImageElement : NamedElement, IElement, IElementOptions
{
public ImageElement()
{
Attributes = new List<IValue>();
Children = new List<IElement>();
Context = null;
Identifier = "image";
}
public override string Accept(IElementVisitor<string> visitor)
{
return visitor.Visit(this);
}
}
}
| 20.961538 | 68 | 0.733945 | [
"MIT"
] | nml-lang/sdk | src/NML.Parser/objects/elements/ImageElement.cs | 545 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using CommunityToolkit.WinUI;
using CommunityToolkit.WinUI.UI.Controls;
using Microsoft.UI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.Devices.Input;
using Windows.Foundation;
using Color = Windows.UI.Color;
namespace UnitTests.XamlIslands.UWPApp
{
[STATestClass]
public partial class XamlIslandsTest_Eyedropper
{
[TestMethod]
public async Task Eyedropper_DoesntCrash()
{
Eyedropper eyedropper = null;
Color? color = null;
_ = App.Dispatcher.EnqueueAsync(async () =>
{
eyedropper = new Eyedropper
{
XamlRoot = App.XamlRoot
};
color = await eyedropper.Open();
});
await App.Dispatcher.EnqueueAsync(async () =>
{
var xamlRoot = App.XamlRoot;
var pos = new Point(xamlRoot.Size.Width / 2, xamlRoot.Size.Height / 2);
uint id = 1;
await eyedropper.InternalPointerPressedAsync(id, pos, PointerDeviceType.Mouse);
await Task.Delay(1000);
for (int i = 0; i < 50; i++)
{
await Task.Delay(100);
eyedropper.InternalPointerMoved(id, pos);
pos.X += 5;
pos.Y += 5;
}
await eyedropper.InternalPointerReleasedAsync(id, pos);
await Task.Delay(1000);
Assert.AreEqual(Colors.CornflowerBlue, color);
});
}
}
} | 30.616667 | 95 | 0.560152 | [
"MIT"
] | ehtick/Uno.WindowsCommunityToolkit | UnitTests/UnitTests.XamlIslands.UWPApp/XamlIslandsTest_Eyedropper.cs | 1,837 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Reddit.Controllers;
using Reddit2Kindle.Contracts;
using Reddit2Kindle.Functions.Contracts.Templates;
using static Reddit2Kindle.Functions.Utils.RedditUtils;
namespace Reddit2Kindle.Functions.Services
{
public class Reddit2KindleService
{
private readonly ILogger<Reddit2KindleService> _logger;
private readonly RazorService _razorService;
private readonly ReadabilityService _readabilityService;
private readonly RedditService _redditService;
private readonly SendGridService _sendGridService;
public Reddit2KindleService(ILogger<Reddit2KindleService> logger, RazorService razorService, ReadabilityService readabilityService,
RedditService redditService, SendGridService sendGridService)
{
_logger = logger;
_razorService = razorService;
_readabilityService = readabilityService;
_redditService = redditService;
_sendGridService = sendGridService;
}
public async Task SendPostAsync(PostRequest request)
{
var post = _redditService.GetPost(request.Post.ToString());
var template = await GetPostTemplateAsync(post);
var attachmentContent = await _razorService.RenderTemplateAsync(template);
await _sendGridService.SendEmailAsync(request.Email, post.Title, attachmentContent);
}
public async Task SendSubredditAsync(SubredditRequest request)
{
var posts = _redditService.GetSubredditPosts(request.Subreddit, request.TimePeriod);
var postTemplates = await Task.WhenAll(posts.Select(GetPostTemplateAsync));
var subredditTemplate = new SubredditTemplate(postTemplates);
var attachmentContent = await _razorService.RenderTemplateAsync(subredditTemplate);
await _sendGridService.SendEmailAsync(request.Email, GenerateTitle(request), attachmentContent);
}
internal async Task<string> RenderPostAsync(PostRequest request)
{
var post = _redditService.GetPost(request.Post.ToString());
var template = await GetPostTemplateAsync(post);
return await _razorService.RenderTemplateAsync(template);
}
internal async Task<string> RenderSubredditAsync(SubredditRequest request)
{
var posts = _redditService.GetSubredditPosts(request.Subreddit, request.TimePeriod);
var postTemplates = await Task.WhenAll(posts.Select(GetPostTemplateAsync));
var subredditTemplate = new SubredditTemplate(postTemplates);
return await _razorService.RenderTemplateAsync(subredditTemplate);
}
private async Task<PostTemplate> GetPostTemplateAsync(Post post)
{
return post switch
{
SelfPost selfPost => new SelfPostTemplate(selfPost),
LinkPost linkPost => new LinkPostTemplate(linkPost, await _readabilityService.GetArticleAsync(linkPost.URL))
};
}
}
}
| 45.535211 | 140 | 0.683576 | [
"MIT"
] | JamieMagee/reddit2kindle | src/Reddit2Kindle.Functions/Services/Reddit2KindleService.cs | 3,235 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
namespace PhonePong.GameScreens
{
class TwoPlayerGameScreen : MainGameScreen
{
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
int topBarMovement = 0;
int bottomBarMovement = 0;
IncreaseSpeed();
UpdateBallPosition();
bottomBarMovement = CheckBottomInput(bottomBarMovement);
topBarMovement = CheckTopInput(topBarMovement);
CheckGameBallCollisions(topBarMovement, bottomBarMovement);
}
}
}
| 19.483871 | 62 | 0.721854 | [
"Apache-2.0"
] | davidov541/WP7Pong | PhonePong/PhonePong/TwoPlayerGameScreen.cs | 604 | C# |
using System;
using System.Diagnostics;
#nullable enable
namespace HotChocolate.Types.Descriptors
{
public abstract class Convention<TDefinition> : Convention
where TDefinition : class
{
private TDefinition? _definition;
protected virtual TDefinition? Definition
{
get
{
return _definition;
}
}
protected internal sealed override void Initialize(IConventionContext context)
{
AssertUninitialized();
Scope = context.Scope;
_definition = CreateDefinition(context);
MarkInitialized();
}
protected internal override void Complete(IConventionContext context)
{
_definition = null;
}
protected abstract TDefinition CreateDefinition(IConventionContext context);
private void AssertUninitialized()
{
Debug.Assert(
!IsInitialized,
"The type must be uninitialized.");
Debug.Assert(
_definition is null,
"The definition should not exist when the type has not been initialized.");
if (IsInitialized || _definition is not null)
{
throw new InvalidOperationException();
}
}
}
}
| 25.148148 | 91 | 0.572165 | [
"MIT"
] | Alxandr/hotchocolate | src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/Convention`1.cs | 1,358 | C# |
namespace DVFSModeling.Core.Algorithms
{
public class SPSATwoOnePhase : SPSAOne
{
const int UP_THRESHOLD = 64;
const int FREQUENCY_PENALTY = 1000;
Random r = new Random(DateTime.Now.Millisecond);
double upscale;
public SPSATwoOnePhase(int[] frequencies, long alpha, long beta, long upscale = 1) : base(frequencies, alpha, beta)
{
this.upscale = upscale;
}
public override int NumberOfObservations => 2;
public override int PredictFrequency(int currentFrequency, int currentLoad)
{
double undisturbedModel = CalculateFunctional(currentFrequency, currentLoad);
var delta = 2 * r.Next(2) - 1;
var disturbedFrequency = FindClosestFrequency(currentFrequency + delta * upscale * beta);
var disturbedLoad = currentLoad * currentFrequency / disturbedFrequency;
double disturbedModel =
CalculateFunctional(disturbedFrequency, disturbedLoad);
var result = currentFrequency - (disturbedModel - undisturbedModel) / beta * alpha * delta;
return FindClosestFrequency(result);
}
private double CalculateFunctional(int currentFrequency, int currentLoad)
{
double model = 0;
if (currentLoad > UP_THRESHOLD)
{
model = 2 << ((currentLoad - UP_THRESHOLD) / 2);
}
var index = indices[currentFrequency];
model += Math.Pow(1.5, index) * FREQUENCY_PENALTY;
return model;
}
}
}
| 30.283019 | 123 | 0.609969 | [
"MIT"
] | Stanislav-Sartasov/DVFSModeling | DVFSModeling.Core/Algorithms/SPSATwoOnePhase.cs | 1,607 | C# |
using System;
using System.Collections.Generic;
namespace ToDo
{
public class ToDoCardList
{
public static List<Card> toDoCardList {get; set;}
static ToDoCardList()
{
toDoCardList = new List<Card>();
}
public static void WriteToDoCardData()
{
foreach (var item in toDoCardList)
{
Console.WriteLine("Başlık : "+item.Title);
Console.WriteLine("İçerik : "+item.Content);
Console.WriteLine("Atanan Kişi : "+item.Appointee);
Console.WriteLine("Büyüklük : "+item.TaskSize);
Console.WriteLine("---");
}
if(toDoCardList.Count==0)
{
Console.WriteLine("~ BOŞ ~");
Console.WriteLine("---");
}
}
}
} | 25.558824 | 67 | 0.490219 | [
"MIT"
] | MuhammetFatihYilmaz/ToDo | ToDoCardList.cs | 878 | C# |
using ErisLib.Server.Packets.Models;
namespace ErisLib.Server.Packets.Server
{
public class TradeAcceptedPacket : Packet
{
public bool[] MyOffers;
public bool[] YourOffers;
public override PacketType Type => PacketType.TRADEACCEPTED;
public override void Read(PacketReader r)
{
MyOffers = new bool[r.ReadInt16()];
for (int i = 0; i < MyOffers.Length; i++)
MyOffers[i] = r.ReadBoolean();
YourOffers = new bool[r.ReadInt16()];
for (int i = 0; i < YourOffers.Length; i++)
YourOffers[i] = r.ReadBoolean();
}
public override void Write(PacketWriter w)
{
w.Write((ushort)MyOffers.Length);
foreach (bool i in MyOffers)
w.Write(i);
w.Write((ushort)YourOffers.Length);
foreach (bool i in YourOffers)
w.Write(i);
}
}
}
| 29.030303 | 68 | 0.544885 | [
"MIT"
] | Azukee/Eris | ErisLib/Server/Packets/Server/TradeAcceptedPacket.cs | 960 | 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.DataBox.Models.Api20210301
{
using static Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Extensions;
/// <summary>
/// Map of filter type and the details to transfer all data. This field is required only if the TransferConfigurationType
/// is given as TransferAll
/// </summary>
public partial class TransferConfigurationTransferAllDetails
{
/// <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.DataBox.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.DataBox.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.DataBox.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.DataBox.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.DataBox.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBox.Models.Api20210301.ITransferConfigurationTransferAllDetails.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataBox.Models.Api20210301.ITransferConfigurationTransferAllDetails.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.DataBox.Models.Api20210301.ITransferConfigurationTransferAllDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonObject json ? new TransferConfigurationTransferAllDetails(json) : null;
}
/// <summary>
/// Serializes this instance of <see cref="TransferConfigurationTransferAllDetails" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonNode"
/// />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataBox.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.DataBox.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="TransferConfigurationTransferAllDetails" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonNode"
/// />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != this._include ? (Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonNode) this._include.ToJson(null,serializationMode) : null, "include" ,container.Add );
AfterToJson(ref container);
return container;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonObject into a new instance of <see cref="TransferConfigurationTransferAllDetails" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonObject instance to deserialize from.</param>
internal TransferConfigurationTransferAllDetails(Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_include = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.DataBox.Runtime.Json.JsonObject>("include"), out var __jsonInclude) ? Microsoft.Azure.PowerShell.Cmdlets.DataBox.Models.Api20210301.TransferAllDetails.FromJson(__jsonInclude) : Include;}
AfterFromJson(json);
}
}
} | 65.873874 | 266 | 0.690235 | [
"MIT"
] | Agazoth/azure-powershell | src/DataBox/generated/api/Models/Api20210301/TransferConfigurationTransferAllDetails.json.cs | 7,202 | 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Ec2
{
/// <summary>
/// > **Note:** There is only a single subscription allowed per account.
///
/// To help you understand the charges for your Spot instances, Amazon EC2 provides a data feed that describes your Spot instance usage and pricing.
/// This data feed is sent to an Amazon S3 bucket that you specify when you subscribe to the data feed.
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/spot_datafeed_subscription.html.markdown.
/// </summary>
public partial class SpotDatafeedSubscription : Pulumi.CustomResource
{
/// <summary>
/// The Amazon S3 bucket in which to store the Spot instance data feed.
/// </summary>
[Output("bucket")]
public Output<string> Bucket { get; private set; } = null!;
/// <summary>
/// Path of folder inside bucket to place spot pricing data.
/// </summary>
[Output("prefix")]
public Output<string?> Prefix { get; private set; } = null!;
/// <summary>
/// Create a SpotDatafeedSubscription 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 SpotDatafeedSubscription(string name, SpotDatafeedSubscriptionArgs args, CustomResourceOptions? options = null)
: base("aws:ec2/spotDatafeedSubscription:SpotDatafeedSubscription", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, ""))
{
}
private SpotDatafeedSubscription(string name, Input<string> id, SpotDatafeedSubscriptionState? state = null, CustomResourceOptions? options = null)
: base("aws:ec2/spotDatafeedSubscription:SpotDatafeedSubscription", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
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 SpotDatafeedSubscription 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="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static SpotDatafeedSubscription Get(string name, Input<string> id, SpotDatafeedSubscriptionState? state = null, CustomResourceOptions? options = null)
{
return new SpotDatafeedSubscription(name, id, state, options);
}
}
public sealed class SpotDatafeedSubscriptionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The Amazon S3 bucket in which to store the Spot instance data feed.
/// </summary>
[Input("bucket", required: true)]
public Input<string> Bucket { get; set; } = null!;
/// <summary>
/// Path of folder inside bucket to place spot pricing data.
/// </summary>
[Input("prefix")]
public Input<string>? Prefix { get; set; }
public SpotDatafeedSubscriptionArgs()
{
}
}
public sealed class SpotDatafeedSubscriptionState : Pulumi.ResourceArgs
{
/// <summary>
/// The Amazon S3 bucket in which to store the Spot instance data feed.
/// </summary>
[Input("bucket")]
public Input<string>? Bucket { get; set; }
/// <summary>
/// Path of folder inside bucket to place spot pricing data.
/// </summary>
[Input("prefix")]
public Input<string>? Prefix { get; set; }
public SpotDatafeedSubscriptionState()
{
}
}
}
| 42.730435 | 172 | 0.636956 | [
"ECL-2.0",
"Apache-2.0"
] | dixler/pulumi-aws | sdk/dotnet/Ec2/SpotDatafeedSubscription.cs | 4,914 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class NullTests
{
[Fact]
public static void DefaultIgnoreNullValuesOnWrite()
{
var obj = new TestClassWithInitializedProperties
{
MyString = null,
MyInt = null,
MyDateTime = null,
MyIntArray = null,
MyIntList = null,
MyNullableIntList = null,
MyObjectList = new List<object> { null },
MyListList = new List<List<object>> { new List<object> { null } },
MyDictionaryList = new List<Dictionary<string, string>> { new Dictionary<string, string>() { ["key"] = null } },
MyStringDictionary = new Dictionary<string, string>() { ["key"] = null },
MyNullableDateTimeDictionary = new Dictionary<string, DateTime?>() { ["key"] = null },
MyObjectDictionary = new Dictionary<string, object>() { ["key"] = null },
MyStringDictionaryDictionary = new Dictionary<string, Dictionary<string, string>>() { ["key"] = null },
MyListDictionary = new Dictionary<string, List<object>>() { ["key"] = null },
MyObjectDictionaryDictionary = new Dictionary<string, Dictionary<string, object>>() { ["key"] = null }
};
string json = JsonSerializer.Serialize(obj);
Assert.Contains(@"""MyString"":null", json);
Assert.Contains(@"""MyInt"":null", json);
Assert.Contains(@"""MyDateTime"":null", json);
Assert.Contains(@"""MyIntArray"":null", json);
Assert.Contains(@"""MyIntList"":null", json);
Assert.Contains(@"""MyNullableIntList"":null", json);
Assert.Contains(@"""MyObjectList"":[null],", json);
Assert.Contains(@"""MyListList"":[[null]],", json);
Assert.Contains(@"""MyDictionaryList"":[{""key"":null}],", json);
Assert.Contains(@"""MyStringDictionary"":{""key"":null},", json);
Assert.Contains(@"""MyNullableDateTimeDictionary"":{""key"":null},", json);
Assert.Contains(@"""MyObjectDictionary"":{""key"":null},", json);
Assert.Contains(@"""MyStringDictionaryDictionary"":{""key"":null},", json);
Assert.Contains(@"""MyListDictionary"":{""key"":null},", json);
Assert.Contains(@"""MyObjectDictionaryDictionary"":{""key"":null}", json);
}
[Fact]
public static void EnableIgnoreNullValuesOnWrite()
{
JsonSerializerOptions options = new JsonSerializerOptions();
options.IgnoreNullValues = true;
var obj = new TestClassWithInitializedProperties
{
MyString = null,
MyInt = null,
MyDateTime = null,
MyIntArray = null,
MyIntList = null,
MyNullableIntList = null,
MyObjectList = new List<object> { null },
MyListList = new List<List<object>> { new List<object> { null } },
MyDictionaryList = new List<Dictionary<string, string>> { new Dictionary<string, string>() { ["key"] = null } },
MyStringDictionary = new Dictionary<string, string>() { ["key"] = null },
MyNullableDateTimeDictionary = new Dictionary<string, DateTime?>() { ["key"] = null },
MyObjectDictionary = new Dictionary<string, object>() { ["key"] = null },
MyStringDictionaryDictionary = new Dictionary<string, Dictionary<string, string>>() { ["key"] = new Dictionary<string, string>() { ["key"] = null } },
MyListDictionary = new Dictionary<string, List<object>>() { ["key"] = new List<object> { null } },
MyObjectDictionaryDictionary = new Dictionary<string, Dictionary<string, object>>() { ["key"] = new Dictionary<string, object>() { ["key"] = null } }
};
string json = JsonSerializer.Serialize(obj, options);
// Roundtrip to verify serialize is accurate.
TestClassWithInitializedProperties newObj = JsonSerializer.Deserialize<TestClassWithInitializedProperties>(json);
Assert.Equal("Hello", newObj.MyString);
Assert.Equal(1, newObj.MyInt);
Assert.Equal(new DateTime(1995, 4, 16), newObj.MyDateTime);
Assert.Equal(1, newObj.MyIntArray[0]);
Assert.Equal(1, newObj.MyIntList[0]);
Assert.Equal(1, newObj.MyNullableIntList[0]);
Assert.Null(newObj.MyObjectList[0]);
Assert.Null(newObj.MyObjectList[0]);
Assert.Null(newObj.MyListList[0][0]);
Assert.Null(newObj.MyDictionaryList[0]["key"]);
Assert.Null(newObj.MyStringDictionary["key"]);
Assert.Null(newObj.MyNullableDateTimeDictionary["key"]);
Assert.Null(newObj.MyObjectDictionary["key"]);
Assert.Null(newObj.MyStringDictionaryDictionary["key"]["key"]);
Assert.Null(newObj.MyListDictionary["key"][0]);
Assert.Null(newObj.MyObjectDictionaryDictionary["key"]["key"]);
var parentObj = new WrapperForTestClassWithInitializedProperties
{
MyClass = obj
};
json = JsonSerializer.Serialize(parentObj, options);
// Roundtrip to ensure serialize is accurate.
WrapperForTestClassWithInitializedProperties newParentObj = JsonSerializer.Deserialize<WrapperForTestClassWithInitializedProperties>(json);
TestClassWithInitializedProperties nestedObj = newParentObj.MyClass;
Assert.Equal("Hello", nestedObj.MyString);
Assert.Equal(1, nestedObj.MyInt);
Assert.Equal(new DateTime(1995, 4, 16), nestedObj.MyDateTime);
Assert.Equal(1, nestedObj.MyIntArray[0]);
Assert.Equal(1, nestedObj.MyIntList[0]);
Assert.Equal(1, nestedObj.MyNullableIntList[0]);
Assert.Null(nestedObj.MyObjectList[0]);
Assert.Null(nestedObj.MyObjectList[0]);
Assert.Null(nestedObj.MyListList[0][0]);
Assert.Null(nestedObj.MyDictionaryList[0]["key"]);
Assert.Null(nestedObj.MyStringDictionary["key"]);
Assert.Null(nestedObj.MyNullableDateTimeDictionary["key"]);
Assert.Null(nestedObj.MyObjectDictionary["key"]);
Assert.Null(nestedObj.MyStringDictionaryDictionary["key"]["key"]);
Assert.Null(nestedObj.MyListDictionary["key"][0]);
Assert.Null(nestedObj.MyObjectDictionaryDictionary["key"]["key"]);
}
[Fact]
public static void NullReferences()
{
var obj = new ObjectWithObjectProperties();
obj.Address = null;
obj.Array = null;
obj.List = null;
obj.IEnumerableT = null;
obj.IListT = null;
obj.ICollectionT = null;
obj.IReadOnlyCollectionT = null;
obj.IReadOnlyListT = null;
obj.StackT = null;
obj.QueueT = null;
obj.HashSetT = null;
obj.LinkedListT = null;
obj.SortedSetT = null;
obj.NullableInt = null;
obj.NullableIntArray = null;
obj.Object = null;
string json = JsonSerializer.Serialize(obj);
Assert.Contains(@"""Address"":null", json);
Assert.Contains(@"""List"":null", json);
Assert.Contains(@"""Array"":null", json);
Assert.Contains(@"""IEnumerableT"":null", json);
Assert.Contains(@"""IListT"":null", json);
Assert.Contains(@"""ICollectionT"":null", json);
Assert.Contains(@"""IReadOnlyCollectionT"":null", json);
Assert.Contains(@"""IReadOnlyListT"":null", json);
Assert.Contains(@"""StackT"":null", json);
Assert.Contains(@"""QueueT"":null", json);
Assert.Contains(@"""HashSetT"":null", json);
Assert.Contains(@"""LinkedListT"":null", json);
Assert.Contains(@"""SortedSetT"":null", json);
Assert.Contains(@"""NullableInt"":null", json);
Assert.Contains(@"""Object"":null", json);
Assert.Contains(@"""NullableIntArray"":null", json);
}
[Fact]
public static void NullArrayElement()
{
string json = JsonSerializer.Serialize(new ObjectWithObjectProperties[]{ null });
Assert.Equal("[null]", json);
}
[Fact]
public static void NullArgumentFail()
{
Assert.Throws<ArgumentNullException>(() => JsonSerializer.Serialize("", (Type)null));
}
[Fact]
public static void NullObjectOutput()
{
{
string output = JsonSerializer.Serialize<string>(null);
Assert.Equal("null", output);
}
{
string output = JsonSerializer.Serialize<string>(null, null);
Assert.Equal("null", output);
}
}
class WrapperForTestClassWithInitializedProperties
{
public TestClassWithInitializedProperties MyClass { get; set; }
}
[Fact]
public static void SerializeDictionaryWithNullValues()
{
Dictionary<string, string> StringVals = new Dictionary<string, string>()
{
["key"] = null,
};
Assert.Equal(@"{""key"":null}", JsonSerializer.Serialize(StringVals));
Dictionary<string, object> ObjVals = new Dictionary<string, object>()
{
["key"] = null,
};
Assert.Equal(@"{""key"":null}", JsonSerializer.Serialize(ObjVals));
Dictionary<string, Dictionary<string, string>> StringDictVals = new Dictionary<string, Dictionary<string, string>>()
{
["key"] = null,
};
Assert.Equal(@"{""key"":null}", JsonSerializer.Serialize(StringDictVals));
Dictionary<string, Dictionary<string, object>> ObjectDictVals = new Dictionary<string, Dictionary<string, object>>()
{
["key"] = null,
};
Assert.Equal(@"{""key"":null}", JsonSerializer.Serialize(ObjectDictVals));
}
[Fact]
public static void WritePocoArray()
{
var input = new MyPoco[] { null, new MyPoco { Foo = "foo" } };
string json = JsonSerializer.Serialize(input, new JsonSerializerOptions { Converters = { new MyPocoConverter() } });
Assert.Equal("[null,{\"Foo\":\"foo\"}]", json);
}
private class MyPoco
{
public string Foo { get; set; }
}
private class MyPocoConverter : JsonConverter<MyPoco>
{
public override MyPoco Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, MyPoco value, JsonSerializerOptions options)
{
if (value == null)
{
throw new InvalidOperationException("The custom converter should never get called with null value.");
}
writer.WriteStartObject();
writer.WriteString(nameof(value.Foo), value.Foo);
writer.WriteEndObject();
}
}
[Fact]
public static void InvalidRootOnWrite()
{
int[,] arr = null;
Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize<int[,]>(arr));
var options = new JsonSerializerOptions
{
IgnoreNullValues = true
};
// We still throw when we have an unsupported root.
Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize<int[,]>(arr, options));
}
}
}
| 44.528986 | 166 | 0.566314 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Text.Json/tests/Serialization/Null.WriteTests.cs | 12,290 | C# |
using Kerberos.NET;
using Kerberos.NET.Crypto;
using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using NextFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
namespace KerberosWebSample
{
internal class KerberosEndToEndMiddleware
{
private readonly KerberosValidator validator;
private readonly NextFunc next;
public KerberosEndToEndMiddleware(NextFunc next)
{
this.next = next;
// NOTE: ValidateAfterDecrypt is a dangerous flag. It should only be used for samples
validator = new KerberosValidator(new KerberosKey("P@ssw0rd!")) { ValidateAfterDecrypt = ValidationActions.None };
}
public async Task Invoke(IDictionary<string, object> environment)
{
var context = new OwinContext(environment);
//validator.Logger = context.TraceOutput.Write;
if (await ParseKerberosHeader(context))
{
await next.Invoke(environment);
}
}
private async Task<bool> ParseKerberosHeader(OwinContext context)
{
string[] authzHeader = null;
if (!context.Request.Headers.TryGetValue("Authorization", out authzHeader) || authzHeader.Length != 1)
{
context.Response.Headers.Add("WWW-Authenticate", new[] { "Negotiate" });
context.Response.StatusCode = 401;
return false;
}
var header = authzHeader.First();
try
{
var authenticator = new KerberosAuthenticator(validator);
var identity = await authenticator.Authenticate(header);
context.Request.User = new ClaimsPrincipal(identity);
return true;
}
catch (Exception ex)
{
context.TraceOutput.WriteLine(ex);
return false;
}
}
}
} | 29.277778 | 126 | 0.603416 | [
"MIT"
] | AlexanderSemenyak/Kerberos.NET | Samples/KerberosWebSample/KerberosEndToEndMiddleware.cs | 2,110 | C# |
// <auto-generated/>
// Contents of: hl7.fhir.r4.core version: 4.0.1
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Hl7.Fhir.Model;
using Hl7.Fhir.Model.JsonExtensions;
using Hl7.Fhir.Serialization;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 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.
*/
namespace Hl7.Fhir.Model.JsonExtensions
{
/// <summary>
/// JSON Serialization Extensions for MessageDefinition
/// </summary>
public static class MessageDefinitionJsonExtensions
{
/// <summary>
/// Serialize a FHIR MessageDefinition into JSON
/// </summary>
public static void SerializeJson(this MessageDefinition current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
{
if (includeStartObject) { writer.WriteStartObject(); }
writer.WriteString("resourceType","MessageDefinition");
// Complex: MessageDefinition, Export: MessageDefinition, Base: DomainResource (DomainResource)
((Hl7.Fhir.Model.DomainResource)current).SerializeJson(writer, options, false);
if ((current.UrlElement != null) && (current.UrlElement.Value != null))
{
writer.WriteString("url",current.UrlElement.Value);
}
if ((current.Identifier != null) && (current.Identifier.Count != 0))
{
writer.WritePropertyName("identifier");
writer.WriteStartArray();
foreach (Identifier val in current.Identifier)
{
val.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if ((current.VersionElement != null) && (current.VersionElement.Value != null))
{
writer.WriteString("version",current.VersionElement.Value);
}
if ((current.NameElement != null) && (current.NameElement.Value != null))
{
writer.WriteString("name",current.NameElement.Value);
}
if ((current.TitleElement != null) && (current.TitleElement.Value != null))
{
writer.WriteString("title",current.TitleElement.Value);
}
if ((current.ReplacesElement != null) && (current.ReplacesElement.Count != 0))
{
writer.WritePropertyName("replaces");
writer.WriteStartArray();
foreach (Canonical val in current.ReplacesElement)
{
writer.WriteStringValue(val.Value);
}
writer.WriteEndArray();
}
writer.WriteString("status",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.StatusElement.Value));
if ((current.ExperimentalElement != null) && (current.ExperimentalElement.Value != null))
{
writer.WriteBoolean("experimental",(bool)current.ExperimentalElement.Value);
}
writer.WriteString("date",current.DateElement.Value);
if ((current.PublisherElement != null) && (current.PublisherElement.Value != null))
{
writer.WriteString("publisher",current.PublisherElement.Value);
}
if ((current.Contact != null) && (current.Contact.Count != 0))
{
writer.WritePropertyName("contact");
writer.WriteStartArray();
foreach (ContactDetail val in current.Contact)
{
val.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if ((current.Description != null) && (current.Description.Value != null))
{
writer.WriteString("description",current.Description.Value);
}
if ((current.UseContext != null) && (current.UseContext.Count != 0))
{
writer.WritePropertyName("useContext");
writer.WriteStartArray();
foreach (UsageContext val in current.UseContext)
{
val.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if ((current.Jurisdiction != null) && (current.Jurisdiction.Count != 0))
{
writer.WritePropertyName("jurisdiction");
writer.WriteStartArray();
foreach (CodeableConcept val in current.Jurisdiction)
{
val.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if ((current.Purpose != null) && (current.Purpose.Value != null))
{
writer.WriteString("purpose",current.Purpose.Value);
}
if ((current.Copyright != null) && (current.Copyright.Value != null))
{
writer.WriteString("copyright",current.Copyright.Value);
}
if ((current.BaseElement != null) && (current.BaseElement.Value != null))
{
writer.WriteString("base",current.BaseElement.Value);
}
if ((current.ParentElement != null) && (current.ParentElement.Count != 0))
{
writer.WritePropertyName("parent");
writer.WriteStartArray();
foreach (Canonical val in current.ParentElement)
{
writer.WriteStringValue(val.Value);
}
writer.WriteEndArray();
}
if (current.Event != null)
{
switch (current.Event)
{
case Coding v_Coding:
writer.WritePropertyName("eventCoding");
v_Coding.SerializeJson(writer, options);
break;
case FhirUri v_FhirUri:
writer.WriteString("eventUri",v_FhirUri.Value);
break;
}
}
if (current.CategoryElement != null)
{
writer.WriteString("category",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.CategoryElement.Value));
}
if ((current.Focus != null) && (current.Focus.Count != 0))
{
writer.WritePropertyName("focus");
writer.WriteStartArray();
foreach (MessageDefinition.FocusComponent val in current.Focus)
{
val.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if (current.ResponseRequiredElement != null)
{
writer.WriteString("responseRequired",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.ResponseRequiredElement.Value));
}
if ((current.AllowedResponse != null) && (current.AllowedResponse.Count != 0))
{
writer.WritePropertyName("allowedResponse");
writer.WriteStartArray();
foreach (MessageDefinition.AllowedResponseComponent val in current.AllowedResponse)
{
val.SerializeJson(writer, options, true);
}
writer.WriteEndArray();
}
if ((current.GraphElement != null) && (current.GraphElement.Count != 0))
{
writer.WritePropertyName("graph");
writer.WriteStartArray();
foreach (Canonical val in current.GraphElement)
{
writer.WriteStringValue(val.Value);
}
writer.WriteEndArray();
}
if (includeStartObject) { writer.WriteEndObject(); }
}
/// <summary>
/// Deserialize JSON into a FHIR MessageDefinition
/// </summary>
public static void DeserializeJson(this MessageDefinition current, ref Utf8JsonReader reader, JsonSerializerOptions options)
{
string propertyName;
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return;
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
propertyName = reader.GetString();
reader.Read();
current.DeserializeJsonProperty(ref reader, options, propertyName);
}
}
throw new JsonException();
}
/// <summary>
/// Deserialize JSON into a FHIR MessageDefinition
/// </summary>
public static void DeserializeJsonProperty(this MessageDefinition current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
{
switch (propertyName)
{
case "url":
current.UrlElement = new FhirUri(reader.GetString());
break;
case "identifier":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.Identifier = new List<Identifier>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Hl7.Fhir.Model.Identifier v_Identifier = new Hl7.Fhir.Model.Identifier();
v_Identifier.DeserializeJson(ref reader, options);
current.Identifier.Add(v_Identifier);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.Identifier.Count == 0)
{
current.Identifier = null;
}
break;
case "version":
current.VersionElement = new FhirString(reader.GetString());
break;
case "name":
current.NameElement = new FhirString(reader.GetString());
break;
case "title":
current.TitleElement = new FhirString(reader.GetString());
break;
case "replaces":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.ReplacesElement = new List<Canonical>();
while (reader.TokenType != JsonTokenType.EndArray)
{
current.ReplacesElement.Add(new Canonical(reader.GetString()));
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.ReplacesElement.Count == 0)
{
current.ReplacesElement = null;
}
break;
case "_replaces":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
int i_replaces = 0;
while (reader.TokenType != JsonTokenType.EndArray)
{
((Hl7.Fhir.Model.Element)current.ReplacesElement[i_replaces++]).DeserializeJson(ref reader, options);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
break;
case "status":
current.StatusElement =new Code<Hl7.Fhir.Model.PublicationStatus>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.PublicationStatus>(reader.GetString()));
break;
case "experimental":
current.ExperimentalElement = new FhirBoolean(reader.GetBoolean());
break;
case "date":
current.DateElement = new FhirDateTime(reader.GetString());
break;
case "publisher":
current.PublisherElement = new FhirString(reader.GetString());
break;
case "contact":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.Contact = new List<ContactDetail>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Hl7.Fhir.Model.ContactDetail v_Contact = new Hl7.Fhir.Model.ContactDetail();
v_Contact.DeserializeJson(ref reader, options);
current.Contact.Add(v_Contact);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.Contact.Count == 0)
{
current.Contact = null;
}
break;
case "description":
current.Description = new Markdown(reader.GetString());
break;
case "useContext":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.UseContext = new List<UsageContext>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Hl7.Fhir.Model.UsageContext v_UseContext = new Hl7.Fhir.Model.UsageContext();
v_UseContext.DeserializeJson(ref reader, options);
current.UseContext.Add(v_UseContext);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.UseContext.Count == 0)
{
current.UseContext = null;
}
break;
case "jurisdiction":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.Jurisdiction = new List<CodeableConcept>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Hl7.Fhir.Model.CodeableConcept v_Jurisdiction = new Hl7.Fhir.Model.CodeableConcept();
v_Jurisdiction.DeserializeJson(ref reader, options);
current.Jurisdiction.Add(v_Jurisdiction);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.Jurisdiction.Count == 0)
{
current.Jurisdiction = null;
}
break;
case "purpose":
current.Purpose = new Markdown(reader.GetString());
break;
case "copyright":
current.Copyright = new Markdown(reader.GetString());
break;
case "base":
current.BaseElement = new Canonical(reader.GetString());
break;
case "_base":
((Hl7.Fhir.Model.Element)current.BaseElement).DeserializeJson(ref reader, options);
break;
case "parent":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.ParentElement = new List<Canonical>();
while (reader.TokenType != JsonTokenType.EndArray)
{
current.ParentElement.Add(new Canonical(reader.GetString()));
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.ParentElement.Count == 0)
{
current.ParentElement = null;
}
break;
case "_parent":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
int i_parent = 0;
while (reader.TokenType != JsonTokenType.EndArray)
{
((Hl7.Fhir.Model.Element)current.ParentElement[i_parent++]).DeserializeJson(ref reader, options);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
break;
case "eventCoding":
current.Event = new Hl7.Fhir.Model.Coding();
current.Event.DeserializeJson(ref reader, options);
break;
case "eventUri":
current.Event = new FhirUri(reader.GetString());
break;
case "category":
current.CategoryElement =new Code<Hl7.Fhir.Model.MessageDefinition.MessageSignificanceCategory>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.MessageDefinition.MessageSignificanceCategory>(reader.GetString()));
break;
case "focus":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.Focus = new List<MessageDefinition.FocusComponent>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Hl7.Fhir.Model.MessageDefinition.FocusComponent v_Focus = new Hl7.Fhir.Model.MessageDefinition.FocusComponent();
v_Focus.DeserializeJson(ref reader, options);
current.Focus.Add(v_Focus);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.Focus.Count == 0)
{
current.Focus = null;
}
break;
case "responseRequired":
current.ResponseRequiredElement =new Code<Hl7.Fhir.Model.messageheader_response_request>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.messageheader_response_request>(reader.GetString()));
break;
case "allowedResponse":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.AllowedResponse = new List<MessageDefinition.AllowedResponseComponent>();
while (reader.TokenType != JsonTokenType.EndArray)
{
Hl7.Fhir.Model.MessageDefinition.AllowedResponseComponent v_AllowedResponse = new Hl7.Fhir.Model.MessageDefinition.AllowedResponseComponent();
v_AllowedResponse.DeserializeJson(ref reader, options);
current.AllowedResponse.Add(v_AllowedResponse);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.AllowedResponse.Count == 0)
{
current.AllowedResponse = null;
}
break;
case "graph":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
current.GraphElement = new List<Canonical>();
while (reader.TokenType != JsonTokenType.EndArray)
{
current.GraphElement.Add(new Canonical(reader.GetString()));
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
if (current.GraphElement.Count == 0)
{
current.GraphElement = null;
}
break;
case "_graph":
if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
{
throw new JsonException();
}
int i_graph = 0;
while (reader.TokenType != JsonTokenType.EndArray)
{
((Hl7.Fhir.Model.Element)current.GraphElement[i_graph++]).DeserializeJson(ref reader, options);
if (!reader.Read())
{
throw new JsonException();
}
if (reader.TokenType == JsonTokenType.EndObject) { reader.Read(); }
}
break;
// Complex: MessageDefinition, Export: MessageDefinition, Base: DomainResource
default:
((Hl7.Fhir.Model.DomainResource)current).DeserializeJsonProperty(ref reader, options, propertyName);
break;
}
}
/// <summary>
/// Serialize a FHIR MessageDefinition#Focus into JSON
/// </summary>
public static void SerializeJson(this MessageDefinition.FocusComponent current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
{
if (includeStartObject) { writer.WriteStartObject(); }
// Component: MessageDefinition#Focus, Export: FocusComponent, Base: BackboneElement (BackboneElement)
((Hl7.Fhir.Model.BackboneElement)current).SerializeJson(writer, options, false);
writer.WriteString("code",Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.CodeElement.Value));
if ((current.ProfileElement != null) && (current.ProfileElement.Value != null))
{
writer.WriteString("profile",current.ProfileElement.Value);
}
writer.WriteNumber("min",(int)current.MinElement.Value);
if ((current.MaxElement != null) && (current.MaxElement.Value != null))
{
writer.WriteString("max",current.MaxElement.Value);
}
if (includeStartObject) { writer.WriteEndObject(); }
}
/// <summary>
/// Deserialize JSON into a FHIR MessageDefinition#Focus
/// </summary>
public static void DeserializeJson(this MessageDefinition.FocusComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options)
{
string propertyName;
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return;
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
propertyName = reader.GetString();
reader.Read();
current.DeserializeJsonProperty(ref reader, options, propertyName);
}
}
throw new JsonException();
}
/// <summary>
/// Deserialize JSON into a FHIR MessageDefinition#Focus
/// </summary>
public static void DeserializeJsonProperty(this MessageDefinition.FocusComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
{
switch (propertyName)
{
case "code":
current.CodeElement =new Code<Hl7.Fhir.Model.ResourceType>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral<Hl7.Fhir.Model.ResourceType>(reader.GetString()));
break;
case "profile":
current.ProfileElement = new Canonical(reader.GetString());
break;
case "_profile":
((Hl7.Fhir.Model.Element)current.ProfileElement).DeserializeJson(ref reader, options);
break;
case "min":
current.MinElement = new UnsignedInt(reader.GetInt32());
break;
case "max":
current.MaxElement = new FhirString(reader.GetString());
break;
// Complex: focus, Export: FocusComponent, Base: BackboneElement
default:
((Hl7.Fhir.Model.BackboneElement)current).DeserializeJsonProperty(ref reader, options, propertyName);
break;
}
}
/// <summary>
/// Serialize a FHIR MessageDefinition#AllowedResponse into JSON
/// </summary>
public static void SerializeJson(this MessageDefinition.AllowedResponseComponent current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
{
if (includeStartObject) { writer.WriteStartObject(); }
// Component: MessageDefinition#AllowedResponse, Export: AllowedResponseComponent, Base: BackboneElement (BackboneElement)
((Hl7.Fhir.Model.BackboneElement)current).SerializeJson(writer, options, false);
writer.WriteString("message",current.MessageElement.Value);
if ((current.Situation != null) && (current.Situation.Value != null))
{
writer.WriteString("situation",current.Situation.Value);
}
if (includeStartObject) { writer.WriteEndObject(); }
}
/// <summary>
/// Deserialize JSON into a FHIR MessageDefinition#AllowedResponse
/// </summary>
public static void DeserializeJson(this MessageDefinition.AllowedResponseComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options)
{
string propertyName;
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return;
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
propertyName = reader.GetString();
reader.Read();
current.DeserializeJsonProperty(ref reader, options, propertyName);
}
}
throw new JsonException();
}
/// <summary>
/// Deserialize JSON into a FHIR MessageDefinition#AllowedResponse
/// </summary>
public static void DeserializeJsonProperty(this MessageDefinition.AllowedResponseComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
{
switch (propertyName)
{
case "message":
current.MessageElement = new Canonical(reader.GetString());
break;
case "_message":
((Hl7.Fhir.Model.Element)current.MessageElement).DeserializeJson(ref reader, options);
break;
case "situation":
current.Situation = new Markdown(reader.GetString());
break;
// Complex: allowedResponse, Export: AllowedResponseComponent, Base: BackboneElement
default:
((Hl7.Fhir.Model.BackboneElement)current).DeserializeJsonProperty(ref reader, options, propertyName);
break;
}
}
/// <summary>
/// Resource converter to support Sytem.Text.Json interop.
/// </summary>
public class MessageDefinitionJsonConverter : JsonConverter<MessageDefinition>
{
/// <summary>
/// Determines whether the specified type can be converted.
/// </summary>
public override bool CanConvert(Type objectType) =>
typeof(MessageDefinition).IsAssignableFrom(objectType);
/// <summary>
/// Writes a specified value as JSON.
/// </summary>
public override void Write(Utf8JsonWriter writer, MessageDefinition value, JsonSerializerOptions options)
{
value.SerializeJson(writer, options, true);
writer.Flush();
}
/// <summary>
/// Reads and converts the JSON to a typed object.
/// </summary>
public override MessageDefinition Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
MessageDefinition target = new MessageDefinition();
target.DeserializeJson(ref reader, options);
return target;
}
}
}
}
// end of file
| 32.970024 | 231 | 0.607884 | [
"MIT"
] | QPC-database/fhir-codegen | test/perfTestCS/SystemTextJsonExt/Model/MessageDefinition.cs | 27,497 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codedeploy-2014-10-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.CodeDeploy.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeDeploy.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetDeployment operation
/// </summary>
public class GetDeploymentResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetDeploymentResponse response = new GetDeploymentResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("deploymentInfo", targetDepth))
{
var unmarshaller = DeploymentInfoUnmarshaller.Instance;
response.DeploymentInfo = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("DeploymentDoesNotExistException"))
{
return DeploymentDoesNotExistExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("DeploymentIdRequiredException"))
{
return DeploymentIdRequiredExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidDeploymentIdException"))
{
return InvalidDeploymentIdExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonCodeDeployException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetDeploymentResponseUnmarshaller _instance = new GetDeploymentResponseUnmarshaller();
internal static GetDeploymentResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetDeploymentResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.838983 | 193 | 0.649138 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeDeploy/Generated/Model/Internal/MarshallTransformations/GetDeploymentResponseUnmarshaller.cs | 4,583 | C# |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Ntfs
{
internal class DirectoryEntry
{
private Directory _directory;
private FileRecordReference _fileReference;
private FileNameRecord _fileDetails;
public DirectoryEntry(Directory directory, FileRecordReference fileReference, FileNameRecord fileDetails)
{
_directory = directory;
_fileReference = fileReference;
_fileDetails = fileDetails;
}
public FileRecordReference Reference
{
get { return _fileReference; }
}
public FileNameRecord Details
{
get { return _fileDetails; }
}
public bool IsDirectory
{
get { return (_fileDetails.Flags & FileAttributeFlags.Directory) != 0; }
}
public string SearchName
{
get
{
string fileName = _fileDetails.FileName;
if (fileName.IndexOf('.') == -1)
{
return fileName + ".";
}
else
{
return fileName;
}
}
}
internal void UpdateFrom(File file)
{
file.FreshenFileName(_fileDetails, true);
_directory.UpdateEntry(this);
}
}
}
| 33.526316 | 114 | 0.60675 | [
"MIT"
] | ChaplinMarchais/DiscUtils | src/Ntfs/DirectoryEntry.cs | 2,548 | C# |
namespace PropertyInformationApi.V1.UseCase
{
public interface IValidatePostcode
{
bool Execute(string postcode);
}
}
| 17.25 | 43 | 0.702899 | [
"MIT"
] | LBHackney-IT/property-information-api | PropertyInformationApi/V1/UseCase/Interfaces/IValidatePostcode.cs | 138 | C# |
namespace Exemplum.Infrastructure.Persistence.Configurations;
using Domain.Todo;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class TodoListConfiguration : IEntityTypeConfiguration<TodoList>
{
public void Configure(EntityTypeBuilder<TodoList> builder)
{
builder.Property(x => x.Title)
.HasMaxLength(300)
.IsRequired();
builder.HasIndex(x => x.Title)
.IsUnique();
builder.Property(x => x.Colour)
.HasConversion(
x => x!.ToString(),
x => Colour.From(x));
}
} | 27.434783 | 71 | 0.638669 | [
"MIT"
] | ForrestTech/Exemplum | src/Infrastructure/Persistence/Configurations/TodoListConfiguration.cs | 633 | C# |
/*
* convertapi
*
* Convert API lets you effortlessly convert file formats and types.
*
* OpenAPI spec version: v1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Client.SwaggerDateConverter;
namespace Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Model
{
/// <summary>
/// Input to a Remove PowerPoint PPTX Presentation Slides request
/// </summary>
[DataContract]
public partial class RemovePptxSlidesRequest : IEquatable<RemovePptxSlidesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RemovePptxSlidesRequest" /> class.
/// </summary>
/// <param name="inputFileBytes">Optional: Bytes of the input file to operate on.</param>
/// <param name="inputFileUrl">Optional: URL of a file to operate on as input. This can be a public URL, or you can also use the begin-editing API to upload a document and pass in the secure URL result from that operation as the URL here (this URL is not public)..</param>
/// <param name="startDeleteSlideNumber">Slide number (1-based) to start deleting slides; inclusive.</param>
/// <param name="endDeleteSlideNumber">Slide number (1-based) to stop deleting slides; inclusive.</param>
public RemovePptxSlidesRequest(byte[] inputFileBytes = default(byte[]), string inputFileUrl = default(string), int? startDeleteSlideNumber = default(int?), int? endDeleteSlideNumber = default(int?))
{
this.InputFileBytes = inputFileBytes;
this.InputFileUrl = inputFileUrl;
this.StartDeleteSlideNumber = startDeleteSlideNumber;
this.EndDeleteSlideNumber = endDeleteSlideNumber;
}
/// <summary>
/// Optional: Bytes of the input file to operate on
/// </summary>
/// <value>Optional: Bytes of the input file to operate on</value>
[DataMember(Name="InputFileBytes", EmitDefaultValue=false)]
public byte[] InputFileBytes { get; set; }
/// <summary>
/// Optional: URL of a file to operate on as input. This can be a public URL, or you can also use the begin-editing API to upload a document and pass in the secure URL result from that operation as the URL here (this URL is not public).
/// </summary>
/// <value>Optional: URL of a file to operate on as input. This can be a public URL, or you can also use the begin-editing API to upload a document and pass in the secure URL result from that operation as the URL here (this URL is not public).</value>
[DataMember(Name="InputFileUrl", EmitDefaultValue=false)]
public string InputFileUrl { get; set; }
/// <summary>
/// Slide number (1-based) to start deleting slides; inclusive
/// </summary>
/// <value>Slide number (1-based) to start deleting slides; inclusive</value>
[DataMember(Name="StartDeleteSlideNumber", EmitDefaultValue=false)]
public int? StartDeleteSlideNumber { get; set; }
/// <summary>
/// Slide number (1-based) to stop deleting slides; inclusive
/// </summary>
/// <value>Slide number (1-based) to stop deleting slides; inclusive</value>
[DataMember(Name="EndDeleteSlideNumber", EmitDefaultValue=false)]
public int? EndDeleteSlideNumber { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RemovePptxSlidesRequest {\n");
sb.Append(" InputFileBytes: ").Append(InputFileBytes).Append("\n");
sb.Append(" InputFileUrl: ").Append(InputFileUrl).Append("\n");
sb.Append(" StartDeleteSlideNumber: ").Append(StartDeleteSlideNumber).Append("\n");
sb.Append(" EndDeleteSlideNumber: ").Append(EndDeleteSlideNumber).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as RemovePptxSlidesRequest);
}
/// <summary>
/// Returns true if RemovePptxSlidesRequest instances are equal
/// </summary>
/// <param name="input">Instance of RemovePptxSlidesRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RemovePptxSlidesRequest input)
{
if (input == null)
return false;
return
(
this.InputFileBytes == input.InputFileBytes ||
(this.InputFileBytes != null &&
this.InputFileBytes.Equals(input.InputFileBytes))
) &&
(
this.InputFileUrl == input.InputFileUrl ||
(this.InputFileUrl != null &&
this.InputFileUrl.Equals(input.InputFileUrl))
) &&
(
this.StartDeleteSlideNumber == input.StartDeleteSlideNumber ||
(this.StartDeleteSlideNumber != null &&
this.StartDeleteSlideNumber.Equals(input.StartDeleteSlideNumber))
) &&
(
this.EndDeleteSlideNumber == input.EndDeleteSlideNumber ||
(this.EndDeleteSlideNumber != null &&
this.EndDeleteSlideNumber.Equals(input.EndDeleteSlideNumber))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.InputFileBytes != null)
hashCode = hashCode * 59 + this.InputFileBytes.GetHashCode();
if (this.InputFileUrl != null)
hashCode = hashCode * 59 + this.InputFileUrl.GetHashCode();
if (this.StartDeleteSlideNumber != null)
hashCode = hashCode * 59 + this.StartDeleteSlideNumber.GetHashCode();
if (this.EndDeleteSlideNumber != null)
hashCode = hashCode * 59 + this.EndDeleteSlideNumber.GetHashCode();
return hashCode;
}
}
}
}
| 44.606061 | 281 | 0.608152 | [
"Apache-2.0"
] | Cloudmersive/Cloudmersive.APIClient.NETCore.DocumentAndDataConvert | client/src/Cloudmersive.APIClient.NETCore.DocumentAndDataConvert/Model/RemovePptxSlidesRequest.cs | 7,360 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CryptoGatherer
{
public enum CodeLanguage
{
Csharp,
C_Cpp,
Go,
Java,
JavaScript,
PHP,
Python,
Ruby,
Rust
}
public enum CryptoAlgorithm
{
Asymmetric_RSA,
Hash_BCrypt,
Hash_Blake,
Hash_Blake2,
Hash_Blake3,
Hash_GOST,
Hash_Grøstl,
Hash_HAS_160,
Hash_HAVAL,
Hash_JH,
Hash_Kupyna,
Hash_MD2,
Hash_MD4,
Hash_MD5,
Hash_MD6,
Hash_RIPEMD,
Hash_SHA_1,
Hash_SHA_2_224,
Hash_SHA_2_256,
Hash_SHA_2_384,
Hash_SHA_2_512,
Hash_SHA3,
Hash_Siphash,
Hash_Skein,
Hash_SM3,
Hash_Snefru,
Hash_SpectralHash,
Hash_Streebog,
Hash_Tiger,
Hash_Whirlpool,
KeyAgreement_Curve25519_X25519,
PRNG,
Symmetric_AES,
Symmetric_Salsa20_ChaCha,
SAFER,
twofish,
anubis,
blowfish,
camellia,
cast5,
DES,
idea,
kasumi,
khazad,
kseed,
multi2,
noekeon,
rc2,
rc5,
rc6,
serpent,
skipjack,
tea,
xtea
// bunch of values added from https://github.com/libtom/libtomcrypt/tree/develop/src/ciphers
}
}
| 18.47561 | 100 | 0.522112 | [
"MIT"
] | dilanbhalla/OSSGadget | src/CryptoGatherer/Types.cs | 1,518 | C# |
using Mirror;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleRulerTool : NetworkBehaviour {
public GameObject rulerObject;
public Camera mainCamera;
GameObject activeRuler;
private void Start() {
if (mainCamera == null) mainCamera = Camera.main;
}
/// <summary>
/// Main method
/// </summary>
public void PlaceRulerTool() {
if (Input.GetMouseButtonDown(0)) {
if (activeRuler != null) CmdDestroyRuler(activeRuler);
Vector2 rawStartPoint = (Vector2)mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector2 startPoint = new Vector2(Mathf.RoundToInt(rawStartPoint.x - 0.5f) + 0.5f, Mathf.RoundToInt(rawStartPoint.y - 0.5f) + 0.5f);
CmdSpawnRuler(startPoint);
}
}
/// <summary>
/// Updates the position of the ruler while the mouse button is being held then calls
/// the command to destroy the ruler when the button is released.
/// </summary>
/// <param name="startPoint">Location being measured from</param>
/// <param name="ruler">Reference to the ruler object</param>
/// <returns></returns>
IEnumerator PlaceRuler(Vector2 startPoint, GameObject ruler) {
Vector2 rawCurrentPos;
Vector2 currentPos;
var rulerComp = ruler.GetComponent<CircleRuler>();
while (Input.GetMouseButton(0)) {
rawCurrentPos = (Vector2)mainCamera.ScreenToWorldPoint(Input.mousePosition);
currentPos = new Vector2(Mathf.RoundToInt(rawCurrentPos.x - 0.5f) + 0.5f, Mathf.RoundToInt(rawCurrentPos.y - 0.5f) + 0.5f);
rulerComp.SetRuler(startPoint, currentPos);
yield return null;
}
}
[Command(requiresAuthority = false)]
private void CmdDestroyRuler(GameObject ruler) {
NetworkServer.Destroy(ruler);
}
[Command(requiresAuthority = false)]
void CmdSpawnRuler(Vector2 startPoint, NetworkConnectionToClient conn = null) {
GameObject ruler = Instantiate(rulerObject, startPoint, Quaternion.identity);
NetworkServer.Spawn(ruler);
RulerSpawned(conn, startPoint, ruler);
}
[TargetRpc]
private void RulerSpawned(NetworkConnection conn, Vector2 startPoint, GameObject ruler) {
activeRuler = ruler;
StartCoroutine(PlaceRuler(startPoint, ruler));
}
}
| 34.277778 | 144 | 0.649514 | [
"MIT"
] | BenThrelfall/DungeonTool | Assets/Scripts/CircleRulerTool.cs | 2,468 | C# |
using System;
using ClearHl7.Helpers;
namespace ClearHl7.V290.Types
{
/// <summary>
/// HL7 Version 2 VR - Value Range.
/// </summary>
public class ValueRange : IType
{
/// <inheritdoc/>
public bool IsSubcomponent { get; set; }
/// <summary>
/// VR.1 - First Data Code Value.
/// </summary>
public string FirstDataCodeValue { get; set; }
/// <summary>
/// VR.2 - Last Data Code Value.
/// </summary>
public string LastDataCodeValue { get; set; }
/// <inheritdoc/>
public void FromDelimitedString(string delimitedString)
{
FromDelimitedString(delimitedString, null);
}
/// <inheritdoc/>
public void FromDelimitedString(string delimitedString, Separators separators)
{
Separators seps = separators ?? new Separators().UsingConfigurationValues();
string[] separator = IsSubcomponent ? seps.SubcomponentSeparator : seps.ComponentSeparator;
string[] segments = delimitedString == null
? Array.Empty<string>()
: delimitedString.Split(separator, StringSplitOptions.None);
FirstDataCodeValue = segments.Length > 0 && segments[0].Length > 0 ? segments[0] : null;
LastDataCodeValue = segments.Length > 1 && segments[1].Length > 0 ? segments[1] : null;
}
/// <inheritdoc/>
public string ToDelimitedString()
{
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;
string separator = IsSubcomponent ? Configuration.SubcomponentSeparator : Configuration.ComponentSeparator;
return string.Format(
culture,
StringHelper.StringFormatSequence(0, 2, separator),
FirstDataCodeValue,
LastDataCodeValue
).TrimEnd(separator.ToCharArray());
}
}
}
| 35.689655 | 119 | 0.571014 | [
"MIT"
] | kamlesh-microsoft/clear-hl7-net | src/ClearHl7/V290/Types/ValueRange.cs | 2,072 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// Extension methods for <see cref="IConventionModel" />.
/// </summary>
public static class ConventionModelExtensions
{
/// <summary>
/// Gets the entity that maps the given entity class. Returns null if no entity type with the given name is found.
/// </summary>
/// <param name="model"> The model to find the entity type in. </param>
/// <param name="type"> The type to find the corresponding entity type for. </param>
/// <returns> The entity type, or <c>null</c> if none if found. </returns>
public static IConventionEntityType FindEntityType([NotNull] this IConventionModel model, [NotNull] Type type)
=> (IConventionEntityType)((IModel)model).FindEntityType(type);
/// <summary>
/// Gets the entity type for the given name, defining navigation name
/// and the defining entity type. Returns null if no matching entity type is found.
/// </summary>
/// <param name="model"> The model to find the entity type in. </param>
/// <param name="type"> The type of the entity type to find. </param>
/// <param name="definingNavigationName"> The defining navigation of the entity type to find. </param>
/// <param name="definingEntityType"> The defining entity type of the entity type to find. </param>
/// <returns> The entity type, or <c>null</c> if none are found. </returns>
public static IConventionEntityType FindEntityType(
[NotNull] this IConventionModel model,
[NotNull] Type type,
[NotNull] string definingNavigationName,
[NotNull] IConventionEntityType definingEntityType)
=> (IConventionEntityType)((IModel)model).FindEntityType(type, definingNavigationName, definingEntityType);
/// <summary>
/// Removes an entity type without a defining navigation from the model.
/// </summary>
/// <param name="model"> The model to remove the entity type from. </param>
/// <param name="name"> The name of the entity type to be removed. </param>
/// <returns> The entity type that was removed. </returns>
public static IConventionEntityType RemoveEntityType(
[NotNull] this IConventionModel model,
[NotNull] string name)
{
Check.NotNull(model, nameof(model));
Check.NotEmpty(name, nameof(name));
return ((Model)model).RemoveEntityType(name);
}
/// <summary>
/// Removes an entity type with a defining navigation from the model.
/// </summary>
/// <param name="model"> The model to remove the entity type from. </param>
/// <param name="name"> The name of the entity type to be removed. </param>
/// <param name="definingNavigationName"> The defining navigation. </param>
/// <param name="definingEntityType"> The defining entity type. </param>
/// <returns> The entity type that was removed. </returns>
public static IConventionEntityType RemoveEntityType(
[NotNull] this IConventionModel model,
[NotNull] string name,
[NotNull] string definingNavigationName,
[NotNull] IConventionEntityType definingEntityType)
{
Check.NotNull(model, nameof(model));
Check.NotEmpty(name, nameof(name));
Check.NotEmpty(definingNavigationName, nameof(definingNavigationName));
Check.NotNull(definingEntityType, nameof(definingEntityType));
return ((Model)model).RemoveEntityType(name);
}
/// <summary>
/// Removes an entity type from the model.
/// </summary>
/// <param name="model"> The model to remove the entity type from. </param>
/// <param name="type"> The entity type to be removed. </param>
/// <returns> The entity type that was removed. </returns>
public static IConventionEntityType RemoveEntityType([NotNull] this IConventionModel model, [NotNull] Type type)
{
Check.NotNull(model, nameof(model));
Check.NotNull(type, nameof(type));
return ((Model)model).RemoveEntityType(type);
}
/// <summary>
/// Removes an entity type with a defining navigation from the model.
/// </summary>
/// <param name="model"> The model to remove the entity type from. </param>
/// <param name="type"> The CLR class that is used to represent instances of this entity type. </param>
/// <param name="definingNavigationName"> The defining navigation. </param>
/// <param name="definingEntityType"> The defining entity type. </param>
/// <returns> The entity type that was removed. </returns>
public static IConventionEntityType RemoveEntityType(
[NotNull] this IConventionModel model,
[NotNull] Type type,
[NotNull] string definingNavigationName,
[NotNull] IConventionEntityType definingEntityType)
=> Check.NotNull((Model)model, nameof(model)).RemoveEntityType(
Check.NotNull(type, nameof(type)),
Check.NotNull(definingNavigationName, nameof(definingNavigationName)),
(EntityType)Check.NotNull(definingEntityType, nameof(definingEntityType)));
/// <summary>
/// Returns the entity types corresponding to the least derived types from the given.
/// </summary>
/// <param name="model"> The model to find the entity types in. </param>
/// <param name="type"> The base type. </param>
/// <param name="condition"> An optional condition for filtering entity types. </param>
/// <returns> List of entity types corresponding to the least derived types from the given. </returns>
public static IReadOnlyList<IConventionEntityType> FindLeastDerivedEntityTypes(
[NotNull] this IConventionModel model,
[NotNull] Type type,
[CanBeNull] Func<IConventionEntityType, bool> condition = null)
=> Check.NotNull((Model)model, nameof(model))
.FindLeastDerivedEntityTypes(type, condition);
/// <summary>
/// <para>
/// Sets the <see cref="PropertyAccessMode" /> to use for properties of all entity types
/// in this model.
/// </para>
/// <para>
/// Note that individual entity types can override this access mode, and individual properties of
/// entity types can override the access mode set on the entity type. The value set here will
/// be used for any property for which no override has been specified.
/// </para>
/// </summary>
/// <param name="model"> The model to set the access mode for. </param>
/// <param name="propertyAccessMode"> The <see cref="PropertyAccessMode" />, or <c>null</c> to clear the mode set.</param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
public static void SetPropertyAccessMode(
[NotNull] this IConventionModel model,
PropertyAccessMode? propertyAccessMode,
bool fromDataAnnotation = false)
=> Check.NotNull((Model)model, nameof(model))
.SetPropertyAccessMode(
propertyAccessMode,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <summary>
/// Returns the configuration source for <see cref="ModelExtensions.GetPropertyAccessMode" />.
/// </summary>
/// <param name="model"> The model to find configuration source for. </param>
/// <returns> The configuration source for <see cref="ModelExtensions.GetPropertyAccessMode" />. </returns>
public static ConfigurationSource? GetPropertyAccessModeConfigurationSource([NotNull] this IConventionModel model)
=> model.FindAnnotation(CoreAnnotationNames.PropertyAccessMode)?.GetConfigurationSource();
/// <summary>
/// Sets the default change tracking strategy to use for entities in the model. This strategy indicates how the
/// context detects changes to properties for an instance of an entity type.
/// </summary>
/// <param name="model"> The model to set the default change tracking strategy for. </param>
/// <param name="changeTrackingStrategy"> The strategy to use. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
public static void SetChangeTrackingStrategy(
[NotNull] this IConventionModel model,
ChangeTrackingStrategy? changeTrackingStrategy,
bool fromDataAnnotation = false)
=> Check.NotNull((Model)model, nameof(model))
.SetChangeTrackingStrategy(
changeTrackingStrategy,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <summary>
/// Returns the configuration source for <see cref="ModelExtensions.GetChangeTrackingStrategy" />.
/// </summary>
/// <param name="model"> The model to find configuration source for. </param>
/// <returns> The configuration source for <see cref="ModelExtensions.GetChangeTrackingStrategy" />. </returns>
public static ConfigurationSource? GetChangeTrackingStrategyConfigurationSource([NotNull] this IConventionModel model)
=> model.FindAnnotation(CoreAnnotationNames.ChangeTrackingStrategy)?.GetConfigurationSource();
/// <summary>
/// Returns a value indicating whether the entity types using the given type should be configured
/// as owned types when discovered.
/// </summary>
/// <param name="model"> The model. </param>
/// <param name="clrType"> The type of the entity type that could be owned. </param>
/// <returns>
/// <c>true</c> if the given type name is marked as owned,
/// <c>null</c> otherwise.
/// </returns>
public static bool IsOwned([NotNull] this IConventionModel model, [NotNull] Type clrType)
=> model.FindIsOwnedConfigurationSource(clrType) != null;
/// <summary>
/// Returns a value indicating whether the entity types using the given type should be configured
/// as owned types when discovered.
/// </summary>
/// <param name="model"> The model. </param>
/// <param name="clrType"> The type of the entity type that could be owned. </param>
/// <returns>
/// The configuration source if the given type name is marked as owned,
/// <c>null</c> otherwise.
/// </returns>
public static ConfigurationSource? FindIsOwnedConfigurationSource([NotNull] this IConventionModel model, [NotNull] Type clrType)
=> Check.NotNull((Model)model, nameof(model)).FindIsOwnedConfigurationSource(
Check.NotNull(clrType, nameof(clrType)));
/// <summary>
/// Marks the given entity type as owned, indicating that when discovered entity types using the given type
/// should be configured as owned.
/// </summary>
/// <param name="model"> The model to add the owned type to. </param>
/// <param name="clrType"> The type of the entity type that should be owned. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
public static void AddOwned([NotNull] this IConventionModel model, [NotNull] Type clrType, bool fromDataAnnotation = false)
=> Check.NotNull((Model)model, nameof(model)).AddOwned(
Check.NotNull(clrType, nameof(clrType)),
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <summary>
/// Indicates whether the given entity type name is ignored.
/// </summary>
/// <param name="model"> The model to check for ignored type. </param>
/// <param name="typeName"> The name of the entity type that could be ignored. </param>
/// <returns> <c>true</c> if the given entity type name is ignored. </returns>
public static bool IsIgnored([NotNull] this IConventionModel model, [NotNull] string typeName)
=> model.FindIgnoredConfigurationSource(typeName) != null;
/// <summary>
/// Indicates whether the given entity type is ignored.
/// </summary>
/// <param name="model"> The model to check for ignored type. </param>
/// <param name="type"> The entity type that might be ignored. </param>
/// <returns> <c>true</c> if the given entity type is ignored. </returns>
public static bool IsIgnored([NotNull] this IConventionModel model, [NotNull] Type type)
=> Check.NotNull((Model)model, nameof(model)).IsIgnored(
Check.NotNull(type, nameof(type)));
/// <summary>
/// Indicates whether the given entity type is ignored.
/// </summary>
/// <param name="model"> The model to check for ignored type. </param>
/// <param name="type"> The entity type that might be ignored. </param>
/// <returns>
/// The configuration source if the given entity type is ignored,
/// <c>null</c> otherwise.
/// </returns>
public static ConfigurationSource? FindIgnoredConfigurationSource(
[NotNull] this IConventionModel model, [NotNull] Type type)
=> Check.NotNull((Model)model, nameof(model)).FindIgnoredConfigurationSource(
Check.NotNull(type, nameof(type)));
/// <summary>
/// Removes the given owned type, indicating that when discovered matching entity types
/// should not be configured as owned.
/// </summary>
/// <param name="model"> The model to remove the owned type name from. </param>
/// <param name="clrType"> The type of the entity type that should not be owned. </param>
public static void RemoveOwned([NotNull] this IConventionModel model, [NotNull] Type clrType)
=> Check.NotNull((Model)model, nameof(model)).RemoveOwned(
Check.NotNull(clrType, nameof(clrType)));
/// <summary>
/// Marks the given entity type as ignored.
/// </summary>
/// <param name="model"> The model to add the ignored type to. </param>
/// <param name="clrType"> The entity type to be ignored. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
public static void AddIgnored([NotNull] this IConventionModel model, [NotNull] Type clrType, bool fromDataAnnotation = false)
=> Check.NotNull((Model)model, nameof(model)).AddIgnored(
Check.NotNull(clrType, nameof(clrType)),
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
}
}
| 57.487365 | 136 | 0.636963 | [
"Apache-2.0"
] | garfbradaz/EntityFrameworkCore | src/EFCore/Extensions/ConventionModelExtensions.cs | 15,924 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using Locadora.Filmes.Dados.Entity.Context;
using Locadora.Filmes.Dominio;
using Locadora.Filmes.Repositorios.Comum;
using Locadora.Filmes.Repositorios.Entity;
using Locadora.Filmes.Web.Filtros;
using Locadora.Filmes.Web.ViewModels.Album;
namespace Locadora.Filmes.Web.Controllers
{
[Authorize]
[LogActionFilter]
public class AlbunsController : Controller
{
private IRepositorioGenerico<Album, int>
repositorioAlbuns = new AlbunsRepositorio(new FilmeDbContext());
// GET: Albuns
public ActionResult Index()
{
return View(Mapper.Map<List<Album>, List<AlbumIndexViewModel>>(repositorioAlbuns.Selecionar()));
}
public ActionResult FiltrarPorNome(string pesquisa)
{
List<Album> albuns = repositorioAlbuns
.Selecionar()
.Where(a => a.Nome.Contains(pesquisa)).ToList();
List<AlbumIndexViewModel> viewModels = Mapper
.Map<List<Album>, List<AlbumIndexViewModel>>(albuns);
return Json(viewModels, JsonRequestBehavior.AllowGet);
}
// GET: Albuns/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Album album = repositorioAlbuns.SelecionarPorId(id.Value);
if (album == null)
{
return HttpNotFound();
}
return View(Mapper.Map<Album, AlbumIndexViewModel>(album));
}
// GET: Albuns/Create
public ActionResult Create()
{
return View();
}
// POST: Albuns/Create
// Para proteger-se contra ataques de excesso de postagem, ative as propriedades específicas às quais deseja se associar.
// Para obter mais detalhes, confira https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Nome,Ano,Descricao,Autor,Email")] AlbumViewModel viewModel)
{
if (ModelState.IsValid)
{
Album album = Mapper.Map<AlbumViewModel, Album>(viewModel);
repositorioAlbuns.Inserir(album);
return RedirectToAction("Index");
}
return View(viewModel);
}
// GET: Albuns/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Album album = repositorioAlbuns.SelecionarPorId(id.Value);
if (album == null)
{
return HttpNotFound();
}
return View(Mapper.Map<Album, AlbumViewModel>(album));
}
// POST: Albuns/Edit/5
// Para proteger-se contra ataques de excesso de postagem, ative as propriedades específicas às quais deseja se associar.
// Para obter mais detalhes, confira https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Nome,Ano,Descricao,Autor,Email")] AlbumViewModel viewModel)
{
if (ModelState.IsValid)
{
Album album = Mapper.Map<AlbumViewModel, Album>(viewModel);
repositorioAlbuns.Alterar(album);
return RedirectToAction("Index");
}
return View(viewModel);
}
// GET: Albuns/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Album album = repositorioAlbuns.SelecionarPorId(id.Value);
if (album == null)
{
return HttpNotFound();
}
return View(Mapper.Map<Album, AlbumIndexViewModel>(album));
}
// POST: Albuns/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
repositorioAlbuns.ExcluirPorId(id);
return RedirectToAction("Index");
}
}
}
| 32.942029 | 130 | 0.587769 | [
"MIT"
] | m4sterin/Locadora-Filmes | Locadora.Filmes.Web/Controllers/AlbunsController.cs | 4,552 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
namespace SignalR.Samples.SimpleChat
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR()
.AddMessagePackProtocol();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseFileServer();
app.UseEndpoints(routes =>
{
routes.MapHub<DemoHub>("/demo");
});
}
}
}
| 33.2 | 123 | 0.604991 | [
"MIT"
] | radu-matei/dotnetcore-samples | simple-chat/Startup.cs | 1,164 | 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.MachineLearningServices.V20180301Preview.Outputs
{
[OutputType]
public sealed class DataFactoryResponse
{
/// <summary>
/// Location for the underlying compute
/// </summary>
public readonly string? ComputeLocation;
/// <summary>
/// The type of compute
/// Expected value is 'DataFactory'.
/// </summary>
public readonly string ComputeType;
/// <summary>
/// The date and time when the compute was created.
/// </summary>
public readonly string CreatedOn;
/// <summary>
/// The description of the Machine Learning compute.
/// </summary>
public readonly string? Description;
/// <summary>
/// The date and time when the compute was last modified.
/// </summary>
public readonly string ModifiedOn;
/// <summary>
/// Errors during provisioning
/// </summary>
public readonly ImmutableArray<Outputs.MachineLearningServiceErrorResponse> ProvisioningErrors;
/// <summary>
/// The provision state of the cluster. Valid values are Unknown, Updating, Provisioning, Succeeded, and Failed.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// ARM resource id of the compute
/// </summary>
public readonly string? ResourceId;
[OutputConstructor]
private DataFactoryResponse(
string? computeLocation,
string computeType,
string createdOn,
string? description,
string modifiedOn,
ImmutableArray<Outputs.MachineLearningServiceErrorResponse> provisioningErrors,
string provisioningState,
string? resourceId)
{
ComputeLocation = computeLocation;
ComputeType = computeType;
CreatedOn = createdOn;
Description = description;
ModifiedOn = modifiedOn;
ProvisioningErrors = provisioningErrors;
ProvisioningState = provisioningState;
ResourceId = resourceId;
}
}
}
| 31.746835 | 120 | 0.615231 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/MachineLearningServices/V20180301Preview/Outputs/DataFactoryResponse.cs | 2,508 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace TaskManager
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 25.909091 | 70 | 0.707018 | [
"MIT"
] | TclasenITVT/Modbus.Net | Samples/TaskManager/Global.asax.cs | 572 | C# |
// ***********************************************************************
// Assembly : ACBr.Net.Sat
// Author : RFTD
// Created : 04-29-2016
//
// Last Modified By : RFTD
// Last Modified On : 05-02-2016
// ***********************************************************************
// <copyright file="ImpostoCOFINSAliq.cs" company="ACBr.Net">
// The MIT License (MIT)
// Copyright (c) 2016 Grupo ACBr.Net
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.ComponentModel;
using ACBr.Net.Core.Generics;
using ACBr.Net.DFe.Core.Attributes;
using ACBr.Net.DFe.Core.Serializer;
using ACBr.Net.Sat.Interfaces;
namespace ACBr.Net.Sat
{
/// <summary>
/// Class ImpostoCOFINSAliq. This class cannot be inherited.
/// </summary>
/// <seealso cref="ACBr.Net.Sat.Interfaces.ICFeCofins" />
public sealed class ImpostoCofinsAliq : GenericClone<ImpostoCofinsAliq>, ICFeCofins
{
#region Events
public event PropertyChangedEventHandler PropertyChanged;
#endregion Events
#region Propriedades
/// <summary>
/// Gets or sets the Cst.
/// </summary>
/// <value>The Cst.</value>
[DFeElement(TipoCampo.Str, "CST", Id = "S07", Min = 2, Max = 2, Ocorrencia = Ocorrencia.Obrigatoria)]
public string Cst { get; set; }
/// <summary>
/// Gets or sets the v bc.
/// </summary>
/// <value>The v bc.</value>
[DFeElement(TipoCampo.De2, "vBC", Id = "S08", Min = 3, Max = 15, Ocorrencia = Ocorrencia.Obrigatoria)]
public decimal VBc { get; set; }
/// <summary>
/// Gets or sets the pcofins.
/// </summary>
/// <value>The pcofins.</value>
[DFeElement(TipoCampo.De4, "pCOFINS", Id = "S09", Min = 5, Max = 5, Ocorrencia = Ocorrencia.Obrigatoria)]
public decimal PCofins { get; set; }
/// <summary>
/// Gets or sets the vcofins.
/// </summary>
/// <value>The vcofins.</value>
[DFeElement(TipoCampo.De2, "vCOFINS", Id = "S10", Min = 1, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)]
public decimal VCofins { get; set; }
#endregion Propriedades
}
} | 40.25 | 115 | 0.605738 | [
"MIT"
] | ACBrNet/ACBr.Net.Sat | src/ACBr.Net.Sat/ImpostoCofinsAliq.cs | 3,381 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.