context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
#if (PLATFORM_X64)
extern alias HPMSdkx64;
using HPMSdkx64::HPMSdk;
#else
extern alias HPMSdkx86;
using HPMSdkx86::HPMSdk;
#endif
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.Messaging;
using HPMInt8 = System.SByte;
using HPMUInt8 = System.Byte;
using HPMInt16 = System.Int16;
using HPMUInt16 = System.UInt16;
using HPMInt32 = System.Int32;
using HPMUInt32 = System.UInt32;
using HPMInt64 = System.Int64;
using HPMUInt64 = System.UInt64;
using HPMError = System.Int32;
using HPMString = System.String;
namespace HansoftSDKSample_CustomSettings
{
class Program
{
HPMSdkSession m_Session;
HPMUInt64 m_NextUpdate;
HPMUInt64 m_NextConnectionAttempt;
CHPMSdkCallback m_Callback;
bool m_bBrokenConnection;
String m_CustomSettings;
const String m_IntegrationIdentifier = "se.hansoft.samplecustomsettings";
const String m_NewValue = "SDKItem1";
Program()
{
m_Session = null;
m_NextUpdate = 0;
m_NextConnectionAttempt = 0;
m_bBrokenConnection = false;
m_Callback = new CHPMSdkCallback();
m_Callback.m_Program = this;
}
~Program()
{
DestroyConnection();
}
class CHPMSdkCallback : HPMSdkCallbacks
{
public Program m_Program;
public override void On_ProcessError(EHPMError _Error)
{
Console.Write("On_ProcessError: " + HPMSdkSession.ErrorToStr(_Error) + "\r\n");
m_Program.m_bBrokenConnection = true;
}
}
HPMUInt64 GetTimeSince1970()
{
DateTime Now = DateTime.UtcNow;
DateTime t1970 = new DateTime(1970, 1, 1);
TimeSpan Span = Now - t1970;
return (HPMUInt64)(Span.Ticks / 10);
}
bool InitConnection()
{
if (m_Session != null)
return true;
HPMUInt64 CurrentTime = GetTimeSince1970();
if (CurrentTime > m_NextConnectionAttempt)
{
m_NextConnectionAttempt = 0;
EHPMSdkDebugMode DebugMode = EHPMSdkDebugMode.Off;
#if (DEBUG)
DebugMode = EHPMSdkDebugMode.Debug; // Set debug flag so we will get memory leak info.
#endif
try
{
// You should change these parameters to match your development server and the SDK account you have created. For more information see SDK documentation.
m_Session = HPMSdkSession.SessionOpen("localhost", 50256, "Company Projects", "SDK", "SDK", m_Callback, null, true, DebugMode, (IntPtr)0, 0, "", "", null);
}
catch (HPMSdkException _Error)
{
Console.WriteLine("SessionOpen failed with error:" + _Error.ErrorAsStr());
return false;
}
catch (HPMSdkManagedException _Error)
{
Console.WriteLine("SessionOpen failed with error:" + _Error.ErrorAsStr());
return false;
}
Console.WriteLine("Successfully opened session.\r\n");
m_Session.GlobalRegisterCustomSettings(m_IntegrationIdentifier, m_CustomSettings);
m_bBrokenConnection = false;
return true;
}
return false;
}
void DestroyConnection()
{
if (m_Session != null)
{
m_Session.GlobalUnregisterCustomSettings(m_IntegrationIdentifier);
HPMSdkSession.SessionDestroy(ref m_Session);
}
m_NextUpdate = 0; // Update when connection is restored
}
void Update()
{
if (InitConnection())
{
try
{
if (m_bBrokenConnection)
{
DestroyConnection();
}
else
{
// Check our stuff
HPMUInt64 CurrentTime = GetTimeSince1970();
if (CurrentTime > m_NextUpdate)
#if (DEBUG)
m_NextUpdate = CurrentTime + 10000000; // Check every 10 seconds
#else
m_NextUpdate = CurrentTime + 120000000; // Check every 120 seconds
#endif
// Get text field
HPMCustomSettingValue EditFieldValue = m_Session.GlobalGetCustomSettingsValue(EHPMCustomSettingsType.Admin, m_IntegrationIdentifier, "GlobalSettings1/TestTab1/Edit");
Console.WriteLine("Example edit field: " + EditFieldValue.m_Value);
// Get selected resources
HPMCustomSettingValue SelectedResourcesValue = m_Session.GlobalGetCustomSettingsValue(EHPMCustomSettingsType.Admin, m_IntegrationIdentifier, "GlobalSettings1/TestTab2/Subset0");
if (SelectedResourcesValue.m_Value.Length > 0)
{
char[] DelimitChars = { ' ' }; // This will not work for values with escaped space in them
String[] Values = SelectedResourcesValue.m_Value.Split(DelimitChars);
foreach (String Value in Values)
{
HPMCustomChoiceValue CustomValue = m_Session.UtilDecodeCustomChoiceValue(Value);
Console.WriteLine("Value " + Value + " has unique ID " + CustomValue.m_UniqueID);
HPMResourceProperties Properties = m_Session.ResourceGetProperties(CustomValue.m_UniqueID);
Console.WriteLine("Name: " + Properties.m_Name + ", Email: " + Properties.m_EmailAddress);
}
}
HPMCustomSettingValue AllChoiceValue = m_Session.GlobalGetCustomSettingsValue(EHPMCustomSettingsType.Admin, m_IntegrationIdentifier, "GlobalSettings1/TestTab3/Subset1/Choices");
Console.WriteLine("All choices in TestTab3: " + AllChoiceValue.m_Value);
// Add new value from SDK if it's not there
if (!AllChoiceValue.m_Value.Contains(m_NewValue))
{
String NewAllChoices = m_NewValue + " " + AllChoiceValue.m_Value;
AllChoiceValue.m_Value = NewAllChoices;
m_Session.GlobalSetCustomSettingsValue(EHPMCustomSettingsType.Admin, m_IntegrationIdentifier, "GlobalSettings1/TestTab3/Subset1/Choices", AllChoiceValue);
}
}
}
catch (HPMSdkException _Error)
{
Console.WriteLine("Exception in processing loop: " + _Error.ErrorAsStr());
}
catch (HPMSdkManagedException _Error)
{
Console.WriteLine("Exception in processing loop: " + _Error.ErrorAsStr());
}
}
}
void Run()
{
try
{
m_CustomSettings = System.IO.File.ReadAllText(@"CustomSettings.ir");
Thread.Sleep(100);
}
catch (Exception _Error)
{
Console.Error.WriteLine("Could not open custom settings file: " + _Error);
System.Environment.Exit(1);
}
// Initialize the SDK
while (!Console.KeyAvailable)
{
Update();
Thread.Sleep(1000);
}
DestroyConnection();
}
static void Main(string[] args)
{
Program MainProgram = new Program();
MainProgram.Run();
}
}
}
| |
///////////////////////////////////////////////////////////////////////////
// Description: Data Access class for the table 'RS_JenisPemeriksaan'
// Generated by LLBLGen v1.21.2003.712 Final on: Thursday, October 11, 2007, 2:03:11 AM
// Because the Base Class already implements IDispose, this class doesn't.
///////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace SIMRS.DataAccess
{
/// <summary>
/// Purpose: Data Access class for the table 'RS_JenisPemeriksaan'.
/// </summary>
public class RS_JenisPemeriksaan : DBInteractionBase
{
#region Class Member Declarations
private SqlBoolean _published;
private SqlDateTime _createdDate, _modifiedDate;
private SqlInt32 _createdBy, _modifiedBy, _ordering, _id;
private SqlString _kode, _nama, _keterangan;
#endregion
/// <summary>
/// Purpose: Class constructor.
/// </summary>
public RS_JenisPemeriksaan()
{
// Nothing for now.
}
/// <summary>
/// Purpose: IsExist method. This method will check Exsisting data from database.
/// </summary>
/// <returns></returns>
public bool IsExist()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPemeriksaan_IsExist]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPemeriksaan_IsExist' reported the ErrorCode: " + _errorCode);
}
return IsExist == 1;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPemeriksaan::IsExist::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Insert method. This method will insert one new row into the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Insert()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPemeriksaan_Insert]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPemeriksaan_Insert' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPemeriksaan::Insert::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method. This method will Update one existing row in the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Update()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPemeriksaan_Update]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPemeriksaan_Update' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPemeriksaan::Update::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Delete()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPemeriksaan_Delete]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPemeriksaan_Delete' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPemeriksaan::Delete::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy</LI>
/// <LI>ModifiedDate</LI>
/// </UL>
/// Will fill all properties corresponding with a field in the table with the value of the row selected.
/// </remarks>
public override DataTable SelectOne()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPemeriksaan_SelectOne]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisPemeriksaan");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPemeriksaan_SelectOne' reported the ErrorCode: " + _errorCode);
}
if (toReturn.Rows.Count > 0)
{
_id = (Int32)toReturn.Rows[0]["Id"];
_kode = (string)toReturn.Rows[0]["Kode"];
_nama = (string)toReturn.Rows[0]["Nama"];
_keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"];
_published = (bool)toReturn.Rows[0]["Published"];
_ordering = (Int32)toReturn.Rows[0]["Ordering"];
_createdBy = (Int32)toReturn.Rows[0]["CreatedBy"];
_createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"];
_modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"];
_modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"];
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPemeriksaan::SelectOne::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: SelectAll method. This method will Select all rows from the table.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override DataTable SelectAll()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPemeriksaan_SelectAll]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisPemeriksaan");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPemeriksaan_SelectAll' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPemeriksaan::SelectAll::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: GetList method. This method will Select all rows from the table where is active.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable GetList()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[RS_JenisPemeriksaan_GetList]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("RS_JenisPemeriksaan");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'RS_JenisPemeriksaan_GetList' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("RS_JenisPemeriksaan::GetList::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
#region Class Property Declarations
public SqlInt32 Id
{
get
{
return _id;
}
set
{
SqlInt32 idTmp = (SqlInt32)value;
if (idTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Id", "Id can't be NULL");
}
_id = value;
}
}
public SqlString Kode
{
get
{
return _kode;
}
set
{
SqlString kodeTmp = (SqlString)value;
if (kodeTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL");
}
_kode = value;
}
}
public SqlString Nama
{
get
{
return _nama;
}
set
{
SqlString namaTmp = (SqlString)value;
if (namaTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL");
}
_nama = value;
}
}
public SqlString Keterangan
{
get
{
return _keterangan;
}
set
{
_keterangan = value;
}
}
public SqlBoolean Published
{
get
{
return _published;
}
set
{
_published = value;
}
}
public SqlInt32 Ordering
{
get
{
return _ordering;
}
set
{
SqlInt32 orderingTmp = (SqlInt32)value;
if (orderingTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL");
}
_ordering = value;
}
}
public SqlInt32 CreatedBy
{
get
{
return _createdBy;
}
set
{
SqlInt32 createdByTmp = (SqlInt32)value;
if (createdByTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL");
}
_createdBy = value;
}
}
public SqlDateTime CreatedDate
{
get
{
return _createdDate;
}
set
{
SqlDateTime createdDateTmp = (SqlDateTime)value;
if (createdDateTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL");
}
_createdDate = value;
}
}
public SqlInt32 ModifiedBy
{
get
{
return _modifiedBy;
}
set
{
_modifiedBy = value;
}
}
public SqlDateTime ModifiedDate
{
get
{
return _modifiedDate;
}
set
{
_modifiedDate = value;
}
}
#endregion
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.DNSGlobalsBinding", Namespace="urn:iControl")]
public partial class LocalLBDNSGlobals : iControlInterface {
public LocalLBDNSGlobals() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// get_cache_edns_buffer_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long get_cache_edns_buffer_size(
) {
object [] results = this.Invoke("get_cache_edns_buffer_size", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginget_cache_edns_buffer_size(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cache_edns_buffer_size", new object[0], callback, asyncState);
}
public long Endget_cache_edns_buffer_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// get_cache_maximum_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long get_cache_maximum_ttl(
) {
object [] results = this.Invoke("get_cache_maximum_ttl", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginget_cache_maximum_ttl(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cache_maximum_ttl", new object[0], callback, asyncState);
}
public long Endget_cache_maximum_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// get_cache_minimum_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long get_cache_minimum_ttl(
) {
object [] results = this.Invoke("get_cache_minimum_ttl", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginget_cache_minimum_ttl(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cache_minimum_ttl", new object[0], callback, asyncState);
}
public long Endget_cache_minimum_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// get_collect_client_ips_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState get_collect_client_ips_state(
) {
object [] results = this.Invoke("get_collect_client_ips_state", new object [0]);
return ((CommonEnabledState)(results[0]));
}
public System.IAsyncResult Beginget_collect_client_ips_state(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_collect_client_ips_state", new object[0], callback, asyncState);
}
public CommonEnabledState Endget_collect_client_ips_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState)(results[0]));
}
//-----------------------------------------------------------------------
// get_collect_query_names_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState get_collect_query_names_state(
) {
object [] results = this.Invoke("get_collect_query_names_state", new object [0]);
return ((CommonEnabledState)(results[0]));
}
public System.IAsyncResult Beginget_collect_query_names_state(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_collect_query_names_state", new object[0], callback, asyncState);
}
public CommonEnabledState Endget_collect_query_names_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState)(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_cache_edns_buffer_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
public void set_cache_edns_buffer_size(
long value
) {
this.Invoke("set_cache_edns_buffer_size", new object [] {
value});
}
public System.IAsyncResult Beginset_cache_edns_buffer_size(long value, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cache_edns_buffer_size", new object[] {
value}, callback, asyncState);
}
public void Endset_cache_edns_buffer_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cache_maximum_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
public void set_cache_maximum_ttl(
long value
) {
this.Invoke("set_cache_maximum_ttl", new object [] {
value});
}
public System.IAsyncResult Beginset_cache_maximum_ttl(long value, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cache_maximum_ttl", new object[] {
value}, callback, asyncState);
}
public void Endset_cache_maximum_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cache_minimum_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
public void set_cache_minimum_ttl(
long value
) {
this.Invoke("set_cache_minimum_ttl", new object [] {
value});
}
public System.IAsyncResult Beginset_cache_minimum_ttl(long value, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cache_minimum_ttl", new object[] {
value}, callback, asyncState);
}
public void Endset_cache_minimum_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_collect_client_ips_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
public void set_collect_client_ips_state(
CommonEnabledState state
) {
this.Invoke("set_collect_client_ips_state", new object [] {
state});
}
public System.IAsyncResult Beginset_collect_client_ips_state(CommonEnabledState state, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_collect_client_ips_state", new object[] {
state}, callback, asyncState);
}
public void Endset_collect_client_ips_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_collect_query_names_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/DNSGlobals",
RequestNamespace="urn:iControl:LocalLB/DNSGlobals", ResponseNamespace="urn:iControl:LocalLB/DNSGlobals")]
public void set_collect_query_names_state(
CommonEnabledState state
) {
this.Invoke("set_collect_query_names_state", new object [] {
state});
}
public System.IAsyncResult Beginset_collect_query_names_state(CommonEnabledState state, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_collect_query_names_state", new object[] {
state}, callback, asyncState);
}
public void Endset_collect_query_names_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
//
// FlickrRemote.cs
//
// Author:
// Lorenzo Milesi <maxxer@yetopen.it>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008-2009 Lorenzo Milesi
// Copyright (C) 2008-2009 Stephane Delcroix
//
// 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.
//
/*
* Simple upload based on the api at
* http://www.flickr.com/services/api/upload.api.html
*
* Modified by acs in order to use Flickr.Net
*
* Modified in order to use the new Auth API
*
* We use now the search API also
*
*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using FlickrNet;
using FSpot;
using FSpot.Core;
using FSpot.Utils;
using FSpot.Filters;
using Hyena;
namespace FSpot.Exporters.Flickr {
public class FlickrRemote {
public static Licenses licenses;
private string frob;
private string token;
private Auth auth;
private FlickrNet.Flickr flickr;
public bool ExportTags;
public bool ExportTagHierarchy;
public bool ExportIgnoreTopLevel;
public FSpot.ProgressItem Progress;
public const string TOKEN_FLICKR = Preferences.APP_FSPOT_EXPORT_TOKENS + "flickr";
public const string TOKEN_23HQ = Preferences.APP_FSPOT_EXPORT_TOKENS + "23hq";
public const string TOKEN_ZOOOMR = Preferences.APP_FSPOT_EXPORT_TOKENS + "zooomr";
public FlickrRemote (string token, Service service)
{
if (token == null || token.Length == 0) {
this.flickr = new FlickrNet.Flickr (service.ApiKey, service.Secret);
this.token = null;
} else {
this.flickr = new FlickrNet.Flickr (service.ApiKey, service.Secret, token);
this.token = token;
}
this.flickr.CurrentService = service.Id;
}
public string Token {
get { return token; }
set {
token = value;
flickr.AuthToken = value;
}
}
public FlickrNet.Flickr Connection {
get { return flickr; }
}
public License[] GetLicenses ()
{
// Licenses won't change normally in a user session
if (licenses == null) {
try {
licenses = flickr.PhotosLicensesGetInfo();
} catch (FlickrNet.FlickrApiException e ) {
Log.Error (e.Code + ": " + e.Verbose );
return null;
}
}
return licenses.LicenseCollection;
}
public ArrayList Search (string[] tags, int licenseId)
{
ArrayList photos_url = new ArrayList ();
// Photos photos = flickr.PhotosSearchText (tags, licenseId);
Photos photos = flickr.PhotosSearch (tags);
if (photos != null) {
foreach (FlickrNet.Photo photo in photos.PhotoCollection) {
photos_url.Add (photo.ThumbnailUrl);
}
}
return photos_url;
}
public ArrayList Search (string tags, int licenseId)
{
ArrayList photos_url = new ArrayList ();
Photos photos = flickr.PhotosSearchText (tags, licenseId);
if (photos != null) {
foreach (FlickrNet.Photo photo in photos.PhotoCollection) {
photos_url.Add (photo.ThumbnailUrl);
}
}
return photos_url;
}
public Auth CheckLogin ()
{
try {
if (frob == null) {
frob = flickr.AuthGetFrob ();
if (frob == null) {
Log.Error ("ERROR: Problems login in Flickr. Don't have a frob");
return null;
}
}
} catch (Exception e) {
Log.Error ("Error logging in: {0}", e.Message);
}
if (token == null) {
try {
auth = flickr.AuthGetToken(frob);
token = auth.Token;
flickr.AuthToken = token;
return auth;
} catch (FlickrNet.FlickrApiException ex) {
Log.Error ("Problems logging in to Flickr - " + ex.Verbose);
return null;
}
}
auth = flickr.AuthCheckToken ("token");
return auth;
}
public string Upload (IPhoto photo, IFilter filter, bool is_public, bool is_family, bool is_friend)
{
if (token == null) {
throw new Exception ("Must Login First");
}
// FIXME flickr needs rotation
string error_verbose;
using (FilterRequest request = new FilterRequest (photo.DefaultVersion.Uri)) {
try {
string tags = null;
filter.Convert (request);
string path = request.Current.LocalPath;
if (ExportTags && photo.Tags != null) {
StringBuilder taglist = new StringBuilder ();
FSpot.Core.Tag [] t = photo.Tags;
FSpot.Core.Tag tag_iter = null;
for (int i = 0; i < t.Length; i++) {
if (i > 0)
taglist.Append (",");
taglist.Append (String.Format ("\"{0}\"", t[i].Name));
// Go through the tag parents
if (ExportTagHierarchy) {
tag_iter = t[i].Category;
while (tag_iter != App.Instance.Database.Tags.RootCategory && tag_iter != null) {
// Skip top level tags because they have no meaning in a linear tag database
if (ExportIgnoreTopLevel && tag_iter.Category == App.Instance.Database.Tags.RootCategory) {
break;
}
// FIXME Look if the tag is already there!
taglist.Append (",");
taglist.Append (String.Format ("\"{0}\"", tag_iter.Name));
tag_iter = tag_iter.Category;
}
}
}
tags = taglist.ToString ();
}
try {
string photoid =
flickr.UploadPicture (path, photo.Name, photo.Description, tags, is_public, is_family, is_friend);
return photoid;
} catch (FlickrNet.FlickrException ex) {
Log.Error ("Problems uploading picture: " + ex.ToString());
error_verbose = ex.ToString();
}
} catch (Exception e) {
// FIXME we need to distinguish between file IO errors and xml errors here
throw new System.Exception ("Error while uploading", e);
}
}
throw new System.Exception (error_verbose);
}
public void TryWebLogin () {
frob = flickr.AuthGetFrob ();
string login_url = flickr.AuthCalcUrl (frob, FlickrNet.AuthLevel.Write);
GtkBeans.Global.ShowUri (null, login_url);
}
public class Service {
public string ApiKey;
public string Secret;
public SupportedService Id;
public string Name;
public string PreferencePath;
public static Service [] Supported = {
new Service (SupportedService.Flickr, "Flickr.com", "c6b39ee183385d9ce4ea188f85945016", "0a951ac44a423a04", TOKEN_FLICKR),
new Service (SupportedService.TwentyThreeHQ, "23hq.com", "c6b39ee183385d9ce4ea188f85945016", "0a951ac44a423a04", TOKEN_23HQ),
new Service (SupportedService.Zooomr, "Zooomr.com", "a2075d8ff1b7b059df761649835562e4", "6c66738681", TOKEN_ZOOOMR)
};
public Service (SupportedService id, string name, string api_key, string secret, string pref)
{
Id = id;
ApiKey = api_key;
Secret = secret;
Name = name;
PreferencePath = pref;
}
public static Service FromSupported (SupportedService id)
{
foreach (Service s in Supported) {
if (s.Id == id)
return s;
}
throw new System.ArgumentException ("Unknown service type");
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Versions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interactive;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Packaging;
using Microsoft.VisualStudio.LanguageServices.SymbolSearch;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Setup
{
[Guid(Guids.RoslynPackageIdString)]
[PackageRegistration(UseManagedResourcesOnly = true)]
[ProvideMenuResource("Menus.ctmenu", version: 13)]
internal class RoslynPackage : AbstractPackage
{
private LibraryManager _libraryManager;
private uint _libraryManagerCookie;
private VisualStudioWorkspace _workspace;
private WorkspaceFailureOutputPane _outputPane;
private IComponentModel _componentModel;
private RuleSetEventHandler _ruleSetEventHandler;
private IDisposable _solutionEventMonitor;
protected override void Initialize()
{
base.Initialize();
FatalError.Handler = FailFast.OnFatalException;
FatalError.NonFatalHandler = WatsonReporter.Report;
// We also must set the FailFast handler for the compiler layer as well
var compilerAssembly = typeof(Compilation).Assembly;
var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true);
var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public);
var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true);
var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic);
property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method));
InitializePortableShim(compilerAssembly);
RegisterFindResultsLibraryManager();
var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel));
_workspace = componentModel.GetService<VisualStudioWorkspace>();
var telemetrySetupExtensions = componentModel.GetExtensions<IRoslynTelemetrySetup>();
foreach (var telemetrySetup in telemetrySetupExtensions)
{
telemetrySetup.Initialize(this);
}
// set workspace output pane
_outputPane = new WorkspaceFailureOutputPane(this, _workspace);
InitializeColors();
// load some services that have to be loaded in UI thread
LoadComponentsInUIContextOnceSolutionFullyLoaded();
_solutionEventMonitor = new SolutionEventMonitor(_workspace);
}
private static void InitializePortableShim(Assembly compilerAssembly)
{
// We eagerly force all of the types to be loaded within the PortableShim because there are scenarios
// in which loading types can trigger the current AppDomain's AssemblyResolve or TypeResolve events.
// If handlers of those events do anything that would cause PortableShim to be accessed recursively,
// bad things can happen. In particular, this fixes the scenario described in TFS bug #1185842.
//
// Note that the fix below is written to be as defensive as possible to do no harm if it impacts other
// scenarios.
// Initialize the PortableShim linked into the Workspaces layer.
Roslyn.Utilities.PortableShim.Initialize();
// Initialize the PortableShim linked into the Compilers layer via reflection.
var compilerPortableShim = compilerAssembly.GetType("Roslyn.Utilities.PortableShim", throwOnError: false);
var initializeMethod = compilerPortableShim?.GetMethod(nameof(Roslyn.Utilities.PortableShim.Initialize), BindingFlags.Static | BindingFlags.NonPublic);
initializeMethod?.Invoke(null, null);
}
private void InitializeColors()
{
// Use VS color keys in order to support theming.
CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey;
CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey;
CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey;
CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey;
CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey;
CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey;
}
protected override void LoadComponentsInUIContext()
{
// we need to load it as early as possible since we can have errors from
// package from each language very early
this.ComponentModel.GetService<VisualStudioDiagnosticListTable>();
this.ComponentModel.GetService<VisualStudioTodoListTable>();
this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this);
this.ComponentModel.GetService<HACK_ThemeColorFixer>();
this.ComponentModel.GetExtensions<IReferencedSymbolsPresenter>();
this.ComponentModel.GetExtensions<INavigableItemsPresenter>();
this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>();
this.ComponentModel.GetService<VirtualMemoryNotificationListener>();
// The misc files workspace needs to be loaded on the UI thread. This way it will have
// the appropriate task scheduler to report events on.
this.ComponentModel.GetService<MiscellaneousFilesWorkspace>();
LoadAnalyzerNodeComponents();
Task.Run(() => LoadComponentsBackground());
}
private void LoadComponentsBackground()
{
// Perf: Initialize the command handlers.
var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>();
commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType);
LoadInteractiveMenus();
this.ComponentModel.GetService<MiscellaneousTodoListTable>();
this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>();
}
private void LoadInteractiveMenus()
{
var menuCommandService = (OleMenuCommandService)GetService(typeof(IMenuCommandService));
var monitorSelectionService = (IVsMonitorSelection)this.GetService(typeof(SVsShellMonitorSelection));
new CSharpResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel)
.InitializeResetInteractiveFromProjectCommand();
new VisualBasicResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel)
.InitializeResetInteractiveFromProjectCommand();
}
internal IComponentModel ComponentModel
{
get
{
if (_componentModel == null)
{
_componentModel = (IComponentModel)GetService(typeof(SComponentModel));
}
return _componentModel;
}
}
protected override void Dispose(bool disposing)
{
UnregisterFindResultsLibraryManager();
DisposeVisualStudioDocumentTrackingService();
UnregisterAnalyzerTracker();
UnregisterRuleSetEventHandler();
ReportSessionWideTelemetry();
if (_solutionEventMonitor != null)
{
_solutionEventMonitor.Dispose();
_solutionEventMonitor = null;
}
base.Dispose(disposing);
}
private void ReportSessionWideTelemetry()
{
PersistedVersionStampLogger.LogSummary();
LinkedFileDiffMergingLogger.ReportTelemetry();
}
private void RegisterFindResultsLibraryManager()
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
_libraryManager = new LibraryManager(this);
if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie)))
{
_libraryManagerCookie = 0;
}
((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true);
}
}
private void UnregisterFindResultsLibraryManager()
{
if (_libraryManagerCookie != 0)
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
objectManager.UnregisterLibrary(_libraryManagerCookie);
_libraryManagerCookie = 0;
}
((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true);
_libraryManager = null;
}
}
private void DisposeVisualStudioDocumentTrackingService()
{
if (_workspace != null)
{
var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService;
documentTrackingService.Dispose();
}
}
private void LoadAnalyzerNodeComponents()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this);
_ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>();
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Register();
}
}
private void UnregisterAnalyzerTracker()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister();
}
private void UnregisterRuleSetEventHandler()
{
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Unregister();
_ruleSetEventHandler = null;
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SouthwindRepository
{
/// <summary>
/// Strongly-typed collection for the OrderDetail class.
/// </summary>
[Serializable]
public partial class OrderDetailCollection : RepositoryList<OrderDetail, OrderDetailCollection>
{
public OrderDetailCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>OrderDetailCollection</returns>
public OrderDetailCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
OrderDetail o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the order details table.
/// </summary>
[Serializable]
public partial class OrderDetail : RepositoryRecord<OrderDetail>, IRecordBase
{
#region .ctors and Default Settings
public OrderDetail()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public OrderDetail(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("order details", TableType.Table, DataService.GetInstance("SouthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 10;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = true;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
colvarOrderID.DefaultSetting = @"";
colvarOrderID.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 10;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = true;
colvarProductID.IsForeignKey = false;
colvarProductID.IsReadOnly = false;
colvarProductID.DefaultSetting = @"";
colvarProductID.ForeignKeyTableName = "";
schema.Columns.Add(colvarProductID);
TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema);
colvarUnitPrice.ColumnName = "UnitPrice";
colvarUnitPrice.DataType = DbType.Decimal;
colvarUnitPrice.MaxLength = 0;
colvarUnitPrice.AutoIncrement = false;
colvarUnitPrice.IsNullable = false;
colvarUnitPrice.IsPrimaryKey = false;
colvarUnitPrice.IsForeignKey = false;
colvarUnitPrice.IsReadOnly = false;
colvarUnitPrice.DefaultSetting = @"";
colvarUnitPrice.ForeignKeyTableName = "";
schema.Columns.Add(colvarUnitPrice);
TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema);
colvarQuantity.ColumnName = "Quantity";
colvarQuantity.DataType = DbType.Int16;
colvarQuantity.MaxLength = 5;
colvarQuantity.AutoIncrement = false;
colvarQuantity.IsNullable = false;
colvarQuantity.IsPrimaryKey = false;
colvarQuantity.IsForeignKey = false;
colvarQuantity.IsReadOnly = false;
colvarQuantity.DefaultSetting = @"";
colvarQuantity.ForeignKeyTableName = "";
schema.Columns.Add(colvarQuantity);
TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema);
colvarDiscount.ColumnName = "Discount";
colvarDiscount.DataType = DbType.Decimal;
colvarDiscount.MaxLength = 0;
colvarDiscount.AutoIncrement = false;
colvarDiscount.IsNullable = false;
colvarDiscount.IsPrimaryKey = false;
colvarDiscount.IsForeignKey = false;
colvarDiscount.IsReadOnly = false;
colvarDiscount.DefaultSetting = @"";
colvarDiscount.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiscount);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["SouthwindRepository"].AddSchema("order details",schema);
}
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get { return GetColumnValue<int>(Columns.OrderID); }
set { SetColumnValue(Columns.OrderID, value); }
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get { return GetColumnValue<int>(Columns.ProductID); }
set { SetColumnValue(Columns.ProductID, value); }
}
[XmlAttribute("UnitPrice")]
[Bindable(true)]
public decimal UnitPrice
{
get { return GetColumnValue<decimal>(Columns.UnitPrice); }
set { SetColumnValue(Columns.UnitPrice, value); }
}
[XmlAttribute("Quantity")]
[Bindable(true)]
public short Quantity
{
get { return GetColumnValue<short>(Columns.Quantity); }
set { SetColumnValue(Columns.Quantity, value); }
}
[XmlAttribute("Discount")]
[Bindable(true)]
public decimal Discount
{
get { return GetColumnValue<decimal>(Columns.Discount); }
set { SetColumnValue(Columns.Discount, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region Typed Columns
public static TableSchema.TableColumn OrderIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn ProductIDColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn UnitPriceColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn QuantityColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn DiscountColumn
{
get { return Schema.Columns[4]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string ProductID = @"ProductID";
public static string UnitPrice = @"UnitPrice";
public static string Quantity = @"Quantity";
public static string Discount = @"Discount";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsCommon.Set, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssStorageProfile", SupportsShouldProcess = true)]
[OutputType(typeof(PSVirtualMachineScaleSet))]
public partial class SetAzureRmVmssStorageProfileCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
public PSVirtualMachineScaleSet VirtualMachineScaleSet { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public string ImageReferencePublisher { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public string ImageReferenceOffer { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public string ImageReferenceSku { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string ImageReferenceVersion { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
[Alias("Name")]
public string OsDiskName { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public CachingTypes? OsDiskCaching { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public string OsDiskCreateOption { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public OperatingSystemTypes? OsDiskOsType { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public string Image { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public string[] VhdContainer { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ImageReferenceId { get; set; }
[Parameter(
Mandatory = false)]
public SwitchParameter OsDiskWriteAccelerator { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string DiffDiskSetting { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
[PSArgumentCompleter("Standard_LRS", "Premium_LRS", "StandardSSD_LRS", "UltraSSD_LRS")]
public string ManagedDisk { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetDataDisk[] DataDisk { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("VirtualMachineScaleSet", "Set"))
{
Run();
}
}
private void Run()
{
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferencePublisher"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Publisher = this.ImageReferencePublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceOffer"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Offer = this.ImageReferenceOffer;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceSku"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Sku = this.ImageReferenceSku;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceVersion"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Version = this.ImageReferenceVersion;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ImageReferenceId"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Id = this.ImageReferenceId;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskName"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Name = this.OsDiskName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskCaching"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching = this.OsDiskCaching;
}
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.WriteAcceleratorEnabled = this.OsDiskWriteAccelerator.IsPresent;
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskCreateOption"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.CreateOption = this.OsDiskCreateOption;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DiffDiskSetting"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
// DiffDiskSettings
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.DiffDiskSettings == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.DiffDiskSettings = new DiffDiskSettings();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.DiffDiskSettings.Option = this.DiffDiskSetting;
}
if (this.MyInvocation.BoundParameters.ContainsKey("OsDiskOsType"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.OsType = this.OsDiskOsType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Image"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
// Image
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image = new VirtualHardDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri = this.Image;
}
if (this.MyInvocation.BoundParameters.ContainsKey("VhdContainer"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers = this.VhdContainer;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ManagedDisk"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new VirtualMachineScaleSetOSDisk();
}
// ManagedDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk = new VirtualMachineScaleSetManagedDiskParameters();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.StorageAccountType = this.ManagedDisk;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DataDisk"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new VirtualMachineScaleSetStorageProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.DataDisks = this.DataDisk;
}
WriteObject(this.VirtualMachineScaleSet);
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;
using System.Linq;
namespace UIWidgets
{
/// <summary>
/// ListViewGameObjects event.
/// </summary>
[System.Serializable]
public class ListViewGameObjectsEvent : UnityEvent<int,GameObject>
{
}
/// <summary>
/// List view with GameObjects.
/// Outdated. Replaced with ListViewCustom. It's provide better interface and usability.
/// </summary>
public class ListViewGameObjects : ListViewBase {
[SerializeField]
List<GameObject> objects = new List<GameObject>();
/// <summary>
/// Gets the objects.
/// </summary>
/// <value>The objects.</value>
public List<GameObject> Objects {
get {
return new List<GameObject>(objects);
}
private set {
UpdateItems(value);
}
}
List<UnityAction<PointerEventData>> callbacksEnter = new List<UnityAction<PointerEventData>>();
List<UnityAction<PointerEventData>> callbacksExit = new List<UnityAction<PointerEventData>>();
/// <summary>
/// Sort function.
/// </summary>
public Func<IEnumerable<GameObject>,IEnumerable<GameObject>> SortFunc = null;
/// <summary>
/// What to do when the object selected.
/// </summary>
public ListViewGameObjectsEvent OnSelectObject = new ListViewGameObjectsEvent();
/// <summary>
/// What to do when the object deselected.
/// </summary>
public ListViewGameObjectsEvent OnDeselectObject = new ListViewGameObjectsEvent();
/// <summary>
/// What to do when the event system send a pointer enter Event.
/// </summary>
public ListViewGameObjectsEvent OnPointerEnterObject = new ListViewGameObjectsEvent();
/// <summary>
/// What to do when the event system send a pointer exit Event.
/// </summary>
public ListViewGameObjectsEvent OnPointerExitObject = new ListViewGameObjectsEvent();
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
Start();
}
[System.NonSerialized]
bool isStartedListViewGameObjects = false;
/// <summary>
/// Start this instance.
/// </summary>
public override void Start()
{
if (isStartedListViewGameObjects)
{
return ;
}
isStartedListViewGameObjects = true;
base.Start();
DestroyGameObjects = true;
UpdateItems();
OnSelect.AddListener(OnSelectCallback);
OnDeselect.AddListener(OnDeselectCallback);
}
/// <summary>
/// Raises the select callback event.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="item">Item.</param>
void OnSelectCallback(int index, ListViewItem item)
{
OnSelectObject.Invoke(index, objects[index]);
}
/// <summary>
/// Raises the deselect callback event.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="item">Item.</param>
void OnDeselectCallback(int index, ListViewItem item)
{
OnDeselectObject.Invoke(index, objects[index]);
}
/// <summary>
/// Raises the pointer enter callback event.
/// </summary>
/// <param name="index">Index.</param>
void OnPointerEnterCallback(int index)
{
OnPointerEnterObject.Invoke(index, objects[index]);
}
/// <summary>
/// Raises the pointer exit callback event.
/// </summary>
/// <param name="index">Index.</param>
void OnPointerExitCallback(int index)
{
OnPointerExitObject.Invoke(index, objects[index]);
}
/// <summary>
/// Updates the items.
/// </summary>
public override void UpdateItems()
{
UpdateItems(objects);
}
/// <summary>
/// Add the specified item.
/// </summary>
/// <param name="item">Item.</param>
/// <returns>Index of added item.</returns>
public virtual int Add(GameObject item)
{
var newObjects = Objects;
newObjects.Add(item);
UpdateItems(newObjects);
var index = objects.IndexOf(item);
return index;
}
/// <summary>
/// Remove the specified item.
/// </summary>
/// <param name="item">Item.</param>
/// <returns>Index of removed item.</returns>
public virtual int Remove(GameObject item)
{
var index = objects.IndexOf(item);
if (index==-1)
{
return index;
}
var newObjects = Objects;
newObjects.Remove(item);
UpdateItems(newObjects);
return index;
}
void RemoveCallback(ListViewItem item, int index)
{
if (item==null)
{
return ;
}
if (index < callbacksEnter.Count)
{
item.onPointerEnter.RemoveListener(callbacksEnter[index]);
}
if (index < callbacksExit.Count)
{
item.onPointerExit.RemoveListener(callbacksExit[index]);
}
}
/// <summary>
/// Removes the callbacks.
/// </summary>
void RemoveCallbacks()
{
base.Items.ForEach(RemoveCallback);
callbacksEnter.Clear();
callbacksExit.Clear();
}
/// <summary>
/// Adds the callbacks.
/// </summary>
void AddCallbacks()
{
base.Items.ForEach(AddCallback);
}
/// <summary>
/// Adds the callback.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="index">Index.</param>
void AddCallback(ListViewItem item, int index)
{
callbacksEnter.Add(ev => OnPointerEnterCallback(index));
callbacksExit.Add(ev => OnPointerExitCallback(index));
item.onPointerEnter.AddListener(callbacksEnter[index]);
item.onPointerExit.AddListener(callbacksExit[index]);
}
/// <summary>
/// Sorts the items.
/// </summary>
/// <returns>The items.</returns>
/// <param name="newItems">New items.</param>
List<GameObject> SortItems(IEnumerable<GameObject> newItems)
{
var temp = newItems;
if (SortFunc!=null)
{
temp = SortFunc(temp);
}
return temp.ToList();
}
/// <summary>
/// Clear items of this instance.
/// </summary>
public override void Clear()
{
if (DestroyGameObjects)
{
objects.ForEach(Destroy);
}
UpdateItems(new List<GameObject>());
}
/// <summary>
/// Updates the items.
/// </summary>
/// <param name="newItems">New items.</param>
void UpdateItems(List<GameObject> newItems)
{
RemoveCallbacks();
newItems = SortItems(newItems);
var new_selected_indicies = SelectedIndicies
.Select(x => objects.Count > x ? newItems.IndexOf(objects[x]) : -1)
.Where(x => x!=-1).ToList();
SelectedIndicies.Except(new_selected_indicies).ForEach(Deselect);
objects = newItems;
base.Items = newItems.Convert(x => x.GetComponent<ListViewItem>() ?? x.AddComponent<ListViewItem>());
SelectedIndicies = new_selected_indicies;
AddCallbacks();
}
/// <summary>
/// This function is called when the MonoBehaviour will be destroyed.
/// </summary>
protected override void OnDestroy()
{
OnSelect.RemoveListener(OnSelectCallback);
OnDeselect.RemoveListener(OnDeselectCallback);
RemoveCallbacks();
base.OnDestroy();
}
}
}
| |
namespace Cyotek.Demo.Windows.Forms
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.generateCodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.openToolStripButton = new System.Windows.Forms.ToolStripButton();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.statusToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.cyotekLinkToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.rootSplitContainer = new System.Windows.Forms.SplitContainer();
this.filePane = new Cyotek.Demo.Windows.Forms.FilePane();
this.tabControl = new System.Windows.Forms.TabControl();
this.previewTabPage = new System.Windows.Forms.TabPage();
this.textSplitContainer = new System.Windows.Forms.SplitContainer();
this.previewTextBox = new System.Windows.Forms.TextBox();
this.previewImageBox = new Cyotek.Windows.Forms.ImageBox();
this.fontTabPage = new System.Windows.Forms.TabPage();
this.fontPropertyGrid = new Cyotek.Demo.BitmapFontViewer.PropertyGrid();
this.texturePagesTabPage = new System.Windows.Forms.TabPage();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.texturePagesListBox = new System.Windows.Forms.ListBox();
this.texturePageImageBox = new Cyotek.Windows.Forms.ImageBox();
this.charactersTabPage = new System.Windows.Forms.TabPage();
this.imageSplitContainer = new System.Windows.Forms.SplitContainer();
this.charactersSplitContainer = new System.Windows.Forms.SplitContainer();
this.charListBox = new System.Windows.Forms.ListBox();
this.characterSplitContainer = new System.Windows.Forms.SplitContainer();
this.characterImageBox = new Cyotek.Windows.Forms.ImageBox();
this.characterPropertyGrid = new Cyotek.Demo.BitmapFontViewer.PropertyGrid();
this.pageImageBox = new Cyotek.Windows.Forms.ImageBox();
this.kerningsTabPage = new System.Windows.Forms.TabPage();
this.kerningsListBox = new System.Windows.Forms.ListBox();
this.menuStrip.SuspendLayout();
this.toolStrip.SuspendLayout();
this.statusStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rootSplitContainer)).BeginInit();
this.rootSplitContainer.Panel1.SuspendLayout();
this.rootSplitContainer.Panel2.SuspendLayout();
this.rootSplitContainer.SuspendLayout();
this.tabControl.SuspendLayout();
this.previewTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.textSplitContainer)).BeginInit();
this.textSplitContainer.Panel1.SuspendLayout();
this.textSplitContainer.Panel2.SuspendLayout();
this.textSplitContainer.SuspendLayout();
this.fontTabPage.SuspendLayout();
this.texturePagesTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.charactersTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.imageSplitContainer)).BeginInit();
this.imageSplitContainer.Panel1.SuspendLayout();
this.imageSplitContainer.Panel2.SuspendLayout();
this.imageSplitContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.charactersSplitContainer)).BeginInit();
this.charactersSplitContainer.Panel1.SuspendLayout();
this.charactersSplitContainer.Panel2.SuspendLayout();
this.charactersSplitContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.characterSplitContainer)).BeginInit();
this.characterSplitContainer.Panel1.SuspendLayout();
this.characterSplitContainer.Panel2.SuspendLayout();
this.characterSplitContainer.SuspendLayout();
this.kerningsTabPage.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(826, 24);
this.menuStrip.TabIndex = 0;
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.toolStripSeparator,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = global::Cyotek.Demo.BitmapFontViewer.Properties.Resources.Open;
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.openToolStripMenuItem.Text = "&Open";
this.openToolStripMenuItem.Click += new System.EventHandler(this.OpenToolStripMenuItem_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(143, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4)));
this.exitToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.generateCodeToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(46, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// generateCodeToolStripMenuItem
//
this.generateCodeToolStripMenuItem.Name = "generateCodeToolStripMenuItem";
this.generateCodeToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.generateCodeToolStripMenuItem.Text = "&Generate Code";
this.generateCodeToolStripMenuItem.Click += new System.EventHandler(this.GenerateCodeToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.AboutToolStripMenuItem_Click);
//
// toolStrip
//
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripButton});
this.toolStrip.Location = new System.Drawing.Point(0, 24);
this.toolStrip.Name = "toolStrip";
this.toolStrip.Size = new System.Drawing.Size(826, 25);
this.toolStrip.TabIndex = 1;
//
// openToolStripButton
//
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Image = global::Cyotek.Demo.BitmapFontViewer.Properties.Resources.Open;
this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Size = new System.Drawing.Size(23, 22);
this.openToolStripButton.Text = "&Open";
this.openToolStripButton.Click += new System.EventHandler(this.OpenToolStripMenuItem_Click);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusToolStripStatusLabel,
this.cyotekLinkToolStripStatusLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 498);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(826, 22);
this.statusStrip.TabIndex = 3;
//
// statusToolStripStatusLabel
//
this.statusToolStripStatusLabel.Name = "statusToolStripStatusLabel";
this.statusToolStripStatusLabel.Size = new System.Drawing.Size(712, 17);
this.statusToolStripStatusLabel.Spring = true;
this.statusToolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// cyotekLinkToolStripStatusLabel
//
this.cyotekLinkToolStripStatusLabel.IsLink = true;
this.cyotekLinkToolStripStatusLabel.Name = "cyotekLinkToolStripStatusLabel";
this.cyotekLinkToolStripStatusLabel.Size = new System.Drawing.Size(99, 17);
this.cyotekLinkToolStripStatusLabel.Text = "www.cyotek.com";
this.cyotekLinkToolStripStatusLabel.Click += new System.EventHandler(this.CyotekLinkToolStripStatusLabel_Click);
//
// rootSplitContainer
//
this.rootSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.rootSplitContainer.Location = new System.Drawing.Point(0, 49);
this.rootSplitContainer.Name = "rootSplitContainer";
//
// rootSplitContainer.Panel1
//
this.rootSplitContainer.Panel1.Controls.Add(this.filePane);
//
// rootSplitContainer.Panel2
//
this.rootSplitContainer.Panel2.Controls.Add(this.tabControl);
this.rootSplitContainer.Size = new System.Drawing.Size(826, 449);
this.rootSplitContainer.SplitterDistance = 275;
this.rootSplitContainer.TabIndex = 2;
//
// filePane
//
this.filePane.Dock = System.Windows.Forms.DockStyle.Fill;
this.filePane.Location = new System.Drawing.Point(0, 0);
this.filePane.Name = "filePane";
this.filePane.SearchPattern = "*.fnt";
this.filePane.Size = new System.Drawing.Size(275, 449);
this.filePane.TabIndex = 0;
this.filePane.SelectedFileChanged += new System.EventHandler(this.FilePane_SelectedFileChanged);
//
// tabControl
//
this.tabControl.Controls.Add(this.previewTabPage);
this.tabControl.Controls.Add(this.fontTabPage);
this.tabControl.Controls.Add(this.texturePagesTabPage);
this.tabControl.Controls.Add(this.charactersTabPage);
this.tabControl.Controls.Add(this.kerningsTabPage);
this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(547, 449);
this.tabControl.TabIndex = 0;
//
// previewTabPage
//
this.previewTabPage.Controls.Add(this.textSplitContainer);
this.previewTabPage.Location = new System.Drawing.Point(4, 22);
this.previewTabPage.Name = "previewTabPage";
this.previewTabPage.Padding = new System.Windows.Forms.Padding(3);
this.previewTabPage.Size = new System.Drawing.Size(539, 423);
this.previewTabPage.TabIndex = 4;
this.previewTabPage.Text = "Preview";
this.previewTabPage.UseVisualStyleBackColor = true;
//
// textSplitContainer
//
this.textSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.textSplitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.textSplitContainer.Location = new System.Drawing.Point(3, 3);
this.textSplitContainer.Name = "textSplitContainer";
this.textSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// textSplitContainer.Panel1
//
this.textSplitContainer.Panel1.Controls.Add(this.previewTextBox);
//
// textSplitContainer.Panel2
//
this.textSplitContainer.Panel2.Controls.Add(this.previewImageBox);
this.textSplitContainer.Size = new System.Drawing.Size(533, 417);
this.textSplitContainer.SplitterDistance = 100;
this.textSplitContainer.TabIndex = 2;
//
// previewTextBox
//
this.previewTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.previewTextBox.Location = new System.Drawing.Point(0, 0);
this.previewTextBox.Multiline = true;
this.previewTextBox.Name = "previewTextBox";
this.previewTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.previewTextBox.Size = new System.Drawing.Size(533, 100);
this.previewTextBox.TabIndex = 0;
this.previewTextBox.TextChanged += new System.EventHandler(this.PreviewTextBox_TextChanged);
//
// previewImageBox
//
this.previewImageBox.BackColor = System.Drawing.SystemColors.Window;
this.previewImageBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.previewImageBox.ForeColor = System.Drawing.SystemColors.WindowText;
this.previewImageBox.GridDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.None;
this.previewImageBox.Location = new System.Drawing.Point(0, 0);
this.previewImageBox.Name = "previewImageBox";
this.previewImageBox.Size = new System.Drawing.Size(533, 313);
this.previewImageBox.TabIndex = 0;
//
// fontTabPage
//
this.fontTabPage.Controls.Add(this.fontPropertyGrid);
this.fontTabPage.Location = new System.Drawing.Point(4, 22);
this.fontTabPage.Name = "fontTabPage";
this.fontTabPage.Padding = new System.Windows.Forms.Padding(3);
this.fontTabPage.Size = new System.Drawing.Size(539, 423);
this.fontTabPage.TabIndex = 1;
this.fontTabPage.Text = "Font";
this.fontTabPage.UseVisualStyleBackColor = true;
//
// fontPropertyGrid
//
this.fontPropertyGrid.CommandsVisibleIfAvailable = false;
this.fontPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.fontPropertyGrid.HelpVisible = false;
this.fontPropertyGrid.Location = new System.Drawing.Point(3, 3);
this.fontPropertyGrid.Name = "fontPropertyGrid";
this.fontPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.Alphabetical;
this.fontPropertyGrid.ReadOnly = true;
this.fontPropertyGrid.Size = new System.Drawing.Size(533, 417);
this.fontPropertyGrid.TabIndex = 0;
this.fontPropertyGrid.ToolbarVisible = false;
//
// texturePagesTabPage
//
this.texturePagesTabPage.Controls.Add(this.splitContainer1);
this.texturePagesTabPage.Location = new System.Drawing.Point(4, 22);
this.texturePagesTabPage.Name = "texturePagesTabPage";
this.texturePagesTabPage.Padding = new System.Windows.Forms.Padding(3);
this.texturePagesTabPage.Size = new System.Drawing.Size(539, 423);
this.texturePagesTabPage.TabIndex = 2;
this.texturePagesTabPage.Text = "Texture Pages";
this.texturePagesTabPage.UseVisualStyleBackColor = true;
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(3, 3);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.texturePagesListBox);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.texturePageImageBox);
this.splitContainer1.Size = new System.Drawing.Size(533, 417);
this.splitContainer1.SplitterDistance = 263;
this.splitContainer1.TabIndex = 1;
//
// texturePagesListBox
//
this.texturePagesListBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.texturePagesListBox.FormattingEnabled = true;
this.texturePagesListBox.IntegralHeight = false;
this.texturePagesListBox.Location = new System.Drawing.Point(0, 0);
this.texturePagesListBox.Name = "texturePagesListBox";
this.texturePagesListBox.Size = new System.Drawing.Size(263, 417);
this.texturePagesListBox.TabIndex = 0;
this.texturePagesListBox.SelectedIndexChanged += new System.EventHandler(this.TexturePagesListBox_SelectedIndexChanged);
//
// texturePageImageBox
//
this.texturePageImageBox.BackColor = System.Drawing.SystemColors.ControlDark;
this.texturePageImageBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.texturePageImageBox.ForeColor = System.Drawing.SystemColors.ControlText;
this.texturePageImageBox.GridDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.None;
this.texturePageImageBox.Location = new System.Drawing.Point(0, 0);
this.texturePageImageBox.Name = "texturePageImageBox";
this.texturePageImageBox.Size = new System.Drawing.Size(266, 417);
this.texturePageImageBox.TabIndex = 1;
//
// charactersTabPage
//
this.charactersTabPage.Controls.Add(this.imageSplitContainer);
this.charactersTabPage.Location = new System.Drawing.Point(4, 22);
this.charactersTabPage.Name = "charactersTabPage";
this.charactersTabPage.Padding = new System.Windows.Forms.Padding(3);
this.charactersTabPage.Size = new System.Drawing.Size(539, 423);
this.charactersTabPage.TabIndex = 0;
this.charactersTabPage.Text = "Characters";
this.charactersTabPage.UseVisualStyleBackColor = true;
//
// imageSplitContainer
//
this.imageSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.imageSplitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.imageSplitContainer.Location = new System.Drawing.Point(3, 3);
this.imageSplitContainer.Name = "imageSplitContainer";
this.imageSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// imageSplitContainer.Panel1
//
this.imageSplitContainer.Panel1.Controls.Add(this.charactersSplitContainer);
//
// imageSplitContainer.Panel2
//
this.imageSplitContainer.Panel2.Controls.Add(this.pageImageBox);
this.imageSplitContainer.Size = new System.Drawing.Size(533, 417);
this.imageSplitContainer.SplitterDistance = 249;
this.imageSplitContainer.TabIndex = 0;
//
// charactersSplitContainer
//
this.charactersSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.charactersSplitContainer.Location = new System.Drawing.Point(0, 0);
this.charactersSplitContainer.Name = "charactersSplitContainer";
//
// charactersSplitContainer.Panel1
//
this.charactersSplitContainer.Panel1.Controls.Add(this.charListBox);
//
// charactersSplitContainer.Panel2
//
this.charactersSplitContainer.Panel2.Controls.Add(this.characterSplitContainer);
this.charactersSplitContainer.Size = new System.Drawing.Size(533, 249);
this.charactersSplitContainer.SplitterDistance = 264;
this.charactersSplitContainer.TabIndex = 0;
//
// charListBox
//
this.charListBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.charListBox.FormattingEnabled = true;
this.charListBox.IntegralHeight = false;
this.charListBox.Location = new System.Drawing.Point(0, 0);
this.charListBox.Name = "charListBox";
this.charListBox.Size = new System.Drawing.Size(264, 249);
this.charListBox.TabIndex = 0;
this.charListBox.SelectedIndexChanged += new System.EventHandler(this.CharListBox_SelectedIndexChanged);
//
// characterSplitContainer
//
this.characterSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.characterSplitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.characterSplitContainer.Location = new System.Drawing.Point(0, 0);
this.characterSplitContainer.Name = "characterSplitContainer";
this.characterSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// characterSplitContainer.Panel1
//
this.characterSplitContainer.Panel1.Controls.Add(this.characterImageBox);
//
// characterSplitContainer.Panel2
//
this.characterSplitContainer.Panel2.Controls.Add(this.characterPropertyGrid);
this.characterSplitContainer.Size = new System.Drawing.Size(265, 249);
this.characterSplitContainer.SplitterDistance = 98;
this.characterSplitContainer.TabIndex = 0;
//
// characterImageBox
//
this.characterImageBox.BackColor = System.Drawing.SystemColors.ControlDark;
this.characterImageBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.characterImageBox.ForeColor = System.Drawing.SystemColors.ControlText;
this.characterImageBox.GridDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.None;
this.characterImageBox.Location = new System.Drawing.Point(0, 0);
this.characterImageBox.Name = "characterImageBox";
this.characterImageBox.Size = new System.Drawing.Size(265, 98);
this.characterImageBox.TabIndex = 0;
//
// characterPropertyGrid
//
this.characterPropertyGrid.CommandsVisibleIfAvailable = false;
this.characterPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.characterPropertyGrid.HelpVisible = false;
this.characterPropertyGrid.Location = new System.Drawing.Point(0, 0);
this.characterPropertyGrid.Name = "characterPropertyGrid";
this.characterPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.Alphabetical;
this.characterPropertyGrid.ReadOnly = true;
this.characterPropertyGrid.Size = new System.Drawing.Size(265, 147);
this.characterPropertyGrid.TabIndex = 0;
this.characterPropertyGrid.ToolbarVisible = false;
//
// pageImageBox
//
this.pageImageBox.BackColor = System.Drawing.SystemColors.ControlDark;
this.pageImageBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pageImageBox.ForeColor = System.Drawing.SystemColors.ControlText;
this.pageImageBox.GridDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.None;
this.pageImageBox.Location = new System.Drawing.Point(0, 0);
this.pageImageBox.Name = "pageImageBox";
this.pageImageBox.Size = new System.Drawing.Size(533, 164);
this.pageImageBox.TabIndex = 0;
this.pageImageBox.Paint += new System.Windows.Forms.PaintEventHandler(this.PageImageBox_Paint);
//
// kerningsTabPage
//
this.kerningsTabPage.Controls.Add(this.kerningsListBox);
this.kerningsTabPage.Location = new System.Drawing.Point(4, 22);
this.kerningsTabPage.Name = "kerningsTabPage";
this.kerningsTabPage.Padding = new System.Windows.Forms.Padding(3);
this.kerningsTabPage.Size = new System.Drawing.Size(539, 423);
this.kerningsTabPage.TabIndex = 3;
this.kerningsTabPage.Text = "Kernings";
this.kerningsTabPage.UseVisualStyleBackColor = true;
//
// kerningsListBox
//
this.kerningsListBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.kerningsListBox.FormattingEnabled = true;
this.kerningsListBox.IntegralHeight = false;
this.kerningsListBox.Location = new System.Drawing.Point(3, 3);
this.kerningsListBox.Name = "kerningsListBox";
this.kerningsListBox.Size = new System.Drawing.Size(533, 417);
this.kerningsListBox.TabIndex = 1;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(826, 520);
this.Controls.Add(this.rootSplitContainer);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.toolStrip);
this.Controls.Add(this.menuStrip);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip;
this.MaximizeBox = true;
this.MinimizeBox = true;
this.Name = "MainForm";
this.ShowIcon = true;
this.ShowInTaskbar = true;
this.Text = "Cyotek Bitmap Font Viewer";
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.rootSplitContainer.Panel1.ResumeLayout(false);
this.rootSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.rootSplitContainer)).EndInit();
this.rootSplitContainer.ResumeLayout(false);
this.tabControl.ResumeLayout(false);
this.previewTabPage.ResumeLayout(false);
this.textSplitContainer.Panel1.ResumeLayout(false);
this.textSplitContainer.Panel1.PerformLayout();
this.textSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.textSplitContainer)).EndInit();
this.textSplitContainer.ResumeLayout(false);
this.fontTabPage.ResumeLayout(false);
this.texturePagesTabPage.ResumeLayout(false);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.charactersTabPage.ResumeLayout(false);
this.imageSplitContainer.Panel1.ResumeLayout(false);
this.imageSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.imageSplitContainer)).EndInit();
this.imageSplitContainer.ResumeLayout(false);
this.charactersSplitContainer.Panel1.ResumeLayout(false);
this.charactersSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.charactersSplitContainer)).EndInit();
this.charactersSplitContainer.ResumeLayout(false);
this.characterSplitContainer.Panel1.ResumeLayout(false);
this.characterSplitContainer.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.characterSplitContainer)).EndInit();
this.characterSplitContainer.ResumeLayout(false);
this.kerningsTabPage.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.SplitContainer rootSplitContainer;
private System.Windows.Forms.SplitContainer imageSplitContainer;
private System.Windows.Forms.SplitContainer characterSplitContainer;
private Cyotek.Windows.Forms.ImageBox characterImageBox;
private Cyotek.Windows.Forms.ImageBox pageImageBox;
private Cyotek.Demo.BitmapFontViewer.PropertyGrid characterPropertyGrid;
private System.Windows.Forms.ListBox charListBox;
private Cyotek.Demo.BitmapFontViewer.PropertyGrid fontPropertyGrid;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.TabPage charactersTabPage;
private System.Windows.Forms.TabPage fontTabPage;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripButton openToolStripButton;
private FilePane filePane;
private System.Windows.Forms.SplitContainer charactersSplitContainer;
private System.Windows.Forms.ToolStripStatusLabel statusToolStripStatusLabel;
private System.Windows.Forms.ToolStripStatusLabel cyotekLinkToolStripStatusLabel;
private System.Windows.Forms.TabPage texturePagesTabPage;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.ListBox texturePagesListBox;
private Cyotek.Windows.Forms.ImageBox texturePageImageBox;
private System.Windows.Forms.TabPage kerningsTabPage;
private System.Windows.Forms.ListBox kerningsListBox;
private System.Windows.Forms.TabPage previewTabPage;
private System.Windows.Forms.SplitContainer textSplitContainer;
private System.Windows.Forms.TextBox previewTextBox;
private Cyotek.Windows.Forms.ImageBox previewImageBox;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem generateCodeToolStripMenuItem;
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// .NET Compact Framework 1.0 has no support for WindowsIdentity
#if !NETCF
// MONO 1.0 has no support for Win32 Logon APIs
#if !MONO
// SSCLI 1.0 has no support for Win32 Logon APIs
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using log4net.Core;
namespace log4net.Util
{
/// <summary>
/// Impersonate a Windows Account
/// </summary>
/// <remarks>
/// <para>
/// This <see cref="SecurityContext"/> impersonates a Windows account.
/// </para>
/// <para>
/// How the impersonation is done depends on the value of <see cref="Impersonate"/>.
/// This allows the context to either impersonate a set of user credentials specified
/// using username, domain name and password or to revert to the process credentials.
/// </para>
/// </remarks>
public class WindowsSecurityContext : SecurityContext, IOptionHandler
{
/// <summary>
/// The impersonation modes for the <see cref="WindowsSecurityContext"/>
/// </summary>
/// <remarks>
/// <para>
/// See the <see cref="WindowsSecurityContext.Credentials"/> property for
/// details.
/// </para>
/// </remarks>
public enum ImpersonationMode
{
/// <summary>
/// Impersonate a user using the credentials supplied
/// </summary>
User,
/// <summary>
/// Revert this the thread to the credentials of the process
/// </summary>
Process
}
#region Member Variables
private ImpersonationMode m_impersonationMode = ImpersonationMode.User;
private string m_userName;
private string m_domainName = Environment.MachineName;
private string m_password;
private WindowsIdentity m_identity;
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public WindowsSecurityContext()
{
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the impersonation mode for this security context
/// </summary>
/// <value>
/// The impersonation mode for this security context
/// </value>
/// <remarks>
/// <para>
/// Impersonate either a user with user credentials or
/// revert this thread to the credentials of the process.
/// The value is one of the <see cref="ImpersonationMode"/>
/// enum.
/// </para>
/// <para>
/// The default value is <see cref="ImpersonationMode.User"/>
/// </para>
/// <para>
/// When the mode is set to <see cref="ImpersonationMode.User"/>
/// the user's credentials are established using the
/// <see cref="UserName"/>, <see cref="DomainName"/> and <see cref="Password"/>
/// values.
/// </para>
/// <para>
/// When the mode is set to <see cref="ImpersonationMode.Process"/>
/// no other properties need to be set. If the calling thread is
/// impersonating then it will be reverted back to the process credentials.
/// </para>
/// </remarks>
public ImpersonationMode Credentials
{
get { return m_impersonationMode; }
set { m_impersonationMode = value; }
}
/// <summary>
/// Gets or sets the Windows username for this security context
/// </summary>
/// <value>
/// The Windows username for this security context
/// </value>
/// <remarks>
/// <para>
/// This property must be set if <see cref="Credentials"/>
/// is set to <see cref="ImpersonationMode.User"/> (the default setting).
/// </para>
/// </remarks>
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}
/// <summary>
/// Gets or sets the Windows domain name for this security context
/// </summary>
/// <value>
/// The Windows domain name for this security context
/// </value>
/// <remarks>
/// <para>
/// The default value for <see cref="DomainName"/> is the local machine name
/// taken from the <see cref="Environment.MachineName"/> property.
/// </para>
/// <para>
/// This property must be set if <see cref="Credentials"/>
/// is set to <see cref="ImpersonationMode.User"/> (the default setting).
/// </para>
/// </remarks>
public string DomainName
{
get { return m_domainName; }
set { m_domainName = value; }
}
/// <summary>
/// Sets the password for the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties.
/// </summary>
/// <value>
/// The password for the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties.
/// </value>
/// <remarks>
/// <para>
/// This property must be set if <see cref="Credentials"/>
/// is set to <see cref="ImpersonationMode.User"/> (the default setting).
/// </para>
/// </remarks>
public string Password
{
set { m_password = value; }
}
#endregion
#region IOptionHandler Members
/// <summary>
/// Initialize the SecurityContext based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// The security context will try to Logon the specified user account and
/// capture a primary token for impersonation.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">The required <see cref="UserName" />,
/// <see cref="DomainName" /> or <see cref="Password" /> properties were not specified.</exception>
public void ActivateOptions()
{
if (m_impersonationMode == ImpersonationMode.User)
{
if (m_userName == null) throw new ArgumentNullException("m_userName");
if (m_domainName == null) throw new ArgumentNullException("m_domainName");
if (m_password == null) throw new ArgumentNullException("m_password");
m_identity = LogonUser(m_userName, m_domainName, m_password);
}
}
#endregion
/// <summary>
/// Impersonate the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties.
/// </summary>
/// <param name="state">caller provided state</param>
/// <returns>
/// An <see cref="IDisposable"/> instance that will revoke the impersonation of this SecurityContext
/// </returns>
/// <remarks>
/// <para>
/// Depending on the <see cref="Credentials"/> property either
/// impersonate a user using credentials supplied or revert
/// to the process credentials.
/// </para>
/// </remarks>
public override IDisposable Impersonate(object state)
{
if (m_impersonationMode == ImpersonationMode.User)
{
if (m_identity != null)
{
return new DisposableImpersonationContext(m_identity.Impersonate());
}
}
else if (m_impersonationMode == ImpersonationMode.Process)
{
// Impersonate(0) will revert to the process credentials
return new DisposableImpersonationContext(WindowsIdentity.Impersonate(IntPtr.Zero));
}
return null;
}
/// <summary>
/// Create a <see cref="WindowsIdentity"/> given the userName, domainName and password.
/// </summary>
/// <param name="userName">the user name</param>
/// <param name="domainName">the domain name</param>
/// <param name="password">the password</param>
/// <returns>the <see cref="WindowsIdentity"/> for the account specified</returns>
/// <remarks>
/// <para>
/// Uses the Windows API call LogonUser to get a principal token for the account. This
/// token is used to initialize the WindowsIdentity.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
private static WindowsIdentity LogonUser(string userName, string domainName, string password)
{
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
IntPtr tokenHandle = IntPtr.Zero;
if(!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle))
{
NativeError error = NativeError.GetLastError();
throw new Exception("Failed to LogonUser ["+userName+"] in Domain ["+domainName+"]. Error: "+ error.ToString());
}
const int SecurityImpersonation = 2;
IntPtr dupeTokenHandle = IntPtr.Zero;
if(!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle))
{
NativeError error = NativeError.GetLastError();
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString());
}
WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle);
// Free the tokens.
if (dupeTokenHandle != IntPtr.Zero)
{
CloseHandle(dupeTokenHandle);
}
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
return identity;
}
#region Native Method Stubs
[DllImport("advapi32.dll", SetLastError=true)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
#endregion
#region DisposableImpersonationContext class
/// <summary>
/// Adds <see cref="IDisposable"/> to <see cref="WindowsImpersonationContext"/>
/// </summary>
/// <remarks>
/// <para>
/// Helper class to expose the <see cref="WindowsImpersonationContext"/>
/// through the <see cref="IDisposable"/> interface.
/// </para>
/// </remarks>
private sealed class DisposableImpersonationContext : IDisposable
{
private readonly WindowsImpersonationContext m_impersonationContext;
/// <summary>
/// Constructor
/// </summary>
/// <param name="impersonationContext">the impersonation context being wrapped</param>
/// <remarks>
/// <para>
/// Constructor
/// </para>
/// </remarks>
public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext)
{
m_impersonationContext = impersonationContext;
}
/// <summary>
/// Revert the impersonation
/// </summary>
/// <remarks>
/// <para>
/// Revert the impersonation
/// </para>
/// </remarks>
public void Dispose()
{
m_impersonationContext.Undo();
}
}
#endregion
}
}
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Autofac;
using Humanizer;
using Microsoft.Owin;
using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
namespace Mandro.Owin.SimpleMVC
{
public class SimpleMvcMiddleware : OwinMiddleware
{
private const string ViewFileExtension = ".cshtml";
private const string ViewsFolderName = "Views";
private Dictionary<string, Type> _controllersMap;
private IContainer _container;
public SimpleMvcMiddleware(OwinMiddleware next)
: base(next)
{
InitializeContainer();
LoadAppDomainControllers();
Razor.SetTemplateService(new TemplateService(new TemplateServiceConfiguration
{
Resolver = new DelegateTemplateResolver(File.ReadAllText)
}));
}
public override async Task Invoke(IOwinContext context)
{
var query = await MvcQuery.ParseAsync(context.Request, _controllersMap);
if (query == null || query.Controller == null)
{
await Next.Invoke(context);
return;
}
if (!await TryAuthenticate(context, query))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Unauthorized");
return;
}
var methodResult = await TryRunControllerMethod(context, query);
if (!methodResult.Success)
{
await Next.Invoke(context);
return;
}
// Check if method returned something we can handle:
// - Uri will cause redirection
// - Byte array will cause immediate write to response
if (methodResult.Result is Uri)
{
context.Response.Redirect((methodResult.Result as Uri).ToString());
return;
}
else if (methodResult.Result is byte[])
{
await context.Response.WriteAsync(methodResult.Result as byte[]);
return;
}
var templateContent = await ReadViewTemplate(query);
var result = await Task.Run(() => Razor.Parse(templateContent, methodResult.Result));
await context.Response.WriteAsync(result);
}
private async static Task<string> ReadViewTemplate(MvcQuery query)
{
var path = ViewsFolderName + "/" + query.Controller + "/" + query.Method + ViewFileExtension;
using (var fileStream = File.OpenRead(path))
using (var fileReader = new StreamReader(fileStream))
{
return await fileReader.ReadToEndAsync();
}
}
private async Task<bool> TryAuthenticate(IOwinContext context, MvcQuery query)
{
var controllerType = _controllersMap[query.Controller];
var controllerMethod = controllerType.GetMethods().FirstOrDefault(method => method.Name == query.Method);
if (controllerType == null || controllerMethod == null)
{
return true;
}
if (NeedsAuthentication(controllerType) || NeedsAuthentication(controllerMethod))
{
var authenticateResult = await context.Authentication.AuthenticateAsync("Cookie");
return authenticateResult != null && authenticateResult.Identity != null;
}
return true;
}
private static bool NeedsAuthentication(ICustomAttributeProvider controllerType)
{
return controllerType.GetCustomAttributes(typeof(AuthorizeAttribute), true).Any();
}
private async Task<MethodResult> TryRunControllerMethod(IOwinContext context, MvcQuery query)
{
var controllerType = _controllersMap[query.Controller];
var instance = _container.Resolve(controllerType);
var controllerMethod = controllerType.GetMethods().FirstOrDefault(method => method.Name == query.Method);
if (controllerMethod != null)
{
var methodParameterValues = GetMethodParameterValues(context, query.Parameters, controllerMethod);
return await Task.Run(() => new MethodResult { Result = controllerMethod.Invoke(instance, methodParameterValues), Success = true });
}
else
{
return new MethodResult { Result = false };
}
}
private static object[] GetMethodParameterValues(IOwinContext context, IDictionary<string, string> parameters, MethodInfo controllerMethod)
{
if (!controllerMethod.GetParameters().Any())
{
return new object[] { };
}
var expandoObject = new ExpandoObject();
var dictionary = expandoObject as IDictionary<string, object>;
foreach (var parameter in parameters)
{
dictionary.Add(parameter.Key.Dehumanize().Replace(" ", string.Empty), parameter.Value);
}
dictionary.Add("Context", context);
return new object[] { expandoObject };
}
private void LoadAppDomainControllers()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var controllers = assemblies.SelectMany(assembly => assembly
.GetTypes()
.Where(type => type.Namespace != null && type.Namespace.EndsWith("Controllers"))
.GroupBy(type => type.Name)
.Select(group => group.First()));
_controllersMap = controllers.ToDictionary(keyItem => keyItem.Name, valueItem => valueItem);
}
private void InitializeContainer()
{
var containerBuilder = new ContainerBuilder();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
containerBuilder.RegisterAssemblyTypes(assembly).AsSelf().AsImplementedInterfaces();
}
_container = containerBuilder.Build();
}
private class MethodResult
{
public bool Success { get; set; }
public object Result { get; set; }
}
private class MvcQuery
{
private const string DefaultController = "Home";
private const string DefaultControllerMethod = "Index";
public static async Task<MvcQuery> ParseAsync(IOwinRequest request, IDictionary<string, Type> controllersMap)
{
return new MvcQuery
{
Controller = GetControllerName(request, controllersMap),
Method = GetMethodName(request, controllersMap),
Parameters = await GetParameters(request, controllersMap)
};
}
private static async Task<IDictionary<string, string>> GetParameters(IOwinRequest request, IDictionary<string, Type> controllersMap)
{
var httpMethod = request.Method.ToLower().Pascalize();
var query = request.Path.Value;
var queryParts = new Queue<string>(query.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries));
if (!queryParts.Any())
{
return new Dictionary<string, string>();
}
var controllerName = queryParts.Dequeue();
if (!controllersMap.ContainsKey(controllerName))
{
return new Dictionary<string, string>();
}
int paramIndex = 1;
var parameters = new Dictionary<string, string>();
if (request.ContentType == "application/x-www-form-urlencoded")
{
var formCollection = await request.ReadFormAsync();
parameters = formCollection.ToDictionary(key => key.Key, value => value.Value.FirstOrDefault());
}
if (queryParts.Any())
{
var potentialMethodName = queryParts.Dequeue();
if (controllersMap[controllerName].GetMethods().All(method => method.Name != httpMethod + potentialMethodName))
{
parameters.Add("Param" + paramIndex++, potentialMethodName);
}
}
while (queryParts.Any())
{
parameters.Add("Param" + paramIndex++, queryParts.Dequeue());
}
return parameters;
}
private static string GetControllerName(IOwinRequest request, IDictionary<string, Type> controllersMap)
{
var query = request.Path.Value;
if (query == "/")
{
return DefaultController;
}
var controllerName = query.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
if (!controllersMap.ContainsKey(controllerName))
{
return null;
}
return controllerName;
}
private static string GetMethodName(IOwinRequest request, IDictionary<string, Type> controllersMap)
{
var httpMethod = request.Method.ToLower().Pascalize();
var query = request.Path.Value;
if (query == "/")
{
return httpMethod + DefaultControllerMethod;
}
var queryParts = new Queue<string>(query.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries));
if (!queryParts.Any())
{
return null;
}
var controllerName = queryParts.Dequeue();
if (!controllersMap.ContainsKey(controllerName))
{
return null;
}
if (queryParts.Any())
{
var potentialMethodName = queryParts.Dequeue();
if (controllersMap[controllerName].GetMethods().Any(method => method.Name == httpMethod + potentialMethodName))
{
return httpMethod + potentialMethodName;
}
}
return httpMethod + DefaultControllerMethod;
}
public IDictionary<string, string> Parameters { get; private set; }
public string Method { get; private set; }
public string Controller { get; private set; }
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Rainbow.Framework.Settings;
namespace Rainbow.Framework.Content.Data
{
/// <summary>
/// IBS Tasks module
/// Class that encapsulates all data logic necessary to add/query/delete
/// tasks within the Portal database.
/// Written by: ??? (the guy did not write his name in the original code)
/// Moved into Rainbow by Jakob Hansen, hansen3000@hotmail.com
/// EHN - By Mike Stone Change Description field to ntext to remove the 3000 char limit
/// </summary>
public class TasksDB
{
/// <summary>
/// GetTasks
/// NOTE: A DataSet is returned from this method to allow this method to support
/// both desktop and mobile Web UI.
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>A DataSet</returns>
public DataSet GetTasks(int moduleID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlDataAdapter myCommand = new SqlDataAdapter("rb_GetTasks", myConnection);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
parameterModuleID.Value = moduleID;
myCommand.SelectCommand.Parameters.Add(parameterModuleID);
// Create and Fill the DataSet
DataSet myDataSet = new DataSet();
try
{
myCommand.Fill(myDataSet);
}
finally
{
myConnection.Close(); //by Manu fix close bug #2
}
// Return the DataSet
return myDataSet;
}
/// <summary>
/// GetSingleTask
/// </summary>
/// <param name="itemID">ItemID</param>
/// <returns>A SqlDataReader</returns>
public SqlDataReader GetSingleTask(int itemID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_GetSingleTask", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Value = itemID;
myCommand.Parameters.Add(parameterItemID);
// Execute the command
myConnection.Open();
SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Return the datareader
return result;
}
/// <summary>
/// Deletes the task.
/// </summary>
/// <param name="itemID">The item ID.</param>
public void DeleteTask(int itemID)
{
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_DeleteTask", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Value = itemID;
myCommand.Parameters.Add(parameterItemID);
// Open the database connection and execute SQL Command
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
}
/// <summary>
/// Adds the task.
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <param name="itemID">The item ID.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="title">The title.</param>
/// <param name="startDate">The start date.</param>
/// <param name="description">The description.</param>
/// <param name="status">The status.</param>
/// <param name="priority">The priority.</param>
/// <param name="assignedto">The assignedto.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="percentComplete">The percent complete.</param>
/// <returns></returns>
public int AddTask(int moduleID, int itemID, string userName, string title, DateTime startDate,
string description, string status, string priority, string assignedto, DateTime dueDate,
int percentComplete)
{
if (userName.Length < 1)
{
userName = "unknown";
}
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_AddTask", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(parameterItemID);
SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
parameterModuleID.Value = moduleID;
myCommand.Parameters.Add(parameterModuleID);
SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
parameterUserName.Value = userName;
myCommand.Parameters.Add(parameterUserName);
SqlParameter parameterStatus = new SqlParameter("@Status", SqlDbType.NVarChar, 20);
parameterStatus.Value = status;
myCommand.Parameters.Add(parameterStatus);
SqlParameter parameterPercentComplete = new SqlParameter("@PercentComplete", SqlDbType.Int, 4);
parameterPercentComplete.Value = percentComplete;
myCommand.Parameters.Add(parameterPercentComplete);
SqlParameter parameterPriority = new SqlParameter("@Priority", SqlDbType.NVarChar, 20);
parameterPriority.Value = priority;
myCommand.Parameters.Add(parameterPriority);
SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100);
parameterTitle.Value = title;
myCommand.Parameters.Add(parameterTitle);
SqlParameter parameterAssignedTo = new SqlParameter("@AssignedTo", SqlDbType.NVarChar, 100);
parameterAssignedTo.Value = assignedto;
myCommand.Parameters.Add(parameterAssignedTo);
SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime, 8);
parameterStartDate.Value = startDate;
myCommand.Parameters.Add(parameterStartDate);
SqlParameter parameterDueDate = new SqlParameter("@DueDate", SqlDbType.DateTime, 8);
parameterDueDate.Value = dueDate;
myCommand.Parameters.Add(parameterDueDate);
SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NText);
parameterDescription.Value = description;
myCommand.Parameters.Add(parameterDescription);
// Open the database connection and execute SQL Command
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
// Return the new Task ItemID
return (int) parameterItemID.Value;
}
/// <summary>
/// Updates the task.
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <param name="itemID">The item ID.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="title">The title.</param>
/// <param name="startDate">The start date.</param>
/// <param name="description">The description.</param>
/// <param name="status">The status.</param>
/// <param name="priority">The priority.</param>
/// <param name="assignedto">The assignedto.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="percentComplete">The percent complete.</param>
public void UpdateTask(int moduleID, int itemID, string userName, string title, DateTime startDate,
string description, string status, string priority, string assignedto, DateTime dueDate,
int percentComplete)
{
if (userName.Length < 1)
{
userName = "unknown";
}
// Create Instance of Connection and Command Object
SqlConnection myConnection = Config.SqlConnectionString;
SqlCommand myCommand = new SqlCommand("rb_UpdateTask", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
parameterItemID.Value = itemID;
myCommand.Parameters.Add(parameterItemID);
SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
parameterUserName.Value = userName;
myCommand.Parameters.Add(parameterUserName);
SqlParameter parameterStatus = new SqlParameter("@Status", SqlDbType.NVarChar, 20);
parameterStatus.Value = status;
myCommand.Parameters.Add(parameterStatus);
SqlParameter parameterPercentComplete = new SqlParameter("@PercentComplete", SqlDbType.Int, 4);
parameterPercentComplete.Value = percentComplete;
myCommand.Parameters.Add(parameterPercentComplete);
SqlParameter parameterPriority = new SqlParameter("@Priority", SqlDbType.NVarChar, 20);
parameterPriority.Value = priority;
myCommand.Parameters.Add(parameterPriority);
SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100);
parameterTitle.Value = title;
myCommand.Parameters.Add(parameterTitle);
SqlParameter parameterAssignedTo = new SqlParameter("@AssignedTo", SqlDbType.NVarChar, 100);
parameterAssignedTo.Value = assignedto;
myCommand.Parameters.Add(parameterAssignedTo);
SqlParameter parameterStartDate = new SqlParameter("@StartDate", SqlDbType.DateTime, 8);
parameterStartDate.Value = startDate;
myCommand.Parameters.Add(parameterStartDate);
SqlParameter parameterDueDate = new SqlParameter("@DueDate", SqlDbType.DateTime, 8);
parameterDueDate.Value = dueDate;
myCommand.Parameters.Add(parameterDueDate);
SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NText);
parameterDescription.Value = description;
myCommand.Parameters.Add(parameterDescription);
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
}
}
}
| |
#region License
/*
* WebHeaderCollection.cs
*
* This code is derived from WebHeaderCollection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc. (http://www.ximian.com)
* Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* 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
#region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
* - Miguel de Icaza <miguel@novell.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a collection of the HTTP headers associated with a request or response.
/// </summary>
[Serializable]
[ComVisible (true)]
public class WebHeaderCollection : NameValueCollection, ISerializable
{
#region Private Fields
private static readonly Dictionary<string, HttpHeaderInfo> _headers;
private bool _internallyUsed;
private HttpHeaderType _state;
#endregion
#region Static Constructor
static WebHeaderCollection ()
{
_headers =
new Dictionary<string, HttpHeaderInfo> (StringComparer.InvariantCultureIgnoreCase) {
{
"Accept",
new HttpHeaderInfo (
"Accept",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"AcceptCharset",
new HttpHeaderInfo (
"Accept-Charset",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptEncoding",
new HttpHeaderInfo (
"Accept-Encoding",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptLanguage",
new HttpHeaderInfo (
"Accept-Language",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptRanges",
new HttpHeaderInfo (
"Accept-Ranges",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Age",
new HttpHeaderInfo (
"Age",
HttpHeaderType.Response)
},
{
"Allow",
new HttpHeaderInfo (
"Allow",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Authorization",
new HttpHeaderInfo (
"Authorization",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"CacheControl",
new HttpHeaderInfo (
"Cache-Control",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Connection",
new HttpHeaderInfo (
"Connection",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue)
},
{
"ContentEncoding",
new HttpHeaderInfo (
"Content-Encoding",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ContentLanguage",
new HttpHeaderInfo (
"Content-Language",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ContentLength",
new HttpHeaderInfo (
"Content-Length",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"ContentLocation",
new HttpHeaderInfo (
"Content-Location",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentMd5",
new HttpHeaderInfo (
"Content-MD5",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentRange",
new HttpHeaderInfo (
"Content-Range",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentType",
new HttpHeaderInfo (
"Content-Type",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Cookie",
new HttpHeaderInfo (
"Cookie",
HttpHeaderType.Request)
},
{
"Cookie2",
new HttpHeaderInfo (
"Cookie2",
HttpHeaderType.Request)
},
{
"Date",
new HttpHeaderInfo (
"Date",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Expect",
new HttpHeaderInfo (
"Expect",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"Expires",
new HttpHeaderInfo (
"Expires",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ETag",
new HttpHeaderInfo (
"ETag",
HttpHeaderType.Response)
},
{
"From",
new HttpHeaderInfo (
"From",
HttpHeaderType.Request)
},
{
"Host",
new HttpHeaderInfo (
"Host",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"IfMatch",
new HttpHeaderInfo (
"If-Match",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"IfModifiedSince",
new HttpHeaderInfo (
"If-Modified-Since",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"IfNoneMatch",
new HttpHeaderInfo (
"If-None-Match",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"IfRange",
new HttpHeaderInfo (
"If-Range",
HttpHeaderType.Request)
},
{
"IfUnmodifiedSince",
new HttpHeaderInfo (
"If-Unmodified-Since",
HttpHeaderType.Request)
},
{
"KeepAlive",
new HttpHeaderInfo (
"Keep-Alive",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"LastModified",
new HttpHeaderInfo (
"Last-Modified",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"Location",
new HttpHeaderInfo (
"Location",
HttpHeaderType.Response)
},
{
"MaxForwards",
new HttpHeaderInfo (
"Max-Forwards",
HttpHeaderType.Request)
},
{
"Pragma",
new HttpHeaderInfo (
"Pragma",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ProxyAuthenticate",
new HttpHeaderInfo (
"Proxy-Authenticate",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ProxyAuthorization",
new HttpHeaderInfo (
"Proxy-Authorization",
HttpHeaderType.Request)
},
{
"ProxyConnection",
new HttpHeaderInfo (
"Proxy-Connection",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Public",
new HttpHeaderInfo (
"Public",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Range",
new HttpHeaderInfo (
"Range",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"Referer",
new HttpHeaderInfo (
"Referer",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"RetryAfter",
new HttpHeaderInfo (
"Retry-After",
HttpHeaderType.Response)
},
{
"SecWebSocketAccept",
new HttpHeaderInfo (
"Sec-WebSocket-Accept",
HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"SecWebSocketExtensions",
new HttpHeaderInfo (
"Sec-WebSocket-Extensions",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInRequest)
},
{
"SecWebSocketKey",
new HttpHeaderInfo (
"Sec-WebSocket-Key",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"SecWebSocketProtocol",
new HttpHeaderInfo (
"Sec-WebSocket-Protocol",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValueInRequest)
},
{
"SecWebSocketVersion",
new HttpHeaderInfo (
"Sec-WebSocket-Version",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInResponse)
},
{
"Server",
new HttpHeaderInfo (
"Server",
HttpHeaderType.Response)
},
{
"SetCookie",
new HttpHeaderInfo (
"Set-Cookie",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"SetCookie2",
new HttpHeaderInfo (
"Set-Cookie2",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Te",
new HttpHeaderInfo (
"TE",
HttpHeaderType.Request)
},
{
"Trailer",
new HttpHeaderInfo (
"Trailer",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"TransferEncoding",
new HttpHeaderInfo (
"Transfer-Encoding",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue)
},
{
"Translate",
new HttpHeaderInfo (
"Translate",
HttpHeaderType.Request)
},
{
"Upgrade",
new HttpHeaderInfo (
"Upgrade",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"UserAgent",
new HttpHeaderInfo (
"User-Agent",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"Vary",
new HttpHeaderInfo (
"Vary",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Via",
new HttpHeaderInfo (
"Via",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Warning",
new HttpHeaderInfo (
"Warning",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"WwwAuthenticate",
new HttpHeaderInfo (
"WWW-Authenticate",
HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
}
};
}
#endregion
#region Internal Constructors
internal WebHeaderCollection (HttpHeaderType state, bool internallyUsed)
{
_state = state;
_internallyUsed = internallyUsed;
}
#endregion
#region Protected Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class from
/// the specified <see cref="SerializationInfo"/> and <see cref="StreamingContext"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that contains the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the source for the deserialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the specified name isn't found in <paramref name="serializationInfo"/>.
/// </exception>
protected WebHeaderCollection (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
try {
_internallyUsed = serializationInfo.GetBoolean ("InternallyUsed");
_state = (HttpHeaderType) serializationInfo.GetInt32 ("State");
var cnt = serializationInfo.GetInt32 ("Count");
for (var i = 0; i < cnt; i++) {
base.Add (
serializationInfo.GetString (i.ToString ()),
serializationInfo.GetString ((cnt + i).ToString ()));
}
}
catch (SerializationException ex) {
throw new ArgumentException (ex.Message, "serializationInfo", ex);
}
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class.
/// </summary>
public WebHeaderCollection ()
{
}
#endregion
#region Internal Properties
internal HttpHeaderType State {
get {
return _state;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets all header names in the collection.
/// </summary>
/// <value>
/// An array of <see cref="string"/> that contains all header names in the collection.
/// </value>
public override string[] AllKeys {
get {
return base.AllKeys;
}
}
/// <summary>
/// Gets the number of headers in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of headers in the collection.
/// </value>
public override int Count {
get {
return base.Count;
}
}
/// <summary>
/// Gets or sets the specified request <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the request <paramref name="header"/>.
/// </value>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to get or set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public string this[HttpRequestHeader header] {
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets or sets the specified response <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the response <paramref name="header"/>.
/// </value>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to get or set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public string this[HttpResponseHeader header] {
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets a collection of header names in the collection.
/// </summary>
/// <value>
/// A <see cref="NameObjectCollectionBase.KeysCollection"/> that contains
/// all header names in the collection.
/// </value>
public override NameObjectCollectionBase.KeysCollection Keys {
get {
return base.Keys;
}
}
#endregion
#region Private Methods
private void add (string name, string value, bool ignoreRestricted)
{
var act = ignoreRestricted
? (Action <string, string>) addWithoutCheckingNameAndRestricted
: addWithoutCheckingName;
doWithCheckingState (act, checkName (name), value, true);
}
private void addWithoutCheckingName (string name, string value)
{
doWithoutCheckingName (base.Add, name, value);
}
private void addWithoutCheckingNameAndRestricted (string name, string value)
{
base.Add (name, checkValue (value));
}
private static int checkColonSeparated (string header)
{
var idx = header.IndexOf (':');
if (idx == -1)
throw new ArgumentException ("No colon could be found.", "header");
return idx;
}
private static HttpHeaderType checkHeaderType (string name)
{
var info = getHeaderInfo (name);
return info == null
? HttpHeaderType.Unspecified
: info.IsRequest && !info.IsResponse
? HttpHeaderType.Request
: !info.IsRequest && info.IsResponse
? HttpHeaderType.Response
: HttpHeaderType.Unspecified;
}
private static string checkName (string name)
{
if (name == null || name.Length == 0)
throw new ArgumentNullException ("name");
name = name.Trim ();
if (!IsHeaderName (name))
throw new ArgumentException ("Contains invalid characters.", "name");
return name;
}
private void checkRestricted (string name)
{
if (!_internallyUsed && isRestricted (name, true))
throw new ArgumentException ("This header must be modified with the appropiate property.");
}
private void checkState (bool response)
{
if (_state == HttpHeaderType.Unspecified)
return;
if (response && _state == HttpHeaderType.Request)
throw new InvalidOperationException (
"This collection has already been used to store the request headers.");
if (!response && _state == HttpHeaderType.Response)
throw new InvalidOperationException (
"This collection has already been used to store the response headers.");
}
private static string checkValue (string value)
{
if (value == null || value.Length == 0)
return String.Empty;
value = value.Trim ();
if (value.Length > 65535)
throw new ArgumentOutOfRangeException ("value", "Greater than 65,535 characters.");
if (!IsHeaderValue (value))
throw new ArgumentException ("Contains invalid characters.", "value");
return value;
}
private static string convert (string key)
{
HttpHeaderInfo info;
return _headers.TryGetValue (key, out info) ? info.Name : String.Empty;
}
private void doWithCheckingState (
Action <string, string> action, string name, string value, bool setState)
{
var type = checkHeaderType (name);
if (type == HttpHeaderType.Request)
doWithCheckingState (action, name, value, false, setState);
else if (type == HttpHeaderType.Response)
doWithCheckingState (action, name, value, true, setState);
else
action (name, value);
}
private void doWithCheckingState (
Action <string, string> action, string name, string value, bool response, bool setState)
{
checkState (response);
action (name, value);
if (setState && _state == HttpHeaderType.Unspecified)
_state = response ? HttpHeaderType.Response : HttpHeaderType.Request;
}
private void doWithoutCheckingName (Action <string, string> action, string name, string value)
{
checkRestricted (name);
action (name, checkValue (value));
}
private static HttpHeaderInfo getHeaderInfo (string name)
{
foreach (var info in _headers.Values)
if (info.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase))
return info;
return null;
}
private static bool isRestricted (string name, bool response)
{
var info = getHeaderInfo (name);
return info != null && info.IsRestricted (response);
}
private void removeWithoutCheckingName (string name, string unuse)
{
checkRestricted (name);
base.Remove (name);
}
private void setWithoutCheckingName (string name, string value)
{
doWithoutCheckingName (base.Set, name, value);
}
#endregion
#region Internal Methods
internal static string Convert (HttpRequestHeader header)
{
return convert (header.ToString ());
}
internal static string Convert (HttpResponseHeader header)
{
return convert (header.ToString ());
}
internal void InternalRemove (string name)
{
base.Remove (name);
}
internal void InternalSet (string header, bool response)
{
var pos = checkColonSeparated (header);
InternalSet (header.Substring (0, pos), header.Substring (pos + 1), response);
}
internal void InternalSet (string name, string value, bool response)
{
value = checkValue (value);
if (IsMultiValue (name, response))
base.Add (name, value);
else
base.Set (name, value);
}
internal static bool IsHeaderName (string name)
{
return name != null && name.Length > 0 && name.IsToken ();
}
internal static bool IsHeaderValue (string value)
{
return value.IsText ();
}
internal static bool IsMultiValue (string headerName, bool response)
{
if (headerName == null || headerName.Length == 0)
return false;
var info = getHeaderInfo (headerName);
return info != null && info.IsMultiValue (response);
}
internal string ToStringMultiValue (bool response)
{
var buff = new StringBuilder ();
Count.Times (
i => {
var key = GetKey (i);
if (IsMultiValue (key, response))
foreach (var val in GetValues (i))
buff.AppendFormat ("{0}: {1}\r\n", key, val);
else
buff.AppendFormat ("{0}: {1}\r\n", key, Get (i));
});
return buff.Append ("\r\n").ToString ();
}
#endregion
#region Protected Methods
/// <summary>
/// Adds a header to the collection without checking if the header is on
/// the restricted header list.
/// </summary>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="headerValue">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> or <paramref name="headerValue"/> contains invalid characters.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="headerValue"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the <paramref name="headerName"/>.
/// </exception>
protected void AddWithoutValidate (string headerName, string headerValue)
{
add (headerName, headerValue, true);
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified <paramref name="header"/> to the collection.
/// </summary>
/// <param name="header">
/// A <see cref="string"/> that represents the header with the name and value separated by
/// a colon (<c>':'</c>).
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="header"/> is <see langword="null"/>, empty, or the name part of
/// <paramref name="header"/> is empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> doesn't contain a colon.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The name or value part of <paramref name="header"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of the value part of <paramref name="header"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the <paramref name="header"/>.
/// </exception>
public void Add (string header)
{
if (header == null || header.Length == 0)
throw new ArgumentNullException ("header");
var pos = checkColonSeparated (header);
add (header.Substring (0, pos), header.Substring (pos + 1), false);
}
/// <summary>
/// Adds the specified request <paramref name="header"/> with
/// the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Add (HttpRequestHeader header, string value)
{
doWithCheckingState (addWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Adds the specified response <paramref name="header"/> with
/// the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Add (HttpResponseHeader header, string value)
{
doWithCheckingState (addWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Adds a header with the specified <paramref name="name"/> and
/// <paramref name="value"/> to the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Add (string name, string value)
{
add (name, value, false);
}
/// <summary>
/// Removes all headers from the collection.
/// </summary>
public override void Clear ()
{
base.Clear ();
_state = HttpHeaderType.Unspecified;
}
/// <summary>
/// Get the value of the header at the specified <paramref name="index"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string Get (int index)
{
return base.Get (index);
}
/// <summary>
/// Get the value of the header with the specified <paramref name="name"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to find.
/// </param>
public override string Get (string name)
{
return base.Get (name);
}
/// <summary>
/// Gets the enumerator used to iterate through the collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> instance used to iterate through the collection.
/// </returns>
public override IEnumerator GetEnumerator ()
{
return base.GetEnumerator ();
}
/// <summary>
/// Get the name of the header at the specified <paramref name="index"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the header name.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string GetKey (int index)
{
return base.GetKey (index);
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="index"/> position of
/// the collection.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string[] GetValues (int index)
{
var vals = base.GetValues (index);
return vals != null && vals.Length > 0 ? vals : null;
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="header"/>.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="header">
/// A <see cref="string"/> that represents the name of the header to find.
/// </param>
public override string[] GetValues (string header)
{
var vals = base.GetValues (header);
return vals != null && vals.Length > 0 ? vals : null;
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (
SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
serializationInfo.AddValue ("InternallyUsed", _internallyUsed);
serializationInfo.AddValue ("State", (int) _state);
var cnt = Count;
serializationInfo.AddValue ("Count", cnt);
cnt.Times (
i => {
serializationInfo.AddValue (i.ToString (), GetKey (i));
serializationInfo.AddValue ((cnt + i).ToString (), Get (i));
});
}
/// <summary>
/// Determines whether the specified header can be set for the request.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to test.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName)
{
return isRestricted (checkName (headerName), false);
}
/// <summary>
/// Determines whether the specified header can be set for the request or the response.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to test.
/// </param>
/// <param name="response">
/// <c>true</c> if does the test for the response; for the request, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName, bool response)
{
return isRestricted (checkName (headerName), response);
}
/// <summary>
/// Implements the <see cref="ISerializable"/> interface and raises the deserialization event
/// when the deserialization is complete.
/// </summary>
/// <param name="sender">
/// An <see cref="object"/> that represents the source of the deserialization event.
/// </param>
public override void OnDeserialization (object sender)
{
}
/// <summary>
/// Removes the specified request <paramref name="header"/> from the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to remove.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Remove (HttpRequestHeader header)
{
doWithCheckingState (removeWithoutCheckingName, Convert (header), null, false, false);
}
/// <summary>
/// Removes the specified response <paramref name="header"/> from the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to remove.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Remove (HttpResponseHeader header)
{
doWithCheckingState (removeWithoutCheckingName, Convert (header), null, true, false);
}
/// <summary>
/// Removes the specified header from the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Remove (string name)
{
doWithCheckingState (removeWithoutCheckingName, checkName (name), null, false);
}
/// <summary>
/// Sets the specified request <paramref name="header"/> to the specified value.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the request header to set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Set (HttpRequestHeader header, string value)
{
doWithCheckingState (setWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Sets the specified response <paramref name="header"/> to the specified value.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the response header to set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Set (HttpResponseHeader header, string value)
{
doWithCheckingState (setWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Sets the specified header to the specified value.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to set.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Set (string name, string value)
{
doWithCheckingState (setWithoutCheckingName, checkName (name), value, true);
}
/// <summary>
/// Converts the current <see cref="WebHeaderCollection"/> to an array of <see cref="byte"/>.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> that receives the converted current
/// <see cref="WebHeaderCollection"/>.
/// </returns>
public byte[] ToByteArray ()
{
return Encoding.UTF8.GetBytes (ToString ());
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current
/// <see cref="WebHeaderCollection"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current <see cref="WebHeaderCollection"/>.
/// </returns>
public override string ToString ()
{
var buff = new StringBuilder ();
Count.Times (i => buff.AppendFormat ("{0}: {1}\r\n", GetKey (i), Get (i)));
return buff.Append ("\r\n").ToString ();
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the current <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (
SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter,
SerializationFormatter = true)]
void ISerializable.GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData (serializationInfo, streamingContext);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System
{
public static class ___AppDomain
{
public static IObservable<System.UInt32> GetTypeInfoCount(this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) =>
{
System.UInt32 pcTInfoOutput = default(System.UInt32);
_AppDomainValueLambda.GetTypeInfoCount(out pcTInfoOutput);
return pcTInfoOutput;
});
}
public static IObservable<System.Reactive.Unit> GetTypeInfo(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.UInt32> iTInfo, IObservable<System.UInt32> lcid, IObservable<System.IntPtr> ppTInfo)
{
return ObservableExt.ZipExecute(_AppDomainValue, iTInfo, lcid, ppTInfo,
(_AppDomainValueLambda, iTInfoLambda, lcidLambda, ppTInfoLambda) =>
_AppDomainValueLambda.GetTypeInfo(iTInfoLambda, lcidLambda, ppTInfoLambda));
}
public static IObservable<System.Guid> GetIDsOfNames(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Guid> riid, IObservable<System.IntPtr> rgszNames, IObservable<System.UInt32> cNames,
IObservable<System.UInt32> lcid, IObservable<System.IntPtr> rgDispId)
{
return Observable.Zip(_AppDomainValue, riid, rgszNames, cNames, lcid, rgDispId,
(_AppDomainValueLambda, riidLambda, rgszNamesLambda, cNamesLambda, lcidLambda, rgDispIdLambda) =>
{
_AppDomainValueLambda.GetIDsOfNames(ref riidLambda, rgszNamesLambda, cNamesLambda, lcidLambda,
rgDispIdLambda);
return riidLambda;
});
}
public static IObservable<System.Guid> Invoke(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.UInt32> dispIdMember, IObservable<System.Guid> riid, IObservable<System.UInt32> lcid,
IObservable<System.Int16> wFlags, IObservable<System.IntPtr> pDispParams,
IObservable<System.IntPtr> pVarResult, IObservable<System.IntPtr> pExcepInfo,
IObservable<System.IntPtr> puArgErr)
{
return Observable.Zip(_AppDomainValue, dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo,
puArgErr,
(_AppDomainValueLambda, dispIdMemberLambda, riidLambda, lcidLambda, wFlagsLambda, pDispParamsLambda,
pVarResultLambda, pExcepInfoLambda, puArgErrLambda) =>
{
_AppDomainValueLambda.Invoke(dispIdMemberLambda, ref riidLambda, lcidLambda, wFlagsLambda,
pDispParamsLambda, pVarResultLambda, pExcepInfoLambda, puArgErrLambda);
return riidLambda;
});
}
public static IObservable<System.String> ToString(this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.ToString());
}
public static IObservable<System.Boolean> Equals(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Object> other)
{
return Observable.Zip(_AppDomainValue, other,
(_AppDomainValueLambda, otherLambda) => _AppDomainValueLambda.Equals(otherLambda));
}
public static IObservable<System.Int32> GetHashCode(this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.GetHashCode());
}
public static IObservable<System.Type> GetType(this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.GetType());
}
public static IObservable<System.Object> InitializeLifetimeService(
this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue,
(_AppDomainValueLambda) => _AppDomainValueLambda.InitializeLifetimeService());
}
public static IObservable<System.Object> GetLifetimeService(this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue,
(_AppDomainValueLambda) => _AppDomainValueLambda.GetLifetimeService());
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access)
{
return Observable.Zip(_AppDomainValue, name, access,
(_AppDomainValueLambda, nameLambda, accessLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access, IObservable<System.String> dir)
{
return Observable.Zip(_AppDomainValue, name, access, dir,
(_AppDomainValueLambda, nameLambda, accessLambda, dirLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, dirLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access,
IObservable<System.Security.Policy.Evidence> evidence)
{
return Observable.Zip(_AppDomainValue, name, access, evidence,
(_AppDomainValueLambda, nameLambda, accessLambda, evidenceLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, evidenceLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access,
IObservable<System.Security.PermissionSet> requiredPermissions,
IObservable<System.Security.PermissionSet> optionalPermissions,
IObservable<System.Security.PermissionSet> refusedPermissions)
{
return Observable.Zip(_AppDomainValue, name, access, requiredPermissions, optionalPermissions,
refusedPermissions,
(_AppDomainValueLambda, nameLambda, accessLambda, requiredPermissionsLambda, optionalPermissionsLambda,
refusedPermissionsLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, requiredPermissionsLambda,
optionalPermissionsLambda, refusedPermissionsLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access, IObservable<System.String> dir,
IObservable<System.Security.Policy.Evidence> evidence)
{
return Observable.Zip(_AppDomainValue, name, access, dir, evidence,
(_AppDomainValueLambda, nameLambda, accessLambda, dirLambda, evidenceLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, dirLambda, evidenceLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access, IObservable<System.String> dir,
IObservable<System.Security.PermissionSet> requiredPermissions,
IObservable<System.Security.PermissionSet> optionalPermissions,
IObservable<System.Security.PermissionSet> refusedPermissions)
{
return Observable.Zip(_AppDomainValue, name, access, dir, requiredPermissions, optionalPermissions,
refusedPermissions,
(_AppDomainValueLambda, nameLambda, accessLambda, dirLambda, requiredPermissionsLambda,
optionalPermissionsLambda, refusedPermissionsLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, dirLambda,
requiredPermissionsLambda, optionalPermissionsLambda, refusedPermissionsLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access,
IObservable<System.Security.Policy.Evidence> evidence,
IObservable<System.Security.PermissionSet> requiredPermissions,
IObservable<System.Security.PermissionSet> optionalPermissions,
IObservable<System.Security.PermissionSet> refusedPermissions)
{
return Observable.Zip(_AppDomainValue, name, access, evidence, requiredPermissions, optionalPermissions,
refusedPermissions,
(_AppDomainValueLambda, nameLambda, accessLambda, evidenceLambda, requiredPermissionsLambda,
optionalPermissionsLambda, refusedPermissionsLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, evidenceLambda,
requiredPermissionsLambda, optionalPermissionsLambda, refusedPermissionsLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access, IObservable<System.String> dir,
IObservable<System.Security.Policy.Evidence> evidence,
IObservable<System.Security.PermissionSet> requiredPermissions,
IObservable<System.Security.PermissionSet> optionalPermissions,
IObservable<System.Security.PermissionSet> refusedPermissions)
{
return Observable.Zip(_AppDomainValue, name, access, dir, evidence, requiredPermissions, optionalPermissions,
refusedPermissions,
(_AppDomainValueLambda, nameLambda, accessLambda, dirLambda, evidenceLambda, requiredPermissionsLambda,
optionalPermissionsLambda, refusedPermissionsLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, dirLambda, evidenceLambda,
requiredPermissionsLambda, optionalPermissionsLambda, refusedPermissionsLambda));
}
public static IObservable<System.Reflection.Emit.AssemblyBuilder> DefineDynamicAssembly(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.Reflection.AssemblyName> name,
IObservable<System.Reflection.Emit.AssemblyBuilderAccess> access, IObservable<System.String> dir,
IObservable<System.Security.Policy.Evidence> evidence,
IObservable<System.Security.PermissionSet> requiredPermissions,
IObservable<System.Security.PermissionSet> optionalPermissions,
IObservable<System.Security.PermissionSet> refusedPermissions, IObservable<System.Boolean> isSynchronized)
{
return Observable.Zip(_AppDomainValue, name, access, dir, evidence, requiredPermissions, optionalPermissions,
refusedPermissions, isSynchronized,
(_AppDomainValueLambda, nameLambda, accessLambda, dirLambda, evidenceLambda, requiredPermissionsLambda,
optionalPermissionsLambda, refusedPermissionsLambda, isSynchronizedLambda) =>
_AppDomainValueLambda.DefineDynamicAssembly(nameLambda, accessLambda, dirLambda, evidenceLambda,
requiredPermissionsLambda, optionalPermissionsLambda, refusedPermissionsLambda,
isSynchronizedLambda));
}
public static IObservable<System.Runtime.Remoting.ObjectHandle> CreateInstance(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> assemblyName,
IObservable<System.String> typeName)
{
return Observable.Zip(_AppDomainValue, assemblyName, typeName,
(_AppDomainValueLambda, assemblyNameLambda, typeNameLambda) =>
_AppDomainValueLambda.CreateInstance(assemblyNameLambda, typeNameLambda));
}
public static IObservable<System.Runtime.Remoting.ObjectHandle> CreateInstanceFrom(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> assemblyFile,
IObservable<System.String> typeName)
{
return Observable.Zip(_AppDomainValue, assemblyFile, typeName,
(_AppDomainValueLambda, assemblyFileLambda, typeNameLambda) =>
_AppDomainValueLambda.CreateInstanceFrom(assemblyFileLambda, typeNameLambda));
}
public static IObservable<System.Runtime.Remoting.ObjectHandle> CreateInstance(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> assemblyName,
IObservable<System.String> typeName, IObservable<System.Object[]> activationAttributes)
{
return Observable.Zip(_AppDomainValue, assemblyName, typeName, activationAttributes,
(_AppDomainValueLambda, assemblyNameLambda, typeNameLambda, activationAttributesLambda) =>
_AppDomainValueLambda.CreateInstance(assemblyNameLambda, typeNameLambda, activationAttributesLambda));
}
public static IObservable<System.Runtime.Remoting.ObjectHandle> CreateInstanceFrom(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> assemblyFile,
IObservable<System.String> typeName, IObservable<System.Object[]> activationAttributes)
{
return Observable.Zip(_AppDomainValue, assemblyFile, typeName, activationAttributes,
(_AppDomainValueLambda, assemblyFileLambda, typeNameLambda, activationAttributesLambda) =>
_AppDomainValueLambda.CreateInstanceFrom(assemblyFileLambda, typeNameLambda,
activationAttributesLambda));
}
public static IObservable<System.Runtime.Remoting.ObjectHandle> CreateInstance(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> assemblyName,
IObservable<System.String> typeName, IObservable<System.Boolean> ignoreCase,
IObservable<System.Reflection.BindingFlags> bindingAttr, IObservable<System.Reflection.Binder> binder,
IObservable<System.Object[]> args, IObservable<System.Globalization.CultureInfo> culture,
IObservable<System.Object[]> activationAttributes,
IObservable<System.Security.Policy.Evidence> securityAttributes)
{
return Observable.Zip(_AppDomainValue, assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
culture, activationAttributes, securityAttributes,
(_AppDomainValueLambda, assemblyNameLambda, typeNameLambda, ignoreCaseLambda, bindingAttrLambda,
binderLambda, argsLambda, cultureLambda, activationAttributesLambda, securityAttributesLambda) =>
_AppDomainValueLambda.CreateInstance(assemblyNameLambda, typeNameLambda, ignoreCaseLambda,
bindingAttrLambda, binderLambda, argsLambda, cultureLambda, activationAttributesLambda,
securityAttributesLambda));
}
public static IObservable<System.Runtime.Remoting.ObjectHandle> CreateInstanceFrom(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> assemblyFile,
IObservable<System.String> typeName, IObservable<System.Boolean> ignoreCase,
IObservable<System.Reflection.BindingFlags> bindingAttr, IObservable<System.Reflection.Binder> binder,
IObservable<System.Object[]> args, IObservable<System.Globalization.CultureInfo> culture,
IObservable<System.Object[]> activationAttributes,
IObservable<System.Security.Policy.Evidence> securityAttributes)
{
return Observable.Zip(_AppDomainValue, assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
culture, activationAttributes, securityAttributes,
(_AppDomainValueLambda, assemblyFileLambda, typeNameLambda, ignoreCaseLambda, bindingAttrLambda,
binderLambda, argsLambda, cultureLambda, activationAttributesLambda, securityAttributesLambda) =>
_AppDomainValueLambda.CreateInstanceFrom(assemblyFileLambda, typeNameLambda, ignoreCaseLambda,
bindingAttrLambda, binderLambda, argsLambda, cultureLambda, activationAttributesLambda,
securityAttributesLambda));
}
public static IObservable<System.Reflection.Assembly> Load(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Reflection.AssemblyName> assemblyRef)
{
return Observable.Zip(_AppDomainValue, assemblyRef,
(_AppDomainValueLambda, assemblyRefLambda) => _AppDomainValueLambda.Load(assemblyRefLambda));
}
public static IObservable<System.Reflection.Assembly> Load(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.String> assemblyString)
{
return Observable.Zip(_AppDomainValue, assemblyString,
(_AppDomainValueLambda, assemblyStringLambda) => _AppDomainValueLambda.Load(assemblyStringLambda));
}
public static IObservable<System.Reflection.Assembly> Load(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Byte[]> rawAssembly)
{
return Observable.Zip(_AppDomainValue, rawAssembly,
(_AppDomainValueLambda, rawAssemblyLambda) => _AppDomainValueLambda.Load(rawAssemblyLambda));
}
public static IObservable<System.Reflection.Assembly> Load(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Byte[]> rawAssembly, IObservable<System.Byte[]> rawSymbolStore)
{
return Observable.Zip(_AppDomainValue, rawAssembly, rawSymbolStore,
(_AppDomainValueLambda, rawAssemblyLambda, rawSymbolStoreLambda) =>
_AppDomainValueLambda.Load(rawAssemblyLambda, rawSymbolStoreLambda));
}
public static IObservable<System.Reflection.Assembly> Load(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Byte[]> rawAssembly, IObservable<System.Byte[]> rawSymbolStore,
IObservable<System.Security.Policy.Evidence> securityEvidence)
{
return Observable.Zip(_AppDomainValue, rawAssembly, rawSymbolStore, securityEvidence,
(_AppDomainValueLambda, rawAssemblyLambda, rawSymbolStoreLambda, securityEvidenceLambda) =>
_AppDomainValueLambda.Load(rawAssemblyLambda, rawSymbolStoreLambda, securityEvidenceLambda));
}
public static IObservable<System.Reflection.Assembly> Load(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Reflection.AssemblyName> assemblyRef,
IObservable<System.Security.Policy.Evidence> assemblySecurity)
{
return Observable.Zip(_AppDomainValue, assemblyRef, assemblySecurity,
(_AppDomainValueLambda, assemblyRefLambda, assemblySecurityLambda) =>
_AppDomainValueLambda.Load(assemblyRefLambda, assemblySecurityLambda));
}
public static IObservable<System.Reflection.Assembly> Load(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.String> assemblyString, IObservable<System.Security.Policy.Evidence> assemblySecurity)
{
return Observable.Zip(_AppDomainValue, assemblyString, assemblySecurity,
(_AppDomainValueLambda, assemblyStringLambda, assemblySecurityLambda) =>
_AppDomainValueLambda.Load(assemblyStringLambda, assemblySecurityLambda));
}
public static IObservable<System.Int32> ExecuteAssembly(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.String> assemblyFile, IObservable<System.Security.Policy.Evidence> assemblySecurity)
{
return Observable.Zip(_AppDomainValue, assemblyFile, assemblySecurity,
(_AppDomainValueLambda, assemblyFileLambda, assemblySecurityLambda) =>
_AppDomainValueLambda.ExecuteAssembly(assemblyFileLambda, assemblySecurityLambda));
}
public static IObservable<System.Int32> ExecuteAssembly(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.String> assemblyFile)
{
return Observable.Zip(_AppDomainValue, assemblyFile,
(_AppDomainValueLambda, assemblyFileLambda) => _AppDomainValueLambda.ExecuteAssembly(assemblyFileLambda));
}
public static IObservable<System.Int32> ExecuteAssembly(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.String> assemblyFile, IObservable<System.Security.Policy.Evidence> assemblySecurity,
IObservable<System.String[]> args)
{
return Observable.Zip(_AppDomainValue, assemblyFile, assemblySecurity, args,
(_AppDomainValueLambda, assemblyFileLambda, assemblySecurityLambda, argsLambda) =>
_AppDomainValueLambda.ExecuteAssembly(assemblyFileLambda, assemblySecurityLambda, argsLambda));
}
public static IObservable<System.Reflection.Assembly[]> GetAssemblies(
this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.GetAssemblies());
}
public static IObservable<System.Reactive.Unit> AppendPrivatePath(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> path)
{
return ObservableExt.ZipExecute(_AppDomainValue, path,
(_AppDomainValueLambda, pathLambda) => _AppDomainValueLambda.AppendPrivatePath(pathLambda));
}
public static IObservable<System.Reactive.Unit> ClearPrivatePath(
this IObservable<System._AppDomain> _AppDomainValue)
{
return
Observable.Do(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.ClearPrivatePath())
.ToUnit();
}
public static IObservable<System.Reactive.Unit> SetShadowCopyPath(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> s)
{
return ObservableExt.ZipExecute(_AppDomainValue, s,
(_AppDomainValueLambda, sLambda) => _AppDomainValueLambda.SetShadowCopyPath(sLambda));
}
public static IObservable<System.Reactive.Unit> ClearShadowCopyPath(
this IObservable<System._AppDomain> _AppDomainValue)
{
return
Observable.Do(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.ClearShadowCopyPath())
.ToUnit();
}
public static IObservable<System.Reactive.Unit> SetCachePath(
this IObservable<System._AppDomain> _AppDomainValue, IObservable<System.String> s)
{
return ObservableExt.ZipExecute(_AppDomainValue, s,
(_AppDomainValueLambda, sLambda) => _AppDomainValueLambda.SetCachePath(sLambda));
}
public static IObservable<System.Reactive.Unit> SetData(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.String> name, IObservable<System.Object> data)
{
return ObservableExt.ZipExecute(_AppDomainValue, name, data,
(_AppDomainValueLambda, nameLambda, dataLambda) => _AppDomainValueLambda.SetData(nameLambda, dataLambda));
}
public static IObservable<System.Object> GetData(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.String> name)
{
return Observable.Zip(_AppDomainValue, name,
(_AppDomainValueLambda, nameLambda) => _AppDomainValueLambda.GetData(nameLambda));
}
public static IObservable<System.Reactive.Unit> SetAppDomainPolicy(
this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Security.Policy.PolicyLevel> domainPolicy)
{
return ObservableExt.ZipExecute(_AppDomainValue, domainPolicy,
(_AppDomainValueLambda, domainPolicyLambda) =>
_AppDomainValueLambda.SetAppDomainPolicy(domainPolicyLambda));
}
public static IObservable<System.Reactive.Unit> SetThreadPrincipal(
this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Security.Principal.IPrincipal> principal)
{
return ObservableExt.ZipExecute(_AppDomainValue, principal,
(_AppDomainValueLambda, principalLambda) => _AppDomainValueLambda.SetThreadPrincipal(principalLambda));
}
public static IObservable<System.Reactive.Unit> SetPrincipalPolicy(
this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.Security.Principal.PrincipalPolicy> policy)
{
return ObservableExt.ZipExecute(_AppDomainValue, policy,
(_AppDomainValueLambda, policyLambda) => _AppDomainValueLambda.SetPrincipalPolicy(policyLambda));
}
public static IObservable<System.Reactive.Unit> DoCallBack(this IObservable<System._AppDomain> _AppDomainValue,
IObservable<System.CrossAppDomainDelegate> theDelegate)
{
return ObservableExt.ZipExecute(_AppDomainValue, theDelegate,
(_AppDomainValueLambda, theDelegateLambda) => _AppDomainValueLambda.DoCallBack(theDelegateLambda));
}
public static IObservable<System.Security.Policy.Evidence> get_Evidence(
this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.Evidence);
}
public static IObservable<System.String> get_FriendlyName(this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.FriendlyName);
}
public static IObservable<System.String> get_BaseDirectory(this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.BaseDirectory);
}
public static IObservable<System.String> get_RelativeSearchPath(
this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue,
(_AppDomainValueLambda) => _AppDomainValueLambda.RelativeSearchPath);
}
public static IObservable<System.Boolean> get_ShadowCopyFiles(
this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.ShadowCopyFiles);
}
public static IObservable<System.String> get_DynamicDirectory(
this IObservable<System._AppDomain> _AppDomainValue)
{
return Observable.Select(_AppDomainValue, (_AppDomainValueLambda) => _AppDomainValueLambda.DynamicDirectory);
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Valle.TpvFinal
{
public partial class ListadoCierres
{
private global::Gtk.VBox vbox1;
private global::Valle.GtkUtilidades.MiLabel lblTitulo;
private global::Gtk.HBox pnePrimcipal;
private global::Gtk.VBox vbox5;
private global::Valle.GtkUtilidades.MiLabel lblInfOriginal;
private global::Gtk.HBox hbox4;
private global::Gtk.ScrolledWindow GtkScrolledOriginal;
private global::Gtk.TreeView lstCierres;
private global::Valle.GtkUtilidades.ScrollTactil scrollOriginal;
private global::Gtk.VBox vbox7;
private global::Valle.GtkUtilidades.MiLabel lblInfSelcecionados;
private global::Gtk.HBox hbox5;
private global::Gtk.ScrolledWindow GtkScrolledSelecionados;
private global::Gtk.TextView txtTicketInf;
private global::Valle.GtkUtilidades.ScrollTactil scrollSeleccionados;
private global::Gtk.HButtonBox hbuttonbox2;
private global::Gtk.Button btnAbrirCajon;
private global::Gtk.VBox vbox166;
private global::Gtk.Image image32;
private global::Gtk.Label label6;
private global::Gtk.Button btnDesglose;
private global::Gtk.VBox vbox163;
private global::Gtk.Image image30;
private global::Gtk.Label label3;
private global::Gtk.Button btnCamareros;
private global::Gtk.VBox vbox165;
private global::Gtk.Image image31;
private global::Gtk.Label label5;
private global::Gtk.Button btnHoras;
private global::Gtk.VBox vbox161;
private global::Gtk.VBox vbox164;
private global::Gtk.Image image28;
private global::Gtk.Label label4;
private global::Gtk.Button btnImprimir;
private global::Gtk.VBox vbox160;
private global::Gtk.Image image27;
private global::Gtk.Button btnMas;
private global::Gtk.VBox vbox159;
private global::Gtk.Image image26;
private global::Gtk.Label label1;
private global::Gtk.Button btnCierre;
private global::Gtk.VBox vbox162;
private global::Gtk.Image image29;
private global::Gtk.Label label2;
private global::Gtk.Button btnSalir;
private global::Gtk.ProgressBar barImformacion;
protected virtual void Init ()
{
global::Stetic.Gui.Initialize (this);
// Widget Valle.TpvFinal.ListadoCierres
this.Name ="Valle.Tpv.iconos.ListadoCierres";
this.Title = global::Mono.Unix.Catalog.GetString ("ListadoCierres");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child Valle.TpvFinal.ListadoCierres.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
// Container child vbox1.Gtk.Box+BoxChild
this.lblTitulo = new global::Valle.GtkUtilidades.MiLabel ();
this.lblTitulo.HeightRequest = 25;
this.lblTitulo.Events = ((global::Gdk.EventMask)(256));
this.lblTitulo.Name = "lblTitulo";
this.vbox1.Add (this.lblTitulo);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.lblTitulo]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.pnePrimcipal = new global::Gtk.HBox ();
this.pnePrimcipal.Name = "pnePrimcipal";
this.pnePrimcipal.Spacing = 6;
this.pnePrimcipal.BorderWidth = ((uint)(15));
// Container child pnePrimcipal.Gtk.Box+BoxChild
this.vbox5 = new global::Gtk.VBox ();
this.vbox5.Name = "vbox5";
this.vbox5.Spacing = 6;
// Container child vbox5.Gtk.Box+BoxChild
this.lblInfOriginal = new global::Valle.GtkUtilidades.MiLabel ();
this.lblInfOriginal.HeightRequest = 25;
this.lblInfOriginal.Events = ((global::Gdk.EventMask)(256));
this.lblInfOriginal.Name = "lblInfOriginal";
this.vbox5.Add (this.lblInfOriginal);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.lblInfOriginal]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child vbox5.Gtk.Box+BoxChild
this.hbox4 = new global::Gtk.HBox ();
this.hbox4.WidthRequest = 350;
this.hbox4.Name = "hbox4";
this.hbox4.Spacing = 6;
// Container child hbox4.Gtk.Box+BoxChild
this.GtkScrolledOriginal = new global::Gtk.ScrolledWindow ();
this.GtkScrolledOriginal.Name = "GtkScrolledWindow";
this.GtkScrolledOriginal.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow.Gtk.Container+ContainerChild
this.lstCierres = new global::Gtk.TreeView ();
this.lstCierres.CanFocus = true;
this.lstCierres.Name = "lstCierres";
this.GtkScrolledOriginal.Add (this.lstCierres);
this.hbox4.Add (this.GtkScrolledOriginal);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.GtkScrolledOriginal]));
w4.Position = 0;
// Container child hbox4.Gtk.Box+BoxChild
this.scrollOriginal = new global::Valle.GtkUtilidades.ScrollTactil ();
this.scrollOriginal.Events = ((global::Gdk.EventMask)(256));
this.scrollOriginal.Name = "scroolOriginal";
this.hbox4.Add (this.scrollOriginal);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.scrollOriginal]));
w5.Position = 1;
w5.Expand = false;
w5.Fill = false;
this.vbox5.Add (this.hbox4);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.hbox4]));
w6.Position = 1;
this.pnePrimcipal.Add (this.vbox5);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.pnePrimcipal[this.vbox5]));
w7.Position = 0;
// Container child pnePrimcipal.Gtk.Box+BoxChild
this.vbox7 = new global::Gtk.VBox ();
this.vbox7.WidthRequest = 350;
this.vbox7.Name = "vbox7";
this.vbox7.Spacing = 6;
// Container child vbox7.Gtk.Box+BoxChild
this.lblInfSelcecionados = new global::Valle.GtkUtilidades.MiLabel ();
this.lblInfSelcecionados.HeightRequest = 25;
this.lblInfSelcecionados.Events = ((global::Gdk.EventMask)(256));
this.lblInfSelcecionados.Name = "lblInfSelcecionados";
this.vbox7.Add (this.lblInfSelcecionados);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.lblInfSelcecionados]));
w8.Position = 0;
w8.Expand = false;
w8.Fill = false;
// Container child vbox7.Gtk.Box+BoxChild
this.hbox5 = new global::Gtk.HBox ();
this.hbox5.Name = "hbox5";
this.hbox5.Spacing = 6;
// Container child hbox5.Gtk.Box+BoxChild
this.GtkScrolledSelecionados = new global::Gtk.ScrolledWindow ();
this.GtkScrolledSelecionados.Name = "GtkScrolledWindow1";
this.GtkScrolledSelecionados.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow1.Gtk.Container+ContainerChild
this.txtTicketInf = new global::Gtk.TextView ();
this.txtTicketInf.CanFocus = true;
this.txtTicketInf.Name = "txtTicketInf";
this.GtkScrolledSelecionados.Add (this.txtTicketInf);
this.hbox5.Add (this.GtkScrolledSelecionados);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.hbox5[this.GtkScrolledSelecionados]));
w10.Position = 0;
// Container child hbox5.Gtk.Box+BoxChild
this.scrollSeleccionados = new global::Valle.GtkUtilidades.ScrollTactil ();
this.scrollSeleccionados.Events = ((global::Gdk.EventMask)(256));
this.scrollSeleccionados.Name = "scrollSeleccionados";
this.hbox5.Add (this.scrollSeleccionados);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.hbox5[this.scrollSeleccionados]));
w11.Position = 1;
w11.Expand = false;
w11.Fill = false;
this.vbox7.Add (this.hbox5);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.hbox5]));
w12.Position = 1;
this.pnePrimcipal.Add (this.vbox7);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.pnePrimcipal[this.vbox7]));
w13.Position = 1;
this.vbox1.Add (this.pnePrimcipal);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.pnePrimcipal]));
w14.Position = 1;
// Container child vbox1.Gtk.Box+BoxChild
this.hbuttonbox2 = new global::Gtk.HButtonBox ();
this.hbuttonbox2.Name = "hbuttonbox2";
this.hbuttonbox2.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnAbrirCajon = new global::Gtk.Button ();
this.btnAbrirCajon.CanFocus = true;
this.btnAbrirCajon.Name = "btnAbrirCajon";
// Container child btnAbrirCajon.Gtk.Container+ContainerChild
this.vbox166 = new global::Gtk.VBox ();
this.vbox166.Name = "vbox166";
this.vbox166.Spacing = 7;
// Container child vbox166.Gtk.Box+BoxChild
this.image32 = new global::Gtk.Image ();
this.image32.Name = "image32";
this.image32.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.STARTUP.ICO");
this.vbox166.Add (this.image32);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.vbox166[this.image32]));
w15.Position = 0;
// Container child vbox166.Gtk.Box+BoxChild
this.label6 = new global::Gtk.Label ();
this.label6.Name = "label6";
this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Abrir</big>\n <small>cajon</small>");
this.label6.UseMarkup = true;
this.vbox166.Add (this.label6);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.vbox166[this.label6]));
w16.Position = 1;
w16.Expand = false;
w16.Fill = false;
this.btnAbrirCajon.Add (this.vbox166);
this.btnAbrirCajon.Label = null;
this.hbuttonbox2.Add (this.btnAbrirCajon);
global::Gtk.ButtonBox.ButtonBoxChild w18 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnAbrirCajon]));
w18.Expand = false;
w18.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnDesglose = new global::Gtk.Button ();
this.btnDesglose.CanFocus = true;
this.btnDesglose.Name = "btnDesglose";
// Container child btnDesglose.Gtk.Container+ContainerChild
this.vbox163 = new global::Gtk.VBox ();
this.vbox163.Name = "vbox163";
this.vbox163.Spacing = 7;
// Container child vbox163.Gtk.Box+BoxChild
this.image30 = new global::Gtk.Image ();
this.image30.Name = "image30";
this.image30.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.M00B.ICO");
this.vbox163.Add (this.image30);
global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.vbox163[this.image30]));
w19.Position = 0;
// Container child vbox163.Gtk.Box+BoxChild
this.label3 = new global::Gtk.Label ();
this.label3.Name = "label3";
this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Desglose</big>");
this.label3.UseMarkup = true;
this.vbox163.Add (this.label3);
global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.vbox163[this.label3]));
w20.Position = 1;
w20.Expand = false;
w20.Fill = false;
this.btnDesglose.Add (this.vbox163);
this.btnDesglose.Label = null;
this.hbuttonbox2.Add (this.btnDesglose);
global::Gtk.ButtonBox.ButtonBoxChild w22 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnDesglose]));
w22.Position = 1;
w22.Expand = false;
w22.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnCamareros = new global::Gtk.Button ();
this.btnCamareros.CanFocus = true;
this.btnCamareros.Name = "btnCamareros";
// Container child btnCamareros.Gtk.Container+ContainerChild
this.vbox165 = new global::Gtk.VBox ();
this.vbox165.Name = "vbox165";
this.vbox165.Spacing = 7;
// Container child vbox165.Gtk.Box+BoxChild
this.image31 = new global::Gtk.Image ();
this.image31.Name = "image31";
this.image31.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.NET14.ICO");
this.vbox165.Add (this.image31);
global::Gtk.Box.BoxChild w23 = ((global::Gtk.Box.BoxChild)(this.vbox165[this.image31]));
w23.Position = 0;
// Container child vbox165.Gtk.Box+BoxChild
this.label5 = new global::Gtk.Label ();
this.label5.Name = "label5";
this.label5.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Calculo</big>\n<small>Camareros</small>");
this.label5.UseMarkup = true;
this.vbox165.Add (this.label5);
global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.vbox165[this.label5]));
w24.Position = 1;
w24.Expand = false;
w24.Fill = false;
this.btnCamareros.Add (this.vbox165);
this.btnCamareros.Label = null;
this.hbuttonbox2.Add (this.btnCamareros);
global::Gtk.ButtonBox.ButtonBoxChild w26 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnCamareros]));
w26.Position = 2;
w26.Expand = false;
w26.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnHoras = new global::Gtk.Button ();
this.btnHoras.CanFocus = true;
this.btnHoras.Name = "btnHoras";
// Container child btnHoras.Gtk.Container+ContainerChild
this.vbox161 = new global::Gtk.VBox ();
this.vbox161.Name = "vbox161";
this.vbox161.Spacing = 7;
// Container child vbox161.Gtk.Box+BoxChild
this.vbox164 = new global::Gtk.VBox ();
this.vbox164.Name = "vbox164";
this.vbox164.Spacing = 7;
// Container child vbox164.Gtk.Box+BoxChild
this.image28 = new global::Gtk.Image ();
this.image28.Name = "image28";
this.image28.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.SCHED06B.ICO");
this.vbox164.Add (this.image28);
global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.vbox164[this.image28]));
w27.Position = 0;
// Container child vbox164.Gtk.Box+BoxChild
this.label4 = new global::Gtk.Label ();
this.label4.Name = "label4";
this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Calculo</big>\n <small>Horas</small>");
this.label4.UseMarkup = true;
this.vbox164.Add (this.label4);
global::Gtk.Box.BoxChild w28 = ((global::Gtk.Box.BoxChild)(this.vbox164[this.label4]));
w28.Position = 1;
w28.Expand = false;
w28.Fill = false;
this.vbox161.Add (this.vbox164);
global::Gtk.Box.BoxChild w29 = ((global::Gtk.Box.BoxChild)(this.vbox161[this.vbox164]));
w29.Position = 0;
this.btnHoras.Add (this.vbox161);
this.btnHoras.Label = null;
this.hbuttonbox2.Add (this.btnHoras);
global::Gtk.ButtonBox.ButtonBoxChild w31 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnHoras]));
w31.Position = 3;
w31.Expand = false;
w31.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnImprimir = new global::Gtk.Button ();
this.btnImprimir.CanFocus = true;
this.btnImprimir.Name = "btnImprimir";
// Container child btnImprimir.Gtk.Container+ContainerChild
this.vbox160 = new global::Gtk.VBox ();
this.vbox160.Name = "vbox160";
this.vbox160.Spacing = 7;
// Container child vbox160.Gtk.Box+BoxChild
this.image27 = new global::Gtk.Image ();
this.image27.Name = "image27";
this.image27.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-print-preview", global::Gtk.IconSize.Dialog);
this.vbox160.Add (this.image27);
global::Gtk.Box.BoxChild w32 = ((global::Gtk.Box.BoxChild)(this.vbox160[this.image27]));
w32.Position = 0;
this.btnImprimir.Add (this.vbox160);
this.btnImprimir.Label = null;
this.hbuttonbox2.Add (this.btnImprimir);
global::Gtk.ButtonBox.ButtonBoxChild w34 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnImprimir]));
w34.Position = 4;
w34.Expand = false;
w34.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnMas = new global::Gtk.Button ();
this.btnMas.CanFocus = true;
this.btnMas.Name = "btnMas";
// Container child btnMas.Gtk.Container+ContainerChild
this.vbox159 = new global::Gtk.VBox ();
this.vbox159.Name = "vbox159";
this.vbox159.Spacing = 7;
// Container child vbox159.Gtk.Box+BoxChild
this.image26 = new global::Gtk.Image ();
this.image26.Name = "image26";
this.image26.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-add", global::Gtk.IconSize.Dialog);
this.vbox159.Add (this.image26);
global::Gtk.Box.BoxChild w35 = ((global::Gtk.Box.BoxChild)(this.vbox159[this.image26]));
w35.Position = 0;
// Container child vbox159.Gtk.Box+BoxChild
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString (" <big>Mas</big>\n<small>Cierres</small>");
this.label1.UseMarkup = true;
this.vbox159.Add (this.label1);
global::Gtk.Box.BoxChild w36 = ((global::Gtk.Box.BoxChild)(this.vbox159[this.label1]));
w36.Position = 1;
w36.Expand = false;
w36.Fill = false;
this.btnMas.Add (this.vbox159);
this.btnMas.Label = null;
this.hbuttonbox2.Add (this.btnMas);
global::Gtk.ButtonBox.ButtonBoxChild w38 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnMas]));
w38.Position = 5;
w38.Expand = false;
w38.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnCierre = new global::Gtk.Button ();
this.btnCierre.WidthRequest = 100;
this.btnCierre.HeightRequest = 100;
this.btnCierre.CanFocus = true;
this.btnCierre.Name = "btnCierre";
// Container child btnCierre.Gtk.Container+ContainerChild
this.vbox162 = new global::Gtk.VBox ();
this.vbox162.Name = "vbox162";
this.vbox162.Spacing = 7;
// Container child vbox162.Gtk.Box+BoxChild
this.image29 = new global::Gtk.Image ();
this.image29.Name = "image29";
this.image29.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.euro.png");
this.vbox162.Add (this.image29);
global::Gtk.Box.BoxChild w39 = ((global::Gtk.Box.BoxChild)(this.vbox162[this.image29]));
w39.Position = 0;
// Container child vbox162.Gtk.Box+BoxChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Cerrar</big>\n <small>caja</small>");
this.label2.UseMarkup = true;
this.vbox162.Add (this.label2);
global::Gtk.Box.BoxChild w40 = ((global::Gtk.Box.BoxChild)(this.vbox162[this.label2]));
w40.Position = 1;
w40.Expand = false;
w40.Fill = false;
this.btnCierre.Add (this.vbox162);
this.btnCierre.Label = null;
this.hbuttonbox2.Add (this.btnCierre);
global::Gtk.ButtonBox.ButtonBoxChild w42 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnCierre]));
w42.Position = 6;
w42.Expand = false;
w42.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnSalir = new global::Gtk.Button ();
this.btnSalir.CanFocus = true;
this.btnSalir.Name = "btnSalir";
this.btnSalir.UseUnderline = true;
// Container child btnSalir.Gtk.Container+ContainerChild
global::Gtk.Alignment w43 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w44 = new global::Gtk.HBox ();
w44.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w45 = new global::Gtk.Image ();
w45.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Dialog);
w44.Add (w45);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w47 = new global::Gtk.Label ();
w44.Add (w47);
w43.Add (w44);
this.btnSalir.Add (w43);
this.hbuttonbox2.Add (this.btnSalir);
global::Gtk.ButtonBox.ButtonBoxChild w51 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnSalir]));
w51.Position = 7;
w51.Expand = false;
w51.Fill = false;
this.vbox1.Add (this.hbuttonbox2);
global::Gtk.Box.BoxChild w52 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbuttonbox2]));
w52.Position = 2;
w52.Expand = false;
// Container child vbox1.Gtk.Box+BoxChild
this.barImformacion = new global::Gtk.ProgressBar ();
this.barImformacion.Name = "barImformacion";
this.vbox1.Add (this.barImformacion);
global::Gtk.Box.BoxChild w53 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.barImformacion]));
w53.Position = 3;
w53.Expand = false;
w53.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.scrollSeleccionados.wScroll = this.GtkScrolledSelecionados;
this.scrollOriginal.wScroll = this.GtkScrolledOriginal;
this.WindowPosition = Gtk.WindowPosition.CenterAlways;
this.SetSizeRequest(800,600);
this.btnDesglose.Visible = false;
this.lstCierres.CursorChanged += new global::System.EventHandler (this.lstCierres_SelectedIndexChanged);
this.btnAbrirCajon.Clicked += new global::System.EventHandler (this.OnBtnAbrirCajonClicked);
this.btnDesglose.Clicked += new global::System.EventHandler (this.OnBtnDesgloseClicked);
this.btnCamareros.Clicked += new global::System.EventHandler (this.OnBtnCamarerosClicked);
this.btnHoras.Clicked += new global::System.EventHandler (this.OnBtnHorasClicked);
this.btnImprimir.Clicked += new global::System.EventHandler (this.OnBtnImprimirClicked);
this.btnMas.Clicked += new global::System.EventHandler (this.OnBtnMasClicked);
this.btnCierre.Clicked += new global::System.EventHandler (this.OnBtnCierreClicked);
this.btnSalir.Clicked += new global::System.EventHandler (this.OnBtnSalirClicked);
}
}
}
| |
using Foundation;
using System;
using System.Diagnostics;
using UIKit;
using System.Net;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace DurianCode.iOS.Places
{
public delegate void PlaceSelected(object sender, JObject locationData);
public enum PlaceType
{
All, Geocode, Address, Establishment, Regions, Cities
}
public class LocationBias
{
public readonly double latitude;
public readonly double longitude;
public readonly int radius;
public LocationBias(double latitude, double longitude, int radius)
{
this.latitude = latitude;
this.longitude = longitude;
this.radius = radius;
}
public override string ToString()
{
return $"&location={latitude},{longitude}&radius={radius}";
}
}
public class LocationObject
{
public double lat { get; set; }
public double lon { get; set; }
public string placeName { get; set; }
public string placeID { get; set; }
}
public partial class PlacesViewController : UIViewController
{
public PlacesViewController(IntPtr handle) : base(handle) { }
public PlacesViewController() { }
public UIView backgroundView;
UISearchBar searchBar;
UIImageView googleAttribution;
UITableView resultsTable;
UITableViewSource tableSource;
public string apiKey { get; set; }
LocationBias locationBias;
string CustomPlaceType;
public event PlaceSelected PlaceSelected;
public override void ViewDidLoad()
{
base.ViewDidLoad();
EdgesForExtendedLayout = UIRectEdge.None;
backgroundView = new UIView(View.Frame);
backgroundView.BackgroundColor = UIColor.White;
View.AddSubview(backgroundView);
searchBar = new UISearchBar();
searchBar.TranslatesAutoresizingMaskIntoConstraints = false;
searchBar.ReturnKeyType = UIReturnKeyType.Done;
View.AddSubview(searchBar);
AddSearchBarConstraints();
searchBar.BecomeFirstResponder();
// TODO - add 'powered by google' attribution image before resultsTable
googleAttribution = new UIImageView();
googleAttribution.Image = UIImage.FromBundle("powered_by_google_on_white");
googleAttribution.TranslatesAutoresizingMaskIntoConstraints = false;
googleAttribution.ContentMode = UIViewContentMode.ScaleAspectFit;
View.AddSubview(googleAttribution);
AddAttributionConstraints();
resultsTable = new UITableView();
tableSource = new ResultsTableSource();
resultsTable.TranslatesAutoresizingMaskIntoConstraints = false;
resultsTable.Source = tableSource;
((ResultsTableSource)resultsTable.Source).apiKey = apiKey;
((ResultsTableSource)resultsTable.Source).RowItemSelected += OnPlaceSelection;
View.AddSubview(resultsTable);
AddResultsTableConstraints();
searchBar.TextChanged += SearchInputChanged;
resultsTable.Hidden = true;
NavigationItem.SetLeftBarButtonItem(
new UIBarButtonItem(UIBarButtonSystemItem.Stop, (sender, args) =>
{
DismissViewController(true, null);
}), true);
}
void AddSearchBarConstraints()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
var sbLeft = searchBar.LeftAnchor.ConstraintEqualTo(View.LeftAnchor);
var sbRight = searchBar.RightAnchor.ConstraintEqualTo(View.RightAnchor);
var sbTop = searchBar.TopAnchor.ConstraintEqualTo(View.TopAnchor);
var sbHeight = searchBar.HeightAnchor.ConstraintEqualTo(45.0f);
NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]
{
sbLeft, sbRight, sbTop, sbHeight
});
UpdateViewConstraints();
}
else
{
searchBar.Frame = new CoreGraphics.CGRect(0, 0, View.Frame.Width, 45.0f);
}
}
void AddAttributionConstraints()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
var gaTop = NSLayoutConstraint.Create(googleAttribution,
NSLayoutAttribute.Top,
NSLayoutRelation.Equal,
searchBar,
NSLayoutAttribute.Bottom,
1, 30.0f);
var gaCenterX = googleAttribution.CenterXAnchor.ConstraintEqualTo(View.CenterXAnchor);
var gaWidth = googleAttribution.WidthAnchor.ConstraintEqualTo(100.0f);
var gaHeight = googleAttribution.HeightAnchor.ConstraintEqualTo(20.0f);
NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]
{
gaTop, gaCenterX, gaWidth, gaHeight
});
UpdateViewConstraints();
}
else
{
googleAttribution.Frame = new CoreGraphics.CGRect(
(View.Frame.Width / 2) - (100 / 2),
searchBar.Frame.Bottom + 30,
100,
20);
}
}
void AddResultsTableConstraints()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
var rtLeft = resultsTable.LeftAnchor.ConstraintEqualTo(View.LeftAnchor);
var rtRight = resultsTable.RightAnchor.ConstraintEqualTo(View.RightAnchor);
var rtTop = resultsTable.TopAnchor.ConstraintEqualTo(searchBar.BottomAnchor);
var rtBottom = resultsTable.BottomAnchor.ConstraintEqualTo(View.BottomAnchor);
NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]
{
rtLeft, rtRight, rtTop, rtBottom
});
UpdateViewConstraints();
}
else
{
resultsTable.Frame = new CoreGraphics.CGRect(0, 45.0f, View.Frame.Width, View.Frame.Height - 45.0f);
}
}
public void SetLocationBias(LocationBias locationBias)
{
this.locationBias = locationBias;
}
public void SetPlaceType(PlaceType placeType)
{
switch (placeType)
{
case PlaceType.All:
CustomPlaceType = "";
break;
case PlaceType.Geocode:
CustomPlaceType = "geocode";
break;
case PlaceType.Address:
CustomPlaceType = "address";
break;
case PlaceType.Establishment:
CustomPlaceType = "establishment";
break;
case PlaceType.Regions:
CustomPlaceType = "(regions)";
break;
case PlaceType.Cities:
CustomPlaceType = "(cities)";
break;
}
}
async void SearchInputChanged(object sender, UISearchBarTextChangedEventArgs e)
{
if (e.SearchText == "")
{
resultsTable.Hidden = true;
}
else
{
resultsTable.Hidden = false;
var predictions = await GetPlaces(e.SearchText);
UpdateTableWithPredictions(predictions);
}
}
async Task<string> GetPlaces(string searchText)
{
if (searchText == "")
return "";
var requestURI = CreatePredictionsUri(searchText);
try
{
WebRequest request = WebRequest.Create(requestURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = await request.GetResponseAsync();
string responseStream = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseStream = sr.ReadToEnd();
}
response.Close();
return responseStream;
}
catch
{
Debug.WriteLine("Something's going wrong with my HTTP request");
return "ERROR";
}
}
void UpdateTableWithPredictions(string predictions)
{
if (predictions == "")
return;
if (predictions == "ERROR")
return; // TODO - handle this better
var deserializedPredictions = JsonConvert.DeserializeObject<LocationPredictions>(predictions);
((ResultsTableSource)resultsTable.Source).predictions = deserializedPredictions;
resultsTable.ReloadData();
}
protected virtual void OnPlaceSelection(object sender, JObject location)
{
if (PlaceSelected != null)
PlaceSelected(this, location);
DismissViewController(true, null);
}
string CreatePredictionsUri(string searchText)
{
var url = "https://maps.googleapis.com/maps/api/place/autocomplete/json";
var input = Uri.EscapeUriString(searchText);
var pType = "";
if (CustomPlaceType != null)
pType = CustomPlaceType;
var constructedUrl = $"{url}?input={input}&types={pType}&key={apiKey}";
if (this.locationBias != null)
constructedUrl = constructedUrl + locationBias;
Console.WriteLine(constructedUrl);
return constructedUrl;
}
}
public class ResultsTableSource : UITableViewSource
{
public LocationPredictions predictions { get; set; }
const string cellIdentifier = "TableCell";
public event PlaceSelected RowItemSelected;
public string apiKey { get; set; }
public ResultsTableSource()
{
predictions = new LocationPredictions();
}
public ResultsTableSource(LocationPredictions predictions)
{
this.predictions = predictions;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
if (predictions.Predictions != null)
return predictions.Predictions.Count;
return 0;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
if (cell == null)
cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier);
cell.TextLabel.Text = predictions.Predictions[indexPath.Row].Description;
return cell;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
var selectedPrediction = predictions.Predictions[indexPath.Row].Place_ID;
ReturnPlaceDetails(selectedPrediction);
}
async void ReturnPlaceDetails(string selectionID)
{
try
{
WebRequest request = WebRequest.Create(CreateDetailsRequestUri(selectionID));
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = await request.GetResponseAsync();
string responseStream = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseStream = sr.ReadToEnd();
}
response.Close();
JObject jObject = JObject.Parse(responseStream);
if (jObject != null && RowItemSelected != null)
RowItemSelected(this, jObject);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
string CreateDetailsRequestUri(string place_id)
{
var url = "https://maps.googleapis.com/maps/api/place/details/json";
return $"{url}?placeid={Uri.EscapeUriString(place_id)}&key={apiKey}";
}
}
}
| |
#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;
using System.Text;
using System.IO;
using System.Xml;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies the state of the <see cref="JsonWriter"/>.
/// </summary>
public enum WriteState
{
/// <summary>
/// An exception has been thrown, which has left the <see cref="JsonWriter"/> in an invalid state.
/// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state.
/// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown.
/// </summary>
Error,
/// <summary>
/// The <see cref="JsonWriter.Close"/> method has been called.
/// </summary>
Closed,
/// <summary>
/// An object is being written.
/// </summary>
Object,
/// <summary>
/// A array is being written.
/// </summary>
Array,
/// <summary>
/// A constructor is being written.
/// </summary>
Constructor,
/// <summary>
/// A property is being written.
/// </summary>
Property,
/// <summary>
/// A write method has not been called.
/// </summary>
Start
}
/// <summary>
/// Specifies formatting options for the <see cref="JsonTextWriter"/>.
/// </summary>
public enum Formatting
{
/// <summary>
/// No special formatting is applied. This is the default.
/// </summary>
None,
/// <summary>
/// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings.
/// </summary>
Indented
}
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
private enum State
{
Start,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Bytes,
Closed,
Error
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] stateArray = new[] {
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* StartProperty */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
};
private int _top;
private readonly List<JTokenType> _stack;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get { return _top; }
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw new JsonWriterException("Invalid state: " + _currentState);
}
}
}
/// <summary>
/// Indicates how the output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set { _formatting = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_stack = new List<JTokenType>(8);
_stack.Add(JTokenType.None);
_currentState = State.Start;
_formatting = Formatting.None;
CloseOutput = true;
}
private void Push(JTokenType value)
{
_top++;
if (_stack.Count <= _top)
_stack.Add(value);
else
_stack[_top] = value;
}
private JTokenType Pop()
{
JTokenType value = Peek();
_top--;
return value;
}
private JTokenType Peek()
{
return _stack[_top];
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public virtual void WriteStartObject()
{
AutoComplete(JsonToken.StartObject);
Push(JTokenType.Object);
}
/// <summary>
/// Writes the end of a Json object.
/// </summary>
public virtual void WriteEndObject()
{
AutoCompleteClose(JsonToken.EndObject);
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public virtual void WriteStartArray()
{
AutoComplete(JsonToken.StartArray);
Push(JTokenType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
AutoCompleteClose(JsonToken.EndArray);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
AutoComplete(JsonToken.StartConstructor);
Push(JTokenType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
AutoCompleteClose(JsonToken.EndConstructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
AutoComplete(JsonToken.PropertyName);
}
/// <summary>
/// Writes the end of the current Json object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth);
}
internal void WriteToken(JsonReader reader, int initialDepth)
{
do
{
switch (reader.TokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
// write a JValue date when the constructor is for a date
if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0)
WriteConstructorDate(reader);
else
WriteStartConstructor(reader.Value.ToString());
break;
case JsonToken.PropertyName:
WritePropertyName(reader.Value.ToString());
break;
case JsonToken.Comment:
WriteComment(reader.Value.ToString());
break;
case JsonToken.Integer:
WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Float:
WriteValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
WriteValue(reader.Value.ToString());
break;
case JsonToken.Boolean:
WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
WriteValue((DateTime)reader.Value);
break;
case JsonToken.Raw:
WriteRawValue((string)reader.Value);
break;
case JsonToken.Bytes:
WriteValue((byte[])reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
}
}
while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
&& reader.Read());
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.Integer)
throw new Exception("Unexpected token while reading date constructor. Expected Integer, got " + reader.TokenType);
long ticks = (long)reader.Value;
DateTime date = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.EndConstructor)
throw new Exception("Unexpected token while reading date constructor. Expected EndConstructor, got " + reader.TokenType);
WriteValue(date);
}
private bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
private bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
WriteEndObject();
break;
case JTokenType.Array:
WriteEndArray();
break;
case JTokenType.Constructor:
WriteEndConstructor();
break;
default:
throw new JsonWriterException("Unexpected type when writing end: " + type);
}
}
private void AutoCompleteAll()
{
while (_top > 0)
{
WriteEnd();
}
}
private JTokenType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JTokenType.Object;
case JsonToken.EndArray:
return JTokenType.Array;
case JsonToken.EndConstructor:
return JTokenType.Constructor;
default:
throw new JsonWriterException("No type for token: " + token);
}
}
private JsonToken GetCloseTokenForType(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
return JsonToken.EndObject;
case JTokenType.Array:
return JsonToken.EndArray;
case JTokenType.Constructor:
return JsonToken.EndConstructor;
default:
throw new JsonWriterException("No close token for type: " + type);
}
}
private void AutoCompleteClose(JsonToken tokenBeingClosed)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
for (int i = 0; i < _top; i++)
{
int currentLevel = _top - i;
if (_stack[currentLevel] == GetTypeForCloseToken(tokenBeingClosed))
{
levelsToComplete = i + 1;
break;
}
}
if (levelsToComplete == 0)
throw new JsonWriterException("No token to close.");
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
WriteIndent();
WriteEnd(token);
}
JTokenType currentLevelType = Peek();
switch (currentLevelType)
{
case JTokenType.Object:
_currentState = State.Object;
break;
case JTokenType.Array:
_currentState = State.Array;
break;
case JTokenType.Constructor:
_currentState = State.Array;
break;
case JTokenType.None:
_currentState = State.Start;
break;
default:
throw new JsonWriterException("Unknown JsonType: " + currentLevelType);
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
int token;
switch (tokenBeingWritten)
{
default:
token = (int)tokenBeingWritten;
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
// a value is being written
token = 7;
break;
}
// gets new state based on the current state and what is being written
State newState = stateArray[token][(int)_currentState];
if (newState == State.Error)
throw new JsonWriterException("Token {0} in state {1} would result in an invalid JavaScript object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()));
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
else if (_currentState == State.Property)
{
if (_formatting == Formatting.Indented)
WriteIndentSpace();
}
WriteState writeState = WriteState;
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((tokenBeingWritten == JsonToken.PropertyName && writeState != WriteState.Start) ||
writeState == WriteState.Array || writeState == WriteState.Constructor)
{
WriteIndent();
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
AutoComplete(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
AutoComplete(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
AutoComplete(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
AutoComplete(JsonToken.Date);
}
#if !PocketPC && !NET20
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
AutoComplete(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#if !PocketPC && !NET20
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
WriteNull();
else
AutoComplete(JsonToken.Bytes);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
WriteNull();
else
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
return;
}
else if (value is IConvertible)
{
IConvertible convertible = value as IConvertible;
switch (convertible.GetTypeCode())
{
case TypeCode.String:
WriteValue(convertible.ToString(CultureInfo.InvariantCulture));
return;
case TypeCode.Char:
WriteValue(convertible.ToChar(CultureInfo.InvariantCulture));
return;
case TypeCode.Boolean:
WriteValue(convertible.ToBoolean(CultureInfo.InvariantCulture));
return;
case TypeCode.SByte:
WriteValue(convertible.ToSByte(CultureInfo.InvariantCulture));
return;
case TypeCode.Int16:
WriteValue(convertible.ToInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt16:
WriteValue(convertible.ToUInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.Int32:
WriteValue(convertible.ToInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Byte:
WriteValue(convertible.ToByte(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt32:
WriteValue(convertible.ToUInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Int64:
WriteValue(convertible.ToInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt64:
WriteValue(convertible.ToUInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.Single:
WriteValue(convertible.ToSingle(CultureInfo.InvariantCulture));
return;
case TypeCode.Double:
WriteValue(convertible.ToDouble(CultureInfo.InvariantCulture));
return;
case TypeCode.DateTime:
WriteValue(convertible.ToDateTime(CultureInfo.InvariantCulture));
return;
case TypeCode.Decimal:
WriteValue(convertible.ToDecimal(CultureInfo.InvariantCulture));
return;
case TypeCode.DBNull:
WriteNull();
return;
}
}
#if !PocketPC && !NET20
else if (value is DateTimeOffset)
{
WriteValue((DateTimeOffset)value);
return;
}
#endif
else if (value is byte[])
{
WriteValue((byte[])value);
return;
}
else if (value is Guid)
{
WriteValue((Guid)value);
return;
}
else if (value is Uri)
{
WriteValue((Uri)value);
return;
}
else if (value is TimeSpan)
{
WriteValue((TimeSpan)value);
return;
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
AutoComplete(JsonToken.Comment);
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
throw new JsonWriterException("Only white space characters should be used.");
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (WriteState != WriteState.Closed)
Close();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Permissions;
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks.AssemblyDependency;
namespace Microsoft.Build.Tasks
{
/// <summary>
/// Class is used to cache system state.
/// </summary>
[Serializable]
internal sealed class SystemState : StateFileBase, ISerializable
{
/// <summary>
/// Cache at the SystemState instance level. Has the same contents as <see cref="instanceLocalFileStateCache"/>.
/// It acts as a flag to enforce that an entry has been checked for staleness only once.
/// </summary>
private Dictionary<string, FileState> upToDateLocalFileStateCache = new Dictionary<string, FileState>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Cache at the SystemState instance level. It is serialized and reused between instances.
/// </summary>
private Hashtable instanceLocalFileStateCache = new Hashtable(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// LastModified information is purely instance-local. It doesn't make sense to
/// cache this for long periods of time since there's no way (without actually
/// calling File.GetLastWriteTimeUtc) to tell whether the cache is out-of-date.
/// </summary>
private Dictionary<string, DateTime> instanceLocalLastModifiedCache = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// DirectoryExists information is purely instance-local. It doesn't make sense to
/// cache this for long periods of time since there's no way (without actually
/// calling Directory.Exists) to tell whether the cache is out-of-date.
/// </summary>
private Dictionary<string, bool> instanceLocalDirectoryExists = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// GetDirectories information is also purely instance-local. This information
/// is only considered good for the lifetime of the task (or whatever) that owns
/// this instance.
/// </summary>
private Dictionary<string, string[]> instanceLocalDirectories = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Additional level of caching kept at the process level.
/// </summary>
private static ConcurrentDictionary<string, FileState> s_processWideFileStateCache = new ConcurrentDictionary<string, FileState>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// XML tables of installed assemblies.
/// </summary>
private RedistList redistList;
/// <summary>
/// True if the contents have changed.
/// </summary>
private bool isDirty;
/// <summary>
/// Delegate used internally.
/// </summary>
private GetLastWriteTime getLastWriteTime;
/// <summary>
/// Cached delegate.
/// </summary>
private GetAssemblyName getAssemblyName;
/// <summary>
/// Cached delegate.
/// </summary>
private GetAssemblyMetadata getAssemblyMetadata;
/// <summary>
/// Cached delegate.
/// </summary>
private FileExists fileExists;
/// <summary>
/// Cached delegate.
/// </summary>
private DirectoryExists directoryExists;
/// <summary>
/// Cached delegate.
/// </summary>
private GetDirectories getDirectories;
/// <summary>
/// Cached delegate
/// </summary>
private GetAssemblyRuntimeVersion getAssemblyRuntimeVersion;
/// <summary>
/// Class that holds the current file state.
/// </summary>
[Serializable]
private sealed class FileState : ISerializable
{
/// <summary>
/// The last modified time for this file.
/// </summary>
private DateTime lastModified;
/// <summary>
/// The fusion name of this file.
/// </summary>
private AssemblyNameExtension assemblyName;
/// <summary>
/// The assemblies that this file depends on.
/// </summary>
internal AssemblyNameExtension[] dependencies;
/// <summary>
/// The scatter files associated with this assembly.
/// </summary>
internal string[] scatterFiles;
/// <summary>
/// FrameworkName the file was built against
/// </summary>
internal FrameworkName frameworkName;
/// <summary>
/// The CLR runtime version for the assembly.
/// </summary>
internal string runtimeVersion;
/// <summary>
/// Default construct.
/// </summary>
internal FileState(DateTime lastModified)
{
this.lastModified = lastModified;
}
/// <summary>
/// Deserializing constuctor.
/// </summary>
internal FileState(SerializationInfo info, StreamingContext context)
{
ErrorUtilities.VerifyThrowArgumentNull(info, nameof(info));
lastModified = new DateTime(info.GetInt64("mod"), (DateTimeKind)info.GetInt32("modk"));
assemblyName = (AssemblyNameExtension)info.GetValue("an", typeof(AssemblyNameExtension));
dependencies = (AssemblyNameExtension[])info.GetValue("deps", typeof(AssemblyNameExtension[]));
scatterFiles = (string[])info.GetValue("sfiles", typeof(string[]));
runtimeVersion = (string)info.GetValue("rtver", typeof(string));
if (info.GetBoolean("fn"))
{
var frameworkNameVersion = (Version) info.GetValue("fnVer", typeof(Version));
var frameworkIdentifier = info.GetString("fnId");
var frameworkProfile = info.GetString("fmProf");
frameworkName = new FrameworkName(frameworkIdentifier, frameworkNameVersion, frameworkProfile);
}
}
/// <summary>
/// Serialize the contents of the class.
/// </summary>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
ErrorUtilities.VerifyThrowArgumentNull(info, nameof(info));
info.AddValue("mod", lastModified.Ticks);
info.AddValue("modk", (int)lastModified.Kind);
info.AddValue("an", assemblyName);
info.AddValue("deps", dependencies);
info.AddValue("sfiles", scatterFiles);
info.AddValue("rtver", runtimeVersion);
info.AddValue("fn", frameworkName != null);
if (frameworkName != null)
{
info.AddValue("fnVer", frameworkName.Version);
info.AddValue("fnId", frameworkName.Identifier);
info.AddValue("fmProf", frameworkName.Profile);
}
}
/// <summary>
/// Gets the last modified date.
/// </summary>
/// <value></value>
internal DateTime LastModified
{
get { return lastModified; }
}
/// <summary>
/// Get or set the assemblyName.
/// </summary>
/// <value></value>
internal AssemblyNameExtension Assembly
{
get { return assemblyName; }
set { assemblyName = value; }
}
/// <summary>
/// Get or set the runtimeVersion
/// </summary>
/// <value></value>
internal string RuntimeVersion
{
get { return runtimeVersion; }
set { runtimeVersion = value; }
}
/// <summary>
/// Get or set the framework name the file was built against
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Could be used in other assemblies")]
internal FrameworkName FrameworkNameAttribute
{
get { return frameworkName; }
set { frameworkName = value; }
}
}
/// <summary>
/// Construct.
/// </summary>
internal SystemState()
{
}
/// <summary>
/// Deserialize the contents of the class.
/// </summary>
internal SystemState(SerializationInfo info, StreamingContext context)
{
ErrorUtilities.VerifyThrowArgumentNull(info, nameof(info));
instanceLocalFileStateCache = (Hashtable)info.GetValue("fileState", typeof(Hashtable));
isDirty = false;
}
/// <summary>
/// Set the target framework paths.
/// This is used to optimize IO in the case of files requested from one
/// of the FX folders.
/// </summary>
/// <param name="installedAssemblyTableInfos">List of Assembly Table Info.</param>
internal void SetInstalledAssemblyInformation
(
AssemblyTableInfo[] installedAssemblyTableInfos
)
{
redistList = RedistList.GetRedistList(installedAssemblyTableInfos);
}
/// <summary>
/// Serialize the contents of the class.
/// </summary>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
ErrorUtilities.VerifyThrowArgumentNull(info, nameof(info));
info.AddValue("fileState", instanceLocalFileStateCache);
}
/// <summary>
/// Flag that indicates
/// </summary>
/// <value></value>
internal bool IsDirty
{
get { return isDirty; }
}
/// <summary>
/// Set the GetLastWriteTime delegate.
/// </summary>
/// <param name="getLastWriteTimeValue">Delegate used to get the last write time.</param>
internal void SetGetLastWriteTime(GetLastWriteTime getLastWriteTimeValue)
{
getLastWriteTime = getLastWriteTimeValue;
}
/// <summary>
/// Cache the results of a GetAssemblyName delegate.
/// </summary>
/// <param name="getAssemblyNameValue">The delegate.</param>
/// <returns>Cached version of the delegate.</returns>
internal GetAssemblyName CacheDelegate(GetAssemblyName getAssemblyNameValue)
{
getAssemblyName = getAssemblyNameValue;
return GetAssemblyName;
}
/// <summary>
/// Cache the results of a GetAssemblyMetadata delegate.
/// </summary>
/// <param name="getAssemblyMetadataValue">The delegate.</param>
/// <returns>Cached version of the delegate.</returns>
internal GetAssemblyMetadata CacheDelegate(GetAssemblyMetadata getAssemblyMetadataValue)
{
getAssemblyMetadata = getAssemblyMetadataValue;
return GetAssemblyMetadata;
}
/// <summary>
/// Cache the results of a FileExists delegate.
/// </summary>
/// <param name="fileExistsValue">The delegate.</param>
/// <returns>Cached version of the delegate.</returns>
internal FileExists CacheDelegate(FileExists fileExistsValue)
{
fileExists = fileExistsValue;
return FileExists;
}
public DirectoryExists CacheDelegate(DirectoryExists directoryExistsValue)
{
directoryExists = directoryExistsValue;
return DirectoryExists;
}
/// <summary>
/// Cache the results of a GetDirectories delegate.
/// </summary>
/// <param name="getDirectoriesValue">The delegate.</param>
/// <returns>Cached version of the delegate.</returns>
internal GetDirectories CacheDelegate(GetDirectories getDirectoriesValue)
{
getDirectories = getDirectoriesValue;
return GetDirectories;
}
/// <summary>
/// Cache the results of a GetAssemblyRuntimeVersion delegate.
/// </summary>
/// <param name="getAssemblyRuntimeVersion">The delegate.</param>
/// <returns>Cached version of the delegate.</returns>
internal GetAssemblyRuntimeVersion CacheDelegate(GetAssemblyRuntimeVersion getAssemblyRuntimeVersion)
{
this.getAssemblyRuntimeVersion = getAssemblyRuntimeVersion;
return GetRuntimeVersion;
}
private FileState GetFileState(string path)
{
// Looking up an assembly to get its metadata can be expensive for projects that reference large amounts
// of assemblies. To avoid that expense, we remember and serialize this information betweeen runs in
// XXXResolveAssemblyReferencesInput.cache files in the intermediate directory and also store it in an
// process-wide cache to share between successive builds.
//
// To determine if this information is up-to-date, we use the last modified date of the assembly, however,
// as calls to GetLastWriteTime can add up over hundreds and hundreds of files, we only check for
// invalidation once per assembly per ResolveAssemblyReference session.
upToDateLocalFileStateCache.TryGetValue(path, out FileState state);
if (state == null)
{ // We haven't seen this file this ResolveAssemblyReference session
state = ComputeFileStateFromCachesAndDisk(path);
upToDateLocalFileStateCache[path] = state;
}
return state;
}
private FileState ComputeFileStateFromCachesAndDisk(string path)
{
DateTime lastModified = GetAndCacheLastModified(path);
FileState cachedInstanceFileState = (FileState)instanceLocalFileStateCache[path];
bool isCachedInInstance = cachedInstanceFileState != null;
bool isCachedInProcess =
s_processWideFileStateCache.TryGetValue(path, out FileState cachedProcessFileState);
bool isInstanceFileStateUpToDate = isCachedInInstance && lastModified == cachedInstanceFileState.LastModified;
bool isProcessFileStateUpToDate = isCachedInProcess && lastModified == cachedProcessFileState.LastModified;
// If the process-wide cache contains an up-to-date FileState, always use it
if (isProcessFileStateUpToDate)
{
// If a FileState already exists in this instance cache due to deserialization, remove it;
// another instance has taken responsibility for serialization, and keeping this would
// result in multiple instances serializing the same data to disk
if (isCachedInInstance)
{
instanceLocalFileStateCache.Remove(path);
isDirty = true;
}
return cachedProcessFileState;
}
// If the process-wide FileState is missing or out-of-date, this instance owns serialization;
// sync the process-wide cache and signal other instances to avoid data duplication
if (isInstanceFileStateUpToDate)
{
return s_processWideFileStateCache[path] = cachedInstanceFileState;
}
// If no up-to-date FileState exists at this point, create one and take ownership
return InitializeFileState(path, lastModified);
}
private DateTime GetAndCacheLastModified(string path)
{
if (!instanceLocalLastModifiedCache.TryGetValue(path, out DateTime lastModified))
{
lastModified = getLastWriteTime(path);
instanceLocalLastModifiedCache[path] = lastModified;
}
return lastModified;
}
private FileState InitializeFileState(string path, DateTime lastModified)
{
var fileState = new FileState(lastModified);
instanceLocalFileStateCache[path] = fileState;
s_processWideFileStateCache[path] = fileState;
isDirty = true;
return fileState;
}
/// <summary>
/// Cached implementation of GetAssemblyName.
/// </summary>
/// <param name="path">The path to the file</param>
/// <returns>The assembly name.</returns>
private AssemblyNameExtension GetAssemblyName(string path)
{
// If the assembly is in an FX folder and its a well-known assembly
// then we can short-circuit the File IO involved with GetAssemblyName()
if (redistList != null)
{
string extension = Path.GetExtension(path);
if (string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase))
{
IEnumerable<AssemblyEntry> assemblyNames = redistList.FindAssemblyNameFromSimpleName
(
Path.GetFileNameWithoutExtension(path)
);
string filename = Path.GetFileName(path);
foreach (AssemblyEntry a in assemblyNames)
{
string pathFromRedistList = Path.Combine(a.FrameworkDirectory, filename);
if (String.Equals(path, pathFromRedistList, StringComparison.OrdinalIgnoreCase))
{
return new AssemblyNameExtension(a.FullName);
}
}
}
}
// Not a well-known FX assembly so now check the cache.
FileState fileState = GetFileState(path);
if (fileState.Assembly == null)
{
fileState.Assembly = getAssemblyName(path);
// Certain assemblies, like mscorlib may not have metadata.
// Avoid continuously calling getAssemblyName on these files by
// recording these as having an empty name.
if (fileState.Assembly == null)
{
fileState.Assembly = AssemblyNameExtension.UnnamedAssembly;
}
isDirty = true;
}
if (fileState.Assembly.IsUnnamedAssembly)
{
return null;
}
return fileState.Assembly;
}
/// <summary>
/// Cached implementation. Given a path, crack it open and retrieve runtimeversion for the assembly.
/// </summary>
/// <param name="path">Path to the assembly.</param>
private string GetRuntimeVersion(string path)
{
FileState fileState = GetFileState(path);
if (String.IsNullOrEmpty(fileState.RuntimeVersion))
{
fileState.RuntimeVersion = getAssemblyRuntimeVersion(path);
isDirty = true;
}
return fileState.RuntimeVersion;
}
/// <summary>
/// Cached implementation. Given an assembly name, crack it open and retrieve the list of dependent
/// assemblies and the list of scatter files.
/// </summary>
/// <param name="path">Path to the assembly.</param>
/// <param name="assemblyMetadataCache">Cache for pre-extracted assembly metadata.</param>
/// <param name="dependencies">Receives the list of dependencies.</param>
/// <param name="scatterFiles">Receives the list of associated scatter files.</param>
/// <param name="frameworkName"></param>
private void GetAssemblyMetadata
(
string path,
ConcurrentDictionary<string, AssemblyMetadata> assemblyMetadataCache,
out AssemblyNameExtension[] dependencies,
out string[] scatterFiles,
out FrameworkName frameworkName
)
{
FileState fileState = GetFileState(path);
if (fileState.dependencies == null)
{
getAssemblyMetadata
(
path,
assemblyMetadataCache,
out fileState.dependencies,
out fileState.scatterFiles,
out fileState.frameworkName
);
isDirty = true;
}
dependencies = fileState.dependencies;
scatterFiles = fileState.scatterFiles;
frameworkName = fileState.frameworkName;
}
/// <summary>
/// Cached implementation of GetDirectories.
/// </summary>
/// <param name="path"></param>
/// <param name="pattern"></param>
/// <returns></returns>
private string[] GetDirectories(string path, string pattern)
{
// Only cache the *. pattern. This is by far the most common pattern
// and generalized caching would require a call to Path.Combine which
// is a string-copy.
if (pattern == "*")
{
instanceLocalDirectories.TryGetValue(path, out string[] cached);
if (cached == null)
{
string[] directories = getDirectories(path, pattern);
instanceLocalDirectories[path] = directories;
return directories;
}
return cached;
}
// This path is currently uncalled. Use assert to tell the dev that adds a new code-path
// that this is an unoptimized path.
Debug.Assert(false, "Using slow-path in SystemState.GetDirectories, was this intentional?");
return getDirectories(path, pattern);
}
/// <summary>
/// Cached implementation of FileExists.
/// </summary>
/// <param name="path">Path to file.</param>
/// <returns>True if the file exists.</returns>
private bool FileExists(string path)
{
DateTime lastModified = GetAndCacheLastModified(path);
return FileTimestampIndicatesFileExists(lastModified);
}
private bool FileTimestampIndicatesFileExists(DateTime lastModified)
{
// TODO: Standardize LastWriteTime value for nonexistent files. See https://github.com/Microsoft/msbuild/issues/3699
return lastModified != DateTime.MinValue && lastModified != NativeMethodsShared.MinFileDate;
}
/// <summary>
/// Cached implementation of DirectoryExists.
/// </summary>
/// <param name="path">Path to file.</param>
/// <returns>True if the directory exists.</returns>
private bool DirectoryExists(string path)
{
if (instanceLocalDirectoryExists.TryGetValue(path, out bool flag))
{
return flag;
}
bool exists = directoryExists(path);
instanceLocalDirectoryExists[path] = exists;
return exists;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.GrainDirectory;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
public class TestGrain : Grain, ITestGrain
{
private string label;
private ILogger logger;
private IDisposable timer;
public TestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
if (this.GetPrimaryKeyLong() == -2)
throw new ArgumentException("Primary key cannot be -2 for this test case");
label = this.GetPrimaryKeyLong().ToString();
logger.Info("OnActivateAsync");
return base.OnActivateAsync();
}
public override Task OnDeactivateAsync()
{
logger.Info("!!! OnDeactivateAsync");
return base.OnDeactivateAsync();
}
public Task<long> GetKey()
{
return Task.FromResult(this.GetPrimaryKeyLong());
}
public Task<string> GetLabel()
{
return Task.FromResult(label);
}
public async Task DoLongAction(TimeSpan timespan, string str)
{
logger.Info("DoLongAction {0} received", str);
await Task.Delay(timespan);
}
public Task SetLabel(string label)
{
this.label = label;
logger.Info("SetLabel {0} received", label);
return Task.CompletedTask;
}
public Task StartTimer()
{
logger.Info("StartTimer.");
timer = base.RegisterTimer(TimerTick, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
return Task.CompletedTask;
}
private Task TimerTick(object data)
{
logger.Info("TimerTick.");
return Task.CompletedTask;
}
public async Task<Tuple<string, string>> TestRequestContext()
{
string bar1 = null;
RequestContext.Set("jarjar", "binks");
var task = Task.Factory.StartNew(() =>
{
bar1 = (string) RequestContext.Get("jarjar");
logger.Info("bar = {0}.", bar1);
});
string bar2 = null;
var ac = Task.Factory.StartNew(() =>
{
bar2 = (string) RequestContext.Get("jarjar");
logger.Info("bar = {0}.", bar2);
});
await Task.WhenAll(task, ac);
return new Tuple<string, string>(bar1, bar2);
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(RuntimeIdentity);
}
public Task<string> GetActivationId()
{
return Task.FromResult(Data.ActivationId.ToString());
}
public Task<ITestGrain> GetGrainReference()
{
return Task.FromResult(this.AsReference<ITestGrain>());
}
public Task<IGrain[]> GetMultipleGrainInterfaces_Array()
{
var grains = new IGrain[5];
for (var i = 0; i < grains.Length; i++)
{
grains[i] = GrainFactory.GetGrain<ITestGrain>(i);
}
return Task.FromResult(grains);
}
public Task<List<IGrain>> GetMultipleGrainInterfaces_List()
{
var grains = new IGrain[5];
for (var i = 0; i < grains.Length; i++)
{
grains[i] = GrainFactory.GetGrain<ITestGrain>(i);
}
return Task.FromResult(grains.ToList());
}
}
public class TestGrainLongActivateAsync : Grain, ITestGrainLongOnActivateAsync
{
public TestGrainLongActivateAsync()
{
}
public override async Task OnActivateAsync()
{
await Task.Delay(TimeSpan.FromSeconds(3));
if (this.GetPrimaryKeyLong() == -2)
throw new ArgumentException("Primary key cannot be -2 for this test case");
await base.OnActivateAsync();
}
public Task<long> GetKey()
{
return Task.FromResult(this.GetPrimaryKeyLong());
}
}
internal class GuidTestGrain : Grain, IGuidTestGrain
{
private string label;
private ILogger logger;
public GuidTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
//if (this.GetPrimaryKeyLong() == -2)
// throw new ArgumentException("Primary key cannot be -2 for this test case");
label = this.GetPrimaryKey().ToString();
logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<Guid> GetKey()
{
return Task.FromResult(this.GetPrimaryKey());
}
public Task<string> GetLabel()
{
return Task.FromResult(label);
}
public Task SetLabel(string label)
{
this.label = label;
return Task.CompletedTask;
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(RuntimeIdentity);
}
public Task<string> GetActivationId()
{
return Task.FromResult(Data.ActivationId.ToString());
}
}
internal class OneWayGrain : Grain, IOneWayGrain, ISimpleGrainObserver
{
private int count;
private TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
private IOneWayGrain other;
private Catalog catalog;
public OneWayGrain(Catalog catalog)
{
this.catalog = catalog;
}
private ILocalGrainDirectory LocalGrainDirectory => this.ServiceProvider.GetRequiredService<ILocalGrainDirectory>();
private ILocalSiloDetails LocalSiloDetails => this.ServiceProvider.GetRequiredService<ILocalSiloDetails>();
public Task Notify()
{
this.count++;
return Task.CompletedTask;
}
public Task Notify(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return Task.CompletedTask;
}
public ValueTask NotifyValueTask(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return default;
}
public async Task<bool> NotifyOtherGrain(IOneWayGrain otherGrain, ISimpleGrainObserver observer)
{
var task = otherGrain.Notify(observer);
var completedSynchronously = task.Status == TaskStatus.RanToCompletion;
await task;
return completedSynchronously;
}
public async Task<bool> NotifyOtherGrainValueTask(IOneWayGrain otherGrain, ISimpleGrainObserver observer)
{
var task = otherGrain.NotifyValueTask(observer);
var completedSynchronously = task.IsCompleted;
await task;
return completedSynchronously;
}
public async Task<IOneWayGrain> GetOtherGrain()
{
return this.other ?? (this.other = await GetGrainOnOtherSilo());
async Task<IOneWayGrain> GetGrainOnOtherSilo()
{
while (true)
{
var candidate = this.GrainFactory.GetGrain<IOneWayGrain>(Guid.NewGuid());
var directorySilo = await candidate.GetPrimaryForGrain();
var thisSilo = await this.GetSiloAddress();
var candidateSilo = await candidate.GetSiloAddress();
if (!directorySilo.Equals(candidateSilo)
&& !directorySilo.Equals(thisSilo)
&& !candidateSilo.Equals(thisSilo))
{
return candidate;
}
}
}
}
public Task<string> GetActivationAddress(IGrain grain)
{
var grainId = ((GrainReference)grain).GrainId;
if (this.catalog.FastLookup(grainId, out var addresses))
{
return Task.FromResult(addresses.Single().ToString());
}
return Task.FromResult<string>(null);
}
public Task NotifyOtherGrain() => this.other.Notify(this.AsReference<ISimpleGrainObserver>());
public Task<int> GetCount() => Task.FromResult(this.count);
public Task Deactivate()
{
this.DeactivateOnIdle();
return Task.CompletedTask;
}
public Task ThrowsOneWay()
{
throw new Exception("GET OUT!");
}
public ValueTask ThrowsOneWayValueTask()
{
throw new Exception("GET OUT (ValueTask)!");
}
public Task<SiloAddress> GetSiloAddress()
{
return Task.FromResult(this.LocalSiloDetails.SiloAddress);
}
public Task<SiloAddress> GetPrimaryForGrain()
{
var grainId = (GrainId)this.GrainId;
var primaryForGrain = this.LocalGrainDirectory.GetPrimaryForGrain(grainId);
return Task.FromResult(primaryForGrain);
}
public void StateChanged(int a, int b)
{
this.tcs.TrySetResult(0);
}
}
public class CanBeOneWayGrain : Grain, ICanBeOneWayGrain
{
private int count;
public Task Notify()
{
this.count++;
return Task.CompletedTask;
}
public Task Notify(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return Task.CompletedTask;
}
public ValueTask NotifyValueTask(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return default;
}
public Task<int> GetCount() => Task.FromResult(this.count);
public Task Throws()
{
throw new Exception("GET OUT!");
}
public ValueTask ThrowsValueTask()
{
throw new Exception("GET OUT!");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Text;
using System.Threading;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Diagnostics.Tests
{
//Complex types are not supported on EventSource for .NET 4.5
public class DiagnosticSourceEventSourceBridgeTests
{
// To avoid interactions between tests when they are run in parallel, we run all these tests in their
// own sub-process using RemoteExecutor.Invoke() However this makes it very inconvinient to debug the test.
// By seting this #if to true you stub out RemoteInvoke and the code will run in-proc which is useful
// in debugging.
#if false
class NullDispose : IDisposable
{
public void Dispose()
{
}
}
static IDisposable RemoteExecutor.Invoke(Action a)
{
a();
return new NullDispose();
}
#endif
/// <summary>
/// Tests the basic functionality of turning on specific EventSources and specifying
/// the events you want.
/// </summary>
[Fact]
public void TestSpecificEvents()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestSpecificEventsSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types You can have whitespace
// before and after each spec.
eventSourceListener.Enable(
" TestSpecificEventsSource/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" +
" TestSpecificEventsSource/TestEvent2:cls_Url=cls.Url\r\n"
);
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(5, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
Assert.Equal("5", eventSourceListener.LastEvent.Arguments["cls_Point_Y"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event that matches the second pattern.
if (diagnosticSourceListener.IsEnabled("TestEvent2"))
diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(4, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hello", eventSourceListener.LastEvent.Arguments["prop2Str"]);
Assert.Equal("8", eventSourceListener.LastEvent.Arguments["prop2Int"]);
Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Emit an event that does not match either pattern. (thus will be filtered out)
if (diagnosticSourceListener.IsEnabled("TestEvent3"))
diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", });
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
/***************************************************************************************/
// Emit an event from another diagnostic source with the same event name.
// It will be filtered out.
using (var diagnosticSourceListener2 = new DiagnosticListener("TestSpecificEventsSource2"))
{
if (diagnosticSourceListener2.IsEnabled("TestEvent1"))
diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
}
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
// Disable all the listener and insure that no more events come through.
eventSourceListener.Disable();
diagnosticSourceListener.Write("TestEvent1", null);
diagnosticSourceListener.Write("TestEvent2", null);
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be received.
}
// Make sure that there are no Diagnostic Listeners left over.
DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen)
{
Assert.True(!listen.Name.StartsWith("BuildTestSource"));
}));
}).Dispose();
}
/// <summary>
/// Test that things work properly for Linux newline conventions.
/// </summary>
[Fact]
public void LinuxNewLineConventions()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("LinuxNewLineConventionsSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types You can have whitespace
// before and after each spec. Use \n rather than \r\n
eventSourceListener.Enable(
" LinuxNewLineConventionsSource/TestEvent1:-cls_Point_X=cls.Point.X\n" +
" LinuxNewLineConventionsSource/TestEvent2:-cls_Url=cls.Url\n"
);
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event that matches the second pattern.
if (diagnosticSourceListener.IsEnabled("TestEvent2"))
diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Emit an event that does not match either pattern. (thus will be filtered out)
if (diagnosticSourceListener.IsEnabled("TestEvent3"))
diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", });
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
}
// Make sure that there are no Diagnostic Listeners left over.
DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen)
{
Assert.True(!listen.Name.StartsWith("BuildTestSource"));
}));
}).Dispose();
}
/// <summary>
/// Tests what happens when you wildcard the source name (empty string)
/// </summary>
[Fact]
public void TestWildCardSourceName()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener1 = new DiagnosticListener("TestWildCardSourceName1"))
using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardSourceName2"))
{
eventSourceListener.Filter = (DiagnosticSourceEvent evnt) => evnt.SourceName.StartsWith("TestWildCardSourceName");
// Turn On Everything. Note that because of concurrent testing, we may get other sources as well.
// but we filter them out because we set eventSourceListener.Filter.
eventSourceListener.Enable("");
Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent1"));
Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent2"));
Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent1"));
Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent2"));
Assert.Equal(0, eventSourceListener.EventCount);
diagnosticSourceListener1.Write("TestEvent1", new { prop111 = "prop111Val", prop112 = 112 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop111Val", eventSourceListener.LastEvent.Arguments["prop111"]);
Assert.Equal("112", eventSourceListener.LastEvent.Arguments["prop112"]);
eventSourceListener.ResetEventCountAndLastEvent();
diagnosticSourceListener1.Write("TestEvent2", new { prop121 = "prop121Val", prop122 = 122 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop121Val", eventSourceListener.LastEvent.Arguments["prop121"]);
Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop122"]);
eventSourceListener.ResetEventCountAndLastEvent();
diagnosticSourceListener2.Write("TestEvent1", new { prop211 = "prop211Val", prop212 = 212 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop211Val", eventSourceListener.LastEvent.Arguments["prop211"]);
Assert.Equal("212", eventSourceListener.LastEvent.Arguments["prop212"]);
eventSourceListener.ResetEventCountAndLastEvent();
diagnosticSourceListener2.Write("TestEvent2", new { prop221 = "prop221Val", prop222 = 122 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop221Val", eventSourceListener.LastEvent.Arguments["prop221"]);
Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop222"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests what happens when you wildcard event name (but not the source name)
/// </summary>
[Fact]
public void TestWildCardEventName()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestWildCardEventNameSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types
eventSourceListener.Enable("TestWildCardEventNameSource");
/***************************************************************************************/
// Emit an event, check that all implicit properties are generated
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit the same event, with a different set of implicit properties
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr2 = "hi2", cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi2", eventSourceListener.LastEvent.Arguments["propStr2"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event with the same schema as the first event. (uses first-event cache)
val = new MyClass() { };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hiThere", propInt = 5, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hiThere", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("5", eventSourceListener.LastEvent.Arguments["propInt"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event with the same schema as the second event. (uses dictionary cache)
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr2 = "hi3", cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi3", eventSourceListener.LastEvent.Arguments["propStr2"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event from another diagnostic source with the same event name.
// It will be filtered out.
using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardEventNameSource2"))
{
if (diagnosticSourceListener2.IsEnabled("TestEvent1"))
diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
}
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
}
}).Dispose();
}
/// <summary>
/// Test what happens when there are nulls passed in the event payloads
/// Basically strings get turned into empty strings and other nulls are typically
/// ignored.
/// </summary>
[Fact]
public void TestNulls()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestNullsTestSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types
eventSourceListener.Enable("TestNullsTestSource/TestEvent1:cls.Url;cls_Point_X=cls.Point.X");
/***************************************************************************************/
// Emit a null arguments object.
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", null);
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(0, eventSourceListener.LastEvent.Arguments.Count);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an arguments object with nulls in it.
MyClass val = null;
string strVal = null;
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { cls = val, propStr = "propVal1", propStrNull = strVal });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("", eventSourceListener.LastEvent.Arguments["cls"]); // Tostring() on a null end up as an empty string.
Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("", eventSourceListener.LastEvent.Arguments["propStrNull"]); // null strings get turned into empty strings
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an arguments object that points at null things
MyClass val1 = new MyClass() { Url = "myUrlVal", Point = null };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { cls = val1, propStr = "propVal1" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val1.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("myUrlVal", eventSourceListener.LastEvent.Arguments["Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an arguments object that points at null things (variation 2)
MyClass val2 = new MyClass() { Url = null, Point = new MyPoint() { X = 8, Y = 9 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { cls = val2, propStr = "propVal1" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val2.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("8", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests the feature that suppresses the implicit inclusion of serialable properties
/// of the payload object.
/// </summary>
[Fact]
public void TestNoImplicitTransforms()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestNoImplicitTransformsSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// use the - prefix to suppress the implicit properties. Thus you should only get propStr and Url.
eventSourceListener.Enable("TestNoImplicitTransformsSource/TestEvent1:-propStr;cls.Url");
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val, propStr2 = "there" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNoImplicitTransformsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests what happens when wacky characters are used in property specs.
/// </summary>
[Fact]
public void TestBadProperties()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestBadPropertiesSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// This has a syntax error in the Url case, so it should be ignored.
eventSourceListener.Enable("TestBadPropertiesSource/TestEvent1:cls.Ur-+l");
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestBadPropertiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
// Tests that messages about DiagnosticSourceEventSource make it out.
[Fact]
public void TestMessages()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestMessagesSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// This is just to make debugging easier.
var messages = new List<string>();
eventSourceListener.OtherEventWritten += delegate (EventWrittenEventArgs evnt)
{
if (evnt.EventName == "Message")
{
var message = (string)evnt.Payload[0];
messages.Add(message);
}
};
// This has a syntax error in the Url case, so it should be ignored.
eventSourceListener.Enable("TestMessagesSource/TestEvent1:-cls.Url");
Assert.Equal(0, eventSourceListener.EventCount);
Assert.True(3 <= messages.Count);
}
}).Dispose();
}
/// <summary>
/// Tests the feature to send the messages as EventSource Activities.
/// </summary>
[Fact]
public void TestActivities()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestActivitiesSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
eventSourceListener.Enable(
"TestActivitiesSource/TestActivity1Start@Activity1Start\r\n" +
"TestActivitiesSource/TestActivity1Stop@Activity1Stop\r\n" +
"TestActivitiesSource/TestActivity2Start@Activity2Start\r\n" +
"TestActivitiesSource/TestActivity2Stop@Activity2Stop\r\n" +
"TestActivitiesSource/TestEvent\r\n"
);
// Start activity 1
diagnosticSourceListener.Write("TestActivity1Start", new { propStr = "start" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity1Start", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Start nested activity 2
diagnosticSourceListener.Write("TestActivity2Start", new { propStr = "start" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity2Start", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Send a normal event
diagnosticSourceListener.Write("TestEvent", new { propStr = "event" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Event", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("event", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop nested activity 2
diagnosticSourceListener.Write("TestActivity2Stop", new { propStr = "stop" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity2Stop", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop activity 1
diagnosticSourceListener.Write("TestActivity1Stop", new { propStr = "stop" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity1Stop", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests that keywords that define shortcuts work.
/// </summary>
[Fact]
public void TestShortcutKeywords()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
// These are look-alikes for the real ones.
using (var aspNetCoreSource = new DiagnosticListener("Microsoft.AspNetCore"))
using (var entityFrameworkCoreSource = new DiagnosticListener("Microsoft.EntityFrameworkCore"))
{
// Sadly we have a problem where if something else has turned on Microsoft-Diagnostics-DiagnosticSource then
// its keywords are ORed with our and because the shortcuts require that IgnoreShortCutKeywords is OFF
// Something outside this test (the debugger seems to do this), will cause the test to fail.
// Currently we simply give up in that case (but it really is a deeper problem.
var IgnoreShortCutKeywords = (EventKeywords)0x0800;
foreach (var eventSource in EventSource.GetSources())
{
if (eventSource.Name == "Microsoft-Diagnostics-DiagnosticSource")
{
if (eventSource.IsEnabled(EventLevel.Informational, IgnoreShortCutKeywords))
return; // Don't do the testing.
}
}
// These are from DiagnosticSourceEventListener.
var Messages = (EventKeywords)0x1;
var Events = (EventKeywords)0x2;
var AspNetCoreHosting = (EventKeywords)0x1000;
var EntityFrameworkCoreCommands = (EventKeywords)0x2000;
// Turn on listener using just the keywords
eventSourceListener.Enable(null, Messages | Events | AspNetCoreHosting | EntityFrameworkCoreCommands);
Assert.Equal(0, eventSourceListener.EventCount);
// Start a ASP.NET Request
aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.BeginRequest",
new
{
httpContext = new
{
Request = new
{
Method = "Get",
Host = "MyHost",
Path = "MyPath",
QueryString = "MyQuery"
}
}
});
// Check that the morphs work as expected.
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.AspNetCore.Hosting.BeginRequest", eventSourceListener.LastEvent.EventName);
Assert.True(4 <= eventSourceListener.LastEvent.Arguments.Count);
Debug.WriteLine("Arg Keys = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Keys));
Debug.WriteLine("Arg Values = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Values));
Assert.Equal("Get", eventSourceListener.LastEvent.Arguments["Method"]);
Assert.Equal("MyHost", eventSourceListener.LastEvent.Arguments["Host"]);
Assert.Equal("MyPath", eventSourceListener.LastEvent.Arguments["Path"]);
Assert.Equal("MyQuery", eventSourceListener.LastEvent.Arguments["QueryString"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Start a SQL command
entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.BeforeExecuteCommand",
new
{
Command = new
{
Connection = new
{
DataSource = "MyDataSource",
Database = "MyDatabase",
},
CommandText = "MyCommand"
}
});
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", eventSourceListener.LastEvent.EventName);
Assert.True(3 <= eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("MyDataSource", eventSourceListener.LastEvent.Arguments["DataSource"]);
Assert.Equal("MyDatabase", eventSourceListener.LastEvent.Arguments["Database"]);
Assert.Equal("MyCommand", eventSourceListener.LastEvent.Arguments["CommandText"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop the SQL command
entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.AfterExecuteCommand", null);
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.EntityFrameworkCore.AfterExecuteCommand", eventSourceListener.LastEvent.EventName);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop the ASP.NET request.
aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.EndRequest",
new
{
httpContext = new
{
Response = new
{
StatusCode = "200"
},
TraceIdentifier = "MyTraceId"
}
});
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.AspNetCore.Hosting.EndRequest", eventSourceListener.LastEvent.EventName);
Assert.True(2 <= eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("MyTraceId", eventSourceListener.LastEvent.Arguments["TraceIdentifier"]);
Assert.Equal("200", eventSourceListener.LastEvent.Arguments["StatusCode"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
[OuterLoop("Runs for several seconds")]
[Fact]
public void Stress_WriteConcurrently_DoesntCrash()
{
const int StressTimeSeconds = 4;
RemoteExecutor.Invoke(() =>
{
using (new TurnOnAllEventListener())
using (var source = new DiagnosticListener("testlistener"))
{
var ce = new CountdownEvent(Environment.ProcessorCount * 2);
for (int i = 0; i < ce.InitialCount; i++)
{
new Thread(() =>
{
DateTime end = DateTime.UtcNow.Add(TimeSpan.FromSeconds(StressTimeSeconds));
while (DateTime.UtcNow < end)
{
source.Write("event1", Tuple.Create(1));
source.Write("event2", Tuple.Create(1, 2));
source.Write("event3", Tuple.Create(1, 2, 3));
source.Write("event4", Tuple.Create(1, 2, 3, 4));
source.Write("event5", Tuple.Create(1, 2, 3, 4, 5));
}
ce.Signal();
})
{ IsBackground = true }.Start();
}
ce.Wait();
}
}).Dispose();
}
[Fact]
public void IndexGetters_DontThrow()
{
RemoteExecutor.Invoke(() =>
{
using (var eventListener = new TestDiagnosticSourceEventListener())
using (var diagnosticListener = new DiagnosticListener("MySource"))
{
eventListener.Enable(
"MySource/MyEvent"
);
// The type MyEvent only declares 3 Properties, but actually
// has 4 due to the implicit Item property from having the index
// operator implemented. The Getter for this Item property
// is unusual for Property getters because it takes
// an int32 as an input. This test ensures that this
// implicit Property isn't implicitly serialized by
// DiagnosticSourceEventSource.
diagnosticListener.Write(
"MyEvent",
new MyEvent
{
Number = 1,
OtherNumber = 2
}
);
Assert.Equal(1, eventListener.EventCount);
Assert.Equal("MySource", eventListener.LastEvent.SourceName);
Assert.Equal("MyEvent", eventListener.LastEvent.EventName);
Assert.True(eventListener.LastEvent.Arguments.Count <= 3);
Assert.Equal("1", eventListener.LastEvent.Arguments["Number"]);
Assert.Equal("2", eventListener.LastEvent.Arguments["OtherNumber"]);
Assert.Equal("2", eventListener.LastEvent.Arguments["Count"]);
}
}).Dispose();
}
}
/****************************************************************************/
// classes to make up data for the tests.
/// <summary>
/// classes for test data.
/// </summary>
internal class MyClass
{
public string Url { get; set; }
public MyPoint Point { get; set; }
}
/// <summary>
/// classes for test data.
/// </summary>
internal class MyPoint
{
public int X { get; set; }
public int Y { get; set; }
}
/// <summary>
/// classes for test data
/// </summary>
internal class MyEvent
{
public int Number { get; set; }
public int OtherNumber { get; set; }
public int Count => 2;
public KeyValuePair<string, object> this[int index] => index switch
{
0 => new KeyValuePair<string, object>(nameof(Number), Number),
1 => new KeyValuePair<string, object>(nameof(OtherNumber), OtherNumber),
_ => throw new IndexOutOfRangeException()
};
}
/****************************************************************************/
// Harness infrastructure
/// <summary>
/// TestDiagnosticSourceEventListener installs a EventWritten callback that updates EventCount and LastEvent.
/// </summary>
internal sealed class TestDiagnosticSourceEventListener : DiagnosticSourceEventListener
{
public TestDiagnosticSourceEventListener()
{
EventWritten += UpdateLastEvent;
}
public int EventCount;
public DiagnosticSourceEvent LastEvent;
#if DEBUG
// Here just for debugging. Lets you see the last 3 events that were sent.
public DiagnosticSourceEvent SecondLast;
public DiagnosticSourceEvent ThirdLast;
#endif
/// <summary>
/// Sets the EventCount to 0 and LastEvent to null
/// </summary>
public void ResetEventCountAndLastEvent()
{
EventCount = 0;
LastEvent = null;
#if DEBUG
SecondLast = null;
ThirdLast = null;
#endif
}
/// <summary>
/// If present, will ignore events that don't cause this filter predicate to return true.
/// </summary>
public Predicate<DiagnosticSourceEvent> Filter;
#region private
private void UpdateLastEvent(DiagnosticSourceEvent anEvent)
{
if (Filter != null && !Filter(anEvent))
return;
#if DEBUG
ThirdLast = SecondLast;
SecondLast = LastEvent;
#endif
EventCount++;
LastEvent = anEvent;
}
#endregion
}
/// <summary>
/// Represents a single DiagnosticSource event.
/// </summary>
internal sealed class DiagnosticSourceEvent
{
public string SourceName;
public string EventName;
public Dictionary<string, string> Arguments;
// Not typically important.
public string EventSourceEventName; // This is the name of the EventSourceEvent that carried the data. Only important for activities.
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("{");
sb.Append(" SourceName: \"").Append(SourceName ?? "").Append("\",").AppendLine();
sb.Append(" EventName: \"").Append(EventName ?? "").Append("\",").AppendLine();
sb.Append(" Arguments: ").Append("[").AppendLine();
bool first = true;
foreach (var keyValue in Arguments)
{
if (!first)
sb.Append(",").AppendLine();
first = false;
sb.Append(" ").Append(keyValue.Key).Append(": \"").Append(keyValue.Value).Append("\"");
}
sb.AppendLine().AppendLine(" ]");
sb.AppendLine("}");
return sb.ToString();
}
}
/// <summary>
/// A helper class that listens to Diagnostic sources and send events to the 'EventWritten'
/// callback. Standard use is to create the class set up the events of interested and
/// use 'Enable'. .
/// </summary>
internal class DiagnosticSourceEventListener : EventListener
{
public DiagnosticSourceEventListener() { }
/// <summary>
/// Will be called when a DiagnosticSource event is fired.
/// </summary>
public new event Action<DiagnosticSourceEvent> EventWritten;
/// <summary>
/// It is possible that there are other events besides those that are being forwarded from
/// the DiagnosticSources. These come here.
/// </summary>
public event Action<EventWrittenEventArgs> OtherEventWritten;
public void Enable(string filterAndPayloadSpecs, EventKeywords keywords = EventKeywords.All)
{
var args = new Dictionary<string, string>();
if (filterAndPayloadSpecs != null)
args.Add("FilterAndPayloadSpecs", filterAndPayloadSpecs);
EnableEvents(_diagnosticSourceEventSource, EventLevel.Verbose, keywords, args);
}
public void Disable()
{
DisableEvents(_diagnosticSourceEventSource);
}
/// <summary>
/// Cleans this class up. Among other things disables the DiagnosticSources being listened to.
/// </summary>
public override void Dispose()
{
if (_diagnosticSourceEventSource != null)
{
Disable();
_diagnosticSourceEventSource = null;
}
}
#region private
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
bool wroteEvent = false;
var eventWritten = EventWritten;
if (eventWritten != null)
{
if (eventData.Payload.Count == 3 && (eventData.EventName == "Event" || eventData.EventName.Contains("Activity")))
{
Debug.Assert(eventData.PayloadNames[0] == "SourceName");
Debug.Assert(eventData.PayloadNames[1] == "EventName");
Debug.Assert(eventData.PayloadNames[2] == "Arguments");
var anEvent = new DiagnosticSourceEvent();
anEvent.EventSourceEventName = eventData.EventName;
anEvent.SourceName = eventData.Payload[0].ToString();
anEvent.EventName = eventData.Payload[1].ToString();
anEvent.Arguments = new Dictionary<string, string>();
var asKeyValueList = eventData.Payload[2] as IEnumerable<object>;
if (asKeyValueList != null)
{
foreach (IDictionary<string, object> keyvalue in asKeyValueList)
{
object key;
keyvalue.TryGetValue("Key", out key);
object value;
keyvalue.TryGetValue("Value", out value);
if (key != null && value != null)
anEvent.Arguments[key.ToString()] = value.ToString();
}
}
eventWritten(anEvent);
wroteEvent = true;
}
}
if (eventData.EventName == "EventSourceMessage" && 0 < eventData.Payload.Count)
System.Diagnostics.Debug.WriteLine("EventSourceMessage: " + eventData.Payload[0].ToString());
var otherEventWritten = OtherEventWritten;
if (otherEventWritten != null && !wroteEvent)
otherEventWritten(eventData);
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name == "Microsoft-Diagnostics-DiagnosticSource")
_diagnosticSourceEventSource = eventSource;
}
EventSource _diagnosticSourceEventSource;
#endregion
}
internal sealed class TurnOnAllEventListener : EventListener
{
protected override void OnEventSourceCreated(EventSource eventSource) => EnableEvents(eventSource, EventLevel.LogAlways);
protected override void OnEventWritten(EventWrittenEventArgs eventData) { }
}
}
| |
using System;
using System.Xml;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Drawing.Design;
using System.IO;
namespace InstallerLib
{
/// <summary>
/// A base component.
/// </summary>
[XmlChild(typeof(InstalledCheck))]
[XmlChild(typeof(InstalledCheckOperator))]
[XmlChild(typeof(DownloadDialog), Max = 1)]
[XmlChild(typeof(EmbedFile))]
[XmlChild(typeof(EmbedFolder))]
public abstract class Component : XmlClass
{
public Component(string type, string name)
{
m_type = type;
Template.Template_component tpl = Template.CurrentTemplate.component(name);
m_display_name = tpl.display_name;
}
#region Attributes
private string m_type;
[Description("Type of the component; can be 'cmd' for executing generic command line installation or 'msi' for installing Windows Installer MSI package or 'openfile' to open a file.")]
[Category("Component")]
[Required]
public string type
{
get { return m_type; }
}
private string m_os_filter;
[Description("Filter to install this component only on all operating systems equal or not equal to the id value(s) specified. Separate multiple operating system ids with comma (',') and use not symbol ('!') for NOT logic (es. '44,!45' ).")]
[Category("Operating System")]
public string os_filter
{
get { return m_os_filter; }
set { m_os_filter = value; }
}
private OperatingSystem m_os_filter_min;
[Description("Filter to install this component only on all operating systems greater or equal to the id value specified. For example to install a component only in Windows 2000 or later use 'win2000'.")]
[Category("Operating System")]
public OperatingSystem os_filter_min
{
get { return m_os_filter_min; }
set { m_os_filter_min = value; }
}
private OperatingSystem m_os_filter_max;
[Description("Filter to install this component only on all operating systems smaller or equal to the id value specified. For example to install a component preceding Windows 2000 use 'winNT4sp6a'.")]
[Category("Operating System")]
public OperatingSystem os_filter_max
{
get { return m_os_filter_max; }
set { m_os_filter_max = value; }
}
private string m_os_filter_lcid;
[Description("Filter to install this component only on all operating system languages equal or not equal to the LCID specified. Separate multiple LCID with comma (',') and use not symbol ('!') for NOT logic (eg. '1044,1033,!1038' ).")]
[Category("Operating System")]
public string os_filter_lcid
{
get { return m_os_filter_lcid; }
set { m_os_filter_lcid = value; }
}
private string m_installcompletemessage;
[Description("Message used after a component is successfully installed. To disable this message leave this property empty.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Install")]
public string installcompletemessage
{
get { return m_installcompletemessage; }
set { m_installcompletemessage = value; }
}
private string m_uninstallcompletemessage;
[Description("Message used after a component is been successfully uninstalled.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Uninstall")]
public string uninstallcompletemessage
{
get { return m_uninstallcompletemessage; }
set { m_uninstallcompletemessage = value; }
}
private bool m_mustreboot = false;
[Description("Indicates whether to reboot automatically after this component is installed or uninstalled successfully. Normally if the system must be restarted, the component tells this setup (with special return code) to stop and restart the system. Setting this option to 'true' forces a reboot without prompting.")]
[Category("Runtime")]
[Required]
public bool mustreboot
{
get { return m_mustreboot; }
set { m_mustreboot = value; }
}
private string m_failed_exec_command_continue;
[Description("Message to display after a component failed to install. The user is then asked whether installation can continue using this message. May contain one '%s' replaced by the description of the component.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Runtime")]
public string failed_exec_command_continue
{
get { return m_failed_exec_command_continue; }
set { m_failed_exec_command_continue = value; }
}
private string m_reboot_required;
[Description("Message used when this component signaled the installer that it requires a reboot.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Runtime")]
public string reboot_required
{
get { return m_reboot_required; }
set { m_reboot_required = value; }
}
private bool m_must_reboot_required = false;
[Description("Component setting for reboot behavior. When 'true', installation won't continue after this component required a reboot.")]
[Category("Runtime")]
[Required]
public bool must_reboot_required
{
get { return m_must_reboot_required; }
set { m_must_reboot_required = value; }
}
private bool m_allow_continue_on_error = true;
[Description("Set to 'true' to prompt the user to continue when a component fails to install.")]
[Category("Runtime")]
[Required]
public bool allow_continue_on_error
{
get { return m_allow_continue_on_error; }
set { m_allow_continue_on_error = value; }
}
private bool m_default_continue_on_error = false;
[Description("The default value of whether to continue when a component fails to install.")]
[Category("Runtime")]
[Required]
public bool default_continue_on_error
{
get { return m_default_continue_on_error; }
set { m_default_continue_on_error = value; }
}
private string m_id;
[Description("Component identity. This value should be unique.")]
[Category("Component")]
[Required]
public string id
{
get { return m_id; }
set { m_id = value; OnDisplayChanged(); }
}
private string m_display_name;
[Description("Component display name. This value is used in some message to replace the '%s' string.")]
[Category("Component")]
[Required]
public string display_name
{
get { return m_display_name; }
set { m_display_name = value; OnDisplayChanged(); }
}
private string m_uninstall_display_name;
[Description("Optional display name of this component during uninstall. Defaults to 'display_name' when blank.")]
[Category("Component")]
public string uninstall_display_name
{
get { return m_uninstall_display_name; }
set { m_uninstall_display_name = value; OnDisplayChanged(); }
}
private bool m_required_install = true;
[Description("Indicates whether the component is required for a successful installation.")]
[Category("Component")]
[Required]
public bool required_install
{
get { return m_required_install; }
set { m_required_install = value; }
}
private bool m_required_uninstall = true;
[Description("Indicates whether the component is required for a successful uninstallation.")]
[Category("Component")]
[Required]
public bool required_uninstall
{
get { return m_required_uninstall; }
set { m_required_uninstall = value; }
}
private bool m_selected_install = true;
[Description("Indicates whether the component is selected by default during install.")]
[Category("Component")]
[Required]
public bool selected_install
{
get { return m_selected_install; }
set { m_selected_install = value; }
}
private bool m_selected_uninstall = true;
[Description("Indicates whether the component is selected by default during uninstall.")]
[Category("Component")]
[Required]
public bool selected_uninstall
{
get { return m_selected_uninstall; }
set { m_selected_uninstall = value; }
}
private string m_note;
[Description("Store any additional free-formed information in this field, not used by the setup.")]
[Category("Component")]
public string note
{
get { return m_note; }
set { m_note = value; }
}
// message for not matching the processor architecture filter
private string m_processor_architecture_filter;
[Description("Type of processor architecture (x86, mips, alpha, ppc, shx, arm, ia64, alpha64, msil, x64, ia32onwin64). Separate by commas, can use the NOT sign ('!') to exclude values. (eg. 'x86,x64' or '!x86').")]
[Category("Filters")]
public string processor_architecture_filter
{
get { return m_processor_architecture_filter; }
set { m_processor_architecture_filter = value; }
}
private string m_status_installed;
[Description("String used to indicate that this component is installed.")]
[Category("Component")]
public string status_installed
{
get { return m_status_installed; }
set { m_status_installed = value; }
}
private string m_status_notinstalled;
[Description("String used to indicate that this component is not installed.")]
[Category("Component")]
public string status_notinstalled
{
get { return m_status_notinstalled; }
set { m_status_notinstalled = value; }
}
private bool m_supports_install = true;
[Description("Indicates whether the component supports the install sequence.")]
[Category("Install")]
[Required]
public bool supports_install
{
get { return m_supports_install; }
set { m_supports_install = value; }
}
private bool m_supports_uninstall = false;
[Description("Indicates whether the component supports the uninstall sequence.")]
[Category("Uninstall")]
[Required]
public bool supports_uninstall
{
get { return m_supports_uninstall; }
set { m_supports_uninstall = value; }
}
private bool m_show_progress_dialog = true;
[Description("Set to 'true' to show the progress dialogs.")]
[Category("Component")]
[Required]
public bool show_progress_dialog
{
get { return m_show_progress_dialog; }
set { m_show_progress_dialog = value; }
}
private bool m_show_cab_dialog = true;
[Description("Set to 'true' to show the CAB extraction dialogs.")]
[Category("Component")]
[Required]
public bool show_cab_dialog
{
get { return m_show_cab_dialog; }
set { m_show_cab_dialog = value; }
}
#endregion
#region Events
protected void OnDisplayChanged()
{
if (DisplayChanged != null)
{
DisplayChanged(this, EventArgs.Empty);
}
}
public event EventHandler DisplayChanged;
#endregion
#region XmlClass Members
public override string XmlTag
{
get { return "component"; }
}
#endregion
protected override void OnXmlWriteTag(XmlWriterEventArgs e)
{
e.XmlWriter.WriteAttributeString("id", string.IsNullOrEmpty(m_id) ? m_display_name : m_id);
e.XmlWriter.WriteAttributeString("display_name", m_display_name);
e.XmlWriter.WriteAttributeString("uninstall_display_name", m_uninstall_display_name);
e.XmlWriter.WriteAttributeString("os_filter", m_os_filter);
e.XmlWriter.WriteAttributeString("os_filter_min", (m_os_filter_min == OperatingSystem.winNone
? "" : Enum.GetName(typeof(OperatingSystem), m_os_filter_min)));
e.XmlWriter.WriteAttributeString("os_filter_max", (m_os_filter_max == OperatingSystem.winNone
? "" : Enum.GetName(typeof(OperatingSystem), m_os_filter_max)));
e.XmlWriter.WriteAttributeString("os_filter_lcid", m_os_filter_lcid);
e.XmlWriter.WriteAttributeString("type", m_type);
e.XmlWriter.WriteAttributeString("installcompletemessage", m_installcompletemessage);
e.XmlWriter.WriteAttributeString("uninstallcompletemessage", m_uninstallcompletemessage);
e.XmlWriter.WriteAttributeString("mustreboot", m_mustreboot.ToString());
e.XmlWriter.WriteAttributeString("reboot_required", m_reboot_required);
e.XmlWriter.WriteAttributeString("must_reboot_required", m_must_reboot_required.ToString());
e.XmlWriter.WriteAttributeString("failed_exec_command_continue", m_failed_exec_command_continue);
e.XmlWriter.WriteAttributeString("allow_continue_on_error", m_allow_continue_on_error.ToString());
e.XmlWriter.WriteAttributeString("default_continue_on_error", m_default_continue_on_error.ToString());
e.XmlWriter.WriteAttributeString("required_install", m_required_install.ToString());
e.XmlWriter.WriteAttributeString("required_uninstall", m_required_uninstall.ToString());
e.XmlWriter.WriteAttributeString("selected_install", m_selected_install.ToString());
e.XmlWriter.WriteAttributeString("selected_uninstall", m_selected_uninstall.ToString());
e.XmlWriter.WriteAttributeString("note", m_note);
e.XmlWriter.WriteAttributeString("processor_architecture_filter", m_processor_architecture_filter);
e.XmlWriter.WriteAttributeString("status_installed", m_status_installed);
e.XmlWriter.WriteAttributeString("status_notinstalled", m_status_notinstalled);
e.XmlWriter.WriteAttributeString("supports_install", m_supports_install.ToString());
e.XmlWriter.WriteAttributeString("supports_uninstall", m_supports_uninstall.ToString());
// dialog options
e.XmlWriter.WriteAttributeString("show_progress_dialog", m_show_progress_dialog.ToString());
e.XmlWriter.WriteAttributeString("show_cab_dialog", m_show_cab_dialog.ToString());
base.OnXmlWriteTag(e);
}
protected override void OnXmlReadTag(XmlElementEventArgs e)
{
// backwards compatible description < 1.8
ReadAttributeValue(e, "description", ref m_display_name);
ReadAttributeValue(e, "display_name", ref m_display_name);
ReadAttributeValue(e, "uninstall_display_name", ref m_uninstall_display_name);
ReadAttributeValue(e, "id", ref m_id);
if (string.IsNullOrEmpty(m_id)) m_id = m_display_name;
ReadAttributeValue(e, "installcompletemessage", ref m_installcompletemessage);
ReadAttributeValue(e, "uninstallcompletemessage", ref m_uninstallcompletemessage);
ReadAttributeValue(e, "mustreboot", ref m_mustreboot);
ReadAttributeValue(e, "reboot_required", ref m_reboot_required);
ReadAttributeValue(e, "must_reboot_required", ref m_must_reboot_required);
ReadAttributeValue(e, "failed_exec_command_continue", ref m_failed_exec_command_continue);
ReadAttributeValue(e, "allow_continue_on_error", ref m_allow_continue_on_error);
ReadAttributeValue(e, "default_continue_on_error", ref m_default_continue_on_error);
// required -> required_install and required_uninstall
if (! ReadAttributeValue(e, "required_install", ref m_required_install))
ReadAttributeValue(e, "required", ref m_required_install);
if (! ReadAttributeValue(e, "required_uninstall", ref m_required_uninstall))
m_required_uninstall = m_required_install;
// selected -> selected_install & selected_uninstall
if (! ReadAttributeValue(e, "selected_install", ref m_selected_install))
ReadAttributeValue(e, "selected", ref m_selected_install);
if (! ReadAttributeValue(e, "selected_uninstall", ref m_selected_uninstall))
m_selected_uninstall = m_selected_install;
// filters
ReadAttributeValue(e, "os_filter", ref m_os_filter);
ReadAttributeValue(e, "os_filter_lcid", ref m_os_filter_lcid);
string os_filter_greater = string.Empty;
if (ReadAttributeValue(e, "os_filter_greater", ref os_filter_greater) && !String.IsNullOrEmpty(os_filter_greater))
m_os_filter_min = (OperatingSystem)(int.Parse(os_filter_greater) + 1);
string os_filter_smaller = string.Empty;
if (ReadAttributeValue(e, "os_filter_smaller", ref os_filter_smaller) && !String.IsNullOrEmpty(os_filter_smaller))
m_os_filter_max = (OperatingSystem)(int.Parse(os_filter_smaller) - 1);
ReadAttributeValue(e, "os_filter_min", ref m_os_filter_min);
ReadAttributeValue(e, "os_filter_max", ref m_os_filter_max);
ReadAttributeValue(e, "note", ref m_note);
ReadAttributeValue(e, "processor_architecture_filter", ref m_processor_architecture_filter);
ReadAttributeValue(e, "status_installed", ref m_status_installed);
ReadAttributeValue(e, "status_notinstalled", ref m_status_notinstalled);
ReadAttributeValue(e, "supports_install", ref m_supports_install);
ReadAttributeValue(e, "supports_uninstall", ref m_supports_uninstall);
// dialog options
ReadAttributeValue(e, "show_progress_dialog", ref m_show_progress_dialog);
ReadAttributeValue(e, "show_cab_dialog", ref m_show_cab_dialog);
base.OnXmlReadTag(e);
}
public static Component CreateFromXml(XmlElement element)
{
Component l_Comp;
string xmltype = element.Attributes["type"].InnerText;
if (xmltype == "msi")
l_Comp = new ComponentMsi();
else if (xmltype == "msu")
l_Comp = new ComponentMsu();
else if (xmltype == "msp")
l_Comp = new ComponentMsp();
else if (xmltype == "cmd")
l_Comp = new ComponentCmd();
else if (xmltype == "openfile")
l_Comp = new ComponentOpenFile();
else if (xmltype == "exe")
l_Comp = new ComponentExe();
else
throw new Exception(string.Format("Invalid type: {0}", xmltype));
l_Comp.FromXml(element);
return l_Comp;
}
/// <summary>
/// Return files to embed for this component.
/// </summary>
/// <param name="parentid"></param>
/// <param name="supportdir"></param>
/// <returns></returns>
public override Dictionary<string, EmbedFileCollection> GetFiles(string parentid, string supportdir)
{
return base.GetFiles(id, supportdir);
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.unity3d.ui
{
public class Button : global::UnityEngine.MonoBehaviour, global::haxe.lang.IHxObject
{
public Button(global::haxe.lang.EmptyObject empty) : base()
{
unchecked
{
}
#line default
}
public Button() : base()
{
unchecked
{
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.prevState = false;
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.autoSwith = false;
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.tooltip = "";
#line 48 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.panel = true;
#line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.defaultMode = 0;
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core = new global::pony.ui.ButtonCore();
}
#line default
}
public static object __hx_createEmpty()
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return new global::pony.unity3d.ui.Button(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static object __hx_create(global::Array arr)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return new global::pony.unity3d.ui.Button();
}
#line default
}
public int defaultMode;
public bool panel;
public string tooltip;
public bool autoSwith;
public global::pony.ui.ButtonCore core;
public bool prevState;
public virtual void Start()
{
unchecked
{
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core._set_mode(this.defaultMode);
if (this.autoSwith)
{
object __temp_stmt635 = default(object);
#line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
{
#line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
object f = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("sw"), ((int) (25764) ))) ), 1);
#line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
__temp_stmt635 = global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core.click.@add(__temp_stmt635, default(global::haxe.lang.Null<int>));
}
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
if ( ! (string.Equals(this.tooltip, "")) )
{
object __temp_stmt636 = default(object);
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
{
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
object f1 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("over"), ((int) (1236832596) ))) ), 0);
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
__temp_stmt636 = global::pony.events._Listener.Listener_Impl_._fromFunction(f1, false);
}
#line 66 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core.change.subArgs(new global::Array<object>(new object[]{new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Focus})})).@add(__temp_stmt636, default(global::haxe.lang.Null<int>));
object __temp_stmt637 = default(object);
#line 67 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
{
#line 67 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
object f2 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("out"), ((int) (5546126) ))) ), 0);
#line 67 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
__temp_stmt637 = global::pony.events._Listener.Listener_Impl_._fromFunction(f2, false);
}
#line 67 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core.change.subArgs(new global::Array<object>(new object[]{new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Default})})).@add(__temp_stmt637, default(global::haxe.lang.Null<int>));
object __temp_stmt638 = default(object);
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
{
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
object f3 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("out"), ((int) (5546126) ))) ), 0);
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
__temp_stmt638 = global::pony.events._Listener.Listener_Impl_._fromFunction(f3, false);
}
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core.change.subArgs(new global::Array<object>(new object[]{new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Press})})).@add(__temp_stmt638, default(global::haxe.lang.Null<int>));
object __temp_stmt639 = default(object);
#line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
{
#line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
object f4 = global::pony._Function.Function_Impl_.@from(((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("out"), ((int) (5546126) ))) ), 0);
#line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
__temp_stmt639 = global::pony.events._Listener.Listener_Impl_._fromFunction(f4, false);
}
#line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core.change.subArgs(new global::Array<object>(new object[]{new global::Array<object>(new object[]{global::pony.ui.ButtonStates.Leave})})).@add(__temp_stmt639, default(global::haxe.lang.Null<int>));
}
}
#line default
}
public virtual void @out()
{
unchecked
{
#line 75 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
global::pony.unity3d.Tooltip.hideText(this);
}
#line default
}
public virtual void over()
{
unchecked
{
#line 79 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
global::pony.unity3d.Tooltip.showText(this.tooltip, "", this, new global::haxe.lang.Null<int>(this.gameObject.layer, true), new global::haxe.lang.Null<bool>(true, true));
}
#line default
}
public virtual void sw(int mode)
{
unchecked
{
#line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core._set_mode(( (( mode == 0 )) ? (2) : (( (( mode == 2 )) ? (0) : (mode) )) ));
}
#line default
}
public virtual void Update()
{
unchecked
{
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
bool h = default(bool);
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
if (( this.panel || ! (global::pony.unity3d.Fixed2dCamera.exists) ))
{
h = ( this.guiTexture as global::UnityEngine.GUIElement ).HitTest(((global::UnityEngine.Vector3) (new global::UnityEngine.Vector3(((float) (( global::UnityEngine.Input.mousePosition.x - global::pony.unity3d.Fixed2dCamera.begin )) ), ((float) (global::UnityEngine.Input.mousePosition.y) ))) ));
}
else
{
h = ( this.guiTexture as global::UnityEngine.GUIElement ).HitTest(((global::UnityEngine.Vector3) (new global::UnityEngine.Vector3(((float) (( global::UnityEngine.Input.mousePosition.x + ( ((double) ((( global::UnityEngine.Screen.width - global::pony.unity3d.Fixed2dCamera.begin ))) ) / 2 ) )) ), ((float) (global::UnityEngine.Input.mousePosition.y) ))) ));
}
bool down = global::UnityEngine.Input.GetMouseButton(0);
if (( this.prevState != h ))
{
if (h)
{
#line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core.mouseOver(down);
}
else
{
this.core.mouseOut();
}
this.prevState = h;
}
#line 96 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
if (down)
{
#line 96 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core.mouseDown();
}
else
{
this.core.mouseUp();
}
}
#line default
}
public virtual bool __hx_deleteField(string field, int hash)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return false;
}
#line default
}
public virtual object __hx_lookupField(string field, int hash, bool throwErrors, bool isCheck)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
if (isCheck)
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return global::haxe.lang.Runtime.undefined;
}
else
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
if (throwErrors)
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found.");
}
else
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return default(object);
}
}
}
#line default
}
public virtual double __hx_lookupField_f(string field, int hash, bool throwErrors)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
if (throwErrors)
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
throw global::haxe.lang.HaxeException.wrap("Field not found or incompatible field type.");
}
else
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return default(double);
}
}
#line default
}
public virtual object __hx_lookupSetField(string field, int hash, object @value)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing.");
}
#line default
}
public virtual double __hx_lookupSetField_f(string field, int hash, double @value)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
throw global::haxe.lang.HaxeException.wrap("Cannot access field for writing or incompatible type.");
}
#line default
}
public virtual double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
switch (hash)
{
case 438291652:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.defaultMode = ((int) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
default:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.__hx_lookupSetField_f(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
switch (hash)
{
case 1575675685:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.hideFlags = ((global::UnityEngine.HideFlags) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 1224700491:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.name = global::haxe.lang.Runtime.toString(@value);
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 5790298:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.tag = global::haxe.lang.Runtime.toString(@value);
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 373703110:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.active = ((bool) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 2117141633:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.enabled = ((bool) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 896046654:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.useGUILayout = ((bool) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 1868699166:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.prevState = ((bool) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 1103412575:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.core = ((global::pony.ui.ButtonCore) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 1679321610:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.autoSwith = ((bool) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 1787604227:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.tooltip = global::haxe.lang.Runtime.toString(@value);
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 1028815620:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.panel = ((bool) (@value) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
case 438291652:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.defaultMode = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return @value;
}
default:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.__hx_lookupSetField(field, hash, @value);
}
}
}
#line default
}
public virtual object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
switch (hash)
{
case 1826409040:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetType"), ((int) (1826409040) ))) );
}
case 304123084:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("ToString"), ((int) (304123084) ))) );
}
case 276486854:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetInstanceID"), ((int) (276486854) ))) );
}
case 295397041:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetHashCode"), ((int) (295397041) ))) );
}
case 1955029599:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Equals"), ((int) (1955029599) ))) );
}
case 1575675685:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.hideFlags;
}
case 1224700491:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.name;
}
case 294420221:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessageUpwards"), ((int) (294420221) ))) );
}
case 139469119:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("SendMessage"), ((int) (139469119) ))) );
}
case 967979664:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentsInChildren"), ((int) (967979664) ))) );
}
case 2122408236:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponents"), ((int) (2122408236) ))) );
}
case 1328964235:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponentInChildren"), ((int) (1328964235) ))) );
}
case 1723652455:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("GetComponent"), ((int) (1723652455) ))) );
}
case 89600725:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CompareTag"), ((int) (89600725) ))) );
}
case 2134927590:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("BroadcastMessage"), ((int) (2134927590) ))) );
}
case 5790298:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.tag;
}
case 373703110:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.active;
}
case 1471506513:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.gameObject;
}
case 1751728597:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.particleSystem;
}
case 524620744:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.particleEmitter;
}
case 964013983:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.hingeJoint;
}
case 1238753076:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.collider;
}
case 674101152:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.guiTexture;
}
case 262266241:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.guiElement;
}
case 1515196979:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.networkView;
}
case 801759432:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.guiText;
}
case 662730966:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.audio;
}
case 853263683:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.renderer;
}
case 1431885287:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.constantForce;
}
case 1261760260:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.animation;
}
case 1962709206:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.light;
}
case 931940005:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.camera;
}
case 1895479501:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.rigidbody;
}
case 1167273324:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.transform;
}
case 2117141633:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.enabled;
}
case 2084823382:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopCoroutine"), ((int) (2084823382) ))) );
}
case 1856815770:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StopAllCoroutines"), ((int) (1856815770) ))) );
}
case 832859768:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine_Auto"), ((int) (832859768) ))) );
}
case 987108662:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("StartCoroutine"), ((int) (987108662) ))) );
}
case 602588383:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("IsInvoking"), ((int) (602588383) ))) );
}
case 1641152943:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("InvokeRepeating"), ((int) (1641152943) ))) );
}
case 1416948632:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Invoke"), ((int) (1416948632) ))) );
}
case 757431474:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("CancelInvoke"), ((int) (757431474) ))) );
}
case 896046654:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.useGUILayout;
}
case 999946793:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Update"), ((int) (999946793) ))) );
}
case 25764:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("sw"), ((int) (25764) ))) );
}
case 1236832596:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("over"), ((int) (1236832596) ))) );
}
case 5546126:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("out"), ((int) (5546126) ))) );
}
case 389604418:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("Start"), ((int) (389604418) ))) );
}
case 1868699166:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.prevState;
}
case 1103412575:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.core;
}
case 1679321610:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.autoSwith;
}
case 1787604227:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.tooltip;
}
case 1028815620:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.panel;
}
case 438291652:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.defaultMode;
}
default:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.__hx_lookupField(field, hash, throwErrors, isCheck);
}
}
}
#line default
}
public virtual double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
switch (hash)
{
case 438291652:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((double) (this.defaultMode) );
}
default:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return this.__hx_lookupField_f(field, hash, throwErrors);
}
}
}
#line default
}
public virtual object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
switch (hash)
{
case 757431474:case 1416948632:case 1641152943:case 602588383:case 987108662:case 832859768:case 1856815770:case 2084823382:case 2134927590:case 89600725:case 1723652455:case 1328964235:case 2122408236:case 967979664:case 139469119:case 294420221:case 1955029599:case 295397041:case 276486854:case 304123084:case 1826409040:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return global::haxe.lang.Runtime.slowCallField(this, field, dynargs);
}
case 999946793:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.Update();
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
break;
}
case 25764:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.sw(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ));
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
break;
}
case 1236832596:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.over();
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
break;
}
case 5546126:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.@out();
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
break;
}
case 389604418:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
this.Start();
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
break;
}
default:
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return ((global::haxe.lang.Function) (this.__hx_getField(field, hash, true, false, false)) ).__hx_invokeDynamic(dynargs);
}
}
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
return default(object);
}
#line default
}
public virtual void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("hideFlags");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("name");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("tag");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("active");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("gameObject");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("particleSystem");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("particleEmitter");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("hingeJoint");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("collider");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("guiTexture");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("guiElement");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("networkView");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("guiText");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("audio");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("renderer");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("constantForce");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("animation");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("light");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("camera");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("rigidbody");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("transform");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("enabled");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("useGUILayout");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("prevState");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("core");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("autoSwith");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("tooltip");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("panel");
#line 45 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/unity3d/ui/Button.hx"
baseArr.push("defaultMode");
}
#line default
}
}
}
| |
using Akka.Actor;
using EasyExecute.ActorSystemFactory;
using EasyExecute.Common;
using EasyExecute.ExecutionQuery;
using EasyExecute.Messages;
using EasyExecute.Reception;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EasyExecuteLib
{
public class EasyExecute
{
private readonly EasyExecuteMain _easyExecuteMain;
internal ActorSystemCreator ActorSystemCreator { get; set; }
internal TimeSpan DefaultMaxExecutionTimePerAskCall = TimeSpan.FromSeconds(5);
internal IActorRef ReceptionActorRef { get; set; }
internal const bool DefaultReturnExistingResultWhenDuplicateId = true;
internal TimeSpan DefaultPurgeInterval = TimeSpan.FromSeconds(30);
internal IActorRef ExecutionQueryActorRef { get; set; }
internal TimeSpan? DefaultCacheExpirationPeriod = TimeSpan.FromDays(365 * 1000);
#region Constructors
public EasyExecute(EasyExecuteOptions easyExecuteOptions = null)
{
easyExecuteOptions = easyExecuteOptions ?? new EasyExecuteOptions();
easyExecuteOptions.serverActorSystemName = (string.IsNullOrEmpty(easyExecuteOptions.serverActorSystemName) && easyExecuteOptions.actorSystem == null)
? Guid.NewGuid().ToString()
: easyExecuteOptions.serverActorSystemName;
_easyExecuteMain = new EasyExecuteMain(this);
ActorSystemCreator = new ActorSystemCreator();
ActorSystemCreator.CreateOrSetUpActorSystem(easyExecuteOptions.serverActorSystemName, easyExecuteOptions.actorSystem, easyExecuteOptions.actorSystemConfig);
ExecutionQueryActorRef = ActorSystemCreator.ServiceActorSystem.ActorOf(Props.Create(() => new ExecutionQueryActor()));
ReceptionActorRef = ActorSystemCreator.ServiceActorSystem.ActorOf(Props.Create(() => new ReceptionActor(easyExecuteOptions.purgeInterval ?? DefaultPurgeInterval, easyExecuteOptions.onWorkerPurged, ExecutionQueryActorRef)));
DefaultMaxExecutionTimePerAskCall = easyExecuteOptions.maxExecutionTimePerAskCall ?? DefaultMaxExecutionTimePerAskCall;
Advanced= new AdvancedOptions();
}
#endregion Constructors
#region HAS ID NO COMMAND HAS RESULT
public async Task<ExecutionResult<TResult>> ExecuteAsync<TResult>(
string id
, Func<Task<TResult>> operation
, TimeSpan? maxExecutionTimePerAskCall = null
, ExecutionRequestOptions executionOptions = null
, Func<ExecutionResult<TResult>, TResult> transformResult = null)
where TResult : class
{
return await _easyExecuteMain.Execute(
id
, new object()
, async (o) => await operation().ConfigureAwait(false)
, null
, maxExecutionTimePerAskCall
, transformResult
, executionOptions).ConfigureAwait(false);
}
public async Task<ExecutionResult<TResult>> ExecuteAsync<TResult>(
string id
, Func<Task<TResult>> operation
, Func<TResult, bool> hasFailed
, TimeSpan? maxExecutionTimePerAskCall = null
, ExecutionRequestOptions executionOptions = null
, Func<ExecutionResult<TResult>, TResult> transformResult = null)
where TResult : class
{
return await _easyExecuteMain.Execute(
id
, new object()
, async(o) => await operation().ConfigureAwait(false)
, hasFailed
, maxExecutionTimePerAskCall
, transformResult
, executionOptions).ConfigureAwait(false);
}
#endregion HAS ID NO COMMAND HAS RESULT
#region HAS ID HAS COMMAND HAS RESULT
public async Task<ExecutionResult<TResult>> ExecuteAsync<TResult, TCommand>(
string id
, TCommand command
, Func<TCommand, Task<TResult>> operation
, TimeSpan? maxExecutionTimePerAskCall = null
, ExecutionRequestOptions executionOptions = null
, Func<ExecutionResult<TResult>, TResult> transformResult = null) where TResult : class
{
return await _easyExecuteMain.Execute(
id
, command
, operation
, null
, maxExecutionTimePerAskCall
, transformResult
, executionOptions).ConfigureAwait(false);
}
public async Task<ExecutionResult<TResult>> ExecuteAsync<TResult, TCommand>(
string id
, TCommand command
, Func<TCommand, Task<TResult>> operation
, Func<TResult, bool> hasFailed
, TimeSpan? maxExecutionTimePerAskCall = null
, ExecutionRequestOptions executionOptions = null
, Func<ExecutionResult<TResult>, TResult> transformResult = null) where TResult : class
{
return await _easyExecuteMain.Execute(
id
, command
, operation
, hasFailed
, maxExecutionTimePerAskCall
, transformResult
, executionOptions).ConfigureAwait(false);
}
#endregion HAS ID HAS COMMAND HAS RESULT
#region HAS ID HAS COMMAND NO RESULT
public async Task<ExecutionResult> ExecuteAsync<TCommand>(
string id
, TCommand command
, Action<TCommand> operation
, TimeSpan? maxExecutionTimePerAskCall = null
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, TCommand>(
id
, command
, (o) => { operation(o); return Task.FromResult(new object()); }
, null
, maxExecutionTimePerAskCall
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
public async Task<ExecutionResult> ExecuteAsync<TCommand>(
string id
, TCommand command
, Action<TCommand> operation
, Func<bool> hasFailed
, TimeSpan? maxExecutionTimePerAskCall = null
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, TCommand>(
id
, command
, (o) => { operation(o); return Task.FromResult(new object()); }
, (r) => hasFailed()
, maxExecutionTimePerAskCall
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
#endregion HAS ID HAS COMMAND NO RESULT
#region HAS ID NO COMMAND NO RESULT
public async Task<ExecutionResult> ExecuteAsync(
string id
, Action operation
, TimeSpan? maxExecutionTimePerAskCall
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, object>(
id
, new object()
, (o) => { operation(); return Task.FromResult(new object()); }
, null
, maxExecutionTimePerAskCall
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
public async Task<ExecutionResult> ExecuteAsync(
string id
, Action operation
, Func<bool> hasFailed
, TimeSpan? maxExecutionTimePerAskCall
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, object>(
id
, new object()
, (o) => { operation(); return Task.FromResult(new object()); }
, (r) => hasFailed()
, maxExecutionTimePerAskCall
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
#endregion HAS ID NO COMMAND NO RESULT
#region NO ID NO COMMAND NO RESULT
public async Task<ExecutionResult> ExecuteAsync(
Action operation
, TimeSpan? maxExecutionTimePerAskCall
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, object>(
Guid.NewGuid().ToString()
, new object()
, (o) => { operation(); return Task.FromResult(new object()); }
, null
, maxExecutionTimePerAskCall
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
public async Task<ExecutionResult> ExecuteAsync(
Action operation
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, object>(
Guid.NewGuid().ToString()
, new object()
, (o) => { operation(); return Task.FromResult(new object()); }
, null
, null
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
public async Task<ExecutionResult> ExecuteAsync(
Action operation
, Func<bool> hasFailed
, TimeSpan? maxExecutionTimePerAskCall
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, object>(
Guid.NewGuid().ToString()
, new object()
, (o) => { operation(); return Task.FromResult(new object()); }
, (r) => hasFailed()
, maxExecutionTimePerAskCall
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
public async Task<ExecutionResult> ExecuteAsync(
Action operation
, Func<bool> hasFailed
, ExecutionRequestOptions executionOptions = null)
{
var result = await _easyExecuteMain.Execute<object, object>(
Guid.NewGuid().ToString()
, new object()
, (o) => { operation(); return Task.FromResult(new object()); }
, (r) => hasFailed()
, null
, null
, executionOptions).ConfigureAwait(false);
return new ExecutionResult()
{
Errors = result.Errors,
Succeeded = result.Succeeded,
WorkerId = result.WorkerId
};
}
#endregion NO ID NO COMMAND NO RESULT
public async Task<ExecutionResult<GetWorkLogCompletedMessage>> GetWorkLogAsync(string workId = null)
{
try
{
var result = await ExecutionQueryActorRef.Ask<GetWorkLogCompletedMessage>(new GetWorkLogMessage(workId)).ConfigureAwait(false);
return new ExecutionResult<GetWorkLogCompletedMessage>()
{
Succeeded = true,
Result = result
};
}
catch (Exception e)
{
return new ExecutionResult<GetWorkLogCompletedMessage>()
{
Succeeded = false,
Errors = new List<string>() { e.Message + " - " + e.InnerException?.Message },
Result = new GetWorkLogCompletedMessage(new List<Worker>(), new List<string>())
};
}
}
public async Task<ExecutionResult<GetWorkHistoryCompletedMessage>> GetWorkHistoryAsync(string workId = null)
{
try
{
var result = await ReceptionActorRef.Ask<GetWorkHistoryCompletedMessage>(new GetWorkHistoryMessage(workId)).ConfigureAwait(false);
return new ExecutionResult<GetWorkHistoryCompletedMessage>()
{
Succeeded = true,
Result = result
};
}
catch (Exception e)
{
return new ExecutionResult<GetWorkHistoryCompletedMessage>()
{
Succeeded = false,
Errors = new List<string>() { e.Message + " - " + e.InnerException?.Message },
Result = new GetWorkHistoryCompletedMessage(new List<Worker>(), DateTime.UtcNow)
};
}
}
private AdvancedOptions Advanced { set; get; }
}
}
| |
using Akka.Actor;
using Akka.DI.Core;
using AkkaPingPong.ActorSystemLib;
using AkkaPingPong.ASLTestKit.Messages;
using AkkaPingPong.ASLTestKit.Mocks;
using AkkaPingPong.ASLTestKit.Models;
using AkkaPingPong.ASLTestKit.State;
using Autofac;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace AkkaPingPong.ASLTestKit
{
public class ActorReceives<T>
{
private ConcurrentDictionary<Tuple<Guid, Type>, object> Mocks { set; get; }
private IContainer Container { set; get; }
private ActorSystem ActorSystem { set; get; }
private T ReceivedMessage { set; get; }
private ConcurrentDictionary<Guid, MockMessages> MessagesReceived { get; }
public ActorReceives(ConcurrentDictionary<Guid, MockMessages> messagesReceived, IContainer container, ActorSystem actorSystem, ConcurrentDictionary<Tuple<Guid, Type>, object> mocks = null, T receivedMessage = default(T))
{
if (container == null) throw new ArgumentNullException(nameof(container));
if (actorSystem == null) throw new ArgumentNullException(nameof(actorSystem));
MessagesReceived = messagesReceived;
ActorSystem = actorSystem;
Container = container;
Mocks = mocks ?? new ConcurrentDictionary<Tuple<Guid, Type>, object>();
ReceivedMessage = receivedMessage;
}
public ActorReceives<TT> WhenActorReceives<TT>()
{
return new ActorReceives<TT>(MessagesReceived, Container, ActorSystem, Mocks);
}
public ActorReceives<MockActorInitializationMessage> WhenActorInitializes()
{
return new ActorReceives<MockActorInitializationMessage>(MessagesReceived, Container, ActorSystem, Mocks);
}
public ActorReceives<T> ItShouldTellAnotherActor<TA>(object message, ActorMetaData parent = null)
{
return ItShouldDo((actorAccess) =>
{
actorAccess.Context.System.LocateActor(typeof(TA), parent).Tell(message);
});
}
public ActorReceives<T> ItShouldTellAnotherActor(Type actorType, object message, ActorSelection parent = null)
{
return ItShouldDo((actorAccess) =>
{
actorAccess.Context.System.LocateActor(actorType, parent).Tell(message);
});
}
public ActorReceives<T> ItShouldTellAnotherActor(IActorRef actorRef, object message = null)
{
return ItShouldDo((actorAccess) =>
{
actorRef.Tell(message);
});
}
public ActorReceives<T> ItShouldDoNothing()
{
return this;
}
public ActorReceives<T> ItShouldCreateChildActor(Type childActorType, ActorSetUpOptions options = null)
{
return ItShouldDo((actorAccess) =>
{
HandleChildActorType(childActorType, actorAccess.ActorChildren, (actor) =>
{
actor.ActorRef = CreateChildActor(actorAccess.Context, actor.ActorType, options ?? new ActorSetUpOptions());
});
});
}
public object Message { get; set; }
public ActorReceives<T> ItShouldForwardItTo<TTC>(object message, ActorSelection parent = null)
{
return ItShouldForwardItTo(typeof(TTC), message, parent);
}
public ActorReceives<T> ItShouldForwardItTo(Type actorType, object message, ActorSelection parent = null)
{
return ItShouldDo((actorAccess) =>
{
var destActor = actorAccess.Context.System.LocateActor(actorType, parent);
destActor.Tell(message, actorAccess.Context.Sender);
});
}
public ActorReceives<T> ItShouldTellItToChildActor<TTC>(object message)
{
return ItShouldTellItToChildActor(typeof(TTC), message);
}
public ActorReceives<T> ItShouldTellItToChildActor(Type actorType, object message)
{
return ItShouldDo((actorAccess) =>
{
HandleChildActorType(actorType, actorAccess.ActorChildren, (actor) =>
{
actor.ActorRef.Tell(message);
});
});
}
private static IActorRef CreateChildActor(IActorContext context, Type actorType, ActorSetUpOptions options)
{
var props = context.DI().Props(actorType);
props = SelectableActor.PrepareProps(options, props);
var actorRef = context.ActorOf(props, SelectableActor.GetActorNameByType(null, actorType));
return actorRef;
}
private static void HandleChildActorType(Type childActorType, Tuple<InjectedActors, InjectedActors, InjectedActors, InjectedActors> injectedActors, Action<InjectedActors> operation)
{
if (injectedActors == null) return;
if (injectedActors.Item1 != null && injectedActors.Item1.ActorType == childActorType)
{
operation(injectedActors.Item1);
}
if (injectedActors.Item2 != null && injectedActors.Item2.ActorType == childActorType)
{
operation(injectedActors.Item2);
}
if (injectedActors.Item3 != null && injectedActors.Item3.ActorType == childActorType)
{
operation(injectedActors.Item3);
}
if (injectedActors.Item4 != null && injectedActors.Item4.ActorType == childActorType)
{
operation(injectedActors.Item4);
}
}
public ActorReceives<T> ItShouldForwardItToChildActor(Type actorType, object message)
{
return ItShouldDo((actorAccess) =>
{
HandleChildActorType(actorType, actorAccess.ActorChildren, (actor) =>
{
actor.ActorRef.Forward(message);
});
});
}
public ActorReceives<T> ItShouldForwardItTo(IActorRef actorType, object message)
{
return ItShouldDo((actorAccess) =>
{
actorType.Forward(message);
});
}
public ActorReceives<T> ItShouldTellSender<TResponse>(TResponse response)
{
return ItShouldDo((actorAccess) =>
{
actorAccess.Context.Sender.Tell(response);
});
}
public IActorRef CreateMockActorRef<TActor>() where TActor : ActorBase
{
var actor = SetUpMockActor<TActor>();
var actorref = ActorSystem.CreateActor<TActor>();
return actorref;
}
public Type SetUpMockActor<TActor>() where TActor : ActorBase
{
var actor = CreateMockActor<TActor>(Mocks);
return actor;
}
public Type CreateMockActor<TActor>() where TActor : ActorBase
{
var actor = SetUpMockActor<TActor>();
var actorref = ActorSystem.CreateActor<TActor>();
return actor;
}
public ActorSelection CreateMockActorSelection<TActor>() where TActor : ActorBase
{
var actor = CreateMockActor<TActor>(Mocks);
ActorSystem.CreateActor<TActor>();
var actorSelection = ActorSystem.LocateActor<TActor>();
return actorSelection;
}
protected Type CreateMockActor<TMockActor>(ConcurrentDictionary<Tuple<Guid, Type>, object> mocks) where TMockActor : ActorBase
{
ItShouldDo((actorAccess) => MessagesReceived.GetOrAdd(Guid.NewGuid(), new MockMessages(actorAccess.Context.Self.ToActorMetaData().Path, typeof(T))));
Console.WriteLine("Setting Up Actor " + typeof(TMockActor).Name + " with " + mocks.Count + " items ....");
foreach (var mock in mocks)
{
var builder = new ContainerBuilder();
builder.RegisterType<TMockActor>();
var mockActorState = new MockActorState();
if (Container.IsRegistered<IMockActorState>())
{
var state = (MockActorState)Container.Resolve<IMockActorState>();
mockActorState = state ?? mockActorState;
}
mockActorState.MockSetUpMessages = mockActorState.MockSetUpMessages ?? new List<MockSetUpMessage>();
mockActorState.MockSetUpMessages.Add(new MockSetUpMessage(typeof(TMockActor), mock.Key.Item2, mock.Value));
Console.WriteLine("When Received is " + mock.Key.Item2 + " The response will be " + mock.Value);
builder.RegisterType<IMockActorState>();
builder.Register<IMockActorState>(c => mockActorState);
builder.Update(Container);
}
var state1 = (MockActorState)Container.Resolve<IMockActorState>();
Console.WriteLine("State now has " + state1.MockSetUpMessages.Count + " items ....");
return typeof(TMockActor);
}
public ActorReceives<T> ItShouldDo(Action operation)
{
Action<ActorAccess> op =(a) => { operation(); };
Mocks.GetOrAdd(new Tuple<Guid, Type>(Guid.NewGuid(), typeof(T)), new ItShouldExecuteLambda(op));
return this;
}
public ActorReceives<T> ItShouldDo(Action<ActorAccess> operation)
{
Action<ActorAccess> op =(a) => { operation(a); };
Mocks.GetOrAdd(new Tuple<Guid, Type>(Guid.NewGuid(), typeof(T)), new ItShouldExecuteLambda(op));
return this;
}
}
public class ActorReceives : ActorReceives<object>
{
public ActorReceives(ConcurrentDictionary<Guid, MockMessages> messagesReceived, IContainer container, ActorSystem actorSystem, ConcurrentDictionary<Tuple<Guid, Type>, object> mocks = null) : base(messagesReceived, container, actorSystem, mocks)
{
}
}
}
| |
// 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.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
namespace System.Data
{
internal sealed class ConstNode : ExpressionNode
{
internal readonly object _val;
internal ConstNode(DataTable table, ValueType type, object constant) : this(table, type, constant, true)
{
}
internal ConstNode(DataTable table, ValueType type, object constant, bool fParseQuotes) : base(table)
{
switch (type)
{
case ValueType.Null:
_val = DBNull.Value;
break;
case ValueType.Numeric:
_val = SmallestNumeric(constant);
break;
case ValueType.Decimal:
_val = SmallestDecimal(constant);
break;
case ValueType.Float:
_val = Convert.ToDouble(constant, NumberFormatInfo.InvariantInfo);
break;
case ValueType.Bool:
_val = Convert.ToBoolean(constant, CultureInfo.InvariantCulture);
break;
case ValueType.Str:
if (fParseQuotes)
{
// replace '' with one '
_val = ((string)constant).Replace("''", "'");
}
else
{
_val = (string)constant;
}
break;
case ValueType.Date:
_val = DateTime.Parse((string)constant, CultureInfo.InvariantCulture);
break;
case ValueType.Object:
_val = constant;
break;
default:
Debug.Fail("NYI");
goto case ValueType.Object;
}
}
internal override void Bind(DataTable table, List<DataColumn> list)
{
BindTable(table);
}
internal override object Eval()
{
return _val;
}
internal override object Eval(DataRow row, DataRowVersion version)
{
return Eval();
}
internal override object Eval(int[] recordNos)
{
return Eval();
}
internal override bool IsConstant()
{
return true;
}
internal override bool IsTableConstant()
{
return true;
}
internal override bool HasLocalAggregate()
{
return false;
}
internal override bool HasRemoteAggregate()
{
return false;
}
internal override ExpressionNode Optimize()
{
return this;
}
private object SmallestDecimal(object constant)
{
if (null == constant)
{
return 0d;
}
else
{
string sval = (constant as string);
if (null != sval)
{
decimal r12;
if (decimal.TryParse(sval, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out r12))
{
return r12;
}
double r8;
if (double.TryParse(sval, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out r8))
{
return r8;
}
}
else
{
IConvertible convertible = (constant as IConvertible);
if (null != convertible)
{
try
{
return convertible.ToDecimal(NumberFormatInfo.InvariantInfo);
}
catch (System.ArgumentException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.FormatException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.InvalidCastException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.OverflowException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
try
{
return convertible.ToDouble(NumberFormatInfo.InvariantInfo);
}
catch (System.ArgumentException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.FormatException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.InvalidCastException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.OverflowException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
}
}
}
return constant;
}
private object SmallestNumeric(object constant)
{
if (null == constant)
{
return 0;
}
else
{
string sval = (constant as string);
if (null != sval)
{
int i4;
if (int.TryParse(sval, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out i4))
{
return i4;
}
long i8;
if (long.TryParse(sval, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out i8))
{
return i8;
}
double r8;
if (double.TryParse(sval, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out r8))
{
return r8;
}
}
else
{
IConvertible convertible = (constant as IConvertible);
if (null != convertible)
{
try
{
return convertible.ToInt32(NumberFormatInfo.InvariantInfo);
}
catch (System.ArgumentException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.FormatException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.InvalidCastException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.OverflowException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
try
{
return convertible.ToInt64(NumberFormatInfo.InvariantInfo);
}
catch (System.ArgumentException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.FormatException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.InvalidCastException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.OverflowException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
try
{
return convertible.ToDouble(NumberFormatInfo.InvariantInfo);
}
catch (System.ArgumentException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.FormatException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.InvalidCastException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
catch (System.OverflowException e)
{
ExceptionBuilder.TraceExceptionWithoutRethrow(e);
}
}
}
}
return constant;
}
}
}
| |
using System;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This class is general purpose class for writing data to a buffer.
///
/// It allows you to write bits as well as bytes
/// Based on DeflaterPending.java
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class PendingBuffer
{
#region Instance Fields
/// <summary>
/// Internal work buffer
/// </summary>
readonly byte[] buffer;
int start;
int end;
uint bits;
int bitCount;
#endregion
#region Constructors
/// <summary>
/// construct instance using default buffer size of 4096
/// </summary>
public PendingBuffer() : this(4096)
{
}
/// <summary>
/// construct instance using specified buffer size
/// </summary>
/// <param name="bufferSize">
/// size to use for internal buffer
/// </param>
public PendingBuffer(int bufferSize)
{
buffer = new byte[bufferSize];
}
#endregion
/// <summary>
/// Clear internal state/buffers
/// </summary>
public void Reset()
{
start = end = bitCount = 0;
}
/// <summary>
/// Write a byte to buffer
/// </summary>
/// <param name="value">
/// The value to write
/// </param>
public void WriteByte(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer[end++] = unchecked((byte)value);
}
/// <summary>
/// Write a short value to buffer LSB first
/// </summary>
/// <param name="value">
/// The value to write.
/// </param>
public void WriteShort(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer[end++] = unchecked((byte)value);
buffer[end++] = unchecked((byte)(value >> 8));
}
/// <summary>
/// write an integer LSB first
/// </summary>
/// <param name="value">The value to write.</param>
public void WriteInt(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer[end++] = unchecked((byte)value);
buffer[end++] = unchecked((byte)(value >> 8));
buffer[end++] = unchecked((byte)(value >> 16));
buffer[end++] = unchecked((byte)(value >> 24));
}
/// <summary>
/// Write a block of data to buffer
/// </summary>
/// <param name="block">data to write</param>
/// <param name="offset">offset of first byte to write</param>
/// <param name="length">number of bytes to write</param>
public void WriteBlock(byte[] block, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
System.Array.Copy(block, offset, buffer, end, length);
end += length;
}
/// <summary>
/// The number of bits written to the buffer
/// </summary>
public int BitCount {
get {
return bitCount;
}
}
/// <summary>
/// Align internal buffer on a byte boundary
/// </summary>
public void AlignToByte()
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
if (bitCount > 0) {
buffer[end++] = unchecked((byte)bits);
if (bitCount > 8) {
buffer[end++] = unchecked((byte)(bits >> 8));
}
}
bits = 0;
bitCount = 0;
}
/// <summary>
/// Write bits to internal buffer
/// </summary>
/// <param name="b">source of bits</param>
/// <param name="count">number of bits to write</param>
public void WriteBits(int b, int count)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("writeBits("+b+","+count+")");
// }
#endif
bits |= (uint)(b << bitCount);
bitCount += count;
if (bitCount >= 16) {
buffer[end++] = unchecked((byte)bits);
buffer[end++] = unchecked((byte)(bits >> 8));
bits >>= 16;
bitCount -= 16;
}
}
/// <summary>
/// Write a short value to internal buffer most significant byte first
/// </summary>
/// <param name="s">value to write</param>
public void WriteShortMSB(int s)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer[end++] = unchecked((byte)(s >> 8));
buffer[end++] = unchecked((byte)s);
}
/// <summary>
/// Indicates if buffer has been flushed
/// </summary>
public bool IsFlushed {
get {
return end == 0;
}
}
/// <summary>
/// Flushes the pending buffer into the given output array. If the
/// output array is to small, only a partial flush is done.
/// </summary>
/// <param name="output">The output array.</param>
/// <param name="offset">The offset into output array.</param>
/// <param name="length">The maximum number of bytes to store.</param>
/// <returns>The number of bytes flushed.</returns>
public int Flush(byte[] output, int offset, int length)
{
if (bitCount >= 8) {
buffer[end++] = unchecked((byte)bits);
bits >>= 8;
bitCount -= 8;
}
if (length > end - start) {
length = end - start;
System.Array.Copy(buffer, start, output, offset, length);
start = 0;
end = 0;
} else {
System.Array.Copy(buffer, start, output, offset, length);
start += length;
}
return length;
}
/// <summary>
/// Convert internal buffer to byte array.
/// Buffer is empty on completion
/// </summary>
/// <returns>
/// The internal buffer contents converted to a byte array.
/// </returns>
public byte[] ToByteArray()
{
AlignToByte();
byte[] result = new byte[end - start];
System.Array.Copy(buffer, start, result, 0, result.Length);
start = 0;
end = 0;
return result;
}
}
}
| |
using System;
using Csla;
using Csla.Data;
using DalEf;
using Csla.Serialization;
using System.ComponentModel.DataAnnotations;
using BusinessObjects.Properties;
using System.Linq;
using BusinessObjects.CoreBusinessClasses;
using BusinessObjects.Common;
namespace BusinessObjects.MDGeneral
{
[Serializable]
public partial class cMDGeneral_Enums_Language: CoreBusinessClass<cMDGeneral_Enums_Language>
{
#region Business Methods
public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty);
#if !SILVERLIGHT
[System.ComponentModel.DataObjectField(true, true)]
#endif
public System.Int32 Id
{
get { return GetProperty(IdProperty); }
internal set { SetProperty(IdProperty, value); }
}
private static readonly PropertyInfo< System.String > nameProperty = RegisterProperty<System.String>(p => p.Name, string.Empty);
[System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))]
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.String Name
{
get { return GetProperty(nameProperty); }
set { SetProperty(nameProperty, value.Trim()); }
}
private static readonly PropertyInfo<System.String> labelProperty = RegisterProperty<System.String>(p => p.Label, string.Empty);
[System.ComponentModel.DataAnnotations.StringLength(10, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))]
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.String Label
{
get { return GetProperty(labelProperty); }
set { SetProperty(labelProperty, value.Trim()); }
}
private static readonly PropertyInfo< bool > defaultLanguageProperty = RegisterProperty<bool>(p => p.DefaultLanguage, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public bool DefaultLanguage
{
get { return GetProperty(defaultLanguageProperty); }
set { SetProperty(defaultLanguageProperty, value); }
}
private static readonly PropertyInfo< bool > inactiveProperty = RegisterProperty<bool>(p => p.Inactive, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public bool Inactive
{
get { return GetProperty(inactiveProperty); }
set { SetProperty(inactiveProperty, value); }
}
protected static readonly PropertyInfo<System.Int32?> companyUsingServiceIdProperty = RegisterProperty<System.Int32?>(p => p.CompanyUsingServiceId, string.Empty);
public System.Int32? CompanyUsingServiceId
{
get { return GetProperty(companyUsingServiceIdProperty); }
set { SetProperty(companyUsingServiceIdProperty, value); }
}
/// <summary>
/// Used for optimistic concurrency.
/// </summary>
[NotUndoable]
internal System.Byte[] LastChanged = new System.Byte[8];
#endregion
#region Factory Methods
public static cMDGeneral_Enums_Language NewMDGeneral_Enums_Language()
{
return DataPortal.Create<cMDGeneral_Enums_Language>();
}
public static cMDGeneral_Enums_Language GetMDGeneral_Enums_Language(int uniqueId)
{
return DataPortal.Fetch<cMDGeneral_Enums_Language>(new SingleCriteria<cMDGeneral_Enums_Language, int>(uniqueId));
}
internal static cMDGeneral_Enums_Language GetMDGeneral_Enums_Language(MDGeneral_Enums_Language data)
{
return DataPortal.Fetch<cMDGeneral_Enums_Language>(data);
}
#endregion
#region Data Access
[RunLocal]
protected override void DataPortal_Create()
{
BusinessRules.CheckRules();
}
private void DataPortal_Fetch(SingleCriteria<cMDGeneral_Enums_Language, int> criteria)
{
using (var ctx = ObjectContextManager<MDGeneralEntities>.GetManager("MDGeneralEntities"))
{
var data = ctx.ObjectContext.MDGeneral_Enums_Language.First(p => p.Id == criteria.Value);
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<string>(nameProperty, data.Name);
LoadProperty<string>(labelProperty, data.Label);
LoadProperty<bool>(defaultLanguageProperty, data.DefaultLanguage);
LoadProperty<bool>(inactiveProperty, data.Inactive);
LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId);
LastChanged = data.LastChanged;
BusinessRules.CheckRules();
}
}
private void DataPortal_Fetch(MDGeneral_Enums_Language data)
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<string>(nameProperty, data.Name);
LoadProperty<string>(labelProperty, data.Label);
LoadProperty<bool>(defaultLanguageProperty, data.DefaultLanguage);
LoadProperty<bool>(inactiveProperty, data.Inactive);
LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId);
LastChanged = data.LastChanged;
BusinessRules.CheckRules();
MarkAsChild();
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ObjectContextManager<MDGeneralEntities>.GetManager("MDGeneralEntities"))
{
var data = new MDGeneral_Enums_Language();
data.Name = ReadProperty<string>(nameProperty);
data.Label = ReadProperty<string>(labelProperty);
data.DefaultLanguage = ReadProperty<bool>(defaultLanguageProperty);
data.Inactive = ReadProperty<bool>(inactiveProperty);
data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty);
ctx.ObjectContext.AddToMDGeneral_Enums_Language(data);
ctx.ObjectContext.SaveChanges();
//Get New id
int newId = data.Id;
//Load New Id into object
LoadProperty(IdProperty, newId);
//Load New EntityKey into Object
LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey));
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ObjectContextManager<MDGeneralEntities>.GetManager("MDGeneralEntities"))
{
var data = new MDGeneral_Enums_Language();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
data.Name = ReadProperty<string>(nameProperty);
data.Label = ReadProperty<string>(labelProperty);
data.DefaultLanguage = ReadProperty<bool>(defaultLanguageProperty);
data.Inactive = ReadProperty<bool>(inactiveProperty);
data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty);
ctx.ObjectContext.SaveChanges();
}
}
#endregion
}
public partial class cMDGeneral_Enums_Language_List : BusinessListBase<cMDGeneral_Enums_Language_List, cMDGeneral_Enums_Language>
{
public static cMDGeneral_Enums_Language_List GetcMDGeneral_Enums_Language_List()
{
return DataPortal.Fetch<cMDGeneral_Enums_Language_List>();
}
public static cMDGeneral_Enums_Language_List GetcMDGeneral_Enums_Language_List(int companyId, int includeInactiveId)
{
return DataPortal.Fetch<cMDGeneral_Enums_Language_List>(new ActiveEnums_Criteria(companyId, includeInactiveId));
}
private void DataPortal_Fetch()
{
using (var ctx = ObjectContextManager<MDGeneralEntities>.GetManager("MDGeneralEntities"))
{
var result = ctx.ObjectContext.MDGeneral_Enums_Language;
foreach (var data in result)
{
var obj = cMDGeneral_Enums_Language.GetMDGeneral_Enums_Language(data);
this.Add(obj);
}
}
}
private void DataPortal_Fetch(ActiveEnums_Criteria criteria)
{
using (var ctx = ObjectContextManager<MDGeneralEntities>.GetManager("MDGeneralEntities"))
{
var result = ctx.ObjectContext.MDGeneral_Enums_Language.Where(p => (p.CompanyUsingServiceId == criteria.CompanyId || (p.CompanyUsingServiceId ?? 0) == 0) && (p.Inactive == false || p.Id == criteria.IncludeInactiveId));
foreach (var data in result)
{
var obj = cMDGeneral_Enums_Language.GetMDGeneral_Enums_Language(data);
this.Add(obj);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DebuggerDisplayAttributeTests : CSharpResultProviderTestBase
{
[Fact]
public void WithoutExpressionHoles()
{
var source = @"
using System.Diagnostics;
class C0 { }
[DebuggerDisplay(""Value"")]
class C1 { }
[DebuggerDisplay(""Value"", Name=""Name"")]
class C2 { }
[DebuggerDisplay(""Value"", Type=""Type"")]
class C3 { }
[DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")]
class C4 { }
class Wrapper
{
C0 c0 = new C0();
C1 c1 = new C1();
C2 c2 = new C2();
C3 c3 = new C3();
C4 c4 = new C4();
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("Wrapper");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
Verify(GetChildren(FormatResult("w", value)),
EvalResult("c0", "{C0}", "C0", "w.c0", DkmEvaluationResultFlags.None),
EvalResult("c1", "Value", "C1", "w.c1", DkmEvaluationResultFlags.None),
EvalResult("Name", "Value", "C2", "w.c2", DkmEvaluationResultFlags.None),
EvalResult("c3", "Value", "Type", "w.c3", DkmEvaluationResultFlags.None),
EvalResult("Name", "Value", "Type", "w.c4", DkmEvaluationResultFlags.None));
}
[Fact]
public void OnlyExpressionHoles()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""{value}"", Name=""{name}"", Type=""{type}"")]
class C
{
string name = ""Name"";
string value = ""Value"";
string type = ""Type"";
}
class Wrapper
{
C c = new C();
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("Wrapper");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
Verify(GetChildren(FormatResult("c", value)),
EvalResult("\"Name\"", "\"Value\"", "\"Type\"", "c.c", DkmEvaluationResultFlags.Expandable));
}
[Fact]
public void FormatStrings()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""<{value}>"", Name=""<{name}>"", Type=""<{type}>"")]
class C
{
string name = ""Name"";
string value = ""Value"";
string type = ""Type"";
}
class Wrapper
{
C c = new C();
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("Wrapper");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
Verify(GetChildren(FormatResult("w", value)),
EvalResult("<\"Name\">", "<\"Value\">", "<\"Type\">", "w.c", DkmEvaluationResultFlags.Expandable));
}
[Fact]
public void BindingError()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""<{missing}>"")]
class C
{
}
";
const string rootExpr = "c"; // Note that this is the full name in all cases - DebuggerDisplayAttribute does not affect it.
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
Verify(FormatResult(rootExpr, value),
EvalResult(rootExpr, "<Problem evaluating expression>", "C", rootExpr, DkmEvaluationResultFlags.None)); // Message inlined without quotation marks.
}
[Fact]
public void RecursiveDebuggerDisplay()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""{value}"")]
class C
{
C value;
C()
{
this.value = this;
}
}
";
const string rootExpr = "c";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
// No stack overflow, since attribute on computed value is ignored.
Verify(FormatResult(rootExpr, value),
EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable));
}
[Fact]
public void MultipleAttributes()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""V1"")]
[DebuggerDisplay(""V2"")]
class C
{
}
";
const string rootExpr = "c";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
// First attribute wins, as in dev12.
Verify(FormatResult(rootExpr, value),
EvalResult(rootExpr, "V1", "C", rootExpr));
}
[Fact]
public void NullValues()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(null, Name=null, Type=null)]
class C
{
}
";
const string rootExpr = "c";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
Verify(FormatResult(rootExpr, value),
EvalResult(rootExpr, "{C}", "C", rootExpr));
}
[Fact]
public void EmptyStringValues()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay("""", Name="""", Type="""")]
class C
{
}
class Wrapper
{
C c = new C();
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("Wrapper");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
Verify(GetChildren(FormatResult("w", value)),
EvalResult("", "", "", "w.c"));
}
[Fact]
public void ConstructedGenericType()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Name"")]
class C<T>
{
}
";
const string rootExpr = "c";
var assembly = GetAssembly(source);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
Verify(FormatResult(rootExpr, value),
EvalResult("c", "Name", "C<int>", rootExpr));
}
[Fact]
public void MemberExpansion()
{
var source = @"
using System.Diagnostics;
interface I
{
D P { get; }
}
class C : I
{
D I.P { get { return new D(); } }
D Q { get { return new D(); } }
}
[DebuggerDisplay(""Value"", Name=""Name"")]
class D
{
}
";
const string rootExpr = "c";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
var root = FormatResult(rootExpr, value);
Verify(root,
EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(root),
EvalResult("Name", "Value", "D", "((I)c).P", DkmEvaluationResultFlags.ReadOnly), // Not "I.Name".
EvalResult("Name", "Value", "D", "c.Q", DkmEvaluationResultFlags.ReadOnly));
}
[Fact]
public void PointerDereferenceExpansion_Null()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")]
unsafe struct Display
{
Display* DisplayPointer;
NoDisplay* NoDisplayPointer;
}
unsafe struct NoDisplay
{
Display* DisplayPointer;
NoDisplay* NoDisplayPointer;
}
class Wrapper
{
Display display = new Display();
}
";
var assembly = GetUnsafeAssembly(source);
var type = assembly.GetType("Wrapper");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
var root = FormatResult("wrapper", value);
Verify(DepthFirstSearch(GetChildren(root).Single(), maxDepth: 3),
EvalResult("Name", "Value", "Type", "wrapper.display", DkmEvaluationResultFlags.Expandable),
EvalResult("DisplayPointer", PointerToString(IntPtr.Zero), "Display*", "wrapper.display.DisplayPointer"),
EvalResult("NoDisplayPointer", PointerToString(IntPtr.Zero), "NoDisplay*", "wrapper.display.NoDisplayPointer"));
}
[Fact]
public void PointerDereferenceExpansion_NonNull()
{
var source = @"
using System;
using System.Diagnostics;
[DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")]
unsafe struct Display
{
public Display* DisplayPointer;
public NoDisplay* NoDisplayPointer;
}
unsafe struct NoDisplay
{
public Display* DisplayPointer;
public NoDisplay* NoDisplayPointer;
}
unsafe class C
{
Display* DisplayPointer;
NoDisplay* NoDisplayPointer;
public C(IntPtr d, IntPtr nd)
{
this.DisplayPointer = (Display*)d;
this.NoDisplayPointer = (NoDisplay*)nd;
this.DisplayPointer->DisplayPointer = this.DisplayPointer;
this.DisplayPointer->NoDisplayPointer = this.NoDisplayPointer;
this.NoDisplayPointer->DisplayPointer = this.DisplayPointer;
this.NoDisplayPointer->NoDisplayPointer = this.NoDisplayPointer;
}
}
";
var assembly = GetUnsafeAssembly(source);
unsafe
{
var displayType = assembly.GetType("Display");
var displayInstance = displayType.Instantiate();
var displayHandle = GCHandle.Alloc(displayInstance, GCHandleType.Pinned);
var displayPtr = displayHandle.AddrOfPinnedObject();
var noDisplayType = assembly.GetType("NoDisplay");
var noDisplayInstance = noDisplayType.Instantiate();
var noDisplayHandle = GCHandle.Alloc(noDisplayInstance, GCHandleType.Pinned);
var noDisplayPtr = noDisplayHandle.AddrOfPinnedObject();
var testType = assembly.GetType("C");
var testInstance = ReflectionUtilities.Instantiate(testType, displayPtr, noDisplayPtr);
var testValue = CreateDkmClrValue(testInstance, testType, evalFlags: DkmEvaluationResultFlags.None);
var displayPtrString = PointerToString(displayPtr);
var noDisplayPtrString = PointerToString(noDisplayPtr);
Verify(DepthFirstSearch(FormatResult("c", testValue), maxDepth: 3),
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable),
EvalResult("DisplayPointer", displayPtrString, "Display*", "c.DisplayPointer", DkmEvaluationResultFlags.Expandable),
EvalResult("*c.DisplayPointer", "Value", "Type", "*c.DisplayPointer", DkmEvaluationResultFlags.Expandable),
EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.DisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable),
EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.DisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable),
EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable),
EvalResult("*c.NoDisplayPointer", "{NoDisplay}", "NoDisplay", "*c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable),
EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.NoDisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable),
EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.NoDisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable));
displayHandle.Free();
noDisplayHandle.Free();
}
}
[Fact]
public void ArrayExpansion()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")]
struct Display
{
public Display[] DisplayArray;
public NoDisplay[] NoDisplayArray;
}
struct NoDisplay
{
public Display[] DisplayArray;
public NoDisplay[] NoDisplayArray;
}
class C
{
public Display[] DisplayArray;
public NoDisplay[] NoDisplayArray;
public C()
{
this.DisplayArray = new[] { new Display() };
this.NoDisplayArray = new[] { new NoDisplay() };
this.DisplayArray[0].DisplayArray = this.DisplayArray;
this.DisplayArray[0].NoDisplayArray = this.NoDisplayArray;
this.NoDisplayArray[0].DisplayArray = this.DisplayArray;
this.NoDisplayArray[0].NoDisplayArray = this.NoDisplayArray;
}
}
";
var assembly = GetUnsafeAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
var root = FormatResult("c", value);
Verify(DepthFirstSearch(root, maxDepth: 4),
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable),
EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray", DkmEvaluationResultFlags.Expandable),
EvalResult("Name", "Value", "Type", "c.DisplayArray[0]", DkmEvaluationResultFlags.Expandable),
EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable),
EvalResult("Name", "Value", "Type", "c.DisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable),
EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.DisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable),
EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.DisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable),
EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray", DkmEvaluationResultFlags.Expandable),
EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable),
EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.NoDisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable),
EvalResult("Name", "Value", "Type", "c.NoDisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable),
EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable),
EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable));
}
[Fact]
public void DebuggerTypeProxyExpansion()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")]
public struct Display { }
public struct NoDisplay { }
[DebuggerTypeProxy(typeof(P))]
public class C
{
public Display DisplayC = new Display();
public NoDisplay NoDisplayC = new NoDisplay();
}
public class P
{
public Display DisplayP = new Display();
public NoDisplay NoDisplayP = new NoDisplay();
public P(C c) { }
}
";
var assembly = GetUnsafeAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
var root = FormatResult("c", value);
Verify(DepthFirstSearch(root, maxDepth: 4),
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable),
EvalResult("Name", "Value", "Type", "new P(c).DisplayP"),
EvalResult("NoDisplayP", "{NoDisplay}", "NoDisplay", "new P(c).NoDisplayP"),
EvalResult("Raw View", null, "", "c, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Name", "Value", "Type", "c.DisplayC"),
EvalResult("NoDisplayC", "{NoDisplay}", "NoDisplay", "c.NoDisplayC"));
}
[Fact]
public void NullInstance()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Hello"")]
class C
{
}
";
const string rootExpr = "c";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(null, type, evalFlags: DkmEvaluationResultFlags.None);
Verify(FormatResult(rootExpr, value),
EvalResult(rootExpr, "null", "C", rootExpr));
}
[Fact]
public void NonGenericDisplayAttributeOnGenericBase()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Type={GetType()}"")]
class A<T> { }
class B : A<int> { }
";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None);
var result = FormatResult("b", value);
Verify(result,
EvalResult("b", "Type={B}", "B", "b", DkmEvaluationResultFlags.None));
}
[WorkItem(1016895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016895")]
[Fact]
public void RootVersusInternal()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Value"", Name = ""Name"")]
class A { }
class B
{
A a;
public B(A a)
{
this.a = a;
}
}
";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var typeB = assembly.GetType("B");
var instanceA = typeA.Instantiate();
var instanceB = typeB.Instantiate(instanceA);
var result = FormatResult("a", CreateDkmClrValue(instanceA));
Verify(result,
EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None));
result = FormatResult("b", CreateDkmClrValue(instanceB));
Verify(GetChildren(result),
EvalResult("Name", "Value", "A", "b.a", DkmEvaluationResultFlags.None));
}
[Fact]
public void Error()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")]
class A
{
}
class B
{
bool f;
internal A P { get { return new A(); } }
internal A Q { get { while(f) { } return new A(); } }
}
";
DkmClrRuntimeInstance runtime = null;
GetMemberValueDelegate getMemberValue = (v, m) => (m == "Q") ? CreateErrorValue(runtime.GetType("A"), "Function evaluation timed out") : null;
runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue);
using (runtime.Load())
{
var type = runtime.GetType("B");
var value = CreateDkmClrValue(type.Instantiate(), type: type);
var evalResult = FormatResult("o", value);
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Name", "Value", "Type", "o.P", DkmEvaluationResultFlags.ReadOnly),
EvalFailedResult("Q", "Function evaluation timed out", "A", "o.Q"),
EvalResult("f", "false", "bool", "o.f", DkmEvaluationResultFlags.Boolean));
}
}
[Fact]
public void UnhandledException()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""Value}"")]
class A
{
internal int Value;
}
";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var instanceA = typeA.Instantiate();
var result = FormatResult("a", CreateDkmClrValue(instanceA));
Verify(result,
EvalFailedResult("a", "Unmatched closing brace in 'Value}'", null, null, DkmEvaluationResultFlags.None));
}
[Fact, WorkItem(171123, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv")]
public void ExceptionDuringEvaluate()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""Make it throw."")]
public class Picard { }
";
var assembly = GetAssembly(source);
var picard = assembly.GetType("Picard");
var jeanLuc = picard.Instantiate();
var result = FormatAsyncResult("says", "says", CreateDkmClrValue(jeanLuc), declaredType: new BadType(picard));
Assert.Equal(BadType.Exception, result.Exception);
}
private class BadType : DkmClrType
{
public static readonly Exception Exception = new TargetInvocationException(new DkmException(DkmExceptionCode.E_PROCESS_DESTROYED));
public BadType(System.Type innerType)
: base((TypeImpl)innerType)
{
}
public override VisualStudio.Debugger.Metadata.Type GetLmrType()
{
if (Environment.StackTrace.Contains("Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.GetTypeName"))
{
throw Exception;
}
return base.GetLmrType();
}
}
private IReadOnlyList<DkmEvaluationResult> DepthFirstSearch(DkmEvaluationResult root, int maxDepth)
{
var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance();
DepthFirstSearchInternal(builder, root, 0, maxDepth);
return builder.ToImmutableAndFree();
}
private void DepthFirstSearchInternal(ArrayBuilder<DkmEvaluationResult> builder, DkmEvaluationResult curr, int depth, int maxDepth)
{
Assert.InRange(depth, 0, maxDepth);
builder.Add(curr);
var childDepth = depth + 1;
if (childDepth <= maxDepth)
{
foreach (var child in GetChildren(curr))
{
DepthFirstSearchInternal(builder, child, childDepth, maxDepth);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using NUnit.Framework;
namespace SpecEasy
{
[TestFixture]
public class Spec
{
[Test, TestCaseSource("TestCases")]
public void Verify(Action test)
{
test();
}
public IList<TestCaseData> TestCases
{
get
{
return BuildTestCases();
}
}
private IList<TestCaseData> BuildTestCases()
{
CreateMethodContexts();
return BuildTestCases(new List<KeyValuePair<string, Context>>(), 0);
}
private IList<TestCaseData> BuildTestCases(List<KeyValuePair<string, Context>> contextList, int depth)
{
var testCases = new List<TestCaseData>();
var cachedWhen = when;
foreach (var namedContext in contexts.Select(kvp => kvp))
{
var givenContext = namedContext.Value;
then = new Dictionary<string, Action>();
contexts = new Dictionary<string, Context>();
when = cachedWhen;
givenContext.EnterContext();
if (depth > 0)
contextList.Add(namedContext);
testCases.AddRange(BuildTestCases(contextList));
testCases.AddRange(BuildTestCases(contextList, depth + 1));
if (contextList.Any())
contextList.Remove(namedContext);
}
return testCases;
}
private IList<TestCaseData> BuildTestCases(List<KeyValuePair<string, Context>> contextList)
{
var testCases = new List<TestCaseData>();
if (!then.Any()) return testCases;
var setupText = new StringBuilder();
var givenDescriptions = contextList.Select(kvp => kvp.Key).ToList();
var givenText = "given ";
foreach (var description in givenDescriptions.Where(IsNamedContext))
{
setupText.AppendLine(givenText + description);
if (givenText == "given ")
givenText = Indent("and ", 1);
}
setupText.AppendLine("when " + when.Key);
const string thenText = "then ";
foreach (var spec in then)
{
var contextListCapture = new List<KeyValuePair<string, Context>>(contextList);
var whenCapture = new KeyValuePair<string, Action>(when.Key, when.Value);
Action executeTest = () =>
{
Before();
try
{
var exceptionThrownAndAsserted = false;
InitializeContext(contextListCapture);
try
{
thrownException = null;
whenCapture.Value();
}
catch (Exception ex)
{
thrownException = ex;
spec.Value();
if (thrownException != null)
{
throw;
}
exceptionThrownAndAsserted = true;
}
if (!exceptionThrownAndAsserted)
{
spec.Value();
}
}
finally
{
After();
}
};
var description = setupText + thenText + spec.Key + Environment.NewLine;
testCases.Add(new TestCaseData(executeTest).SetName(description));
}
return testCases;
}
protected void AssertWasThrown<T>(Action<T> expectation = null) where T : Exception
{
var expectedException = thrownException as T;
if (expectedException == null)
throw new Exception("Expected exception was not thrown");
if (expectation != null)
{
try
{
expectation(expectedException);
}
catch (Exception exc)
{
var message = string.Format("The expected exception type was thrown but the specified constraint failed. Constraint Exception: {0}{1}",
Environment.NewLine, exc.Message);
throw new Exception(message, exc);
}
}
thrownException = null;
}
private Dictionary<string, Action> then = new Dictionary<string, Action>();
private Dictionary<string, Context> contexts = new Dictionary<string, Context>();
private KeyValuePair<string, Action> when;
protected IContext Given(string description, Action setup)
{
if (contexts.ContainsKey(description)) throw new Exception("Reusing a given description");
return contexts[description] = new Context(setup);
}
protected IContext Given(Action setup)
{
return contexts[CreateUnnamedContextName()] = new Context(setup);
}
protected IContext Given(string description)
{
return Given(description, () => { });
}
protected virtual IContext ForWhen(string description, Action action)
{
return contexts[CreateUnnamedContextName()] = new Context(() => { }, () => When(description, action));
}
protected virtual void When(string description, Action action)
{
when = new KeyValuePair<string, Action>(description, action);
}
protected IVerifyContext Then(string description, Action specification)
{
then[description] = specification;
return new VerifyContext(Then);
}
private int nuSpecContextId;
private string CreateUnnamedContextName()
{
return "SPECEASY" + (nuSpecContextId++).ToString(CultureInfo.InvariantCulture);
}
private static bool IsNamedContext(string name)
{
return !name.StartsWith("SPECEASY");
}
private Exception thrownException;
private void CreateMethodContexts()
{
var type = GetType();
var methods = type.GetMethods();
var baseMethods = type.BaseType != null ? type.BaseType.GetMethods() : new MethodInfo[] {};
var declaredMethods = methods.Where(m => baseMethods.All(bm => bm.Name != m.Name))
.Where(m => !m.GetParameters().Any() && m.ReturnType == typeof(void));
foreach (var m in declaredMethods)
{
var method = m;
Given(method.Name).Verify(() => method.Invoke(this, null));
}
}
private bool hasCalledBefore;
private void Before()
{
if (!hasCalledBefore)
{
BeforeEachExample();
hasCalledBefore = true;
}
}
private void After()
{
if (hasCalledBefore)
{
AfterEachExample();
hasCalledBefore = false;
}
}
protected virtual void BeforeEachExample() { }
protected virtual void AfterEachExample() { }
private void InitializeContext(IEnumerable<KeyValuePair<string, Context>> contextList)
{
foreach (var action in contextList.Select(kvp => kvp.Value))
{
Before();
action.SetupContext();
}
}
private static string Indent(string text, int depth)
{
return new string(' ', depth * 2) + text;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Datastore.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedDatastoreClientTest
{
[xunit::FactAttribute]
public void LookupRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.Lookup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse response = client.Lookup(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task LookupRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.LookupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LookupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse responseCallSettings = await client.LookupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LookupResponse responseCancellationToken = await client.LookupAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Lookup()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.Lookup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse response = client.Lookup(request.ProjectId, request.ReadOptions, request.Keys);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task LookupAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.LookupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LookupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse responseCallSettings = await client.LookupAsync(request.ProjectId, request.ReadOptions, request.Keys, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LookupResponse responseCancellationToken = await client.LookupAsync(request.ProjectId, request.ReadOptions, request.Keys, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RunQueryRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RunQueryRequest request = new RunQueryRequest
{
ReadOptions = new ReadOptions(),
PartitionId = new PartitionId(),
Query = new Query(),
GqlQuery = new GqlQuery(),
ProjectId = "project_id43ad98b0",
};
RunQueryResponse expectedResponse = new RunQueryResponse
{
Batch = new QueryResultBatch(),
Query = new Query(),
};
mockGrpcClient.Setup(x => x.RunQuery(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RunQueryResponse response = client.RunQuery(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RunQueryRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RunQueryRequest request = new RunQueryRequest
{
ReadOptions = new ReadOptions(),
PartitionId = new PartitionId(),
Query = new Query(),
GqlQuery = new GqlQuery(),
ProjectId = "project_id43ad98b0",
};
RunQueryResponse expectedResponse = new RunQueryResponse
{
Batch = new QueryResultBatch(),
Query = new Query(),
};
mockGrpcClient.Setup(x => x.RunQueryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RunQueryResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RunQueryResponse responseCallSettings = await client.RunQueryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RunQueryResponse responseCancellationToken = await client.RunQueryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BeginTransactionRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
TransactionOptions = new TransactionOptions(),
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransaction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse response = client.BeginTransaction(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BeginTransactionRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
TransactionOptions = new TransactionOptions(),
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransactionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BeginTransactionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse responseCallSettings = await client.BeginTransactionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BeginTransactionResponse responseCancellationToken = await client.BeginTransactionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BeginTransaction()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransaction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse response = client.BeginTransaction(request.ProjectId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BeginTransactionAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransactionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BeginTransactionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse responseCallSettings = await client.BeginTransactionAsync(request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BeginTransactionResponse responseCancellationToken = await client.BeginTransactionAsync(request.ProjectId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CommitRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse response = client.Commit(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CommitRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse responseCallSettings = await client.CommitAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CommitResponse responseCancellationToken = await client.CommitAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Commit1()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse response = client.Commit(request.ProjectId, request.Mode, request.Transaction, request.Mutations);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task Commit1Async()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse responseCallSettings = await client.CommitAsync(request.ProjectId, request.Mode, request.Transaction, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CommitResponse responseCancellationToken = await client.CommitAsync(request.ProjectId, request.Mode, request.Transaction, request.Mutations, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Commit2()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse response = client.Commit(request.ProjectId, request.Mode, request.Mutations);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task Commit2Async()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse responseCallSettings = await client.CommitAsync(request.ProjectId, request.Mode, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CommitResponse responseCancellationToken = await client.CommitAsync(request.ProjectId, request.Mode, request.Mutations, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RollbackRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.Rollback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse response = client.Rollback(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RollbackRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.RollbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RollbackResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse responseCallSettings = await client.RollbackAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RollbackResponse responseCancellationToken = await client.RollbackAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Rollback()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.Rollback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse response = client.Rollback(request.ProjectId, request.Transaction);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RollbackAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.RollbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RollbackResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse responseCallSettings = await client.RollbackAsync(request.ProjectId, request.Transaction, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RollbackResponse responseCancellationToken = await client.RollbackAsync(request.ProjectId, request.Transaction, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AllocateIdsRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse response = client.AllocateIds(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AllocateIdsRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AllocateIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse responseCallSettings = await client.AllocateIdsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AllocateIdsResponse responseCancellationToken = await client.AllocateIdsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AllocateIds()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse response = client.AllocateIds(request.ProjectId, request.Keys);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AllocateIdsAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AllocateIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse responseCallSettings = await client.AllocateIdsAsync(request.ProjectId, request.Keys, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AllocateIdsResponse responseCancellationToken = await client.AllocateIdsAsync(request.ProjectId, request.Keys, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ReserveIdsRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
DatabaseId = "database_idbff1efc9",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse response = client.ReserveIds(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ReserveIdsRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
DatabaseId = "database_idbff1efc9",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReserveIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse responseCallSettings = await client.ReserveIdsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReserveIdsResponse responseCancellationToken = await client.ReserveIdsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ReserveIds()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse response = client.ReserveIds(request.ProjectId, request.Keys);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ReserveIdsAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReserveIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse responseCallSettings = await client.ReserveIdsAsync(request.ProjectId, request.Keys, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReserveIdsResponse responseCancellationToken = await client.ReserveIdsAsync(request.ProjectId, request.Keys, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CameraMetadataTag.cs" company="Google LLC">
//
// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// This enum follows the layout of NdkCameraMetadataTags.
/// The values in the file are used for requesting / marshaling camera image's metadata.
/// The comments have been removed to keep the code readable. Please refer to
/// NdkCameraMetadataTags.h for documentation:
/// https://developer.android.com/ndk/reference/ndk_camera_metadata_tags_8h.html .
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1602:EnumerationItemsMustBeDocumented",
Justification = "NdkCameraMetadataTags.")]
public enum CameraMetadataTag
{
SectionColorCorrection = 0,
SectionControl = 1,
SectionEdge = 3,
SectionFlash = 4,
SectionFlashInfo = 5,
SectionHotPixel = 6,
SectionJpeg = 7,
SectionLens = 8,
SectionLensInfo = 9,
SectionNoiseReduction = 10,
SectionRequest = 12,
SectionScaler = 13,
SectionSensor = 14,
SectionSensorInfo = 15,
SectionShading = 16,
SectionStatistics = 17,
SectionStatisticsInfo = 18,
SectionTonemap = 19,
SectionInfo = 21,
SectionBlackLevel = 22,
SectionSync = 23,
SectionDepth = 25,
// Start Value Of Each Section.
ColorCorrectionStart = SectionColorCorrection << 16,
ControlStart = SectionControl << 16,
EdgeStart = SectionEdge << 16,
FlashStart = SectionFlash << 16,
FlashInfoStart = SectionFlashInfo << 16,
HotPixelStart = SectionHotPixel << 16,
JpegStart = SectionJpeg << 16,
LensStart = SectionLens << 16,
LensInfoStart = SectionLensInfo << 16,
NoiseReductionStart = SectionNoiseReduction << 16,
RequestStart = SectionRequest << 16,
ScalerStart = SectionScaler << 16,
SensorStart = SectionSensor << 16,
SensorInfoStart = SectionSensorInfo << 16,
ShadingStart = SectionShading << 16,
StatisticsStart = SectionStatistics << 16,
StatisticsInfoStart = SectionStatisticsInfo << 16,
TonemapStart = SectionTonemap << 16,
InfoStart = SectionInfo << 16,
BlackLevelStart = SectionBlackLevel << 16,
SyncStart = SectionSync << 16,
DepthStart = SectionDepth << 16,
// Note that we only expose the keys that could be used in the camera metadata from the
// capture result. The keys may only appear in CameraCharacteristics are not exposed here.
ColorCorrectionMode = // Byte (Enum)
ColorCorrectionStart,
ColorCorrectionTransform = // Rational[33]
ColorCorrectionStart + 1,
ColorCorrectionGains = // Float[4]
ColorCorrectionStart + 2,
ColorCorrectionAberrationMode = // Byte (Enum)
ColorCorrectionStart + 3,
ControlAeAntibandingMode = // Byte (Enum)
ControlStart,
ControlAeExposureCompensation = // Int32
ControlStart + 1,
ControlAeLock = // Byte (Enum)
ControlStart + 2,
ControlAeMode = // Byte (Enum)
ControlStart + 3,
ControlAeRegions = // Int32[5areaCount]
ControlStart + 4,
ControlAeTargetFpsRange = // Int32[2]
ControlStart + 5,
ControlAePrecaptureTrigger = // Byte (Enum)
ControlStart + 6,
ControlAfMode = // Byte (Enum)
ControlStart + 7,
ControlAfRegions = // Int32[5areaCount]
ControlStart + 8,
ControlAfTrigger = // Byte (Enum)
ControlStart + 9,
ControlAwbLock = // Byte (Enum)
ControlStart + 10,
ControlAwbMode = // Byte (Enum)
ControlStart + 11,
ControlAwbRegions = // Int32[5areaCount]
ControlStart + 12,
ControlCaptureIntent = // Byte (Enum)
ControlStart + 13,
ControlEffectMode = // Byte (Enum)
ControlStart + 14,
ControlMode = // Byte (Enum)
ControlStart + 15,
ControlSceneMode = // Byte (Enum)
ControlStart + 16,
ControlVideoStabilizationMode = // Byte (Enum)
ControlStart + 17,
ControlAeState = // Byte (Enum)
ControlStart + 31,
ControlAfState = // Byte (Enum)
ControlStart + 32,
ControlAwbState = // Byte (Enum)
ControlStart + 34,
ControlPostRawSensitivityBoost = // Int32
ControlStart + 40,
EdgeMode = // Byte (Enum)
EdgeStart,
FlashMode = // Byte (Enum)
FlashStart + 2,
FlashState = // Byte (Enum)
FlashStart + 5,
HotPixelMode = // Byte (Enum)
HotPixelStart,
JpegGpsCoordinates = // Double[3]
JpegStart,
JpegGpsProcessingMethod = // Byte
JpegStart + 1,
JpegGpsTimestamp = // Int64
JpegStart + 2,
JpegOrientation = // Int32
JpegStart + 3,
JpegQuality = // Byte
JpegStart + 4,
JpegThumbnailQuality = // Byte
JpegStart + 5,
JpegThumbnailSize = // Int32[2]
JpegStart + 6,
LensAperture = // Float
LensStart,
LensFilterDensity = // Float
LensStart + 1,
LensFocalLength = // Float
LensStart + 2,
LensFocusDistance = // Float
LensStart + 3,
LensOpticalStabilizationMode = // Byte (Enum)
LensStart + 4,
LensPoseRotation = // Float[4]
LensStart + 6,
LensPoseTranslation = // Float[3]
LensStart + 7,
LensFocusRange = // Float[2]
LensStart + 8,
LensState = // Byte (Enum)
LensStart + 9,
LensIntrinsicCalibration = // Float[5]
LensStart + 10,
LensRadialDistortion = // Float[6]
LensStart + 11,
NoiseReductionMode = // Byte (Enum)
NoiseReductionStart,
RequestPipelineDepth = // Byte
RequestStart + 9,
ScalerCropRegion = // Int32[4]
ScalerStart,
SensorExposureTime = // Int64
SensorStart,
SensorFrameDuration = // Int64
SensorStart + 1,
SensorSensitivity = // Int32
SensorStart + 2,
SensorTimestamp = // Int64
SensorStart + 16,
SensorNeutralColorPoint = // Rational[3]
SensorStart + 18,
SensorNoiseProfile = // Double[2Cfa Channels]
SensorStart + 19,
SensorGreenSplit = // Float
SensorStart + 22,
SensorTestPatternData = // Int32[4]
SensorStart + 23,
SensorTestPatternMode = // Int32 (Enum)
SensorStart + 24,
SensorRollingShutterSkew = // Int64
SensorStart + 26,
SensorDynamicBlackLevel = // Float[4]
SensorStart + 28,
SensorDynamicWhiteLevel = // Int32
SensorStart + 29,
ShadingMode = // Byte (Enum)
ShadingStart,
StatisticsFaceDetectMode = // Byte (Enum)
StatisticsStart,
StatisticsHotPixelMapMode = // Byte (Enum)
StatisticsStart + 3,
StatisticsFaceIds = // Int32[N]
StatisticsStart + 4,
StatisticsFaceLandmarks = // Int32[N6]
StatisticsStart + 5,
StatisticsFaceRectangles = // Int32[N4]
StatisticsStart + 6,
StatisticsFaceScores = // Byte[N]
StatisticsStart + 7,
StatisticsLensShadingMap = // Float[4nm]
StatisticsStart + 11,
StatisticsSceneFlicker = // Byte (Enum)
StatisticsStart + 14,
StatisticsHotPixelMap = // Int32[2n]
StatisticsStart + 15,
StatisticsLensShadingMapMode = // Byte (Enum)
StatisticsStart + 16,
TonemapCurveBlue = // Float[N2]
TonemapStart,
TonemapCurveGreen = // Float[N2]
TonemapStart + 1,
TonemapCurveRed = // Float[N2]
TonemapStart + 2,
TonemapMode = // Byte (Enum)
TonemapStart + 3,
TonemapGamma = // Float
TonemapStart + 6,
TonemapPresetCurve = // Byte (Enum)
TonemapStart + 7,
BlackLevelLock = // Byte (Enum)
BlackLevelStart,
SyncFrameNumber = // Int64 (Enum)
SyncStart,
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERLevel;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C11_City_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="C11_City_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="C10_City"/> collection.
/// </remarks>
[Serializable]
public partial class C11_City_ReChild : BusinessBase<C11_City_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C11_City_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C11_City_ReChild"/> object.</returns>
internal static C11_City_ReChild NewC11_City_ReChild()
{
return DataPortal.CreateChild<C11_City_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="C11_City_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="city_ID2">The City_ID2 parameter of the C11_City_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="C11_City_ReChild"/> object.</returns>
internal static C11_City_ReChild GetC11_City_ReChild(int city_ID2)
{
return DataPortal.FetchChild<C11_City_ReChild>(city_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C11_City_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C11_City_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C11_City_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C11_City_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="city_ID2">The City ID2.</param>
protected void Child_Fetch(int city_ID2)
{
var args = new DataPortalHookArgs(city_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<IC11_City_ReChildDal>();
var data = dal.Fetch(city_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="C11_City_ReChild"/> object from the given <see cref="C11_City_ReChildDto"/>.
/// </summary>
/// <param name="data">The C11_City_ReChildDto to use.</param>
private void Fetch(C11_City_ReChildDto data)
{
// Value properties
LoadProperty(City_Child_NameProperty, data.City_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="C11_City_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C10_City parent)
{
var dto = new C11_City_ReChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IC11_City_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C11_City_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(C10_City parent)
{
if (!IsDirty)
return;
var dto = new C11_City_ReChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IC11_City_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="C11_City_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(C10_City parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IC11_City_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.City_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Common;
/// <summary>
/// Wraps IGridCache implementation to simplify async mode testing.
/// </summary>
internal class CacheTestAsyncWrapper<TK, TV> : ICache<TK, TV>
{
private readonly ICache<TK, TV> _cache;
/// <summary>
/// Initializes a new instance of the <see cref="CacheTestAsyncWrapper{K, V}"/> class.
/// </summary>
/// <param name="cache">The cache to be wrapped.</param>
public CacheTestAsyncWrapper(ICache<TK, TV> cache)
{
Debug.Assert(cache.IsAsync, "GridCacheTestAsyncWrapper only works with async caches.");
_cache = cache;
}
/** <inheritDoc /> */
public ICache<TK, TV> WithAsync()
{
return this;
}
/** <inheritDoc /> */
public bool IsAsync
{
get { return true; }
}
/** <inheritDoc /> */
public IFuture GetFuture()
{
Debug.Fail("GridCacheTestAsyncWrapper.Future() should not be called. It always returns null.");
return null;
}
/** <inheritDoc /> */
public IFuture<TResult> GetFuture<TResult>()
{
Debug.Fail("GridCacheTestAsyncWrapper.Future() should not be called. It always returns null.");
return null;
}
/** <inheritDoc /> */
public string Name
{
get { return _cache.Name; }
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _cache.Ignite; }
}
/** <inheritDoc /> */
public bool IsEmpty
{
get { return _cache.IsEmpty; }
}
/** <inheritDoc /> */
public bool KeepPortable
{
get { return _cache.KeepPortable; }
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
return _cache.WithSkipStore().WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
return _cache.WithExpiryPolicy(plc).WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepPortable<TK1, TV1>()
{
return _cache.WithKeepPortable<TK1, TV1>().WrapAsync();
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LoadCache(p, args);
WaitResult();
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LocalLoadCache(p, args);
WaitResult();
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
_cache.ContainsKey(key);
return GetResult<bool>();
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
_cache.ContainsKeys(keys);
return GetResult<bool>();
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
_cache.LocalPeek(key, modes);
return GetResult<TV>();
}
/** <inheritDoc /> */
public TV Get(TK key)
{
_cache.Get(key);
return GetResult<TV>();
}
/** <inheritDoc /> */
public IDictionary<TK, TV> GetAll(IEnumerable<TK> keys)
{
_cache.GetAll(keys);
return GetResult<IDictionary<TK, TV>>();
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
_cache.Put(key, val);
WaitResult();
}
/** <inheritDoc /> */
public TV GetAndPut(TK key, TV val)
{
_cache.GetAndPut(key, val);
return GetResult<TV>();
}
/** <inheritDoc /> */
public TV GetAndReplace(TK key, TV val)
{
_cache.GetAndReplace(key, val);
return GetResult<TV>();
}
/** <inheritDoc /> */
public TV GetAndRemove(TK key)
{
_cache.GetAndRemove(key);
return GetResult<TV>();
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
_cache.PutIfAbsent(key, val);
return GetResult<bool>();
}
/** <inheritDoc /> */
public TV GetAndPutIfAbsent(TK key, TV val)
{
_cache.GetAndPutIfAbsent(key, val);
return GetResult<TV>();
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
_cache.Replace(key, val);
return GetResult<bool>();
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
_cache.Replace(key, oldVal, newVal);
return GetResult<bool>();
}
/** <inheritDoc /> */
public void PutAll(IDictionary<TK, TV> vals)
{
_cache.PutAll(vals);
WaitResult();
}
/** <inheritDoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
_cache.LocalEvict(keys);
}
/** <inheritDoc /> */
public void Clear()
{
_cache.Clear();
WaitResult();
}
/** <inheritDoc /> */
public void Clear(TK key)
{
_cache.Clear(key);
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
_cache.ClearAll(keys);
}
/** <inheritDoc /> */
public void LocalClear(TK key)
{
_cache.LocalClear(key);
}
/** <inheritDoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
_cache.LocalClearAll(keys);
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
_cache.Remove(key);
return GetResult<bool>();
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
_cache.Remove(key, val);
return GetResult<bool>();
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
_cache.RemoveAll(keys);
WaitResult();
}
/** <inheritDoc /> */
public void RemoveAll()
{
_cache.RemoveAll();
WaitResult();
}
/** <inheritDoc /> */
public int LocalSize(params CachePeekMode[] modes)
{
return _cache.LocalSize(modes);
}
/** <inheritDoc /> */
public int Size(params CachePeekMode[] modes)
{
_cache.Size(modes);
return GetResult<int>();
}
/** <inheritDoc /> */
public void LocalPromote(IEnumerable<TK> keys)
{
_cache.LocalPromote(keys);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return _cache.QueryFields(qry);
}
/** <inheritDoc /> */
IContinuousQueryHandle ICache<TK, TV>.QueryContinuous(ContinuousQuery<TK, TV> qry)
{
return _cache.QueryContinuous(qry);
}
/** <inheritDoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
return _cache.QueryContinuous(qry, initialQry);
}
/** <inheritDoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(params CachePeekMode[] peekModes)
{
return _cache.GetLocalEntries(peekModes);
}
/** <inheritDoc /> */
public TR Invoke<TR, TA>(TK key, ICacheEntryProcessor<TK, TV, TA, TR> processor, TA arg)
{
_cache.Invoke(key, processor, arg);
return GetResult<TR>();
}
/** <inheritDoc /> */
public IDictionary<TK, ICacheEntryProcessorResult<TR>> InvokeAll<TR, TA>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TA, TR> processor, TA arg)
{
_cache.InvokeAll(keys, processor, arg);
return GetResult<IDictionary<TK, ICacheEntryProcessorResult<TR>>>();
}
/** <inheritDoc /> */
public ICacheLock Lock(TK key)
{
return _cache.Lock(key);
}
/** <inheritDoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
return _cache.LockAll(keys);
}
/** <inheritDoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
return _cache.IsLocalLocked(key, byCurrentThread);
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return _cache.GetMetrics();
}
/** <inheritDoc /> */
public IFuture Rebalance()
{
return _cache.Rebalance();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
return _cache.WithNoRetries();
}
/** <inheritDoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return _cache.GetEnumerator();
}
/** <inheritDoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Waits for the async result.
/// </summary>
private void WaitResult()
{
GetResult<object>();
}
/// <summary>
/// Gets the async result.
/// </summary>
private T GetResult<T>()
{
return _cache.GetFuture<T>().Get();
}
}
/// <summary>
/// Extension methods for IGridCache.
/// </summary>
public static class CacheExtensions
{
/// <summary>
/// Wraps specified instance into GridCacheTestAsyncWrapper.
/// </summary>
public static ICache<TK, TV> WrapAsync<TK, TV>(this ICache<TK, TV> cache)
{
return new CacheTestAsyncWrapper<TK, TV>(cache);
}
}
}
| |
/*
* Copyright 2006 Jeremias Maerki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace ZXing.Datamatrix.Encoder
{
/// <summary>
/// Symbol info table for DataMatrix.
/// </summary>
internal class SymbolInfo
{
internal static readonly SymbolInfo[] PROD_SYMBOLS = {
new SymbolInfo(false, 3, 5, 8, 8, 1),
new SymbolInfo(false, 5, 7, 10, 10, 1),
/*rect*/new SymbolInfo(true, 5, 7, 16, 6, 1),
new SymbolInfo(false, 8, 10, 12, 12, 1),
/*rect*/new SymbolInfo(true, 10, 11, 14, 6, 2),
new SymbolInfo(false, 12, 12, 14, 14, 1),
/*rect*/new SymbolInfo(true, 16, 14, 24, 10, 1),
new SymbolInfo(false, 18, 14, 16, 16, 1),
new SymbolInfo(false, 22, 18, 18, 18, 1),
/*rect*/new SymbolInfo(true, 22, 18, 16, 10, 2),
new SymbolInfo(false, 30, 20, 20, 20, 1),
/*rect*/new SymbolInfo(true, 32, 24, 16, 14, 2),
new SymbolInfo(false, 36, 24, 22, 22, 1),
new SymbolInfo(false, 44, 28, 24, 24, 1),
/*rect*/new SymbolInfo(true, 49, 28, 22, 14, 2),
new SymbolInfo(false, 62, 36, 14, 14, 4),
new SymbolInfo(false, 86, 42, 16, 16, 4),
new SymbolInfo(false, 114, 48, 18, 18, 4),
new SymbolInfo(false, 144, 56, 20, 20, 4),
new SymbolInfo(false, 174, 68, 22, 22, 4),
new SymbolInfo(false, 204, 84, 24, 24, 4, 102, 42),
new SymbolInfo(false, 280, 112, 14, 14, 16, 140, 56),
new SymbolInfo(false, 368, 144, 16, 16, 16, 92, 36),
new SymbolInfo(false, 456, 192, 18, 18, 16, 114, 48),
new SymbolInfo(false, 576, 224, 20, 20, 16, 144, 56),
new SymbolInfo(false, 696, 272, 22, 22, 16, 174, 68),
new SymbolInfo(false, 816, 336, 24, 24, 16, 136, 56),
new SymbolInfo(false, 1050, 408, 18, 18, 36, 175, 68),
new SymbolInfo(false, 1304, 496, 20, 20, 36, 163, 62),
new DataMatrixSymbolInfo144(),
};
private static SymbolInfo[] symbols = PROD_SYMBOLS;
/**
* Overrides the symbol info set used by this class. Used for testing purposes.
*
* @param override the symbol info set to use
*/
public static void overrideSymbolSet(SymbolInfo[] @override)
{
symbols = @override;
}
private readonly bool rectangular;
internal readonly int dataCapacity;
internal readonly int errorCodewords;
public readonly int matrixWidth;
public readonly int matrixHeight;
private readonly int dataRegions;
private readonly int rsBlockData;
private readonly int rsBlockError;
public SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords,
int matrixWidth, int matrixHeight, int dataRegions)
: this(rectangular, dataCapacity, errorCodewords, matrixWidth, matrixHeight, dataRegions,
dataCapacity, errorCodewords)
{
}
internal SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords,
int matrixWidth, int matrixHeight, int dataRegions,
int rsBlockData, int rsBlockError)
{
this.rectangular = rectangular;
this.dataCapacity = dataCapacity;
this.errorCodewords = errorCodewords;
this.matrixWidth = matrixWidth;
this.matrixHeight = matrixHeight;
this.dataRegions = dataRegions;
this.rsBlockData = rsBlockData;
this.rsBlockError = rsBlockError;
}
public static SymbolInfo lookup(int dataCodewords)
{
return lookup(dataCodewords, SymbolShapeHint.FORCE_NONE, true);
}
public static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape)
{
return lookup(dataCodewords, shape, true);
}
public static SymbolInfo lookup(int dataCodewords, bool allowRectangular, bool fail)
{
SymbolShapeHint shape = allowRectangular
? SymbolShapeHint.FORCE_NONE : SymbolShapeHint.FORCE_SQUARE;
return lookup(dataCodewords, shape, fail);
}
private static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape, bool fail)
{
return lookup(dataCodewords, shape, null, null, fail);
}
public static SymbolInfo lookup(int dataCodewords,
SymbolShapeHint shape,
Dimension minSize,
Dimension maxSize,
bool fail)
{
foreach (SymbolInfo symbol in symbols)
{
if (shape == SymbolShapeHint.FORCE_SQUARE && symbol.rectangular)
{
continue;
}
if (shape == SymbolShapeHint.FORCE_RECTANGLE && !symbol.rectangular)
{
continue;
}
if (minSize != null
&& (symbol.getSymbolWidth() < minSize.Width
|| symbol.getSymbolHeight() < minSize.Height))
{
continue;
}
if (maxSize != null
&& (symbol.getSymbolWidth() > maxSize.Width
|| symbol.getSymbolHeight() > maxSize.Height))
{
continue;
}
if (dataCodewords <= symbol.dataCapacity)
{
return symbol;
}
}
if (fail)
{
throw new ArgumentException(
"Can't find a symbol arrangement that matches the message. Data codewords: "
+ dataCodewords);
}
return null;
}
int getHorizontalDataRegions()
{
switch (dataRegions)
{
case 1:
return 1;
case 2:
return 2;
case 4:
return 2;
case 16:
return 4;
case 36:
return 6;
default:
throw new InvalidOperationException("Cannot handle this number of data regions");
}
}
int getVerticalDataRegions()
{
switch (dataRegions)
{
case 1:
return 1;
case 2:
return 1;
case 4:
return 2;
case 16:
return 4;
case 36:
return 6;
default:
throw new InvalidOperationException("Cannot handle this number of data regions");
}
}
public int getSymbolDataWidth()
{
return getHorizontalDataRegions() * matrixWidth;
}
public int getSymbolDataHeight()
{
return getVerticalDataRegions() * matrixHeight;
}
public int getSymbolWidth()
{
return getSymbolDataWidth() + (getHorizontalDataRegions() * 2);
}
public int getSymbolHeight()
{
return getSymbolDataHeight() + (getVerticalDataRegions() * 2);
}
public int getCodewordCount()
{
return dataCapacity + errorCodewords;
}
virtual public int getInterleavedBlockCount()
{
return dataCapacity / rsBlockData;
}
virtual public int getDataLengthForInterleavedBlock(int index)
{
return rsBlockData;
}
public int getErrorLengthForInterleavedBlock(int index)
{
return rsBlockError;
}
public override String ToString()
{
var sb = new StringBuilder();
sb.Append(rectangular ? "Rectangular Symbol:" : "Square Symbol:");
sb.Append(" data region ").Append(matrixWidth).Append('x').Append(matrixHeight);
sb.Append(", symbol size ").Append(getSymbolWidth()).Append('x').Append(getSymbolHeight());
sb.Append(", symbol data size ").Append(getSymbolDataWidth()).Append('x').Append(getSymbolDataHeight());
sb.Append(", codewords ").Append(dataCapacity).Append('+').Append(errorCodewords);
return sb.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Umbraco.Core.Auditing;
using Umbraco.Core.Events;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the Macro Service, which is an easy access to operations involving <see cref="IMacro"/>
/// </summary>
public class MacroService : RepositoryService, IMacroService
{
public MacroService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
}
/// <summary>
/// Returns an enum <see cref="MacroTypes"/> based on the properties on the Macro
/// </summary>
/// <returns><see cref="MacroTypes"/></returns>
internal static MacroTypes GetMacroType(IMacro macro)
{
if (string.IsNullOrEmpty(macro.XsltPath) == false)
return MacroTypes.Xslt;
if (string.IsNullOrEmpty(macro.ScriptPath) == false)
{
//we need to check if the file path saved is a virtual path starting with ~/Views/MacroPartials, if so then this is
//a partial view macro, not a script macro
//we also check if the file exists in ~/App_Plugins/[Packagename]/Views/MacroPartials, if so then it is also a partial view.
return (macro.ScriptPath.InvariantStartsWith(SystemDirectories.MvcViews + "/MacroPartials/")
|| (Regex.IsMatch(macro.ScriptPath, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled | RegexOptions.IgnoreCase)))
? MacroTypes.PartialView
: MacroTypes.Script;
}
if (string.IsNullOrEmpty(macro.ControlType) == false && macro.ControlType.InvariantContains(".ascx"))
return MacroTypes.UserControl;
if (string.IsNullOrEmpty(macro.ControlType) == false && string.IsNullOrEmpty(macro.ControlAssembly) == false)
return MacroTypes.CustomControl;
return MacroTypes.Unknown;
}
/// <summary>
/// Gets an <see cref="IMacro"/> object by its alias
/// </summary>
/// <param name="alias">Alias to retrieve an <see cref="IMacro"/> for</param>
/// <returns>An <see cref="IMacro"/> object</returns>
public IMacro GetByAlias(string alias)
{
using (var repository = RepositoryFactory.CreateMacroRepository(UowProvider.GetUnitOfWork()))
{
var q = new Query<IMacro>();
q.Where(macro => macro.Alias == alias);
return repository.GetByQuery(q).FirstOrDefault();
}
}
///// <summary>
///// Gets a list all available <see cref="IMacro"/> objects
///// </summary>
///// <param name="aliases">Optional array of aliases to limit the results</param>
///// <returns>An enumerable list of <see cref="IMacro"/> objects</returns>
//public IEnumerable<IMacro> GetAll(params string[] aliases)
//{
// using (var repository = RepositoryFactory.CreateMacroRepository(UowProvider.GetUnitOfWork()))
// {
// if (aliases.Any())
// {
// return GetAllByAliases(repository, aliases);
// }
// return repository.GetAll();
// }
//}
public IEnumerable<IMacro> GetAll(params int[] ids)
{
using (var repository = RepositoryFactory.CreateMacroRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
public IMacro GetById(int id)
{
using (var repository = RepositoryFactory.CreateMacroRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
//private IEnumerable<IMacro> GetAllByAliases(IMacroRepository repo, IEnumerable<string> aliases)
//{
// foreach (var alias in aliases)
// {
// var q = new Query<IMacro>();
// q.Where(macro => macro.Alias == alias);
// yield return repo.GetByQuery(q).FirstOrDefault();
// }
//}
/// <summary>
/// Deletes an <see cref="IMacro"/>
/// </summary>
/// <param name="macro"><see cref="IMacro"/> to delete</param>
/// <param name="userId">Optional id of the user deleting the macro</param>
public void Delete(IMacro macro, int userId = 0)
{
if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IMacro>(macro), this))
return;
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMacroRepository(uow))
{
repository.Delete(macro);
uow.Commit();
Deleted.RaiseEvent(new DeleteEventArgs<IMacro>(macro, false), this);
}
Audit(AuditType.Delete, "Delete Macro performed by user", userId, -1);
}
/// <summary>
/// Saves an <see cref="IMacro"/>
/// </summary>
/// <param name="macro"><see cref="IMacro"/> to save</param>
/// <param name="userId">Optional Id of the user deleting the macro</param>
public void Save(IMacro macro, int userId = 0)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMacro>(macro), this))
return;
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMacroRepository(uow))
{
repository.AddOrUpdate(macro);
uow.Commit();
Saved.RaiseEvent(new SaveEventArgs<IMacro>(macro, false), this);
}
Audit(AuditType.Save, "Save Macro performed by user", userId, -1);
}
///// <summary>
///// Gets a list all available <see cref="IMacroPropertyType"/> plugins
///// </summary>
///// <returns>An enumerable list of <see cref="IMacroPropertyType"/> objects</returns>
//public IEnumerable<IMacroPropertyType> GetMacroPropertyTypes()
//{
// return MacroPropertyTypeResolver.Current.MacroPropertyTypes;
//}
///// <summary>
///// Gets an <see cref="IMacroPropertyType"/> by its alias
///// </summary>
///// <param name="alias">Alias to retrieve an <see cref="IMacroPropertyType"/> for</param>
///// <returns>An <see cref="IMacroPropertyType"/> object</returns>
//public IMacroPropertyType GetMacroPropertyTypeByAlias(string alias)
//{
// return MacroPropertyTypeResolver.Current.MacroPropertyTypes.FirstOrDefault(x => x.Alias == alias);
//}
private void Audit(AuditType type, string message, int userId, int objectId)
{
var uow = UowProvider.GetUnitOfWork();
using (var auditRepo = RepositoryFactory.CreateAuditRepository(uow))
{
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
}
#region Event Handlers
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IMacroService, DeleteEventArgs<IMacro>> Deleting;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IMacroService, DeleteEventArgs<IMacro>> Deleted;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IMacroService, SaveEventArgs<IMacro>> Saving;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IMacroService, SaveEventArgs<IMacro>> Saved;
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysDireccione class.
/// </summary>
[Serializable]
public partial class SysDireccioneCollection : ActiveList<SysDireccione, SysDireccioneCollection>
{
public SysDireccioneCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysDireccioneCollection</returns>
public SysDireccioneCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysDireccione o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_Direcciones table.
/// </summary>
[Serializable]
public partial class SysDireccione : ActiveRecord<SysDireccione>, IActiveRecord
{
#region .ctors and Default Settings
public SysDireccione()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysDireccione(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysDireccione(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysDireccione(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_Direcciones", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdDireccion = new TableSchema.TableColumn(schema);
colvarIdDireccion.ColumnName = "idDireccion";
colvarIdDireccion.DataType = DbType.Decimal;
colvarIdDireccion.MaxLength = 0;
colvarIdDireccion.AutoIncrement = true;
colvarIdDireccion.IsNullable = false;
colvarIdDireccion.IsPrimaryKey = true;
colvarIdDireccion.IsForeignKey = false;
colvarIdDireccion.IsReadOnly = false;
colvarIdDireccion.DefaultSetting = @"";
colvarIdDireccion.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdDireccion);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "Nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarResponsable = new TableSchema.TableColumn(schema);
colvarResponsable.ColumnName = "Responsable";
colvarResponsable.DataType = DbType.String;
colvarResponsable.MaxLength = 100;
colvarResponsable.AutoIncrement = false;
colvarResponsable.IsNullable = true;
colvarResponsable.IsPrimaryKey = false;
colvarResponsable.IsForeignKey = false;
colvarResponsable.IsReadOnly = false;
colvarResponsable.DefaultSetting = @"";
colvarResponsable.ForeignKeyTableName = "";
schema.Columns.Add(colvarResponsable);
TableSchema.TableColumn colvarTelefono = new TableSchema.TableColumn(schema);
colvarTelefono.ColumnName = "Telefono";
colvarTelefono.DataType = DbType.String;
colvarTelefono.MaxLength = 30;
colvarTelefono.AutoIncrement = false;
colvarTelefono.IsNullable = true;
colvarTelefono.IsPrimaryKey = false;
colvarTelefono.IsForeignKey = false;
colvarTelefono.IsReadOnly = false;
colvarTelefono.DefaultSetting = @"";
colvarTelefono.ForeignKeyTableName = "";
schema.Columns.Add(colvarTelefono);
TableSchema.TableColumn colvarEmail = new TableSchema.TableColumn(schema);
colvarEmail.ColumnName = "email";
colvarEmail.DataType = DbType.String;
colvarEmail.MaxLength = 100;
colvarEmail.AutoIncrement = false;
colvarEmail.IsNullable = true;
colvarEmail.IsPrimaryKey = false;
colvarEmail.IsForeignKey = false;
colvarEmail.IsReadOnly = false;
colvarEmail.DefaultSetting = @"";
colvarEmail.ForeignKeyTableName = "";
schema.Columns.Add(colvarEmail);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_Direcciones",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdDireccion")]
[Bindable(true)]
public decimal IdDireccion
{
get { return GetColumnValue<decimal>(Columns.IdDireccion); }
set { SetColumnValue(Columns.IdDireccion, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("Responsable")]
[Bindable(true)]
public string Responsable
{
get { return GetColumnValue<string>(Columns.Responsable); }
set { SetColumnValue(Columns.Responsable, value); }
}
[XmlAttribute("Telefono")]
[Bindable(true)]
public string Telefono
{
get { return GetColumnValue<string>(Columns.Telefono); }
set { SetColumnValue(Columns.Telefono, value); }
}
[XmlAttribute("Email")]
[Bindable(true)]
public string Email
{
get { return GetColumnValue<string>(Columns.Email); }
set { SetColumnValue(Columns.Email, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre,string varResponsable,string varTelefono,string varEmail)
{
SysDireccione item = new SysDireccione();
item.Nombre = varNombre;
item.Responsable = varResponsable;
item.Telefono = varTelefono;
item.Email = varEmail;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(decimal varIdDireccion,string varNombre,string varResponsable,string varTelefono,string varEmail)
{
SysDireccione item = new SysDireccione();
item.IdDireccion = varIdDireccion;
item.Nombre = varNombre;
item.Responsable = varResponsable;
item.Telefono = varTelefono;
item.Email = varEmail;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdDireccionColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ResponsableColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn TelefonoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn EmailColumn
{
get { return Schema.Columns[4]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdDireccion = @"idDireccion";
public static string Nombre = @"Nombre";
public static string Responsable = @"Responsable";
public static string Telefono = @"Telefono";
public static string Email = @"email";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using UIKit;
using CoreGraphics;
namespace PaintCode
{
/// <summary>
/// Blue button example
/// http://paintcodeapp.com/examples.html
/// </summary>
/// <remarks>
/// This implementation only deals with Normal and Pressed states.
/// There is no handling for the Disabled state.
/// </remarks>
public class BlueButton : UIButton {
bool isPressed;
public UIColor NormalColor;
/// <summary>
/// Invoked when the user touches
/// </summary>
public event Action<BlueButton> Tapped;
/// <summary>
/// Creates a new instance of the GlassButton using the specified dimensions
/// </summary>
public BlueButton (CGRect frame) : base (frame)
{
NormalColor = UIColor.FromRGBA (0.00f, 0.37f, 0.89f, 1.00f);
}
/// <summary>
/// Whether the button is rendered enabled or not.
/// </summary>
public override bool Enabled {
get {
return base.Enabled;
}
set {
base.Enabled = value;
SetNeedsDisplay ();
}
}
public override bool BeginTracking (UITouch uitouch, UIEvent uievent)
{
SetNeedsDisplay ();
isPressed = true;
return base.BeginTracking (uitouch, uievent);
}
public override void EndTracking (UITouch uitouch, UIEvent uievent)
{
if (isPressed && Enabled){
if (Tapped != null)
Tapped (this);
}
isPressed = false;
SetNeedsDisplay ();
base.EndTracking (uitouch, uievent);
}
public override bool ContinueTracking (UITouch uitouch, UIEvent uievent)
{
var touch = uievent.AllTouches.AnyObject as UITouch;
if (Bounds.Contains (touch.LocationInView (this)))
isPressed = true;
else
isPressed = false;
return base.ContinueTracking (uitouch, uievent);
}
public override void Draw (CGRect rect)
{
using (var context = UIGraphics.GetCurrentContext ()) {
var bounds = Bounds;
//UIColor background = Enabled ? isPressed ? HighlightedColor : NormalColor : DisabledColor;
UIColor buttonColor = NormalColor; //UIColor.FromRGBA (0.00f, 0.37f, 0.89f, 1.00f);
var buttonColorRGBA = new nfloat[4];
buttonColor.GetRGBA (
out buttonColorRGBA [0],
out buttonColorRGBA [1],
out buttonColorRGBA [2],
out buttonColorRGBA [3]
);
if (isPressed) {
// Get the Hue Saturation Brightness Alpha copy of the color
var buttonColorHSBA = new nfloat[4];
buttonColor.GetHSBA (
out buttonColorHSBA [0],
out buttonColorHSBA [1],
out buttonColorHSBA [2],
out buttonColorHSBA [3]
);
// Change the brightness to a fixed value (0.5f)
buttonColor = UIColor.FromHSBA (buttonColorHSBA [0], buttonColorHSBA [1], 0.5f, buttonColorHSBA [3]);
// Re-set the base buttonColorRGBA because everything else is relative to it
buttonColorRGBA = new nfloat[4];
buttonColor.GetRGBA (
out buttonColorRGBA [0],
out buttonColorRGBA [1],
out buttonColorRGBA [2],
out buttonColorRGBA [3]
);
}
using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) {
// ------------- START PAINTCODE -------------
//// Color Declarations
UIColor upColorOut = UIColor.FromRGBA (0.79f, 0.79f, 0.79f, 1.00f);
UIColor bottomColorDown = UIColor.FromRGBA (0.21f, 0.21f, 0.21f, 1.00f);
UIColor upColorInner = UIColor.FromRGBA (0.17f, 0.18f, 0.20f, 1.00f);
UIColor bottomColorInner = UIColor.FromRGBA (0.98f, 0.98f, 0.99f, 1.00f);
UIColor buttonFlareUpColor = UIColor.FromRGBA (
(buttonColorRGBA [0] * 0.3f + 0.7f),
(buttonColorRGBA [1] * 0.3f + 0.7f),
(buttonColorRGBA [2] * 0.3f + 0.7f),
(buttonColorRGBA [3] * 0.3f + 0.7f)
);
UIColor buttonTopColor = UIColor.FromRGBA (
(buttonColorRGBA [0] * 0.8f),
(buttonColorRGBA [1] * 0.8f),
(buttonColorRGBA [2] * 0.8f),
(buttonColorRGBA [3] * 0.8f + 0.2f)
);
UIColor buttonBottomColor = UIColor.FromRGBA (
(buttonColorRGBA [0] * 0 + 1),
(buttonColorRGBA [1] * 0 + 1),
(buttonColorRGBA [2] * 0 + 1),
(buttonColorRGBA [3] * 0 + 1)
);
UIColor buttonFlareBottomColor = UIColor.FromRGBA (
(buttonColorRGBA [0] * 0.8f + 0.2f),
(buttonColorRGBA [1] * 0.8f + 0.2f),
(buttonColorRGBA [2] * 0.8f + 0.2f),
(buttonColorRGBA [3] * 0.8f + 0.2f)
);
UIColor flareWhite = UIColor.FromRGBA (1.00f, 1.00f, 1.00f, 0.83f);
//// Gradient Declarations
var ringGradientColors = new CGColor [] {
upColorOut.CGColor,
bottomColorDown.CGColor
};
var ringGradientLocations = new nfloat [] { 0, 1 };
var ringGradient = new CGGradient (colorSpace, ringGradientColors, ringGradientLocations);
var ringInnerGradientColors = new CGColor [] {
upColorInner.CGColor,
bottomColorInner.CGColor
};
var ringInnerGradientLocations = new nfloat [] { 0, 1 };
var ringInnerGradient = new CGGradient (colorSpace, ringInnerGradientColors, ringInnerGradientLocations);
var buttonGradientColors = new CGColor [] {
buttonBottomColor.CGColor,
buttonTopColor.CGColor
};
var buttonGradientLocations = new nfloat [] { 0, 1 };
var buttonGradient = new CGGradient (colorSpace, buttonGradientColors, buttonGradientLocations);
var overlayGradientColors = new CGColor [] {
flareWhite.CGColor,
UIColor.Clear.CGColor
};
var overlayGradientLocations = new nfloat [] { 0, 1 };
var overlayGradient = new CGGradient (colorSpace, overlayGradientColors, overlayGradientLocations);
var buttonFlareGradientColors = new CGColor [] {
buttonFlareUpColor.CGColor,
buttonFlareBottomColor.CGColor
};
var buttonFlareGradientLocations = new nfloat [] { 0, 1 };
var buttonFlareGradient = new CGGradient (colorSpace, buttonFlareGradientColors, buttonFlareGradientLocations);
//// Shadow Declarations
var buttonInnerShadow = UIColor.Black.CGColor;
var buttonInnerShadowOffset = new CGSize (0, -0);
var buttonInnerShadowBlurRadius = 5;
var buttonOuterShadow = UIColor.Black.CGColor;
var buttonOuterShadowOffset = new CGSize (0, 2);
var buttonOuterShadowBlurRadius = isPressed ? 2 : 5; // ADDED this code after PaintCode
//// outerOval Drawing
var outerOvalPath = UIBezierPath.FromOval (new CGRect (5, 5, 63, 63));
context.SaveState ();
context.SetShadow (buttonOuterShadowOffset, buttonOuterShadowBlurRadius, buttonOuterShadow);
context.BeginTransparencyLayer (null);
outerOvalPath.AddClip ();
context.DrawLinearGradient (ringGradient, new CGPoint (36.5f, 5), new CGPoint (36.5f, 68), 0);
context.EndTransparencyLayer ();
context.RestoreState ();
//// overlayOval Drawing
var overlayOvalPath = UIBezierPath.FromOval (new CGRect (5, 5, 63, 63));
context.SaveState ();
overlayOvalPath.AddClip ();
context.DrawRadialGradient (overlayGradient,
new CGPoint (36.5f, 12.23f), 17.75f,
new CGPoint (36.5f, 36.5f), 44.61f,
CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation);
context.RestoreState ();
//// innerOval Drawing
var innerOvalPath = UIBezierPath.FromOval (new CGRect (12, 12, 49, 49));
context.SaveState ();
innerOvalPath.AddClip ();
context.DrawLinearGradient (ringInnerGradient, new CGPoint (36.5f, 12), new CGPoint (36.5f, 61), 0);
context.RestoreState ();
//// buttonOval Drawing
var buttonOvalPath = UIBezierPath.FromOval (new CGRect (14, 13, 46, 46));
context.SaveState ();
buttonOvalPath.AddClip ();
context.DrawRadialGradient (buttonGradient,
new CGPoint (37, 63.23f), 2.44f,
new CGPoint (37, 44.48f), 23.14f,
CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation);
context.RestoreState ();
////// buttonOval Inner Shadow
var buttonOvalBorderRect = buttonOvalPath.Bounds;
buttonOvalBorderRect.Inflate (buttonInnerShadowBlurRadius, buttonInnerShadowBlurRadius);
buttonOvalBorderRect.Offset (-buttonInnerShadowOffset.Width, -buttonInnerShadowOffset.Height);
buttonOvalBorderRect = CGRect.Union (buttonOvalBorderRect, buttonOvalPath.Bounds);
buttonOvalBorderRect.Inflate (1, 1);
var buttonOvalNegativePath = UIBezierPath.FromRect (buttonOvalBorderRect);
buttonOvalNegativePath.AppendPath (buttonOvalPath);
buttonOvalNegativePath.UsesEvenOddFillRule = true;
context.SaveState ();
{
var xOffset = buttonInnerShadowOffset.Width + (float)Math.Round (buttonOvalBorderRect.Width);
var yOffset = buttonInnerShadowOffset.Height;
context.SetShadow (
new CGSize (xOffset + (xOffset >= 0 ? 0.1f : -0.1f), yOffset + (yOffset >= 0 ? 0.1f : -0.1f)),
buttonInnerShadowBlurRadius,
buttonInnerShadow);
buttonOvalPath.AddClip ();
var transform = CGAffineTransform.MakeTranslation (-(float)Math.Round (buttonOvalBorderRect.Width), 0);
buttonOvalNegativePath.ApplyTransform (transform);
UIColor.Gray.SetFill ();
buttonOvalNegativePath.Fill ();
}
context.RestoreState ();
//// flareOval Drawing
var flareOvalPath = UIBezierPath.FromOval (new CGRect (22, 14, 29, 15));
context.SaveState ();
flareOvalPath.AddClip ();
context.DrawLinearGradient (buttonFlareGradient, new CGPoint (36.5f, 14), new CGPoint (36.5f, 29), 0);
context.RestoreState ();
// ------------- END PAINTCODE -------------
}
}
}
}
}
| |
/***************************************************************************
* Expression.cs
*
* Copyright (C) 2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Abakos.Compiler
{
public class Expression
{
private string raw_expression;
private Queue<Symbol> infix_queue;
private Queue<Symbol> postfix_queue;
private Dictionary<string, double> variable_table = new Dictionary<string, double>();
private static Regex tokenizer_regex = null;
public Expression(string expression)
{
raw_expression = "(" + expression + ")";
infix_queue = ToInfixQueue(raw_expression);
postfix_queue = ToPostfixQueue(infix_queue);
}
public void DefineVariable(string variable, double value)
{
if(variable_table.ContainsKey(variable)) {
variable_table[variable] = value;
} else {
variable_table.Add(variable, value);
}
}
public Queue<Symbol> InfixQueue {
get { return infix_queue; }
}
public Queue<Symbol> PostfixQueue {
get { return postfix_queue; }
}
public string RawExpression {
get { return raw_expression; }
}
public static Queue<Symbol> ToInfixQueue(string expression)
{
if(tokenizer_regex == null) {
Queue<string> skipped = new Queue<string>();
StringBuilder expr = new StringBuilder();
expr.Append("([\\,");
foreach(OperatorSymbol op in OperatorSymbol.Operators) {
if(op.Name.Length > 1){
skipped.Enqueue(op.Name);
continue;
}
expr.Append("\\");
expr.Append(op.Name);
}
foreach(GroupSymbol gp in GroupSymbol.GroupSymbols) {
expr.Append("\\");
expr.Append(gp.Name);
}
expr.Append("]{1}");
while(skipped.Count > 0) {
expr.Append("|");
expr.Append(skipped.Dequeue());
}
expr.Append(")");
tokenizer_regex = new Regex(expr.ToString(), RegexOptions.IgnorePatternWhitespace);
}
string [] tokens = tokenizer_regex.Split(expression);
List<Symbol> symbol_list = new List<Symbol>();
for(int i = 0; i < tokens.Length; i++) {
string token = tokens[i].Trim();
string next_token = null;
if(token == String.Empty) {
continue;
}
if(i < tokens.Length - 1) {
next_token = tokens[i + 1].Trim();
}
Symbol symbol = Symbol.FromString(token, next_token);
symbol_list.Add(symbol);
// I'm too tired to fix this at the stack/execution level right now;
// injecting void at the parsing level for zero-arg functions
if(symbol_list.Count >= 3 && GroupSymbol.IsRight(symbol) &&
GroupSymbol.IsLeft(symbol_list[symbol_list.Count - 2]) &&
symbol_list[symbol_list.Count - 3] is FunctionSymbol) {
symbol_list.Insert(symbol_list.Count - 1, new VoidSymbol());
}
}
Queue<Symbol> queue = new Queue<Symbol>();
foreach(Symbol symbol in symbol_list) {
queue.Enqueue(symbol);
}
return queue;
}
public static Queue<Symbol> ToPostfixQueue(Queue<Symbol> infix)
{
Stack<Symbol> stack = new Stack<Symbol>();
Queue<Symbol> postfix = new Queue<Symbol>();
Symbol temp_symbol;
foreach(Symbol symbol in infix) {
if(symbol is ValueSymbol) {
postfix.Enqueue(symbol);
} else if(GroupSymbol.IsLeft(symbol)) {
stack.Push(symbol);
} else if(GroupSymbol.IsRight(symbol)) {
while(stack.Count > 0) {
temp_symbol = stack.Pop();
if(GroupSymbol.IsLeft(temp_symbol)) {
break;
}
postfix.Enqueue(temp_symbol);
}
} else {
if(stack.Count > 0) {
temp_symbol = stack.Pop();
while(stack.Count != 0 && OperationSymbol.Compare(temp_symbol, symbol)) {
postfix.Enqueue(temp_symbol);
temp_symbol = stack.Pop();
}
if(OperationSymbol.Compare(temp_symbol, symbol)) {
postfix.Enqueue(temp_symbol);
} else {
stack.Push(temp_symbol);
}
}
stack.Push(symbol);
}
}
while(stack.Count > 0) {
postfix.Enqueue(stack.Pop());
}
return postfix;
}
public Stack<Symbol> Evaluate()
{
return EvaluatePostfix(postfix_queue, variable_table);
}
public double EvaluateNumeric()
{
return ((NumberSymbol)Evaluate().Pop()).Value;
}
public static Stack<Symbol> EvaluatePostfix(Queue<Symbol> postfix, IDictionary<string, double> variableTable)
{
Stack<Symbol> stack = new Stack<Symbol>();
foreach(Symbol current_symbol in postfix) {
if(current_symbol is VariableSymbol) {
stack.Push((current_symbol as VariableSymbol).Resolve(variableTable));
} else if(current_symbol is ValueSymbol || current_symbol is CommaSymbol) {
stack.Push(current_symbol);
} else if(current_symbol is OperatorSymbol) {
Symbol a = stack.Pop();
Symbol b = stack.Pop();
stack.Push((current_symbol as OperatorSymbol).Evaluate(b, a));
} else if(current_symbol is FunctionSymbol) {
Stack<Symbol> argument_stack = new Stack<Symbol>();
if(stack.Count > 0) {
Symbol argument = stack.Pop();
if(!(argument is CommaSymbol) && !(argument is VoidSymbol)) {
argument_stack.Push(argument);
} else if(argument is CommaSymbol) {
while(argument is CommaSymbol) {
argument = stack.Pop();
argument_stack.Push(argument);
argument = stack.Pop();
if(!(argument is CommaSymbol)) {
argument_stack.Push(argument);
}
}
}
}
stack.Push(FunctionTable.Execute(current_symbol as FunctionSymbol, argument_stack));
}
}
return stack;
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CertificatesOperations operations.
/// </summary>
internal partial class CertificatesOperations : IServiceOperations<LogicManagementClient>, ICertificatesOperations
{
/// <summary>
/// Initializes a new instance of the CertificatesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal CertificatesOperations(LogicManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the LogicManagementClient
/// </summary>
public LogicManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of integration account certificates.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IntegrationAccountCertificate>>> ListByIntegrationAccountsWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByIntegrationAccounts", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IntegrationAccountCertificate>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IntegrationAccountCertificate>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets an integration account certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='certificateName'>
/// The integration account certificate name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IntegrationAccountCertificate>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{certificateName}", System.Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IntegrationAccountCertificate>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountCertificate>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an integration account certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='certificateName'>
/// The integration account certificate name.
/// </param>
/// <param name='certificate'>
/// The integration account certificate.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IntegrationAccountCertificate>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, IntegrationAccountCertificate certificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (certificate == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificate");
}
if (certificate != null)
{
certificate.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("certificate", certificate);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{certificateName}", System.Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(certificate != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(certificate, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IntegrationAccountCertificate>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountCertificate>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountCertificate>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an integration account certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='certificateName'>
/// The integration account certificate name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{certificateName}", System.Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of integration account certificates.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IntegrationAccountCertificate>>> ListByIntegrationAccountsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByIntegrationAccountsNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IntegrationAccountCertificate>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IntegrationAccountCertificate>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Text
{
public abstract partial class SymbolTable
{
#region Private data
private readonly byte[][] _symbols; // this could be flattened into a single array
private readonly ParsingTrie.Node[] _parsingTrie; // prefix tree used for parsing
#endregion Private data
#region Constructors
protected SymbolTable(byte[][] symbols)
{
_symbols = symbols;
_parsingTrie = ParsingTrie.Create(symbols);
}
#endregion Constructors
#region Static instances
public readonly static SymbolTable InvariantUtf8 = new Utf8InvariantSymbolTable();
public readonly static SymbolTable InvariantUtf16 = new Utf16InvariantSymbolTable();
#endregion Static instances
public bool TryEncode(Symbol symbol, Span<byte> destination, out int bytesWritten)
{
byte[] bytes = _symbols[(int)symbol];
bytesWritten = bytes.Length;
if (bytesWritten > destination.Length)
{
bytesWritten = 0;
return false;
}
if (bytesWritten == 2)
{
destination[0] = bytes[0];
destination[1] = bytes[1];
return true;
}
if (bytesWritten == 1)
{
destination[0] = bytes[0];
return true;
}
new Span<byte>(bytes).CopyTo(destination);
return true;
}
public abstract bool TryEncode(byte utf8, Span<byte> destination, out int bytesWritten);
public abstract bool TryEncode(ReadOnlySpan<byte> utf8, Span<byte> destination, out int bytesConsumed, out int bytesWritten);
public bool TryParse(ReadOnlySpan<byte> source, out Symbol symbol, out int bytesConsumed)
{
int trieIndex = 0;
int codeUnitIndex = 0;
bytesConsumed = 0;
while (true)
{
if (_parsingTrie[trieIndex].ValueOrNumChildren == 0) // if numChildren == 0, we're on a leaf & we've found our value and completed the code unit
{
symbol = (Symbol)_parsingTrie[trieIndex].IndexOrSymbol; // return the parsed value
if (VerifySuffix(source, codeUnitIndex, symbol))
{
bytesConsumed = _symbols[(int)symbol].Length;
return true;
}
else
{
symbol = 0;
bytesConsumed = 0;
return false;
}
}
else
{
int search = BinarySearch(trieIndex, codeUnitIndex, source[codeUnitIndex]); // we search the _parsingTrie for the nextByte
if (search > 0) // if we found a node
{
trieIndex = _parsingTrie[search].IndexOrSymbol;
bytesConsumed++;
codeUnitIndex++;
}
else
{
symbol = 0;
bytesConsumed = 0;
return false;
}
}
}
}
public abstract bool TryParse(ReadOnlySpan<byte> source, out byte utf8, out int bytesConsumed);
public abstract bool TryParse(ReadOnlySpan<byte> source, Span<byte> utf8, out int bytesConsumed, out int bytesWritten);
#region Public UTF-16 to UTF-8 helpers
public bool TryEncode(ReadOnlySpan<char> source, Span<byte> destination, out int bytesConsumed, out int bytesWritten)
{
ReadOnlySpan<byte> srcBytes = source.AsBytes();
if (this == SymbolTable.InvariantUtf16)
return TryEncodeUtf16(srcBytes, destination, out bytesConsumed, out bytesWritten);
const int BufferSize = 256;
int srcLength = srcBytes.Length;
if (srcLength <= 0)
{
bytesConsumed = bytesWritten = 0;
return true;
}
Span<byte> temp;
unsafe
{
byte* pTemp = stackalloc byte[BufferSize];
temp = new Span<byte>(pTemp, BufferSize);
}
bytesWritten = 0;
bytesConsumed = 0;
while (srcLength > bytesConsumed)
{
var status = Encoders.Utf8.ConvertFromUtf16(srcBytes, temp, out int consumed, out int written);
if (status == Buffers.TransformationStatus.InvalidData)
goto ExitFailed;
srcBytes = srcBytes.Slice(consumed);
bytesConsumed += consumed;
if (!TryEncode(temp.Slice(0, written), destination, out consumed, out written))
goto ExitFailed;
destination = destination.Slice(written);
bytesWritten += written;
}
return true;
ExitFailed:
return false;
}
private bool TryEncodeUtf16(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesConsumed, out int bytesWritten)
{
// NOTE: There is no validation of this UTF-16 encoding. A caller is expected to do any validation on their own if
// they don't trust the data.
bytesConsumed = source.Length;
bytesWritten = destination.Length;
if (bytesConsumed > bytesWritten)
{
source = source.Slice(0, bytesWritten);
bytesConsumed = bytesWritten;
}
else
{
bytesWritten = bytesConsumed;
}
source.CopyTo(destination);
return true;
}
#endregion Public UTF-16 to UTF-8 helpers
#region Private helpers
// This binary search implementation returns an int representing either:
// - the index of the item searched for (if the value is positive)
// - the index of the location where the item should be placed to maintain a sorted list (if the value is negative)
private int BinarySearch(int nodeIndex, int level, byte value)
{
int maxMinLimits = _parsingTrie[nodeIndex].IndexOrSymbol;
if (maxMinLimits != 0 && value > (uint)maxMinLimits >> 24 && value < (uint)(maxMinLimits << 16) >> 24)
{
// See the comments on the struct above for more information about this format
return (int)(nodeIndex + ((uint)(maxMinLimits << 8) >> 24) + value - ((uint)maxMinLimits >> 24));
}
int leftBound = nodeIndex + 1, rightBound = nodeIndex + _parsingTrie[nodeIndex].ValueOrNumChildren;
int midIndex = 0;
while (true)
{
if (leftBound > rightBound) // if the search failed
{
// this loop is necessary because binary search takes the floor
// of the middle, which means it can give incorrect indices for insertion.
// we should never iterate up more than two indices.
while (midIndex < nodeIndex + _parsingTrie[nodeIndex].ValueOrNumChildren
&& _parsingTrie[midIndex].ValueOrNumChildren < value)
{
midIndex++;
}
return -midIndex;
}
midIndex = (leftBound + rightBound) / 2; // find the middle value
byte mValue = _parsingTrie[midIndex].ValueOrNumChildren;
if (mValue < value)
leftBound = midIndex + 1;
else if (mValue > value)
rightBound = midIndex - 1;
else
return midIndex;
}
}
private bool VerifySuffix(ReadOnlySpan<byte> buffer, int codeUnitIndex, Symbol symbol)
{
int codeUnitLength = _symbols[(int)symbol].Length;
if (codeUnitIndex == codeUnitLength - 1)
return true;
for (int i = 0; i < codeUnitLength - codeUnitIndex; i++)
{
if (buffer[i + codeUnitIndex] != _symbols[(int)symbol][i + codeUnitIndex])
return false;
}
return true;
}
#endregion Private helpers
}
}
| |
using UnityEngine;
using UnityEngine.Audio;
namespace OVR
{
//-------------------------------------------------------------------------
// Types
//-------------------------------------------------------------------------
public enum EmitterChannel {
None = -1,
Reserved = 0, // plays on the single reserved emitter
Any // queues to the next available emitter
}
[System.Serializable]
public class MixerSnapshot {
public AudioMixerSnapshot snapshot = null;
public float transitionTime = 0.25f;
}
/*
-----------------------
GameManager Sound Routines
-----------------------
*/
public partial class AudioManager : MonoBehaviour {
public enum Fade {
In,
Out
}
private float audioMaxFallOffDistanceSqr = 25.0f * 25.0f; // past this distance, sounds are ignored for the local player
private SoundEmitter[] soundEmitters = null; // pool of sound emitters to play sounds through
private FastList<SoundEmitter> playingEmitters = new FastList<SoundEmitter>();
private FastList<SoundEmitter> nextFreeEmitters = new FastList<SoundEmitter>();
private MixerSnapshot currentSnapshot = null;
static private GameObject soundEmitterParent = null; // parent object for the sound emitters
static private Transform staticListenerPosition = null; // play position for regular 2D sounds
static private bool showPlayingEmitterCount = false;
static private bool forceShowEmitterCount = false;
static private bool soundEnabled = true;
static public bool SoundEnabled { get { return soundEnabled; } }
static readonly AnimationCurve defaultReverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } );
/*
-----------------------
InitializeSoundSystem()
initialize persistent sound emitter objects that live across scene loads
-----------------------
*/
void InitializeSoundSystem() {
int bufferLength = 960;
int numBuffers = 4;
AudioSettings.GetDSPBufferSize( out bufferLength, out numBuffers );
if ( Application.isPlaying ) {
Debug.Log( "[AudioManager] Audio Sample Rate: " + AudioSettings.outputSampleRate );
Debug.Log( "[AudioManager] Audio Buffer Length: " + bufferLength + " Size: " + numBuffers );
}
// find the audio listener for playing regular 2D sounds
AudioListener audioListenerObject = GameObject.FindObjectOfType<AudioListener>() as AudioListener;
if ( audioListenerObject == null ) {
Debug.LogError( "[AudioManager] Missing AudioListener object! Add one to the scene." );
} else {
staticListenerPosition = audioListenerObject.transform;
}
// we allocate maxSoundEmitters + reserved channels
soundEmitters = new SoundEmitter[maxSoundEmitters+(int)EmitterChannel.Any];
// see if the sound emitters have already been created, if so, nuke it, it shouldn't exist in the scene upon load
soundEmitterParent = GameObject.Find( "__SoundEmitters__" );
if ( soundEmitterParent != null ) {
// delete any sound emitters hanging around
Destroy( soundEmitterParent );
}
// create them all
soundEmitterParent = new GameObject( "__SoundEmitters__" );
for ( int i = 0; i < maxSoundEmitters + (int)EmitterChannel.Any; i++ ) {
GameObject emitterObject = new GameObject( "SoundEmitter_" + i );
emitterObject.transform.parent = soundEmitterParent.transform;
emitterObject.transform.position = Vector3.zero;
// don't ever save this to the scene
emitterObject.hideFlags = HideFlags.DontSaveInEditor;
// add the sound emitter components
soundEmitters[i] = emitterObject.AddComponent<SoundEmitter>();
soundEmitters[i].SetDefaultParent( soundEmitterParent.transform );
soundEmitters[i].SetChannel( i );
soundEmitters[i].Stop();
// save off the original index
soundEmitters[i].originalIdx = i;
}
// reset the free emitter lists
ResetFreeEmitters();
soundEmitterParent.hideFlags = HideFlags.DontSaveInEditor;
audioMaxFallOffDistanceSqr = audioMaxFallOffDistance * audioMaxFallOffDistance;
}
/*
-----------------------
UpdateFreeEmitters()
-----------------------
*/
void UpdateFreeEmitters() {
if ( verboseLogging ) {
if ( Input.GetKeyDown( KeyCode.A ) ) {
forceShowEmitterCount = !forceShowEmitterCount;
}
if ( forceShowEmitterCount ) {
showPlayingEmitterCount = true;
}
}
// display playing emitter count when the sound system is overwhelmed
int total = 0, veryLow = 0, low = 0, def = 0, high = 0, veryHigh = 0;
// find emitters that are done playing and add them to the nextFreeEmitters list
for ( int i = 0; i < playingEmitters.size; ) {
if ( playingEmitters[i] == null ) {
Debug.LogError( "[AudioManager] ERROR: playingEmitters list had a null emitter! Something nuked a sound emitter!!!" );
playingEmitters.RemoveAtFast( i );
return;
}
if ( !playingEmitters[i].IsPlaying() ) {
// add to the free list and remove from the playing list
if ( verboseLogging ) {
if ( nextFreeEmitters.Contains( playingEmitters[i] ) ) {
Debug.LogError( "[AudioManager] ERROR: playing sound emitter already in the free emitters list!" );
}
}
playingEmitters[i].Stop();
nextFreeEmitters.Add( playingEmitters[i] );
playingEmitters.RemoveAtFast( i );
continue;
}
// debugging/profiling
if ( verboseLogging && showPlayingEmitterCount ) {
total++;
switch ( playingEmitters[i].priority ) {
case SoundPriority.VeryLow: veryLow++; break;
case SoundPriority.Low: low++; break;
case SoundPriority.Default: def++; break;
case SoundPriority.High: high++; break;
case SoundPriority.VeryHigh: veryHigh++; break;
}
}
i++;
}
if ( verboseLogging && showPlayingEmitterCount ) {
Debug.LogWarning( string.Format( "[AudioManager] Playing sounds: Total {0} | VeryLow {1} | Low {2} | Default {3} | High {4} | VeryHigh {5} | Free {6}", Fmt( total ), Fmt( veryLow ), Fmt( low ), Fmt( def ), Fmt( high ), Fmt( veryHigh ), FmtFree( nextFreeEmitters.Count ) ) );
showPlayingEmitterCount = false;
}
}
/*
-----------------------
Fmt()
-----------------------
*/
string Fmt( int count ) {
float t = count / (float)theAudioManager.maxSoundEmitters;
if ( t < 0.5f ) {
return "<color=green>" + count.ToString() + "</color>";
} else if ( t < 0.7 ) {
return "<color=yellow>" + count.ToString() + "</color>";
} else {
return "<color=red>" + count.ToString() + "</color>";
}
}
/*
-----------------------
FmtFree()
-----------------------
*/
string FmtFree( int count ) {
float t = count / (float)theAudioManager.maxSoundEmitters;
if ( t < 0.2f ) {
return "<color=red>" + count.ToString() + "</color>";
} else if ( t < 0.3 ) {
return "<color=yellow>" + count.ToString() + "</color>";
} else {
return "<color=green>" + count.ToString() + "</color>";
}
}
/*
-----------------------
OnPreSceneLoad()
-----------------------
*/
void OnPreSceneLoad() {
// move any attached sounds back to the sound emitters parent before changing levels so they don't get destroyed
Debug.Log( "[AudioManager] OnPreSceneLoad cleanup" );
for ( int i = 0; i < soundEmitters.Length; i++ ) {
soundEmitters[i].Stop();
soundEmitters[i].ResetParent( soundEmitterParent.transform );
}
// reset our emitter lists
ResetFreeEmitters();
}
/*
-----------------------
ResetFreeEmitters()
-----------------------
*/
void ResetFreeEmitters() {
nextFreeEmitters.Clear();
playingEmitters.Clear();
for ( int i = (int)EmitterChannel.Any; i < soundEmitters.Length; i++ ) {
nextFreeEmitters.Add( soundEmitters[i] );
}
}
/*
-----------------------
FadeOutSoundChannel()
utility function to fade out a playing sound channel
-----------------------
*/
static public void FadeOutSoundChannel( int channel, float delaySecs, float fadeTime ) {
theAudioManager.soundEmitters[channel].FadeOutDelayed( delaySecs, fadeTime );
}
/*
-----------------------
StopSound()
-----------------------
*/
static public bool StopSound( int idx, bool fadeOut = true, bool stopReserved = false ) {
if ( !stopReserved && ( idx == (int)EmitterChannel.Reserved ) ) {
return false;
}
if ( !fadeOut ) {
theAudioManager.soundEmitters[idx].Stop();
}
else {
theAudioManager.soundEmitters[idx].FadeOut( theAudioManager.soundFxFadeSecs );
}
return true;
}
/*
-----------------------
FadeInSound()
-----------------------
*/
public static void FadeInSound( int idx, float fadeTime, float volume ) {
theAudioManager.soundEmitters[idx].FadeIn( fadeTime, volume );
}
/*
-----------------------
FadeInSound()
-----------------------
*/
public static void FadeInSound( int idx, float fadeTime ) {
theAudioManager.soundEmitters[idx].FadeIn( fadeTime );
}
/*
-----------------------
FadeOutSound()
-----------------------
*/
public static void FadeOutSound( int idx, float fadeTime ) {
theAudioManager.soundEmitters[idx].FadeOut( fadeTime );
}
/*
-----------------------
StopAllSounds()
-----------------------
*/
public static void StopAllSounds( bool fadeOut, bool stopReserved = false ) {
for ( int i = 0; i < theAudioManager.soundEmitters.Length; i++ ) {
StopSound( i, fadeOut, stopReserved );
}
}
/*
-----------------------
MuteAllSounds()
-----------------------
*/
public void MuteAllSounds( bool mute, bool muteReserved = false ) {
for ( int i = 0; i < soundEmitters.Length; i++ ) {
if ( !muteReserved && ( i == (int)EmitterChannel.Reserved ) ) {
continue;
}
soundEmitters[i].audioSource.mute = true;
}
}
/*
-----------------------
UnMuteAllSounds()
-----------------------
*/
public void UnMuteAllSounds( bool unmute, bool unmuteReserved = false ) {
for ( int i = 0; i < soundEmitters.Length; i++ ) {
if ( !unmuteReserved && ( i == (int)EmitterChannel.Reserved ) ) {
continue;
}
if ( soundEmitters[i].audioSource.isPlaying ) {
soundEmitters[i].audioSource.mute = false;
}
}
}
/*
-----------------------
GetEmitterEndTime()
-----------------------
*/
static public float GetEmitterEndTime( int idx ) {
return theAudioManager.soundEmitters[idx].endPlayTime;
}
/*
-----------------------
SetEmitterTime()
-----------------------
*/
static public float SetEmitterTime( int idx, float time ) {
return theAudioManager.soundEmitters[idx].time = time;
}
/*
-----------------------
PlaySound()
-----------------------
*/
static public int PlaySound( AudioClip clip, float volume, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float pitchVariance = 1.0f, bool loop = false ) {
if ( !SoundEnabled ) {
return -1;
}
return PlaySoundAt( ( staticListenerPosition != null ) ? staticListenerPosition.position : Vector3.zero, clip, volume, src, delay, pitchVariance, loop );
}
/*
-----------------------
FindFreeEmitter()
-----------------------
*/
static private int FindFreeEmitter( EmitterChannel src, SoundPriority priority ) {
// default to the reserved emitter
SoundEmitter next = theAudioManager.soundEmitters[0];
if ( src == EmitterChannel.Any ) {
// pull from the free emitter list if possible
if ( theAudioManager.nextFreeEmitters.size > 0 ) {
// return the first in the list
next = theAudioManager.nextFreeEmitters[0];
// remove it from the free list
theAudioManager.nextFreeEmitters.RemoveAtFast( 0 );
} else {
// no free emitters available so pull from the lowest priority sound
if ( priority == SoundPriority.VeryLow ) {
// skip low priority sounds
return -1;
} else {
// find a playing emitter that has a lower priority than what we're requesting
// TODO - we could first search for Very Low, then Low, etc ... TBD if it's worth the effort
next = theAudioManager.playingEmitters.Find( item => item != null && item.priority < priority );
if ( next == null ) {
// last chance to find a free emitter
if ( priority < SoundPriority.Default ) {
// skip sounds less than the default priority
if ( theAudioManager.verboseLogging ) {
Debug.LogWarning( "[AudioManager] skipping sound " + priority );
}
return -1;
} else {
// grab a default priority emitter so that we don't cannabalize a high priority sound
next = theAudioManager.playingEmitters.Find( item => item != null && item.priority <= SoundPriority.Default ); ;
}
}
if ( next != null ) {
if ( theAudioManager.verboseLogging ) {
Debug.LogWarning( "[AudioManager] cannabalizing " + next.originalIdx + " Time: " + Time.time );
}
// remove it from the playing list
next.Stop();
theAudioManager.playingEmitters.RemoveFast( next );
}
}
}
}
if ( next == null ) {
Debug.LogError( "[AudioManager] ERROR - absolutely couldn't find a free emitter! Priority = " + priority + " TOO MANY PlaySound* calls!" );
showPlayingEmitterCount = true;
return -1;
}
return next.originalIdx;
}
/*
-----------------------
PlaySound()
-----------------------
*/
static public int PlaySound( SoundFX soundFX, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f ) {
if ( !SoundEnabled ) {
return -1;
}
return PlaySoundAt( ( staticListenerPosition != null ) ? staticListenerPosition.position : Vector3.zero, soundFX, src, delay );
}
/*
-----------------------
PlaySoundAt()
-----------------------
*/
static public int PlaySoundAt( Vector3 position, SoundFX soundFX, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float volumeOverride = 1.0f, float pitchMultiplier = 1.0f ) {
if ( !SoundEnabled ) {
return -1;
}
AudioClip clip = soundFX.GetClip();
if ( clip == null ) {
return -1;
}
// check the distance from the local player and ignore sounds out of range
if ( staticListenerPosition != null ) {
float distFromListener = ( staticListenerPosition.position - position ).sqrMagnitude;
if ( distFromListener > theAudioManager.audioMaxFallOffDistanceSqr ) {
return -1;
}
if ( distFromListener > soundFX.MaxFalloffDistSquared ) {
return -1;
}
}
// check max playing sounds
if ( soundFX.ReachedGroupPlayLimit() ) {
if ( theAudioManager.verboseLogging ) {
Debug.Log( "[AudioManager] PlaySoundAt() with " + soundFX.name + " skipped due to group play limit" );
}
return -1;
}
int idx = FindFreeEmitter( src, soundFX.priority );
if ( idx == -1 ) {
// no free emitters - should only happen on very low priority sounds
return -1;
}
SoundEmitter emitter = theAudioManager.soundEmitters[idx];
// make sure to detach the emitter from a previous parent
emitter.ResetParent( soundEmitterParent.transform );
emitter.gameObject.SetActive( true );
// set up the sound emitter
AudioSource audioSource = emitter.audioSource;
ONSPAudioSource osp = emitter.osp;
audioSource.enabled = true;
audioSource.volume = Mathf.Clamp01( Mathf.Clamp01( theAudioManager.volumeSoundFX * soundFX.volume ) * volumeOverride * soundFX.GroupVolumeOverride );
audioSource.pitch = soundFX.GetPitch() * pitchMultiplier;
audioSource.time = 0.0f;
audioSource.spatialBlend = 1.0f;
audioSource.rolloffMode = soundFX.falloffCurve;
if ( soundFX.falloffCurve == AudioRolloffMode.Custom ) {
audioSource.SetCustomCurve( AudioSourceCurveType.CustomRolloff, soundFX.volumeFalloffCurve );
}
audioSource.SetCustomCurve( AudioSourceCurveType.ReverbZoneMix, soundFX.reverbZoneMix );
audioSource.dopplerLevel = 0;
audioSource.clip = clip;
audioSource.spread = soundFX.spread;
audioSource.loop = soundFX.looping;
audioSource.mute = false;
audioSource.minDistance = soundFX.falloffDistance.x;
audioSource.maxDistance = soundFX.falloffDistance.y;
audioSource.outputAudioMixerGroup = soundFX.GetMixerGroup( AudioManager.EmitterGroup );
// set the play time so we can check when sounds are done
emitter.endPlayTime = Time.time + clip.length + delay;
// cache the default volume for fading
emitter.defaultVolume = audioSource.volume;
// sound priority
emitter.priority = soundFX.priority;
// reset this
emitter.onFinished = null;
// update the sound group limits
emitter.SetPlayingSoundGroup( soundFX.Group );
// add to the playing list
if ( src == EmitterChannel.Any ) {
theAudioManager.playingEmitters.AddUnique( emitter );
}
// OSP properties
if ( osp != null ) {
osp.EnableSpatialization = soundFX.ospProps.enableSpatialization;
osp.EnableRfl = theAudioManager.enableSpatializedFastOverride || soundFX.ospProps.useFastOverride ? true : false;
osp.Gain = soundFX.ospProps.gain;
osp.UseInvSqr = soundFX.ospProps.enableInvSquare;
osp.Near = soundFX.ospProps.invSquareFalloff.x;
osp.Far = soundFX.ospProps.invSquareFalloff.y;
audioSource.spatialBlend = (soundFX.ospProps.enableSpatialization) ? 1.0f : 0.8f;
// make sure to set the properties in the audio source before playing
osp.SetParameters(ref audioSource);
}
audioSource.transform.position = position;
if ( theAudioManager.verboseLogging ) {
Debug.Log( "[AudioManager] PlaySoundAt() channel = " + idx + " soundFX = " + soundFX.name + " volume = " + emitter.volume + " Delay = " + delay + " time = " + Time.time + "\n" );
}
// play the sound
if ( delay > 0f ) {
audioSource.PlayDelayed( delay );
} else {
audioSource.Play();
}
return idx;
}
/*
-----------------------
PlayRandomSoundAt()
-----------------------
*/
static public int PlayRandomSoundAt( Vector3 position, AudioClip[] clips, float volume, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float pitch = 1.0f, bool loop = false ) {
if ( ( clips == null ) || ( clips.Length == 0 ) ) {
return -1;
}
int idx = Random.Range( 0, clips.Length );
return PlaySoundAt( position, clips[idx], volume, src, delay, pitch, loop );
}
/*
-----------------------
PlaySoundAt()
-----------------------
*/
static public int PlaySoundAt( Vector3 position, AudioClip clip, float volume = 1.0f, EmitterChannel src = EmitterChannel.Any, float delay = 0.0f, float pitch = 1.0f, bool loop = false ) {
if ( !SoundEnabled ) {
return -1;
}
if ( clip == null ) {
return -1;
}
// check the distance from the local player and ignore sounds out of range
if ( staticListenerPosition != null ) {
if ( ( staticListenerPosition.position - position ).sqrMagnitude > theAudioManager.audioMaxFallOffDistanceSqr ) {
// no chance of being heard
return -1;
}
}
int idx = FindFreeEmitter( src, 0 );
if ( idx == -1 ) {
// no free emitters - should only happen on very low priority sounds
return -1;
}
SoundEmitter emitter = theAudioManager.soundEmitters[idx];
// make sure to detach the emitter from a previous parent
emitter.ResetParent( soundEmitterParent.transform );
emitter.gameObject.SetActive( true );
// set up the sound emitter
AudioSource audioSource = emitter.audioSource;
ONSPAudioSource osp = emitter.osp;
audioSource.enabled = true;
audioSource.volume = Mathf.Clamp01( theAudioManager.volumeSoundFX * volume );
audioSource.pitch = pitch;
audioSource.spatialBlend = 0.8f;
audioSource.rolloffMode = AudioRolloffMode.Linear;
audioSource.SetCustomCurve( AudioSourceCurveType.ReverbZoneMix, defaultReverbZoneMix );
audioSource.dopplerLevel = 0.0f;
audioSource.clip = clip;
audioSource.spread = 0.0f;
audioSource.loop = loop;
audioSource.mute = false;
audioSource.minDistance = theAudioManager.audioMinFallOffDistance;
audioSource.maxDistance = theAudioManager.audioMaxFallOffDistance;
audioSource.outputAudioMixerGroup = AudioManager.EmitterGroup;
// set the play time so we can check when sounds are done
emitter.endPlayTime = Time.time + clip.length + delay;
// cache the default volume for fading
emitter.defaultVolume = audioSource.volume;
// default priority
emitter.priority = 0;
// reset this
emitter.onFinished = null;
// update the sound group limits
emitter.SetPlayingSoundGroup( null );
// add to the playing list
if ( src == EmitterChannel.Any ) {
theAudioManager.playingEmitters.AddUnique( emitter );
}
// disable spatialization (by default for regular AudioClips)
if ( osp != null ) {
osp.EnableSpatialization = false;
}
audioSource.transform.position = position;
if ( theAudioManager.verboseLogging ) {
Debug.Log( "[AudioManager] PlaySoundAt() channel = " + idx + " clip = " + clip.name + " volume = " + emitter.volume + " Delay = " + delay + " time = " + Time.time + "\n" );
}
// play the sound
if ( delay > 0f ) {
audioSource.PlayDelayed( delay );
} else {
audioSource.Play();
}
return idx;
}
/*
-----------------------
SetOnFinished()
-----------------------
*/
public static void SetOnFinished( int emitterIdx, System.Action onFinished ) {
if ( emitterIdx >= 0 && emitterIdx < theAudioManager.maxSoundEmitters ) {
theAudioManager.soundEmitters[emitterIdx].SetOnFinished( onFinished );
}
}
/*
-----------------------
SetOnFinished()
-----------------------
*/
public static void SetOnFinished( int emitterIdx, System.Action<object> onFinished, object obj ) {
if ( emitterIdx >= 0 && emitterIdx < theAudioManager.maxSoundEmitters ) {
theAudioManager.soundEmitters[emitterIdx].SetOnFinished( onFinished, obj );
}
}
/*
-----------------------
AttachSoundToParent()
-----------------------
*/
public static void AttachSoundToParent( int idx, Transform parent ) {
if ( theAudioManager.verboseLogging ) {
string parentName = parent.name;
if ( parent.parent != null ) {
parentName = parent.parent.name + "/" + parentName;
}
Debug.Log( "[AudioManager] ATTACHING INDEX " + idx + " to " + parentName );
}
theAudioManager.soundEmitters[idx].ParentTo( parent );
}
/*
-----------------------
DetachSoundFromParent()
-----------------------
*/
public static void DetachSoundFromParent( int idx ) {
if ( theAudioManager.verboseLogging ) {
Debug.Log( "[AudioManager] DETACHING INDEX " + idx );
}
theAudioManager.soundEmitters[idx].DetachFromParent();
}
/*
-----------------------
DetachSoundsFromParent()
-----------------------
*/
public static void DetachSoundsFromParent( SoundEmitter[] emitters, bool stopSounds = true ) {
if ( emitters == null ) {
return;
}
foreach ( SoundEmitter emitter in emitters ) {
if ( emitter.defaultParent != null ) {
if ( stopSounds ) {
emitter.Stop();
}
emitter.DetachFromParent();
// make sure it's active
emitter.gameObject.SetActive( true );
} else {
if ( stopSounds ) {
emitter.Stop();
}
}
}
}
/*
-----------------------
SetEmitterMixerGroup()
-----------------------
*/
public static void SetEmitterMixerGroup( int idx, AudioMixerGroup mixerGroup ) {
if ( ( theAudioManager != null ) && ( idx > -1 ) ) {
theAudioManager.soundEmitters[idx].SetAudioMixer( mixerGroup );
}
}
/*
-----------------------
GetActiveSnapshot()
-----------------------
*/
public static MixerSnapshot GetActiveSnapshot() {
return ( theAudioManager != null ) ? theAudioManager.currentSnapshot : null;
}
/*
-----------------------
SetCurrentSnapshot()
-----------------------
*/
public static void SetCurrentSnapshot( MixerSnapshot mixerSnapshot ) {
#if UNITY_EDITOR
if ( mixerSnapshot == null || mixerSnapshot.snapshot == null ) {
Debug.LogError( "[AudioManager] ERROR setting empty mixer snapshot!" );
} else {
Debug.Log( "[AudioManager] Setting audio mixer snapshot: " + ( ( mixerSnapshot != null && mixerSnapshot.snapshot != null ) ? mixerSnapshot.snapshot.name : "None" ) + " Time: " + Time.time );
}
#endif
if ( theAudioManager != null ) {
if ( ( mixerSnapshot != null ) && ( mixerSnapshot.snapshot != null ) ) {
mixerSnapshot.snapshot.TransitionTo( mixerSnapshot.transitionTime );
} else {
mixerSnapshot = null;
}
theAudioManager.currentSnapshot = mixerSnapshot;
}
}
/*
-----------------------
BlendWithCurrentSnapshot()
-----------------------
*/
public static void BlendWithCurrentSnapshot( MixerSnapshot blendSnapshot, float weight, float blendTime = 0.0f ) {
if ( theAudioManager != null ) {
if ( theAudioManager.audioMixer == null ) {
Debug.LogWarning( "[AudioManager] can't call BlendWithCurrentSnapshot if the audio mixer is not set!" );
return;
}
if ( blendTime == 0.0f ) {
blendTime = Time.deltaTime;
}
if ( ( theAudioManager.currentSnapshot != null ) && (theAudioManager.currentSnapshot.snapshot != null ) ) {
if ( ( blendSnapshot != null ) && ( blendSnapshot.snapshot != null ) ) {
weight = Mathf.Clamp01( weight );
if ( weight == 0.0f ) {
// revert to the default snapshot
theAudioManager.currentSnapshot.snapshot.TransitionTo( blendTime );
} else {
AudioMixerSnapshot[] snapshots = new AudioMixerSnapshot[] { theAudioManager.currentSnapshot.snapshot, blendSnapshot.snapshot };
float[] weights = new float[] { 1.0f - weight, weight };
theAudioManager.audioMixer.TransitionToSnapshots( snapshots, weights, blendTime );
}
}
}
}
}
}
} // namespace OVR
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace TasksWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridViewHeaderCell.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms
{
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms.VisualStyles;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell"]/*' />
/// <devdoc>
/// <para>Identifies a cell in the dataGridView.</para>
/// </devdoc>
///
public class DataGridViewHeaderCell : DataGridViewCell
{
private const byte DATAGRIDVIEWHEADERCELL_themeMargin = 100; // used to calculate the margins required for XP theming rendering
private static Type defaultFormattedValueType = typeof(System.String);
private static Type defaultValueType = typeof(System.Object);
private static Type cellType = typeof(DataGridViewHeaderCell);
private static Rectangle rectThemeMargins = new Rectangle(-1, -1, 0, 0);
private static readonly int PropValueType = PropertyStore.CreateKey();
private static readonly int PropButtonState = PropertyStore.CreateKey();
private static readonly int PropFlipXPThemesBitmap = PropertyStore.CreateKey();
private const string AEROTHEMEFILENAME = "Aero.msstyles";
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.DataGridViewHeaderCell"]/*' />
public DataGridViewHeaderCell()
{
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.ButtonState"]/*' />
protected ButtonState ButtonState
{
get
{
bool found;
int buttonState = this.Properties.GetInteger(PropButtonState, out found);
if (found)
{
return (ButtonState) buttonState;
}
return ButtonState.Normal;
}
}
private ButtonState ButtonStatePrivate
{
[
SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible") // Enum.IsDefined is OK here. Only specific flag combinations are allowed, and it's debug only anyways.
]
set
{
Debug.Assert(Enum.IsDefined(typeof(ButtonState), value));
if (this.ButtonState != value)
{
this.Properties.SetInteger(PropButtonState, (int) value);
}
}
}
protected override void Dispose(bool disposing) {
if (FlipXPThemesBitmap != null && disposing) {
FlipXPThemesBitmap.Dispose();
}
base.Dispose(disposing);
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.Displayed"]/*' />
[
Browsable(false)
]
public override bool Displayed
{
get
{
if (this.DataGridView == null || !this.DataGridView.Visible)
{
// No detached or invisible element is displayed.
return false;
}
if (this.OwningRow != null)
{
// row header cell
return this.DataGridView.RowHeadersVisible && this.OwningRow.Displayed;
}
if (this.OwningColumn != null)
{
// column header cell
return this.DataGridView.ColumnHeadersVisible && this.OwningColumn.Displayed;
}
// top left header cell
Debug.Assert(!this.DataGridView.LayoutInfo.dirty);
return this.DataGridView.LayoutInfo.TopLeftHeader != Rectangle.Empty;
}
}
internal Bitmap FlipXPThemesBitmap
{
get
{
return (Bitmap)this.Properties.GetObject(PropFlipXPThemesBitmap);
}
set
{
if (value != null || this.Properties.ContainsObject(PropFlipXPThemesBitmap))
{
this.Properties.SetObject(PropFlipXPThemesBitmap, value);
}
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.FormattedValueType"]/*' />
public override Type FormattedValueType
{
get
{
return defaultFormattedValueType;
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.Frozen"]/*' />
[
Browsable(false)
]
public override bool Frozen
{
get
{
if (this.OwningRow != null)
{
// row header cell
return this.OwningRow.Frozen;
}
if (this.OwningColumn != null)
{
// column header cell
return this.OwningColumn.Frozen;
}
if (this.DataGridView != null)
{
// top left header cell
return true;
}
// detached header cell
return false;
}
}
internal override bool HasValueType
{
get
{
return this.Properties.ContainsObject(PropValueType) && this.Properties.GetObject(PropValueType) != null;
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.ReadOnly"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override bool ReadOnly
{
get
{
return true;
}
set
{
throw new InvalidOperationException(SR.GetString(SR.DataGridView_HeaderCellReadOnlyProperty, "ReadOnly"));
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.Resizable"]/*' />
[
Browsable(false)
]
public override bool Resizable
{
get
{
if (this.OwningRow != null)
{
// must be a row header cell
return (this.OwningRow.Resizable == DataGridViewTriState.True) || (this.DataGridView != null && this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing);
}
if (this.OwningColumn != null)
{
// must be a column header cell
return (this.OwningColumn.Resizable == DataGridViewTriState.True) ||
(this.DataGridView != null && this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing);
}
// must be the top left header cell
return this.DataGridView != null && (this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing);
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.Selected"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override bool Selected
{
get
{
return false;
}
set
{
throw new InvalidOperationException(SR.GetString(SR.DataGridView_HeaderCellReadOnlyProperty, "Selected"));
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.ValueType"]/*' />
public override Type ValueType
{
get
{
Type valueType = (Type) this.Properties.GetObject(PropValueType);
if (valueType != null)
{
return valueType;
}
return defaultValueType;
}
set
{
if (value != null || this.Properties.ContainsObject(PropValueType))
{
this.Properties.SetObject(PropValueType, value);
}
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.Visible"]/*' />
[
Browsable(false)
]
public override bool Visible
{
get
{
if (this.OwningRow != null)
{
// row header cell
return this.OwningRow.Visible &&
(this.DataGridView == null || this.DataGridView.RowHeadersVisible);
}
if (this.OwningColumn != null)
{
// column header cell
return this.OwningColumn.Visible &&
(this.DataGridView == null || this.DataGridView.ColumnHeadersVisible);
}
if (this.DataGridView != null)
{
// top left header cell
return this.DataGridView.RowHeadersVisible && this.DataGridView.ColumnHeadersVisible;
}
return false;
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.Clone"]/*' />
public override object Clone()
{
DataGridViewHeaderCell dataGridViewCell;
Type thisType = this.GetType();
if (thisType == cellType) //performance improvement
{
dataGridViewCell = new DataGridViewHeaderCell();
}
else
{
// SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info..
//
dataGridViewCell = (DataGridViewHeaderCell)System.Activator.CreateInstance(thisType);
}
base.CloneInternal(dataGridViewCell);
dataGridViewCell.Value = this.Value;
return dataGridViewCell;
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.GetInheritedContextMenuStrip"]/*' />
public override ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex)
{
ContextMenuStrip contextMenuStrip = GetContextMenuStrip(rowIndex);
if (contextMenuStrip != null)
{
return contextMenuStrip;
}
if (this.DataGridView != null)
{
return this.DataGridView.ContextMenuStrip;
}
else
{
return null;
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.GetInheritedState"]/*' />
public override DataGridViewElementStates GetInheritedState(int rowIndex)
{
DataGridViewElementStates state = DataGridViewElementStates.ResizableSet | DataGridViewElementStates.ReadOnly;
if (this.OwningRow != null)
{
// row header cell
if ((this.DataGridView == null && rowIndex != -1) ||
(this.DataGridView != null && (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count)))
{
throw new ArgumentException(SR.GetString(SR.InvalidArgument, "rowIndex", rowIndex.ToString(CultureInfo.CurrentCulture)));
}
if (this.DataGridView != null && this.DataGridView.Rows.SharedRow(rowIndex) != this.OwningRow)
{
throw new ArgumentException(SR.GetString(SR.InvalidArgument, "rowIndex", rowIndex.ToString(CultureInfo.CurrentCulture)));
}
state |= (this.OwningRow.GetState(rowIndex) & DataGridViewElementStates.Frozen);
if (this.OwningRow.GetResizable(rowIndex) == DataGridViewTriState.True || (this.DataGridView != null && this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing))
{
state |= DataGridViewElementStates.Resizable;
}
if (this.OwningRow.GetVisible(rowIndex) && (this.DataGridView == null || this.DataGridView.RowHeadersVisible))
{
state |= DataGridViewElementStates.Visible;
if (this.OwningRow.GetDisplayed(rowIndex))
{
state |= DataGridViewElementStates.Displayed;
}
}
}
else if (this.OwningColumn != null)
{
// column header cell
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
state |= (this.OwningColumn.State & DataGridViewElementStates.Frozen);
if (this.OwningColumn.Resizable == DataGridViewTriState.True ||
(this.DataGridView != null && this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing))
{
state |= DataGridViewElementStates.Resizable;
}
if (this.OwningColumn.Visible && (this.DataGridView == null || this.DataGridView.ColumnHeadersVisible))
{
state |= DataGridViewElementStates.Visible;
if (this.OwningColumn.Displayed)
{
state |= DataGridViewElementStates.Displayed;
}
}
}
else if (this.DataGridView != null)
{
// top left header cell
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
state |= DataGridViewElementStates.Frozen;
if (this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing)
{
state |= DataGridViewElementStates.Resizable;
}
if (this.DataGridView.RowHeadersVisible && this.DataGridView.ColumnHeadersVisible)
{
state |= DataGridViewElementStates.Visible;
if (this.DataGridView.LayoutInfo.TopLeftHeader != Rectangle.Empty)
{
state |= DataGridViewElementStates.Displayed;
}
}
}
#if DEBUG
if (this.OwningRow == null || this.OwningRow.Index != -1)
{
DataGridViewElementStates stateDebug = DataGridViewElementStates.ResizableSet;
if (this.Displayed)
{
stateDebug |= DataGridViewElementStates.Displayed;
}
if (this.Frozen)
{
stateDebug |= DataGridViewElementStates.Frozen;
}
if (this.ReadOnly)
{
stateDebug |= DataGridViewElementStates.ReadOnly;
}
if (this.Resizable)
{
stateDebug |= DataGridViewElementStates.Resizable;
}
if (this.Selected)
{
stateDebug |= DataGridViewElementStates.Selected;
}
if (this.Visible)
{
stateDebug |= DataGridViewElementStates.Visible;
}
Debug.Assert(state == stateDebug);
}
#endif
return state;
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.GetSize"]/*' />
protected override Size GetSize(int rowIndex)
{
if (this.DataGridView == null)
{
// detached cell
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
return new Size(-1, -1);
}
if (this.OwningColumn != null)
{
// must be a column header cell
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
return new Size(this.OwningColumn.Thickness, this.DataGridView.ColumnHeadersHeight);
}
else if (this.OwningRow != null)
{
// must be a row header cell
if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
if (this.DataGridView.Rows.SharedRow(rowIndex) != this.OwningRow)
{
throw new ArgumentException(SR.GetString(SR.InvalidArgument, "rowIndex", rowIndex.ToString(CultureInfo.CurrentCulture)));
}
return new Size(this.DataGridView.RowHeadersWidth, this.OwningRow.GetHeight(rowIndex));
}
else
{
// must be the top left header cell
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
return new Size(this.DataGridView.RowHeadersWidth, this.DataGridView.ColumnHeadersHeight);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static Rectangle GetThemeMargins(Graphics g)
{
if (rectThemeMargins.X == -1)
{
Rectangle rectCell = new Rectangle(0, 0, DATAGRIDVIEWHEADERCELL_themeMargin, DATAGRIDVIEWHEADERCELL_themeMargin);
Rectangle rectContent = DataGridViewHeaderCellRenderer.VisualStyleRenderer.GetBackgroundContentRectangle(g, rectCell);
rectThemeMargins.X = rectContent.X;
rectThemeMargins.Y = rectContent.Y;
rectThemeMargins.Width = DATAGRIDVIEWHEADERCELL_themeMargin - rectContent.Right;
rectThemeMargins.Height = DATAGRIDVIEWHEADERCELL_themeMargin - rectContent.Bottom;
// On WinXP, the theming margins for a header are unexpectedly (3, 0, 0, 0) when you'd expect something like (0, 0, 2, 3)
if (rectThemeMargins.X == 3 &&
rectThemeMargins.Y + rectThemeMargins.Width + rectThemeMargins.Height == 0)
{
rectThemeMargins = new Rectangle(0, 0, 2, 3);
}
else
{
// On Vista, the theming margins for a header are unexpectedly (0, 0, 0, 0) when you'd expect something like (2, 1, 0, 2)
// Padding themePadding = DataGridViewHeaderCellRenderer.VisualStyleRenderer.GetMargins(g, MarginProperty.ContentMargins); /* or MarginProperty.SizingMargins */
// does not work either at this time. It AVs -So we hard code the margins for now.
try
{
string themeFilename = System.IO.Path.GetFileName(System.Windows.Forms.VisualStyles.VisualStyleInformation.ThemeFilename);
if (String.Equals(themeFilename, AEROTHEMEFILENAME, StringComparison.OrdinalIgnoreCase))
{
rectThemeMargins = new Rectangle(2, 1, 0, 2);
}
}
catch
{
}
}
}
return rectThemeMargins;
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.GetValue"]/*' />
protected override object GetValue(int rowIndex)
{
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
return this.Properties.GetObject(PropCellValue);
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.MouseDownUnsharesRow"]/*' />
protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return e.Button == MouseButtons.Left && this.DataGridView.ApplyVisualStylesToHeaderCells;
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.MouseEnterUnsharesRow"]/*' />
protected override bool MouseEnterUnsharesRow(int rowIndex)
{
return this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X &&
rowIndex == this.DataGridView.MouseDownCellAddress.Y &&
this.DataGridView.ApplyVisualStylesToHeaderCells;
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.MouseLeaveUnsharesRow"]/*' />
protected override bool MouseLeaveUnsharesRow(int rowIndex)
{
return this.ButtonState != ButtonState.Normal && this.DataGridView.ApplyVisualStylesToHeaderCells;
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.MouseUpUnsharesRow"]/*' />
protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return e.Button == MouseButtons.Left && this.DataGridView.ApplyVisualStylesToHeaderCells;
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.OnMouseDown"]/*' />
protected override void OnMouseDown(DataGridViewCellMouseEventArgs e)
{
if (this.DataGridView == null)
{
return;
}
if (e.Button == MouseButtons.Left &&
this.DataGridView.ApplyVisualStylesToHeaderCells &&
!this.DataGridView.ResizingOperationAboutToStart)
{
UpdateButtonState(ButtonState.Pushed, e.RowIndex);
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.OnMouseEnter"]/*' />
protected override void OnMouseEnter(int rowIndex)
{
if (this.DataGridView == null)
{
return;
}
if (this.DataGridView.ApplyVisualStylesToHeaderCells)
{
if (this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X &&
rowIndex == this.DataGridView.MouseDownCellAddress.Y &&
this.ButtonState == ButtonState.Normal &&
Control.MouseButtons == MouseButtons.Left &&
!this.DataGridView.ResizingOperationAboutToStart)
{
UpdateButtonState(ButtonState.Pushed, rowIndex);
}
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.OnMouseLeave"]/*' />
protected override void OnMouseLeave(int rowIndex)
{
if (this.DataGridView == null)
{
return;
}
if (this.DataGridView.ApplyVisualStylesToHeaderCells)
{
if (this.ButtonState != ButtonState.Normal)
{
Debug.Assert(this.ButtonState == ButtonState.Pushed);
Debug.Assert(this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X);
Debug.Assert(rowIndex == this.DataGridView.MouseDownCellAddress.Y);
UpdateButtonState(ButtonState.Normal, rowIndex);
}
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.OnMouseUp"]/*' />
protected override void OnMouseUp(DataGridViewCellMouseEventArgs e)
{
if (this.DataGridView == null)
{
return;
}
if (e.Button == MouseButtons.Left && this.DataGridView.ApplyVisualStylesToHeaderCells)
{
UpdateButtonState(ButtonState.Normal, e.RowIndex);
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.Paint"]/*' />
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates dataGridViewElementState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
if (DataGridViewCell.PaintBorder(paintParts))
{
PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
}
if (DataGridViewCell.PaintBackground(paintParts))
{
Rectangle valBounds = cellBounds;
Rectangle borderWidths = BorderWidths(advancedBorderStyle);
valBounds.Offset(borderWidths.X, borderWidths.Y);
valBounds.Width -= borderWidths.Right;
valBounds.Height -= borderWidths.Bottom;
bool cellSelected = (dataGridViewElementState & DataGridViewElementStates.Selected) != 0;
SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor);
if (br.Color.A == 255)
{
graphics.FillRectangle(br, valBounds);
}
}
}
/// <include file='doc\DataGridViewHeaderCell.uex' path='docs/doc[@for="DataGridViewHeaderCell.ToString"]/*' />
/// <devdoc>
/// <para>
/// Gets the row Index and column Index of the cell.
/// </para>
/// </devdoc>
public override string ToString()
{
return "DataGridViewHeaderCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }";
}
private void UpdateButtonState(ButtonState newButtonState, int rowIndex)
{
Debug.Assert(this.DataGridView != null);
this.ButtonStatePrivate = newButtonState;
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
}
private class DataGridViewHeaderCellRenderer
{
private static VisualStyleRenderer visualStyleRenderer;
private DataGridViewHeaderCellRenderer()
{
}
public static VisualStyleRenderer VisualStyleRenderer
{
get
{
if (visualStyleRenderer == null)
{
visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.Header.Item.Normal);
}
return visualStyleRenderer;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using GLTF.Math;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using GLTF.Schema;
namespace GLTF.Extensions
{
public static class JsonReaderExtensions
{
public static List<string> ReadStringList(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<string>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(reader.Value.ToString());
}
return list;
}
public static List<double> ReadDoubleList(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<double>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(double.Parse(reader.Value.ToString()));
}
return list;
}
public static List<int> ReadInt32List(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<int>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(int.Parse(reader.Value.ToString()));
}
return list;
}
public static List<T> ReadList<T>(this JsonReader reader, Func<T> deserializerFunc)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<T>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(deserializerFunc());
// deserializerFunc can advance to EndArray. We need to check for this case as well.
if (reader.TokenType == JsonToken.EndArray)
{
break;
}
}
return list;
}
public static TextureInfo DeserializeAsTexture(this JToken token, GLTFRoot root)
{
TextureInfo textureInfo = null;
if (token != null)
{
JObject textureObject = token as JObject;
if (textureObject == null)
{
throw new Exception("JToken used for Texture deserialization was not a JObject. It was a " + token.Type.ToString());
}
#if DEBUG
// Broken on il2cpp. Don't ship debug DLLs there.
System.Diagnostics.Debug.WriteLine("textureObject is " + textureObject.Type + " with a value of: " + textureObject[TextureInfo.INDEX].Type + " " + textureObject.ToString());
#endif
int indexVal = textureObject[TextureInfo.INDEX].DeserializeAsInt();
textureInfo = new TextureInfo()
{
Index = new TextureId()
{
Id = indexVal,
Root = root
}
};
}
return textureInfo;
}
public static int DeserializeAsInt(this JToken token)
{
if (token != null)
{
JValue intValue = token as JValue;
if (intValue == null)
{
throw new Exception("JToken used for int deserialization was not a JValue. It was a " + token.Type.ToString());
}
return (int)intValue;
}
return 0;
}
public static double DeserializeAsDouble(this JToken token)
{
if (token != null)
{
JValue doubleValue = token as JValue;
if (doubleValue == null)
{
throw new Exception("JToken used for double deserialization was not a JValue. It was a " + token.Type.ToString());
}
return (double)doubleValue;
}
return 0d;
}
public static Color ReadAsRGBAColor(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
}
var color = new Color
{
R = (float) reader.ReadAsDouble().Value,
G = (float) reader.ReadAsDouble().Value,
B = (float) reader.ReadAsDouble().Value,
A = (float) reader.ReadAsDouble().Value
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
}
return color;
}
public static Color DeserializeAsColor(this JToken token)
{
Color color = Color.White;
if (token != null)
{
JArray colorArray = token as JArray;
if (colorArray == null)
{
throw new Exception("JToken used for Color deserialization was not a JArray. It was a " + token.Type.ToString());
}
if (colorArray.Count != 4)
{
throw new Exception("JArray used for Color deserialization did not have 4 entries for RGBA. It had " + colorArray.Count);
}
color = new Color
{
R = (float)colorArray[0].DeserializeAsDouble(),
G = (float)colorArray[1].DeserializeAsDouble(),
B = (float)colorArray[2].DeserializeAsDouble(),
A = (float)colorArray[3].DeserializeAsDouble()
};
}
return color;
}
public static Color ReadAsRGBColor(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
var color = new Color
{
R = (float) reader.ReadAsDouble().Value,
G = (float) reader.ReadAsDouble().Value,
B = (float) reader.ReadAsDouble().Value,
A = 1.0f
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
}
return color;
}
public static Vector3 ReadAsVector3(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
var vector = new Vector3
{
X = (float) reader.ReadAsDouble().Value,
Y = (float) reader.ReadAsDouble().Value,
Z = (float) reader.ReadAsDouble().Value
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
return vector;
}
public static Vector2 DeserializeAsVector2(this JToken token)
{
Vector2 vector = new Vector2();
if (token != null)
{
JArray vectorArray = token as JArray;
if (vectorArray == null)
{
throw new Exception("JToken used for Vector2 deserialization was not a JArray. It was a " + token.Type.ToString());
}
if (vectorArray.Count != 2)
{
throw new Exception("JArray used for Vector2 deserialization did not have 2 entries for XY. It had " + vectorArray.Count);
}
vector = new Vector2
{
X = (float)vectorArray[0].DeserializeAsDouble(),
Y = (float)vectorArray[1].DeserializeAsDouble()
};
}
return vector;
}
public static Vector3 DeserializeAsVector3(this JToken token)
{
Vector3 vector = new Vector3();
if (token != null)
{
JArray vectorArray = token as JArray;
if (vectorArray == null)
{
throw new Exception("JToken used for Vector3 deserialization was not a JArray. It was a " + token.Type.ToString());
}
if (vectorArray.Count != 3)
{
throw new Exception("JArray used for Vector3 deserialization did not have 3 entries for XYZ. It had " + vectorArray.Count);
}
vector = new Vector3
{
X = (float)vectorArray[0].DeserializeAsDouble(),
Y = (float)vectorArray[1].DeserializeAsDouble(),
Z = (float)vectorArray[2].DeserializeAsDouble()
};
}
return vector;
}
public static Quaternion ReadAsQuaternion(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
var quat = new Quaternion
{
X = (float) reader.ReadAsDouble().Value,
Y = (float) reader.ReadAsDouble().Value,
Z = (float) reader.ReadAsDouble().Value,
W = (float) reader.ReadAsDouble().Value
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
return quat;
}
public static Dictionary<string, T> ReadAsDictionary<T>(this JsonReader reader, Func<T> deserializerFunc, bool skipStartObjectRead = false)
{
if (!skipStartObjectRead && reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception(string.Format("Dictionary must be an object at: {0}.", reader.Path));
}
var dict = new Dictionary<string, T>();
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
dict.Add(reader.Value.ToString(), deserializerFunc());
}
return dict;
}
public static Dictionary<string, object> ReadAsObjectDictionary(this JsonReader reader, bool skipStartObjectRead = false)
{
if (!skipStartObjectRead && reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception(string.Format("Dictionary must be an object at: {0}", reader.Path));
}
var dict = new Dictionary<string, object>();
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
dict.Add(reader.Value.ToString(), ReadDictionaryValue(reader));
}
return dict;
}
private static object ReadDictionaryValue(JsonReader reader)
{
if (!reader.Read())
{
return null;
}
switch (reader.TokenType)
{
case JsonToken.StartArray:
return reader.ReadObjectList();
case JsonToken.StartObject:
return reader.ReadAsObjectDictionary(true);
default:
return reader.Value;
}
}
private static List<object> ReadObjectList(this JsonReader reader)
{
var list = new List<object>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(reader.Value);
}
return list;
}
public static T ReadStringEnum<T>(this JsonReader reader)
{
return (T) Enum.Parse(typeof(T), reader.ReadAsString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
namespace System.Data.ProviderBase
{
internal sealed class SchemaMapping
{
// DataColumns match in length and name order as the DataReader, no chapters
private const int MapExactMatch = 0;
// DataColumns has different length, but correct name order as the DataReader, no chapters
private const int MapDifferentSize = 1;
// DataColumns may have different length, but a differant name ordering as the DataReader, no chapters
private const int MapReorderedValues = 2;
// DataColumns may have different length, but correct name order as the DataReader, with chapters
private const int MapChapters = 3;
// DataColumns may have different length, but a differant name ordering as the DataReader, with chapters
private const int MapChaptersReordered = 4;
// map xml string data to DataColumn with DataType=typeof(SqlXml)
private const int SqlXml = 1;
// map xml string data to DataColumn with DataType=typeof(XmlDocument)
private const int XmlDocument = 2;
private readonly DataSet _dataSet; // the current dataset, may be null if we are only filling a DataTable
private DataTable _dataTable; // the current DataTable, should never be null
private readonly DataAdapter _adapter;
private readonly DataReaderContainer _dataReader;
private readonly DataTable _schemaTable; // will be null if Fill without schema
private readonly DataTableMapping _tableMapping;
// unique (generated) names based from DataReader.GetName(i)
private readonly string[] _fieldNames;
private readonly object[] _readerDataValues;
private object[] _mappedDataValues; // array passed to dataRow.AddUpdate(), if needed
private int[] _indexMap; // index map that maps dataValues -> _mappedDataValues, if needed
private bool[] _chapterMap; // which DataReader indexes have chapters
private int[] _xmlMap; // map which value in _readerDataValues to convert to a Xml datatype, (SqlXml/XmlDocument)
private int _mappedMode; // modes as described as above
private int _mappedLength;
private readonly LoadOption _loadOption;
internal SchemaMapping(DataAdapter adapter, DataSet dataset, DataTable datatable, DataReaderContainer dataReader, bool keyInfo,
SchemaType schemaType, string sourceTableName, bool gettingData,
DataColumn parentChapterColumn, object parentChapterValue)
{
Debug.Assert(null != adapter, nameof(adapter));
Debug.Assert(null != dataReader, nameof(dataReader));
Debug.Assert(0 < dataReader.FieldCount, "FieldCount");
Debug.Assert(null != dataset || null != datatable, "SchemaMapping - null dataSet");
Debug.Assert(SchemaType.Mapped == schemaType || SchemaType.Source == schemaType, "SetupSchema - invalid schemaType");
_dataSet = dataset; // setting DataSet implies chapters are supported
_dataTable = datatable; // setting only DataTable, not DataSet implies chapters are not supported
_adapter = adapter;
_dataReader = dataReader;
if (keyInfo)
{
_schemaTable = dataReader.GetSchemaTable();
}
if (adapter.ShouldSerializeFillLoadOption())
{
_loadOption = adapter.FillLoadOption;
}
else if (adapter.AcceptChangesDuringFill)
{
_loadOption = (LoadOption)4; // true
}
else
{
_loadOption = (LoadOption)5; //false
}
MissingMappingAction mappingAction;
MissingSchemaAction schemaAction;
if (SchemaType.Mapped == schemaType)
{
mappingAction = _adapter.MissingMappingAction;
schemaAction = _adapter.MissingSchemaAction;
if (!string.IsNullOrEmpty(sourceTableName))
{
_tableMapping = _adapter.GetTableMappingBySchemaAction(sourceTableName, sourceTableName, mappingAction);
}
else if (null != _dataTable)
{
int index = _adapter.IndexOfDataSetTable(_dataTable.TableName);
if (-1 != index)
{
_tableMapping = _adapter.TableMappings[index];
}
else
{
_tableMapping = mappingAction switch
{
MissingMappingAction.Passthrough => new DataTableMapping(_dataTable.TableName, _dataTable.TableName),
MissingMappingAction.Ignore => null,
MissingMappingAction.Error => throw ADP.MissingTableMappingDestination(_dataTable.TableName),
_ => throw ADP.InvalidMissingMappingAction(mappingAction),
};
}
}
}
else if (SchemaType.Source == schemaType)
{
mappingAction = System.Data.MissingMappingAction.Passthrough;
schemaAction = Data.MissingSchemaAction.Add;
if (!string.IsNullOrEmpty(sourceTableName))
{
_tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(null, sourceTableName, sourceTableName, mappingAction);
}
else if (null != _dataTable)
{
int index = _adapter.IndexOfDataSetTable(_dataTable.TableName);
if (-1 != index)
{
_tableMapping = _adapter.TableMappings[index];
}
else
{
_tableMapping = new DataTableMapping(_dataTable.TableName, _dataTable.TableName);
}
}
}
else
{
throw ADP.InvalidSchemaType(schemaType);
}
if (null != _tableMapping)
{
if (null == _dataTable)
{
_dataTable = _tableMapping.GetDataTableBySchemaAction(_dataSet, schemaAction);
}
if (null != _dataTable)
{
_fieldNames = GenerateFieldNames(dataReader);
if (null == _schemaTable)
{
_readerDataValues = SetupSchemaWithoutKeyInfo(mappingAction, schemaAction, gettingData, parentChapterColumn, parentChapterValue);
}
else
{
_readerDataValues = SetupSchemaWithKeyInfo(mappingAction, schemaAction, gettingData, parentChapterColumn, parentChapterValue);
}
}
// else (null == _dataTable) which means ignore (mapped to nothing)
}
}
internal DataReaderContainer DataReader
{
get
{
return _dataReader;
}
}
internal DataTable DataTable
{
get
{
return _dataTable;
}
}
internal object[] DataValues
{
get
{
return _readerDataValues;
}
}
internal void ApplyToDataRow(DataRow dataRow)
{
DataColumnCollection columns = dataRow.Table.Columns;
_dataReader.GetValues(_readerDataValues);
object[] mapped = GetMappedValues();
bool[] readOnly = new bool[mapped.Length];
for (int i = 0; i < readOnly.Length; ++i)
{
readOnly[i] = columns[i].ReadOnly;
}
try
{
try
{
// allow all columns to be written to
for (int i = 0; i < readOnly.Length; ++i)
{
if (0 == columns[i].Expression.Length)
{
columns[i].ReadOnly = false;
}
}
for (int i = 0; i < mapped.Length; ++i)
{
if (null != mapped[i])
{
dataRow[i] = mapped[i];
}
}
}
finally
{
// ReadOnly
// reset readonly flag on all columns
for (int i = 0; i < readOnly.Length; ++i)
{
if (0 == columns[i].Expression.Length)
{
columns[i].ReadOnly = readOnly[i];
}
}
}
}
finally
{ // FreeDataRowChapters
if (null != _chapterMap)
{
FreeDataRowChapters();
}
}
}
private void MappedChapterIndex()
{ // mode 4
int length = _mappedLength;
for (int i = 0; i < length; i++)
{
int k = _indexMap[i];
if (0 <= k)
{
_mappedDataValues[k] = _readerDataValues[i]; // from reader to dataset
if (_chapterMap[i])
{
_mappedDataValues[k] = null; // InvalidCast from DataReader to AutoIncrement DataColumn
}
}
}
}
private void MappedChapter()
{ // mode 3
int length = _mappedLength;
for (int i = 0; i < length; i++)
{
_mappedDataValues[i] = _readerDataValues[i]; // from reader to dataset
if (_chapterMap[i])
{
_mappedDataValues[i] = null; // InvalidCast from DataReader to AutoIncrement DataColumn
}
}
}
private void MappedIndex()
{ // mode 2
Debug.Assert(_mappedLength == _indexMap.Length, "incorrect precomputed length");
int length = _mappedLength;
for (int i = 0; i < length; i++)
{
int k = _indexMap[i];
if (0 <= k)
{
_mappedDataValues[k] = _readerDataValues[i]; // from reader to dataset
}
}
}
private void MappedValues()
{ // mode 1
Debug.Assert(_mappedLength == Math.Min(_readerDataValues.Length, _mappedDataValues.Length), "incorrect precomputed length");
int length = _mappedLength;
for (int i = 0; i < length; ++i)
{
_mappedDataValues[i] = _readerDataValues[i]; // from reader to dataset
};
}
private object[] GetMappedValues()
{ // mode 0
if (null != _xmlMap)
{
for (int i = 0; i < _xmlMap.Length; ++i)
{
if (0 != _xmlMap[i])
{
// get the string/SqlString xml value
string xml = _readerDataValues[i] as string;
if ((null == xml) && (_readerDataValues[i] is System.Data.SqlTypes.SqlString))
{
System.Data.SqlTypes.SqlString x = (System.Data.SqlTypes.SqlString)_readerDataValues[i];
if (!x.IsNull)
{
xml = x.Value;
}
else
{
_readerDataValues[i] = _xmlMap[i] switch
{
// map strongly typed SqlString.Null to SqlXml.Null
SqlXml => System.Data.SqlTypes.SqlXml.Null,
_ => DBNull.Value,
};
}
}
if (null != xml)
{
switch (_xmlMap[i])
{
case SqlXml: // turn string into a SqlXml value for DataColumn
System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(xml), settings, (string)null);
_readerDataValues[i] = new System.Data.SqlTypes.SqlXml(reader);
break;
case XmlDocument: // turn string into XmlDocument value for DataColumn
System.Xml.XmlDocument document = new System.Xml.XmlDocument();
document.LoadXml(xml);
_readerDataValues[i] = document;
break;
}
// default: let value fallthrough to DataSet which may fail with ArgumentException
}
}
}
}
switch (_mappedMode)
{
default:
case MapExactMatch:
Debug.Assert(0 == _mappedMode, "incorrect mappedMode");
Debug.Assert((null == _chapterMap) && (null == _indexMap) && (null == _mappedDataValues), "incorrect MappedValues");
return _readerDataValues; // from reader to dataset
case MapDifferentSize:
Debug.Assert((null == _chapterMap) && (null == _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
MappedValues();
break;
case MapReorderedValues:
Debug.Assert((null == _chapterMap) && (null != _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
MappedIndex();
break;
case MapChapters:
Debug.Assert((null != _chapterMap) && (null == _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
MappedChapter();
break;
case MapChaptersReordered:
Debug.Assert((null != _chapterMap) && (null != _indexMap) && (null != _mappedDataValues), "incorrect MappedValues");
MappedChapterIndex();
break;
}
return _mappedDataValues;
}
internal void LoadDataRowWithClear()
{
// for FillErrorEvent to ensure no values leftover from previous row
for (int i = 0; i < _readerDataValues.Length; ++i)
{
_readerDataValues[i] = null;
}
LoadDataRow();
}
internal void LoadDataRow()
{
try
{
_dataReader.GetValues(_readerDataValues);
object[] mapped = GetMappedValues();
DataRow dataRow;
switch (_loadOption)
{
case LoadOption.OverwriteChanges:
case LoadOption.PreserveChanges:
case LoadOption.Upsert:
dataRow = _dataTable.LoadDataRow(mapped, _loadOption);
break;
case (LoadOption)4: // true
dataRow = _dataTable.LoadDataRow(mapped, true);
break;
case (LoadOption)5: // false
dataRow = _dataTable.LoadDataRow(mapped, false);
break;
default:
Debug.Fail("unexpected LoadOption");
throw ADP.InvalidLoadOption(_loadOption);
}
if ((null != _chapterMap) && (null != _dataSet))
{
LoadDataRowChapters(dataRow);
}
}
finally
{
if (null != _chapterMap)
{
FreeDataRowChapters();
}
}
}
private void FreeDataRowChapters()
{
for (int i = 0; i < _chapterMap.Length; ++i)
{
if (_chapterMap[i])
{
IDisposable disposable = (_readerDataValues[i] as IDisposable);
if (null != disposable)
{
_readerDataValues[i] = null;
disposable.Dispose();
}
}
}
}
internal int LoadDataRowChapters(DataRow dataRow)
{
int datarowadded = 0;
int rowLength = _chapterMap.Length;
for (int i = 0; i < rowLength; ++i)
{
if (_chapterMap[i])
{
object readerValue = _readerDataValues[i];
if ((null != readerValue) && !Convert.IsDBNull(readerValue))
{
_readerDataValues[i] = null;
using (IDataReader nestedReader = (IDataReader)readerValue)
{
if (!nestedReader.IsClosed)
{
Debug.Assert(null != _dataSet, "if chapters, then Fill(DataSet,...) not Fill(DataTable,...)");
object parentChapterValue;
DataColumn parentChapterColumn;
if (null == _indexMap)
{
parentChapterColumn = _dataTable.Columns[i];
parentChapterValue = dataRow[parentChapterColumn];
}
else
{
parentChapterColumn = _dataTable.Columns[_indexMap[i]];
parentChapterValue = dataRow[parentChapterColumn];
}
// correct on Fill, not FillFromReader
string chapterTableName = _tableMapping.SourceTable + _fieldNames[i];
DataReaderContainer readerHandler = DataReaderContainer.Create(nestedReader, _dataReader.ReturnProviderSpecificTypes);
datarowadded += _adapter.FillFromReader(_dataSet, null, chapterTableName, readerHandler, 0, 0, parentChapterColumn, parentChapterValue);
}
}
}
}
}
return datarowadded;
}
private int[] CreateIndexMap(int count, int index)
{
int[] values = new int[count];
for (int i = 0; i < index; ++i)
{
values[i] = i;
}
return values;
}
private static string[] GenerateFieldNames(DataReaderContainer dataReader)
{
string[] fieldNames = new string[dataReader.FieldCount];
for (int i = 0; i < fieldNames.Length; ++i)
{
fieldNames[i] = dataReader.GetName(i);
}
ADP.BuildSchemaTableInfoTableNames(fieldNames);
return fieldNames;
}
private DataColumn[] ResizeColumnArray(DataColumn[] rgcol, int len)
{
Debug.Assert(rgcol != null, "invalid call to ResizeArray");
Debug.Assert(len <= rgcol.Length, "invalid len passed to ResizeArray");
var tmp = new DataColumn[len];
Array.Copy(rgcol, 0, tmp, 0, len);
return tmp;
}
private void AddItemToAllowRollback(ref List<object> items, object value)
{
if (null == items)
{
items = new List<object>();
}
items.Add(value);
}
private void RollbackAddedItems(List<object> items)
{
if (null != items)
{
for (int i = items.Count - 1; 0 <= i; --i)
{
// remove columns that were added now that we are failing
if (null != items[i])
{
DataColumn column = (items[i] as DataColumn);
if (null != column)
{
if (null != column.Table)
{
column.Table.Columns.Remove(column);
}
}
else
{
DataTable table = (items[i] as DataTable);
if (null != table)
{
if (null != table.DataSet)
{
table.DataSet.Tables.Remove(table);
}
}
}
}
}
}
}
private object[] SetupSchemaWithoutKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn parentChapterColumn, object chapterValue)
{
int[] columnIndexMap = null;
bool[] chapterIndexMap = null;
int mappingCount = 0;
int count = _dataReader.FieldCount;
object[] dataValues = null;
List<object> addedItems = null;
try
{
DataColumnCollection columnCollection = _dataTable.Columns;
columnCollection.EnsureAdditionalCapacity(count + (chapterValue != null ? 1 : 0));
// We can always just create column if there are no existing column or column mappings, and the mapping action is passthrough
bool alwaysCreateColumns = ((_dataTable.Columns.Count == 0) && ((_tableMapping.ColumnMappings == null) || (_tableMapping.ColumnMappings.Count == 0)) && (mappingAction == MissingMappingAction.Passthrough));
for (int i = 0; i < count; ++i)
{
bool ischapter = false;
Type fieldType = _dataReader.GetFieldType(i);
if (null == fieldType)
{
throw ADP.MissingDataReaderFieldType(i);
}
// if IDataReader, hierarchy exists and we will use an Int32,AutoIncrementColumn in this table
if (typeof(IDataReader).IsAssignableFrom(fieldType))
{
if (null == chapterIndexMap)
{
chapterIndexMap = new bool[count];
}
chapterIndexMap[i] = ischapter = true;
fieldType = typeof(int);
}
else if (typeof(System.Data.SqlTypes.SqlXml).IsAssignableFrom(fieldType))
{
if (null == _xmlMap)
{ // map to DataColumn with DataType=typeof(SqlXml)
_xmlMap = new int[count];
}
_xmlMap[i] = SqlXml; // track its xml data
}
else if (typeof(System.Xml.XmlReader).IsAssignableFrom(fieldType))
{
fieldType = typeof(string); // map to DataColumn with DataType=typeof(string)
if (null == _xmlMap)
{
_xmlMap = new int[count];
}
_xmlMap[i] = XmlDocument; // track its xml data
}
DataColumn dataColumn;
if (alwaysCreateColumns)
{
dataColumn = DataColumnMapping.CreateDataColumnBySchemaAction(_fieldNames[i], _fieldNames[i], _dataTable, fieldType, schemaAction);
}
else
{
dataColumn = _tableMapping.GetDataColumn(_fieldNames[i], fieldType, _dataTable, mappingAction, schemaAction);
}
if (null == dataColumn)
{
if (null == columnIndexMap)
{
columnIndexMap = CreateIndexMap(count, i);
}
columnIndexMap[i] = -1;
continue; // null means ignore (mapped to nothing)
}
else if ((null != _xmlMap) && (0 != _xmlMap[i]))
{
if (typeof(System.Data.SqlTypes.SqlXml) == dataColumn.DataType)
{
_xmlMap[i] = SqlXml;
}
else if (typeof(System.Xml.XmlDocument) == dataColumn.DataType)
{
_xmlMap[i] = XmlDocument;
}
else
{
_xmlMap[i] = 0; // datacolumn is not a specific Xml dataType, i.e. string
int total = 0;
for (int x = 0; x < _xmlMap.Length; ++x)
{
total += _xmlMap[x];
}
if (0 == total)
{ // not mapping to a specific Xml datatype, get rid of the map
_xmlMap = null;
}
}
}
if (null == dataColumn.Table)
{
if (ischapter)
{
dataColumn.AllowDBNull = false;
dataColumn.AutoIncrement = true;
dataColumn.ReadOnly = true;
}
AddItemToAllowRollback(ref addedItems, dataColumn);
columnCollection.Add(dataColumn);
}
else if (ischapter && !dataColumn.AutoIncrement)
{
throw ADP.FillChapterAutoIncrement();
}
if (null != columnIndexMap)
{
columnIndexMap[i] = dataColumn.Ordinal;
}
else if (i != dataColumn.Ordinal)
{
columnIndexMap = CreateIndexMap(count, i);
columnIndexMap[i] = dataColumn.Ordinal;
}
// else i == dataColumn.Ordinal and columnIndexMap can be optimized out
mappingCount++;
}
bool addDataRelation = false;
DataColumn chapterColumn = null;
if (null != chapterValue)
{ // add the extra column in the child table
Type fieldType = chapterValue.GetType();
chapterColumn = _tableMapping.GetDataColumn(_tableMapping.SourceTable, fieldType, _dataTable, mappingAction, schemaAction);
if (null != chapterColumn)
{
if (null == chapterColumn.Table)
{
AddItemToAllowRollback(ref addedItems, chapterColumn);
columnCollection.Add(chapterColumn);
addDataRelation = (null != parentChapterColumn);
}
mappingCount++;
}
}
if (0 < mappingCount)
{
if ((null != _dataSet) && (null == _dataTable.DataSet))
{
// Allowed to throw exception if DataTable is from wrong DataSet
AddItemToAllowRollback(ref addedItems, _dataTable);
_dataSet.Tables.Add(_dataTable);
}
if (gettingData)
{
if (null == columnCollection)
{
columnCollection = _dataTable.Columns;
}
_indexMap = columnIndexMap;
_chapterMap = chapterIndexMap;
dataValues = SetupMapping(count, columnCollection, chapterColumn, chapterValue);
}
else
{
// debug only, but for retail debug ability
_mappedMode = -1;
}
}
else
{
_dataTable = null;
}
if (addDataRelation)
{
AddRelation(parentChapterColumn, chapterColumn);
}
}
catch (Exception e) when (ADP.IsCatchableOrSecurityExceptionType(e))
{
RollbackAddedItems(addedItems);
throw;
}
return dataValues;
}
private object[] SetupSchemaWithKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn parentChapterColumn, object chapterValue)
{
// must sort rows from schema table by ordinal because Jet is sorted by coumn name
DbSchemaRow[] schemaRows = DbSchemaRow.GetSortedSchemaRows(_schemaTable, _dataReader.ReturnProviderSpecificTypes);
Debug.Assert(null != schemaRows, "SchemaSetup - null DbSchemaRow[]");
Debug.Assert(_dataReader.FieldCount <= schemaRows.Length, "unexpected fewer rows in Schema than FieldCount");
if (0 == schemaRows.Length)
{
_dataTable = null;
return null;
}
// Everett behavior, always add a primary key if a primary key didn't exist before
// Whidbey behavior, same as Everett unless using LoadOption then add primary key only if no columns previously existed
bool addPrimaryKeys = (((0 == _dataTable.PrimaryKey.Length) && ((4 <= (int)_loadOption) || (0 == _dataTable.Rows.Count)))
|| (0 == _dataTable.Columns.Count));
DataColumn[] keys = null;
int keyCount = 0;
bool isPrimary = true; // assume key info (if any) is about a primary key
string keyBaseTable = null;
string commonBaseTable = null;
bool keyFromMultiTable = false;
bool commonFromMultiTable = false;
int[] columnIndexMap = null;
bool[] chapterIndexMap = null;
int mappingCount = 0;
object[] dataValues = null;
List<object> addedItems = null;
DataColumnCollection columnCollection = _dataTable.Columns;
try
{
for (int sortedIndex = 0; sortedIndex < schemaRows.Length; ++sortedIndex)
{
DbSchemaRow schemaRow = schemaRows[sortedIndex];
int unsortedIndex = schemaRow.UnsortedIndex;
bool ischapter = false;
Type fieldType = schemaRow.DataType;
if (null == fieldType)
{
fieldType = _dataReader.GetFieldType(sortedIndex);
}
if (null == fieldType)
{
throw ADP.MissingDataReaderFieldType(sortedIndex);
}
// if IDataReader, hierarchy exists and we will use an Int32,AutoIncrementColumn in this table
if (typeof(IDataReader).IsAssignableFrom(fieldType))
{
if (null == chapterIndexMap)
{
chapterIndexMap = new bool[schemaRows.Length];
}
chapterIndexMap[unsortedIndex] = ischapter = true;
fieldType = typeof(int);
}
else if (typeof(System.Data.SqlTypes.SqlXml).IsAssignableFrom(fieldType))
{
if (null == _xmlMap)
{
_xmlMap = new int[schemaRows.Length];
}
_xmlMap[sortedIndex] = SqlXml;
}
else if (typeof(System.Xml.XmlReader).IsAssignableFrom(fieldType))
{
fieldType = typeof(string);
if (null == _xmlMap)
{
_xmlMap = new int[schemaRows.Length];
}
_xmlMap[sortedIndex] = XmlDocument;
}
DataColumn dataColumn = null;
if (!schemaRow.IsHidden)
{
dataColumn = _tableMapping.GetDataColumn(_fieldNames[sortedIndex], fieldType, _dataTable, mappingAction, schemaAction);
}
string basetable = /*schemaRow.BaseServerName+schemaRow.BaseCatalogName+schemaRow.BaseSchemaName+*/ schemaRow.BaseTableName;
if (null == dataColumn)
{
if (null == columnIndexMap)
{
columnIndexMap = CreateIndexMap(schemaRows.Length, unsortedIndex);
}
columnIndexMap[unsortedIndex] = -1;
// if the column is not mapped and it is a key, then don't add any key information
if (schemaRow.IsKey)
{
// if the hidden key comes from a different table - don't throw away the primary key
// example SELECT [T2].[ID], [T2].[ProdID], [T2].[VendorName] FROM [Vendor] AS [T2], [Prod] AS [T1] WHERE (([T1].[ProdID] = [T2].[ProdID]))
if (keyFromMultiTable || (schemaRow.BaseTableName == keyBaseTable))
{
addPrimaryKeys = false; // don't add any future keys now
keys = null; // get rid of any keys we've seen
}
}
continue; // null means ignore (mapped to nothing)
}
else if ((null != _xmlMap) && (0 != _xmlMap[sortedIndex]))
{
if (typeof(System.Data.SqlTypes.SqlXml) == dataColumn.DataType)
{
_xmlMap[sortedIndex] = SqlXml;
}
else if (typeof(System.Xml.XmlDocument) == dataColumn.DataType)
{
_xmlMap[sortedIndex] = XmlDocument;
}
else
{
_xmlMap[sortedIndex] = 0; // datacolumn is not a specific Xml dataType, i.e. string
int total = 0;
for (int x = 0; x < _xmlMap.Length; ++x)
{
total += _xmlMap[x];
}
if (0 == total)
{ // not mapping to a specific Xml datatype, get rid of the map
_xmlMap = null;
}
}
}
if (schemaRow.IsKey)
{
if (basetable != keyBaseTable)
{
if (null == keyBaseTable)
{
keyBaseTable = basetable;
}
else keyFromMultiTable = true;
}
}
if (ischapter)
{
if (null == dataColumn.Table)
{
dataColumn.AllowDBNull = false;
dataColumn.AutoIncrement = true;
dataColumn.ReadOnly = true;
}
else if (!dataColumn.AutoIncrement)
{
throw ADP.FillChapterAutoIncrement();
}
}
else
{
if (!commonFromMultiTable)
{
if ((basetable != commonBaseTable) && (!string.IsNullOrEmpty(basetable)))
{
if (null == commonBaseTable)
{
commonBaseTable = basetable;
}
else
{
commonFromMultiTable = true;
}
}
}
if (4 <= (int)_loadOption)
{
if (schemaRow.IsAutoIncrement && DataColumn.IsAutoIncrementType(fieldType))
{
// CONSIDER: use T-SQL "IDENT_INCR('table_or_view')" and "IDENT_SEED('table_or_view')"
// functions to obtain the actual increment and seed values
dataColumn.AutoIncrement = true;
if (!schemaRow.AllowDBNull)
{
dataColumn.AllowDBNull = false;
}
}
// setup maxLength, only for string columns since this is all the DataSet supports
if (fieldType == typeof(string))
{
// schemaRow.Size is count of characters for string columns, count of bytes otherwise
dataColumn.MaxLength = schemaRow.Size > 0 ? schemaRow.Size : -1;
}
if (schemaRow.IsReadOnly)
{
dataColumn.ReadOnly = true;
}
if (!schemaRow.AllowDBNull && (!schemaRow.IsReadOnly || schemaRow.IsKey))
{
dataColumn.AllowDBNull = false;
}
if (schemaRow.IsUnique && !schemaRow.IsKey && !fieldType.IsArray)
{
// note, arrays are not comparable so only mark non-arrays as unique, ie timestamp columns
// are unique, but not comparable
dataColumn.Unique = true;
if (!schemaRow.AllowDBNull)
{
dataColumn.AllowDBNull = false;
}
}
}
else if (null == dataColumn.Table)
{
dataColumn.AutoIncrement = schemaRow.IsAutoIncrement;
dataColumn.AllowDBNull = schemaRow.AllowDBNull;
dataColumn.ReadOnly = schemaRow.IsReadOnly;
dataColumn.Unique = schemaRow.IsUnique;
if (fieldType == typeof(string) || (fieldType == typeof(SqlTypes.SqlString)))
{
// schemaRow.Size is count of characters for string columns, count of bytes otherwise
dataColumn.MaxLength = schemaRow.Size;
}
}
}
if (null == dataColumn.Table)
{
if (4 > (int)_loadOption)
{
AddAdditionalProperties(dataColumn, schemaRow.DataRow);
}
AddItemToAllowRollback(ref addedItems, dataColumn);
columnCollection.Add(dataColumn);
}
// The server sends us one key per table according to these rules.
//
// 1. If the table has a primary key, the server sends us this key.
// 2. If the table has a primary key and a unique key, it sends us the primary key
// 3. if the table has no primary key but has a unique key, it sends us the unique key
//
// In case 3, we will promote a unique key to a primary key IFF all the columns that compose
// that key are not nullable since no columns in a primary key can be null. If one or more
// of the keys is nullable, then we will add a unique constraint.
//
if (addPrimaryKeys && schemaRow.IsKey)
{
if (keys == null)
{
keys = new DataColumn[schemaRows.Length];
}
keys[keyCount++] = dataColumn;
// see case 3 above, we do want dataColumn.AllowDBNull not schemaRow.AllowDBNull
// otherwise adding PrimaryKey will change AllowDBNull to false
if (isPrimary && dataColumn.AllowDBNull)
{
isPrimary = false;
}
}
if (null != columnIndexMap)
{
columnIndexMap[unsortedIndex] = dataColumn.Ordinal;
}
else if (unsortedIndex != dataColumn.Ordinal)
{
columnIndexMap = CreateIndexMap(schemaRows.Length, unsortedIndex);
columnIndexMap[unsortedIndex] = dataColumn.Ordinal;
}
mappingCount++;
}
bool addDataRelation = false;
DataColumn chapterColumn = null;
if (null != chapterValue)
{ // add the extra column in the child table
Type fieldType = chapterValue.GetType();
chapterColumn = _tableMapping.GetDataColumn(_tableMapping.SourceTable, fieldType, _dataTable, mappingAction, schemaAction);
if (null != chapterColumn)
{
if (null == chapterColumn.Table)
{
chapterColumn.ReadOnly = true;
chapterColumn.AllowDBNull = false;
AddItemToAllowRollback(ref addedItems, chapterColumn);
columnCollection.Add(chapterColumn);
addDataRelation = (null != parentChapterColumn);
}
mappingCount++;
}
}
if (0 < mappingCount)
{
if ((null != _dataSet) && null == _dataTable.DataSet)
{
AddItemToAllowRollback(ref addedItems, _dataTable);
_dataSet.Tables.Add(_dataTable);
}
// setup the key
if (addPrimaryKeys && (null != keys))
{
if (keyCount < keys.Length)
{
keys = ResizeColumnArray(keys, keyCount);
}
if (isPrimary)
{
_dataTable.PrimaryKey = keys;
}
else
{
UniqueConstraint unique = new UniqueConstraint("", keys);
ConstraintCollection constraints = _dataTable.Constraints;
int constraintCount = constraints.Count;
for (int i = 0; i < constraintCount; ++i)
{
if (unique.Equals(constraints[i]))
{
unique = null;
break;
}
}
if (null != unique)
{
constraints.Add(unique);
}
}
}
if (!commonFromMultiTable && !string.IsNullOrEmpty(commonBaseTable) && string.IsNullOrEmpty(_dataTable.TableName))
{
_dataTable.TableName = commonBaseTable;
}
if (gettingData)
{
_indexMap = columnIndexMap;
_chapterMap = chapterIndexMap;
dataValues = SetupMapping(schemaRows.Length, columnCollection, chapterColumn, chapterValue);
}
else
{
// debug only, but for retail debug ability
_mappedMode = -1;
}
}
else
{
_dataTable = null;
}
if (addDataRelation)
{
AddRelation(parentChapterColumn, chapterColumn);
}
}
catch (Exception e) when (ADP.IsCatchableOrSecurityExceptionType(e))
{
RollbackAddedItems(addedItems);
throw;
}
return dataValues;
}
private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow)
{
DataColumnCollection columns = schemaRow.Table.Columns;
DataColumn column;
column = columns[SchemaTableOptionalColumn.DefaultValue];
if (null != column)
{
targetColumn.DefaultValue = schemaRow[column];
}
column = columns[SchemaTableOptionalColumn.AutoIncrementSeed];
if (null != column)
{
object value = schemaRow[column];
if (DBNull.Value != value)
{
targetColumn.AutoIncrementSeed = ((IConvertible)value).ToInt64(CultureInfo.InvariantCulture);
}
}
column = columns[SchemaTableOptionalColumn.AutoIncrementStep];
if (null != column)
{
object value = schemaRow[column];
if (DBNull.Value != value)
{
targetColumn.AutoIncrementStep = ((IConvertible)value).ToInt64(CultureInfo.InvariantCulture);
}
}
column = columns[SchemaTableOptionalColumn.ColumnMapping];
if (null != column)
{
object value = schemaRow[column];
if (DBNull.Value != value)
{
targetColumn.ColumnMapping = (MappingType)((IConvertible)value).ToInt32(CultureInfo.InvariantCulture);
}
}
column = columns[SchemaTableOptionalColumn.BaseColumnNamespace];
if (null != column)
{
object value = schemaRow[column];
if (DBNull.Value != value)
{
targetColumn.Namespace = ((IConvertible)value).ToString(CultureInfo.InvariantCulture);
}
}
column = columns[SchemaTableOptionalColumn.Expression];
if (null != column)
{
object value = schemaRow[column];
if (DBNull.Value != value)
{
targetColumn.Expression = ((IConvertible)value).ToString(CultureInfo.InvariantCulture);
}
}
}
private void AddRelation(DataColumn parentChapterColumn, DataColumn chapterColumn)
{
if (null != _dataSet)
{
string name = /*parentChapterColumn.ColumnName + "_" +*/ chapterColumn.ColumnName;
DataRelation relation = new DataRelation(name, new DataColumn[] { parentChapterColumn }, new DataColumn[] { chapterColumn }, false);
int index = 1;
string tmp = name;
DataRelationCollection relations = _dataSet.Relations;
while (-1 != relations.IndexOf(tmp))
{
tmp = name + index;
index++;
}
relation.RelationName = tmp;
relations.Add(relation);
}
}
private object[] SetupMapping(int count, DataColumnCollection columnCollection, DataColumn chapterColumn, object chapterValue)
{
object[] dataValues = new object[count];
if (null == _indexMap)
{
int mappingCount = columnCollection.Count;
bool hasChapters = (null != _chapterMap);
if ((count != mappingCount) || hasChapters)
{
_mappedDataValues = new object[mappingCount];
if (hasChapters)
{
_mappedMode = MapChapters;
_mappedLength = count;
}
else
{
_mappedMode = MapDifferentSize;
_mappedLength = Math.Min(count, mappingCount);
}
}
else
{
_mappedMode = MapExactMatch; /* _mappedLength doesn't matter */
}
}
else
{
_mappedDataValues = new object[columnCollection.Count];
_mappedMode = ((null == _chapterMap) ? MapReorderedValues : MapChaptersReordered);
_mappedLength = count;
}
if (null != chapterColumn)
{ // value from parent tracked into child table
_mappedDataValues[chapterColumn.Ordinal] = chapterValue;
}
return dataValues;
}
}
}
| |
//
// Authors
// Jonathan Shore
//
// Copyright:
// 2012 Systematic Trading LLC
// 2002 Systematic Trading LLC
//
// This software is only to be used for the purpose for which
// it has been provided. No part of it is to be reproduced,
// disassembled, transmitted, stored in a retrieval system nor
// translated in any human or computer language in any way or
// for any other purposes whatsoever without the prior written
// consent of Systematic Trading LLC
//
//
//
using System;
using System.Diagnostics;
namespace com.stg.common.collections
{
/// <summary>
/// This is a stable sort (using merge sort) that also tracks the sort order index
/// of the resulting sorted values.
/// <p/>
/// This is not an in-place sort and requires auxilliary storage for both the values and indices. Hence
/// is presented as a class rather than a function.
/// <p/>
/// Also note, that because of retained and working state, this class is not thread-safe, if shared by multiple
/// threads. Should be instantiated as thread-local if it is intended to be shared across threads
/// </summary>
public class SortStableWithOrdering<V>
{
public SortStableWithOrdering (int maxsize, Comparison<V> cmp)
{
_tmp_data = new V[maxsize];
_tmp_indices = new int[maxsize];
_cmp = cmp;
}
public SortStableWithOrdering (Comparison<V> cmp)
: this (256, cmp)
{
}
// Functions
/// <summary>
/// Sort the specified data, with data in original form and ordering presenting the sort order
/// </summary>
/// <param name='data'>
/// Data to be sorted
/// </param>
/// <param name='ordering'>
/// Ordering is an array of int with the same dimension as the data to be sorted
/// </param>
public void SortOrder (
V[] data,
int[] ordering,
int Istart = 0,
int Iend = -1)
{
if (Iend < 0)
Iend = data.Length - 1;
var len = (Iend - Istart + 1);
Debug.Assert (len == ordering.Length, "ordering must be of the same length as the data to be sorted");
// adjust for size if necessary
if (data.Length > _tmp_data.Length)
{
_tmp_data = new V[len];
_tmp_indices = new int[len];
}
// initial ordering
for (int i = 0 ; i < len ; i++)
ordering[i] = Istart + i;
MergeSortWithOrder (data, ordering, 0, len-1);
}
/// <summary>
/// Sort the specified data
/// </summary>
/// <param name='data'>
/// Data to be sorted
/// </param>
public void Sort (
V[] data,
int Istart = 0,
int Iend = -1)
{
if (Iend < 0)
Iend = data.Length - 1;
var len = (Iend - Istart + 1);
// adjust for size if necessary
if (len > _tmp_data.Length)
_tmp_data = new V[len];
MergeSort (data, Istart, Iend);
}
#region MergeSort without order-index tracking
private void MergeSort (V[] data, int left, int right)
{
// if single element (or none), nothing to do
if (right <= left)
return;
// create 2 sorted streams: [left, mid] and [mid+1, right]
var mid = (left + right) / 2;
MergeSort (data, left, mid);
MergeSort (data, mid+1, right);
// now merge the 2 sorted streams of [left, mid] and [mid+1, right]
Merge (data, left, mid+1, right);
}
private void Merge (V[] data, int left, int division, int right)
{
var Lptr = left;
var Rptr = division;
var Tptr = left;
// select from each sorted sequence
while (Lptr < division && Rptr <= right)
{
var cmp = _cmp (data[Lptr], data[Rptr]);
if (cmp <= 0)
{
_tmp_data[Tptr++] = data[Lptr++];
}
else
{
_tmp_data[Tptr++] = data[Rptr++];
}
}
// cleanup on residual left over in left sequence (if any)
while (Lptr < division)
{
_tmp_data[Tptr++] = data[Lptr++];
}
// cleanup on residual left over in right sequence (if any)
while (Rptr <= right)
{
_tmp_data[Tptr++] = data[Rptr++];
}
// now copy back in from tmp arrays into the destination
Array.Copy (_tmp_data, left, data, left, (right - left + 1));
}
#endregion
#region MergeSort with order-index tracking
private void MergeSortWithOrder (V[] data, int[] ordering, int left, int right)
{
// if single element (or none), nothing to do
if (right <= left)
return;
// create 2 sorted streams: [left, mid] and [mid+1, right]
var mid = (left + right) / 2;
MergeSortWithOrder (data, ordering, left, mid);
MergeSortWithOrder (data, ordering, mid+1, right);
// now merge the 2 sorted streams of [left, mid] and [mid+1, right]
MergeWithOrder (data, ordering, left, mid+1, right);
}
private void MergeWithOrder (V[] data, int[] ordering, int left, int division, int right)
{
var Lptr = left;
var Rptr = division;
var Tptr = left;
// select from each sorted sequence
while (Lptr < division && Rptr <= right)
{
var I_Lptr = ordering [Lptr];
var I_Rptr = ordering [Rptr];
var cmp = _cmp (data[I_Lptr], data[I_Rptr]);
if (cmp <= 0)
{
_tmp_indices[Tptr++] = ordering[Lptr++];
}
else
{
_tmp_indices[Tptr++] = ordering[Rptr++];
}
}
// cleanup on residual left over in left sequence (if any)
while (Lptr < division)
{
_tmp_indices[Tptr++] = ordering[Lptr++];
}
// cleanup on residual left over in right sequence (if any)
while (Rptr <= right)
{
_tmp_indices[Tptr++] = ordering[Rptr++];
}
// now copy back in from tmp arrays into the destination
Array.Copy (_tmp_indices, left, ordering, left, (right - left + 1));
}
#endregion
// Variables
private V[] _tmp_data;
private int[] _tmp_indices;
private Comparison<V> _cmp;
}
}
| |
/*
* Copyright (c) 2018 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Algolia.Search.Clients;
using Algolia.Search.Http;
using Algolia.Search.Models.Enums;
using Algolia.Search.Models.Search;
using Algolia.Search.Transport;
using NUnit.Framework;
namespace Algolia.Search.Test.RetryStrategyTest
{
[TestFixture]
[Parallelizable]
public class RetryStrategyTest
{
[Test]
[Parallelizable]
public async Task TestRetryStrategyEndToEnd()
{
// Create a index with a valid client
var indexName = TestHelper.GetTestIndexName("test_retry_e2e");
var index = BaseTest.SearchClient.InitIndex(indexName);
var res = await index.SaveObjectAsync(new { title = "title" }, autoGenerateObjectId: true);
res.Wait();
// Create a client with a bad host to test that the retry worked as expected
var hosts = new List<StatefulHost>
{
// Bad host, will fail with
// System.Net.Http.HttpRequestException:
// The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException:
new StatefulHost
{
Url = "expired.badssl.com",
Up = true,
LastUse = DateTime.UtcNow,
Accept = CallType.Read | CallType.Write,
},
new StatefulHost
{
Url = $"{TestHelper.ApplicationId1}-dsn.algolia.net",
Up = true,
LastUse = DateTime.UtcNow,
Accept = CallType.Read | CallType.Write,
}
};
// Warning /!\ Only use search key here /!\
SearchConfig config = new SearchConfig(TestHelper.ApplicationId1, TestHelper.SearchKey1)
{
CustomHosts = hosts
};
var client = new SearchClient(config);
var idx = client.InitIndex(indexName);
var search = await idx.SearchAsync<Object>(new Query(""));
Assert.AreEqual(1, search.NbHits);
}
[TestCase(CallType.Read)]
[TestCase(CallType.Write)]
[Parallelizable]
public void TestRetryStrategyResetExpired(CallType callType)
{
var commonHosts = new List<StatefulHost>
{
new StatefulHost
{
Url = "-1.algolianet.com",
Up = true,
LastUse = DateTime.UtcNow,
Accept = CallType.Read | CallType.Write,
},
new StatefulHost
{
Url = "-2.algolianet.com",
Up = true,
LastUse = DateTime.UtcNow,
Accept = CallType.Read | CallType.Write,
},
new StatefulHost
{
Url = "-3.algolianet.com",
Up = false,
LastUse = DateTime.UtcNow,
Accept = CallType.Read | CallType.Write,
}
};
SearchConfig config = new SearchConfig(TestHelper.ApplicationId1, TestHelper.AdminKey1)
{
CustomHosts = commonHosts
};
// TODO
RetryStrategy retryStrategy = new RetryStrategy(config);
var hosts = retryStrategy.GetTryableHost(callType);
Assert.True(hosts.Count(h => h.Up) == 2);
}
[TestCase(CallType.Read, 500)]
[TestCase(CallType.Write, 500)]
[TestCase(CallType.Read, 300)]
[TestCase(CallType.Write, 300)]
[Parallelizable]
public void TestRetryStrategyRetriableFailure(CallType callType, int httpErrorCode)
{
var searchConfig = new SearchConfig("appId", "apiKey");
RetryStrategy retryStrategy = new RetryStrategy(searchConfig);
var hosts = retryStrategy.GetTryableHost(callType);
Assert.True(hosts.Count(h => h.Up) == 4);
var decision = retryStrategy.Decide(hosts.ElementAt(0),
new AlgoliaHttpResponse { HttpStatusCode = httpErrorCode });
Assert.True(decision.HasFlag(RetryOutcomeType.Retry));
var updatedHosts = retryStrategy.GetTryableHost(callType);
Assert.True(updatedHosts.Count(h => h.Up) == 3);
var decisionAfterNetworkError =
retryStrategy.Decide(hosts.ElementAt(0), new AlgoliaHttpResponse { IsNetworkError = true });
Assert.True(decisionAfterNetworkError.HasFlag(RetryOutcomeType.Retry));
var updatedHostsAfterNetworkError = retryStrategy.GetTryableHost(callType);
Assert.True(updatedHostsAfterNetworkError.Count(h => h.Up) == 2);
}
[TestCase(CallType.Read, 400)]
[TestCase(CallType.Write, 400)]
[TestCase(CallType.Read, 404)]
[TestCase(CallType.Write, 404)]
[Parallelizable]
public void TestRetryStrategyFailureDecision(CallType callType, int httpErrorCode)
{
var searchConfig = new SearchConfig("appId", "apiKey");
RetryStrategy retryStrategy = new RetryStrategy(searchConfig);
var hosts = retryStrategy.GetTryableHost(callType);
var decision = retryStrategy.Decide(hosts.ElementAt(0),
new AlgoliaHttpResponse { HttpStatusCode = httpErrorCode });
Assert.True(decision.HasFlag(RetryOutcomeType.Failure));
}
[TestCase(CallType.Read)]
[Parallelizable]
public void TestRetryStrategyMultiThread(CallType callType)
{
var searchConfig = new SearchConfig("appId", "apiKey");
RetryStrategy retryStrategy = new RetryStrategy(searchConfig);
var initialHosts = retryStrategy.GetTryableHost(callType);
Assert.That(initialHosts, Has.Exactly(4).Items);
Task task1 = Task.Run(() =>
{
var hosts = retryStrategy.GetTryableHost(callType);
retryStrategy.Decide(hosts.ElementAt(0), new AlgoliaHttpResponse { HttpStatusCode = 200 });
Console.WriteLine(Thread.CurrentThread.Name);
});
Task task2 = Task.Run(() =>
{
var hosts = retryStrategy.GetTryableHost(callType);
retryStrategy.Decide(hosts.ElementAt(0), new AlgoliaHttpResponse { HttpStatusCode = 500 });
});
Task.WaitAll(task1, task2);
var updatedHosts = retryStrategy.GetTryableHost(callType);
Assert.That(updatedHosts, Has.Exactly(3).Items);
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AllReady.Configuration;
using AllReady.Constants;
using AllReady.Controllers;
using AllReady.Extensions;
using AllReady.Features.Admin;
using AllReady.Features.Manage;
using AllReady.Models;
using AllReady.UnitTest.Extensions;
using AllReady.ViewModels.Account;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace AllReady.UnitTest.Controllers
{
public class AdminControllerTests
{
[Fact]
public void RegisterReturnsViewResult()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var result = sut.Register();
Assert.IsType<ViewResult>(result);
}
[Fact]
public void RegisterHasHttpGetAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.Register()).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void RegisterHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.Register()).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task RegisterReturnsViewResultWhenModelStateIsNotValid()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
sut.AddModelStateError();
var result = await sut.Register(It.IsAny<RegisterViewModel>());
Assert.IsType<ViewResult>(result);
}
[Fact]
public async Task RegisterReturnsCorrectModelWhenModelStateIsNotValid()
{
var model = new RegisterViewModel();
var sut = CreateAdminControllerWithNoInjectedDependencies();
sut.AddModelStateError();
var result = await sut.Register(model) as ViewResult;
var modelResult = result.ViewData.Model as RegisterViewModel;
Assert.IsType<RegisterViewModel>(modelResult);
Assert.Same(model, modelResult);
}
[Fact]
public async Task RegisterInvokesCreateAsyncWithCorrectUserAndPassword()
{
const string defaultTimeZone = "DefaultTimeZone";
var model = new RegisterViewModel { Email = "email", Password = "Password" };
var generalSettings = new Mock<IOptions<GeneralSettings>>();
generalSettings.Setup(x => x.Value).Returns(new GeneralSettings { DefaultTimeZone = defaultTimeZone });
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed());
var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object);
await sut.Register(model);
userManager.Verify(x => x.CreateAsync(It.Is<ApplicationUser>(au =>
au.UserName == model.Email &&
au.Email == model.Email &&
au.TimeZoneId == defaultTimeZone),
model.Password));
}
[Fact]
public async Task RegisterInvokesGenerateEmailConfirmationTokenAsyncWithCorrectUserWhenUserCreationIsSuccessful()
{
const string defaultTimeZone = "DefaultTimeZone";
var model = new RegisterViewModel { Email = "email", Password = "Password" };
var generalSettings = new Mock<IOptions<GeneralSettings>>();
generalSettings.Setup(x => x.Value).Returns(new GeneralSettings { DefaultTimeZone = defaultTimeZone });
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success);
var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), null, generalSettings.Object);
sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
sut.Url = Mock.Of<IUrlHelper>();
await sut.Register(model);
userManager.Verify(x => x.GenerateEmailConfirmationTokenAsync(It.Is<ApplicationUser>(au =>
au.UserName == model.Email &&
au.Email == model.Email &&
au.TimeZoneId == defaultTimeZone)));
}
[Fact]
public async Task RegisterInvokesUrlActionWithCorrectParametersWhenUserCreationIsSuccessful()
{
const string requestScheme = "requestScheme";
var generalSettings = new Mock<IOptions<GeneralSettings>>();
generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(It.IsAny<string>());
var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), null, generalSettings.Object);
sut.SetFakeHttpRequestSchemeTo(requestScheme);
var urlHelper = new Mock<IUrlHelper>();
sut.Url = urlHelper.Object;
await sut.Register(new RegisterViewModel());
//note: I can't test the Values part here b/c I do not have control over the Id generation (which is a guid represented as as string) on ApplicationUser b/c it's new'ed up in the controller
urlHelper.Verify(mock => mock.Action(It.Is<UrlActionContext>(uac =>
uac.Action == "ConfirmEmail" &&
uac.Controller == ControllerNames.Admin &&
uac.Protocol == requestScheme)),
Times.Once);
}
[Fact]
public async Task RegisterSendsSendConfirmAccountEmailWithCorrectDataWhenUserCreationIsSuccessful()
{
const string callbackUrl = "callbackUrl";
var model = new RegisterViewModel { Email = "email" };
var generalSettings = new Mock<IOptions<GeneralSettings>>();
generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(It.IsAny<string>());
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(callbackUrl);
var mediator = new Mock<IMediator>();
var sut = new AdminController(userManager.Object, null, mediator.Object, null, generalSettings.Object);
sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
sut.Url = urlHelper.Object;
await sut.Register(model);
mediator.Verify(x => x.SendAsync(It.Is<SendConfirmAccountEmail>(y => y.Email == model.Email && y.CallbackUrl == callbackUrl)));
}
[Fact]
public async Task RegisterRedirectsToCorrectActionWhenUserCreationIsSuccessful()
{
var generalSettings = new Mock<IOptions<GeneralSettings>>();
generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync((IdentityResult.Success));
userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(It.IsAny<string>());
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(It.IsAny<string>());
var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), null, generalSettings.Object);
sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
sut.Url = urlHelper.Object;
var result = await sut.Register(new RegisterViewModel()) as RedirectToActionResult;
Assert.Equal(nameof(AdminController.DisplayEmail), result.ActionName);
Assert.Equal(ControllerNames.Admin, result.ControllerName);
}
[Fact]
public async Task RegisterAddsIdentityResultErrorsToModelStateErrorsWhenUserCreationIsNotSuccessful()
{
var generalSettings = new Mock<IOptions<GeneralSettings>>();
generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());
var identityResult = IdentityResult.Failed(new IdentityError { Description = "IdentityErrorDescription" });
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(identityResult);
var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object);
sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
await sut.Register(new RegisterViewModel());
var errorMessages = sut.ModelState.GetErrorMessages();
Assert.Equal(errorMessages.Single(), identityResult.Errors.Select(x => x.Description).Single());
}
[Fact]
public async Task RegisterReturnsViewResultAndCorrectModelWhenUserCreationIsNotSuccessful()
{
var model = new RegisterViewModel();
var generalSettings = new Mock<IOptions<GeneralSettings>>();
generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed());
var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object);
sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
var result = await sut.Register(model) as ViewResult;
var modelResult = result.ViewData.Model as RegisterViewModel;
Assert.IsType<ViewResult>(result);
Assert.IsType<RegisterViewModel>(modelResult);
Assert.Same(model, modelResult);
}
[Fact]
public void DisplayEmailReturnsViewResult()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var result = sut.DisplayEmail();
Assert.IsType<ViewResult>(result);
}
[Fact]
public void DisplayEmailHasHttpGetAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DisplayEmail()).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void DisplayEmailHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.DisplayEmail()).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task ConfirmEmailReturnsErrorWhenCodeIsNull()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var result = await sut.ConfirmEmail(null, null) as ViewResult;
Assert.Equal("Error", result.ViewName);
}
[Fact]
public async Task ConfirmEmailReturnsErrorWhenCannotFindUserByUserId()
{
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var sut = new AdminController(userManager.Object, null, null, null, null);
var result = await sut.ConfirmEmail(null, "code") as ViewResult;
Assert.Equal("Error", result.ViewName);
}
[Fact]
public async Task ConfirmEmailInvokesFindByIdAsyncWithCorrectUserId()
{
const string userId = "userId";
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var sut = new AdminController(userManager.Object, null, null, null, null);
await sut.ConfirmEmail(userId, "code");
userManager.Verify(x => x.FindByIdAsync(userId), Times.Once);
}
[Fact]
public async Task ConfirmEmailInvokesConfirmEmailAsyncWithCorrectUserAndCode()
{
const string code = "code";
var user = new ApplicationUser();
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(user);
userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed());
var sut = new AdminController(userManager.Object, null, null, null, null);
await sut.ConfirmEmail(null, code);
userManager.Verify(x => x.ConfirmEmailAsync(user, code), Times.Once);
}
[Fact]
public async Task ConfirmEmailInvokesUrlActionWithCorrectParametersWhenUsersEmailIsConfirmedSuccessfully()
{
const string requestScheme = "requestScheme";
const string userId = "1";
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser { Id = userId });
userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success);
var settings = new Mock<IOptions<SampleDataSettings>>();
settings.Setup(x => x.Value).Returns(new SampleDataSettings());
var urlHelper = new Mock<IUrlHelper>();
var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), settings.Object, null);
sut.SetFakeHttpRequestSchemeTo(requestScheme);
sut.Url = urlHelper.Object;
await sut.ConfirmEmail(It.IsAny<string>(), "code");
urlHelper.Verify(x => x.Action(It.Is<UrlActionContext>(uac =>
uac.Action == "EditUser" &&
uac.Controller == "Site" &&
uac.Protocol == requestScheme &&
uac.Values.ToString() == $"{{ area = Admin, userId = {userId} }}")),
Times.Once);
}
[Fact]
public async Task ConfirmEmailSendsSendApproveOrganizationUserAccountEmailWithCorrectDataWhenUsersEmailIsConfirmedSuccessfully()
{
const string defaultAdminUserName = "requestScheme";
const string callbackUrl = "callbackUrl";
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser());
userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success);
var settings = new Mock<IOptions<SampleDataSettings>>();
settings.Setup(x => x.Value).Returns(new SampleDataSettings { DefaultAdminUsername = defaultAdminUserName });
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(callbackUrl);
var mediator = new Mock<IMediator>();
var sut = new AdminController(userManager.Object, null, mediator.Object, settings.Object, null);
sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
sut.Url = urlHelper.Object;
await sut.ConfirmEmail(It.IsAny<string>(), "code");
mediator.Verify(x => x.SendAsync(It.Is<SendApproveOrganizationUserAccountEmail>(y => y.DefaultAdminUsername == defaultAdminUserName && y.CallbackUrl == callbackUrl)));
}
[Fact]
public async Task ConfirmEmailReturnsCorrectViewWhenUsersConfirmationIsSuccessful()
{
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser());
userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success);
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(It.IsAny<string>());
var settings = new Mock<IOptions<SampleDataSettings>>();
settings.Setup(x => x.Value).Returns(new SampleDataSettings { DefaultAdminUsername = It.IsAny<string>() });
var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), settings.Object, null);
sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
sut.Url = urlHelper.Object;
var result = await sut.ConfirmEmail("userId", "code") as ViewResult;
Assert.Equal("ConfirmEmail", result.ViewName);
}
[Fact]
public async Task ConfirmEmailReturnsCorrectViewWhenUsersConfirmationIsUnsuccessful()
{
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser());
userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed());
var sut = new AdminController(userManager.Object, null, null, null, null);
var result = await sut.ConfirmEmail("userId", "code") as ViewResult;
Assert.Equal("Error", result.ViewName);
}
[Fact]
public void ConfirmEmailHasHttpGetAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.ConfirmEmail(It.IsAny<string>(), It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void ConfirmEmailHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.ConfirmEmail(It.IsAny<string>(), It.IsAny<string>())).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void ForgotPasswordReturnsView()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var result = sut.ForgotPassword();
Assert.IsType<ViewResult>(result);
}
[Fact]
public void ForgotPasswordHasHttpGetAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.ForgotPassword()).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void ForgotPasswordHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.ForgotPassword()).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task SendCodeGetInvokesGetTwoFactorAuthenticationUserAsync()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
var sut = new AdminController(null, signInManager.Object, null, null, null);
await sut.SendCode(It.IsAny<string>(), It.IsAny<bool>());
signInManager.Verify(x => x.GetTwoFactorAuthenticationUserAsync(), Times.Once);
}
[Fact]
public async Task SendCodeGetReturnsErrorViewWhenCannotFindUser()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
var sut = new AdminController(null, signInManager.Object, null, null, null);
var result = await sut.SendCode(null, It.IsAny<bool>()) as ViewResult;
Assert.Equal("Error", result.ViewName);
}
[Fact]
public async Task SendCodeGetInvokesGetValidTwoFactorProvidersAsyncWithCorrectUser()
{
var applicationUser = new ApplicationUser();
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser);
userManager.Setup(x => x.GetValidTwoFactorProvidersAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(new List<string>());
var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null);
await sut.SendCode(null, It.IsAny<bool>());
userManager.Verify(x => x.GetValidTwoFactorProvidersAsync(applicationUser), Times.Once);
}
[Fact]
public async Task SendCodeGetReturnsSendCodeViewModelWithCorrectData()
{
const string returnUrl = "returnUrl";
const bool rememberMe = true;
var userFactors = new List<string> { "userFactor1", "userFactor2" };
var expectedProviders = userFactors.Select(factor => new SelectListItem { Text = factor, Value = factor }).ToList();
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser());
userManager.Setup(x => x.GetValidTwoFactorProvidersAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(userFactors);
var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null);
var result = await sut.SendCode(returnUrl, rememberMe) as ViewResult;
var modelResult = result.ViewData.Model as SendCodeViewModel;
Assert.Equal(modelResult.ReturnUrl, returnUrl);
Assert.Equal(modelResult.RememberMe, rememberMe);
Assert.Equal(expectedProviders, modelResult.Providers, new SelectListItemComparer());
}
[Fact]
public void SendCodeGetHasHttpGetAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<string>(), It.IsAny<bool>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void SendCodeGetHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<string>(), It.IsAny<bool>())).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task SendCodePostWithInvalidModelStateReturnsView()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
sut.AddModelStateError();
var result = await sut.SendCode(It.IsAny<SendCodeViewModel>());
Assert.IsType<ViewResult>(result);
}
[Fact]
public async Task SendCodePostInvokesGetTwoFactorAuthenticationUserAsync()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
var sut = new AdminController(null, signInManager.Object, null, null, null);
await sut.SendCode(It.IsAny<SendCodeViewModel>());
signInManager.Verify(x => x.GetTwoFactorAuthenticationUserAsync(), Times.Once);
}
[Fact]
public async Task SendCodePosReturnsErrorViewWhenUserIsNotFound()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
var sut = new AdminController(null, signInManager.Object, null, null, null);
var result = await sut.SendCode(It.IsAny<SendCodeViewModel>()) as ViewResult;
Assert.Equal("Error", result.ViewName);
}
[Fact]
public async Task SendCodePostInvokesGenerateTwoFactorTokenAsyncWithCorrectUserAndTokenProvider()
{
var applicationUser = new ApplicationUser();
var model = new SendCodeViewModel { SelectedProvider = "Email" };
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser);
var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null);
await sut.SendCode(model);
userManager.Verify(x => x.GenerateTwoFactorTokenAsync(applicationUser, model.SelectedProvider), Times.Once);
}
[Fact]
public async Task SendCodePostReturnsErrorViewWhenAuthenticationTokenIsNull()
{
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser());
var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null);
var result = await sut.SendCode(new SendCodeViewModel()) as ViewResult;
Assert.Equal("Error", result.ViewName);
}
[Fact]
public async Task SendCodePostSendsSendSecurityCodeEmailWithCorrectDataWhenSelectedProviderIsEmail()
{
const string token = "token";
const string usersEmailAddress = "usersEmailAddress";
var applicationUser = new ApplicationUser();
var model = new SendCodeViewModel { SelectedProvider = "Email" };
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
var mediator = new Mock<IMediator>();
userManager.Setup(x => x.GenerateTwoFactorTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(token);
userManager.Setup(x => x.GetEmailAsync(applicationUser)).ReturnsAsync(usersEmailAddress);
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser);
var sut = new AdminController(userManager.Object, signInManager.Object, mediator.Object, null, null);
await sut.SendCode(model);
mediator.Verify(x => x.SendAsync(It.Is<SendSecurityCodeEmail>(y => y.Email == usersEmailAddress && y.Token == token)));
}
[Fact]
public async Task SendCodePostSendsSendSecurityCodeSmsWithCorrectDataWhenSelectedProviderIsPhone()
{
const string token = "token";
const string usersPhoneNumber = "usersPhoneNumber";
var applicationUser = new ApplicationUser();
var model = new SendCodeViewModel { SelectedProvider = "Phone" };
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
var mediator = new Mock<IMediator>();
userManager.Setup(x => x.GenerateTwoFactorTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(token);
userManager.Setup(x => x.GetPhoneNumberAsync(applicationUser)).ReturnsAsync(usersPhoneNumber);
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser);
var sut = new AdminController(userManager.Object, signInManager.Object, mediator.Object, null, null);
await sut.SendCode(model);
mediator.Verify(x => x.SendAsync(It.Is<SendAccountSecurityTokenSms>(y => y.PhoneNumber == usersPhoneNumber && y.Token == token)));
}
[Fact]
public async Task SendCodePostReturnsRedirectToActionResult()
{
var model = new SendCodeViewModel { SelectedProvider = string.Empty, ReturnUrl = "ReturnUrl", RememberMe = true };
var routeValues = new Dictionary<string, object>
{
["Provider"] = model.SelectedProvider,
["ReturnUrl"] = model.ReturnUrl,
["RememberMe"] = model.RememberMe
};
var userManager = UserManagerMockHelper.CreateUserManagerMock();
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser());
userManager.Setup(x => x.GenerateTwoFactorTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync("token");
var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null);
var result = await sut.SendCode(model) as RedirectToActionResult;
Assert.Equal(nameof(AdminController.VerifyCode), result.ActionName);
Assert.Equal(result.RouteValues, routeValues);
}
[Fact]
public void SendCodePostGetHasHttpPostAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<SendCodeViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void SendCodePostHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<SendCodeViewModel>())).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void SendCodePostHasValidateAntiForgeryTokenAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<SendCodeViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task VerifyCodeGetInvokesGetTwoFactorAuthenticationUserAsync()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
var sut = new AdminController(null, signInManager.Object, null, null, null);
await sut.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>());
signInManager.Verify(x => x.GetTwoFactorAuthenticationUserAsync(), Times.Once);
}
[Fact]
public async Task VerifyCodeGetReturnsErrorViewWhenUserIsNull()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
var sut = new AdminController(null, signInManager.Object, null, null, null);
var result = await sut.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()) as ViewResult;
Assert.Equal("Error", result.ViewName);
}
[Fact]
public async Task VerifyCodeGetReturnsCorrectViewModel()
{
const string provider = "provider";
const bool rememberMe = true;
const string returnUrl = "returnUrl";
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser());
var sut = new AdminController(null, signInManager.Object, null, null, null);
var result = await sut.VerifyCode(provider, rememberMe, returnUrl) as ViewResult;
var modelResult = result.ViewData.Model as VerifyCodeViewModel;
Assert.Equal(modelResult.Provider, provider);
Assert.Equal(modelResult.ReturnUrl, returnUrl);
Assert.Equal(modelResult.RememberMe, rememberMe);
}
[Fact]
public void VerifyCodeGetHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>())).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void VerifyCodeGetHasHttpGetAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task VerifyCodePostReturnsReturnsCorrectViewAndCorrectModelWhenModelStateIsInvalid()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
sut.AddModelStateError();
var result = await sut.VerifyCode(new VerifyCodeViewModel()) as ViewResult;
var modelResult = result.ViewData.Model as VerifyCodeViewModel;
Assert.IsType<ViewResult>(result);
Assert.IsType<VerifyCodeViewModel>(modelResult);
}
[Fact]
public async Task VerifyCodePostInvokesTwoFactorSignInAsyncWithCorrectParameters()
{
var model = new VerifyCodeViewModel
{
Provider = "provider",
Code = "code",
RememberBrowser = true,
RememberMe = true
};
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(new Microsoft.AspNetCore.Identity.SignInResult());
var sut = new AdminController(null, signInManager.Object, null, null, null);
await sut.VerifyCode(model);
signInManager.Verify(x => x.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser));
}
[Fact]
public async Task VerifyCodePostAddsErrorMessageToModelStateErrorWhenTwoFactorSignInAsyncIsNotSuccessful()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(new Microsoft.AspNetCore.Identity.SignInResult());
var sut = new AdminController(null, signInManager.Object, null, null, null);
await sut.VerifyCode(new VerifyCodeViewModel());
var errorMessage = sut.ModelState.GetErrorMessages().Single();
Assert.Equal("Invalid code.", errorMessage);
}
[Fact]
public async Task VerifyCodePostReturnsLockoutViewIfTwoFactorSignInAsyncFailsAndIsLockedOut()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.LockedOut);
var sut = new AdminController(null, signInManager.Object, null, null, null);
var result = await sut.VerifyCode(new VerifyCodeViewModel()) as ViewResult;
Assert.Equal("Lockout", result.ViewName);
}
[Fact]
public async Task VerifyCodePostRedirectsToReturnUrlWhenTwoFactorSignInAsyncSucceedsAndReturnUrlIsLocalUrl()
{
var model = new VerifyCodeViewModel { ReturnUrl = "returnUrl" };
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success);
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.IsLocalUrl(model.ReturnUrl)).Returns(true);
var sut = new AdminController(null, signInManager.Object, null, null, null) { Url = urlHelper.Object };
var result = await sut.VerifyCode(model) as RedirectResult;
Assert.Equal(result.Url, model.ReturnUrl);
}
[Fact]
public async Task VerifyCodePostRedirectsToHomeControllerIndexWhenTwoFactorSignInAsyncSucceedsAndReturnUrlIsNotLocalUrl()
{
var signInManager = SignInManagerMockHelper.CreateSignInManagerMock();
signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>()))
.ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success);
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.IsLocalUrl(It.IsAny<string>())).Returns(false);
var sut = new AdminController(null, signInManager.Object, null, null, null) { Url = urlHelper.Object };
var result = await sut.VerifyCode(new VerifyCodeViewModel()) as RedirectToPageResult;
Assert.Equal(result.PageName, "/Index");
}
[Fact]
public void VerifyCodePostHasAllowAnonymousAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<VerifyCodeViewModel>())).OfType<AllowAnonymousAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void VerifyCodePostHasHttpPostAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<VerifyCodeViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void VerifyCodePostHasValidateAntiForgeryTokenAttribute()
{
var sut = CreateAdminControllerWithNoInjectedDependencies();
var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<VerifyCodeViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
private static AdminController CreateAdminControllerWithNoInjectedDependencies() => new AdminController(null, null, null, null, null);
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
#pragma warning disable 1591 // disable warning on missing comments
using System;
using Adaptive.SimpleBinaryEncoding;
namespace Adaptive.SimpleBinaryEncoding.Tests.Generated
{
public class ChannelReset
{
public const ushort TemplateId = (ushort)4;
public const byte TemplateVersion = (byte)1;
public const ushort BlockLength = (ushort)9;
public const string SematicType = "X";
private readonly ChannelReset _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public ChannelReset()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = TemplateVersion;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset,
int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(value);
_limit = value;
}
}
public const int TransactTimeSchemaId = 60;
public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "UTCTimestamp";
}
return "";
}
public const ulong TransactTimeNullValue = 0x8000000000000000UL;
public const ulong TransactTimeMinValue = 0x0UL;
public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL;
public ulong TransactTime
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 0, value);
}
}
public const int MatchEventIndicatorSchemaId = 5799;
public static string MatchEventIndicatorMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "MultipleCharValue";
}
return "";
}
public MatchEventIndicator MatchEventIndicator
{
get
{
return (MatchEventIndicator)_buffer.Uint8Get(_offset + 8);
}
set
{
_buffer.Uint8Put(_offset + 8, (byte)value);
}
}
private readonly NoMDEntriesGroup _noMDEntries = new NoMDEntriesGroup();
public const long NoMDEntriesSchemaId = 268;
public NoMDEntriesGroup NoMDEntries
{
get
{
_noMDEntries.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _noMDEntries;
}
}
public NoMDEntriesGroup NoMDEntriesCount(int count)
{
_noMDEntries.WrapForEncode(_parentMessage, _buffer, count);
return _noMDEntries;
}
public class NoMDEntriesGroup
{
private readonly GroupSize _dimensions = new GroupSize();
private ChannelReset _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(ChannelReset parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_count = _dimensions.NumInGroup;
_blockLength = _dimensions.BlockLength;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + 3;
}
public void WrapForEncode(ChannelReset parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.NumInGroup = (byte)count;
_dimensions.BlockLength = (ushort)2;
_index = -1;
_count = count;
_blockLength = 2;
parentMessage.Limit = parentMessage.Limit + 3;
}
public int Count { get { return _count; } }
public bool HasNext { get { return _index + 1 < _count; } }
public NoMDEntriesGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public const int MDUpdateActionSchemaId = 279;
public static string MDUpdateActionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public const sbyte MDUpdateActionNullValue = (sbyte)-128;
public const sbyte MDUpdateActionMinValue = (sbyte)-127;
public const sbyte MDUpdateActionMaxValue = (sbyte)127;
public sbyte MDUpdateAction { get { return (sbyte)0; } }
public const int MDEntryTypeSchemaId = 269;
public static string MDEntryTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public const byte MDEntryTypeNullValue = (byte)0;
public const byte MDEntryTypeMinValue = (byte)32;
public const byte MDEntryTypeMaxValue = (byte)126;
private static readonly byte[] _MDEntryTypeValue = {74};
public const int MDEntryTypeLength = 1;
public byte MDEntryType(int index)
{
return _MDEntryTypeValue[index];
}
public int GetMDEntryType(byte[] dst, int offset, int length)
{
int bytesCopied = Math.Min(length, 1);
Array.Copy(_MDEntryTypeValue, 0, dst, offset, bytesCopied);
return bytesCopied;
}
public const int ApplIDSchemaId = 1180;
public static string ApplIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public const short ApplIDNullValue = (short)-32768;
public const short ApplIDMinValue = (short)-32767;
public const short ApplIDMaxValue = (short)32767;
public short ApplID
{
get
{
return _buffer.Int16GetLittleEndian(_offset + 0);
}
set
{
_buffer.Int16PutLittleEndian(_offset + 0, value);
}
}
}
}
}
| |
#region License
//
// Copyright (c) 2010, Nathan Brown
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Infrastructure.Extensions;
using FluentMigrator.Model;
using FluentMigrator.SqlServer;
using JetBrains.Annotations;
using Microsoft.Extensions.Options;
namespace FluentMigrator.Runner.Generators.SqlServer
{
public class SqlServer2005Generator : SqlServer2000Generator
{
private static readonly HashSet<string> _supportedAdditionalFeatures = new HashSet<string>
{
SqlServerExtensions.IncludesList,
SqlServerExtensions.OnlineIndex,
SqlServerExtensions.RowGuidColumn,
SqlServerExtensions.SchemaAuthorization,
};
public SqlServer2005Generator()
: this(new SqlServer2005Quoter())
{
}
public SqlServer2005Generator(
[NotNull] SqlServer2005Quoter quoter)
: this(quoter, new OptionsWrapper<GeneratorOptions>(new GeneratorOptions()))
{
}
public SqlServer2005Generator(
[NotNull] SqlServer2005Quoter quoter,
[NotNull] IOptions<GeneratorOptions> generatorOptions)
: this(
new SqlServer2005Column(new SqlServer2005TypeMap(), quoter),
quoter,
new SqlServer2005DescriptionGenerator(),
generatorOptions)
{
}
protected SqlServer2005Generator(
[NotNull] IColumn column,
[NotNull] IQuoter quoter,
[NotNull] IDescriptionGenerator descriptionGenerator,
[NotNull] IOptions<GeneratorOptions> generatorOptions)
: base(column, quoter, descriptionGenerator, generatorOptions)
{
}
public override string AddColumn { get { return "ALTER TABLE {0} ADD {1}"; } }
public override string CreateSchema { get { return "CREATE SCHEMA {0}{1}"; } }
public override string CreateIndex { get { return "CREATE {0}{1}INDEX {2} ON {3} ({4}){5}{6}{7}"; } }
public override string DropIndex { get { return "DROP INDEX {0} ON {1}{2}"; } }
public override string IdentityInsert { get { return "SET IDENTITY_INSERT {0} {1}"; } }
public override string CreateForeignKeyConstraint { get { return "ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4}){5}{6}"; } }
public virtual string GetIncludeString(CreateIndexExpression column)
{
var includes = column.GetAdditionalFeature<IList<IndexIncludeDefinition>>(SqlServerExtensions.IncludesList);
string[] indexIncludes = new string[includes?.Count ?? 0];
if (includes != null)
{
for (int i = 0; i != includes.Count; i++)
{
var includeDef = includes[i];
indexIncludes[i] = Quoter.QuoteColumnName(includeDef.Name);
}
}
return includes?.Count > 0 ? " INCLUDE (" + string.Join(", ", indexIncludes) + ")" : string.Empty;
}
public virtual string GetFilterString(CreateIndexExpression createIndexExpression)
{
return string.Empty;
}
public virtual string GetWithOptions(ISupportAdditionalFeatures expression)
{
var items = new List<string>();
var isOnline = expression.GetAdditionalFeature(SqlServerExtensions.OnlineIndex, (bool?)null);
if (isOnline.HasValue)
{
items.Add($"ONLINE={(isOnline.Value ? "ON" : "OFF")}");
}
return string.Join(", ", items);
}
public override bool IsAdditionalFeatureSupported(string feature)
{
return _supportedAdditionalFeatures.Contains(feature)
|| base.IsAdditionalFeatureSupported(feature);
}
public override string Generate(CreateTableExpression expression)
{
var descriptionStatements = DescriptionGenerator.GenerateDescriptionStatements(expression);
var createTableStatement = base.Generate(expression);
var descriptionStatementsArray = descriptionStatements as string[] ?? descriptionStatements.ToArray();
if (!descriptionStatementsArray.Any())
return createTableStatement;
return ComposeStatements(createTableStatement, descriptionStatementsArray);
}
public override string Generate(AlterTableExpression expression)
{
var descriptionStatement = DescriptionGenerator.GenerateDescriptionStatement(expression);
if (string.IsNullOrEmpty(descriptionStatement))
return base.Generate(expression);
return descriptionStatement;
}
public override string Generate(CreateColumnExpression expression)
{
var alterTableStatement = base.Generate(expression);
var descriptionStatement = DescriptionGenerator.GenerateDescriptionStatement(expression);
if (string.IsNullOrEmpty(descriptionStatement))
return alterTableStatement;
return ComposeStatements(alterTableStatement, new[] { descriptionStatement });
}
public override string Generate(AlterColumnExpression expression)
{
var alterTableStatement = base.Generate(expression);
var descriptionStatement = DescriptionGenerator.GenerateDescriptionStatement(expression);
if (string.IsNullOrEmpty(descriptionStatement))
return alterTableStatement;
return ComposeStatements(alterTableStatement, new[] { descriptionStatement });
}
public override string Generate(CreateForeignKeyExpression expression)
{
if (expression.ForeignKey.PrimaryColumns.Count != expression.ForeignKey.ForeignColumns.Count)
{
throw new ArgumentException("Number of primary columns and secondary columns must be equal");
}
List<string> primaryColumns = new List<string>();
List<string> foreignColumns = new List<string>();
foreach (var column in expression.ForeignKey.PrimaryColumns)
{
primaryColumns.Add(Quoter.QuoteColumnName(column));
}
foreach (var column in expression.ForeignKey.ForeignColumns)
{
foreignColumns.Add(Quoter.QuoteColumnName(column));
}
return string.Format(
CreateForeignKeyConstraint,
Quoter.QuoteTableName(expression.ForeignKey.ForeignTable, expression.ForeignKey.ForeignTableSchema),
Quoter.QuoteColumnName(expression.ForeignKey.Name),
string.Join(", ", foreignColumns.ToArray()),
Quoter.QuoteTableName(expression.ForeignKey.PrimaryTable, expression.ForeignKey.PrimaryTableSchema),
string.Join(", ", primaryColumns.ToArray()),
Column.FormatCascade("DELETE", expression.ForeignKey.OnDelete),
Column.FormatCascade("UPDATE", expression.ForeignKey.OnUpdate)
);
}
public override string Generate(CreateIndexExpression expression)
{
string[] indexColumns = new string[expression.Index.Columns.Count];
IndexColumnDefinition columnDef;
for (int i = 0; i < expression.Index.Columns.Count; i++)
{
columnDef = expression.Index.Columns.ElementAt(i);
if (columnDef.Direction == Direction.Ascending)
{
indexColumns[i] = Quoter.QuoteColumnName(columnDef.Name) + " ASC";
}
else
{
indexColumns[i] = Quoter.QuoteColumnName(columnDef.Name) + " DESC";
}
}
var withParts = GetWithOptions(expression);
var withPart = !string.IsNullOrEmpty(withParts)
? $" WITH ({withParts})"
: string.Empty;
var result = string.Format(
CreateIndex,
GetUniqueString(expression),
GetClusterTypeString(expression),
Quoter.QuoteIndexName(expression.Index.Name),
Quoter.QuoteTableName(expression.Index.TableName, expression.Index.SchemaName),
string.Join(", ", indexColumns),
GetIncludeString(expression),
GetFilterString(expression),
withPart);
return result;
}
public override string Generate(DeleteIndexExpression expression)
{
var withParts = GetWithOptions(expression);
var withPart = !string.IsNullOrEmpty(withParts)
? $" WITH ({withParts})"
: string.Empty;
return string.Format(
DropIndex,
Quoter.QuoteIndexName(expression.Index.Name),
Quoter.QuoteTableName(expression.Index.TableName, expression.Index.SchemaName),
withPart);
}
public override string Generate(CreateConstraintExpression expression)
{
var withParts = GetWithOptions(expression);
var withPart = !string.IsNullOrEmpty(withParts)
? $" WITH ({withParts})"
: string.Empty;
return $"{base.Generate(expression)}{withPart}";
}
public override string Generate(DeleteDefaultConstraintExpression expression)
{
string sql =
"DECLARE @default sysname, @sql nvarchar(max);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('{0}')" + Environment.NewLine +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('{0}')" + Environment.NewLine +
"AND name = '{1}'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE {0} DROP CONSTRAINT ' + QUOTENAME(@default);" + Environment.NewLine +
"EXEC sp_executesql @sql;";
return string.Format(sql, Quoter.QuoteTableName(expression.TableName, expression.SchemaName), expression.ColumnName);
}
public override string Generate(DeleteConstraintExpression expression)
{
var withParts = GetWithOptions(expression);
var withPart = !string.IsNullOrEmpty(withParts)
? $" WITH ({withParts})"
: string.Empty;
return $"{base.Generate(expression)}{withPart}";
}
public override string Generate(CreateSchemaExpression expression)
{
string authFragment;
if (expression.AdditionalFeatures.TryGetValue(SqlServerExtensions.SchemaAuthorization, out var authorization))
{
authFragment = $" AUTHORIZATION {Quoter.QuoteSchemaName((string)authorization)}";
}
else
{
authFragment = string.Empty;
}
return string.Format(CreateSchema, Quoter.QuoteSchemaName(expression.SchemaName), authFragment);
}
public override string Generate(DeleteSchemaExpression expression)
{
return string.Format(DropSchema, Quoter.QuoteSchemaName(expression.SchemaName));
}
public override string Generate(AlterSchemaExpression expression)
{
return string.Format(AlterSchema, Quoter.QuoteSchemaName(expression.DestinationSchemaName), Quoter.QuoteTableName(expression.TableName, expression.SourceSchemaName));
}
private string ComposeStatements(string ddlStatement, IEnumerable<string> otherStatements)
{
var otherStatementsArray = otherStatements.ToArray();
var statementsBuilder = new StringBuilder();
statementsBuilder.AppendLine(ddlStatement);
statementsBuilder.AppendLine("GO");
statementsBuilder.AppendLine(string.Join(";", otherStatementsArray));
return statementsBuilder.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Management.Automation;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Inner command class used to manage the sub pipelines
/// it determines which command should process the incoming objects
/// based on the object type
///
/// This class is the implementation class for out-console and out-file.
/// </summary>
internal sealed class OutputManagerInner : ImplementationCommandBase
{
#region tracer
[TraceSource("format_out_OutputManagerInner", "OutputManagerInner")]
internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner");
#endregion tracer
#region LineOutput
internal LineOutput LineOutput
{
set
{
lock (_syncRoot)
{
_lo = value;
if (_isStopped)
{
_lo.StopProcessing();
}
}
}
}
private LineOutput _lo = null;
#endregion
/// <summary>
/// Handler for processing each object coming through the pipeline
/// it forwards the call to the pipeline manager object.
/// </summary>
internal override void ProcessRecord()
{
PSObject so = this.ReadObject();
if (so == null || so == AutomationNull.Value)
{
return;
}
// on demand initialization when the first pipeline
// object is initialized
if (_mgr == null)
{
_mgr = new SubPipelineManager();
_mgr.Initialize(_lo, this.OuterCmdlet().Context);
}
#if false
// if the object supports IEnumerable,
// unpack the object and process each member separately
IEnumerable e = PSObjectHelper.GetEnumerable (so);
if (e == null)
{
this.mgr.Process (so);
}
else
{
foreach (object obj in e)
{
this.mgr.Process (PSObjectHelper.AsPSObject (obj));
}
}
#else
_mgr.Process(so);
#endif
}
/// <summary>
/// Handler for processing shut down. It forwards the call to the
/// pipeline manager object.
/// </summary>
internal override void EndProcessing()
{
// shut down only if we ever processed a pipeline object
if (_mgr != null)
_mgr.ShutDown();
}
internal override void StopProcessing()
{
lock (_syncRoot)
{
if (_lo != null)
{
_lo.StopProcessing();
}
_isStopped = true;
}
}
/// <summary>
/// Make sure we dispose of the sub pipeline manager.
/// </summary>
protected override void InternalDispose()
{
base.InternalDispose();
if (_mgr != null)
{
_mgr.Dispose();
_mgr = null;
}
}
/// <summary>
/// Instance of the pipeline manager object.
/// </summary>
private SubPipelineManager _mgr = null;
/// <summary>
/// True if the cmdlet has been stopped.
/// </summary>
private bool _isStopped = false;
/// <summary>
/// Lock object.
/// </summary>
private readonly object _syncRoot = new object();
}
/// <summary>
/// Object managing the sub-pipelines that execute
/// different output commands (or different instances of the
/// default one)
/// </summary>
internal sealed class SubPipelineManager : IDisposable
{
/// <summary>
/// Entry defining a command to be run in a separate pipeline.
/// </summary>
private sealed class CommandEntry : IDisposable
{
/// <summary>
/// Instance of pipeline wrapper object.
/// </summary>
internal CommandWrapper command = new CommandWrapper();
/// <summary>
/// </summary>
/// <param name="typeName">ETS type name of the object to process.</param>
/// <returns>True if there is a match.</returns>
internal bool AppliesToType(string typeName)
{
foreach (string s in _applicableTypes)
{
if (string.Equals(s, typeName, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// Just dispose of the inner command wrapper.
/// </summary>
public void Dispose()
{
if (this.command == null)
return;
this.command.Dispose();
this.command = null;
}
/// <summary>
/// Ordered list of ETS type names this object is handling.
/// </summary>
private readonly StringCollection _applicableTypes = new StringCollection();
}
/// <summary>
/// Initialize the pipeline manager before any object is processed.
/// </summary>
/// <param name="lineOutput">LineOutput to pass to the child pipelines.</param>
/// <param name="context">ExecutionContext to pass to the child pipelines.</param>
internal void Initialize(LineOutput lineOutput, ExecutionContext context)
{
_lo = lineOutput;
InitializeCommandsHardWired(context);
}
/// <summary>
/// Hard wired registration helper for specialized types.
/// </summary>
/// <param name="context">ExecutionContext to pass to the child pipeline.</param>
private void InitializeCommandsHardWired(ExecutionContext context)
{
// set the default handler
RegisterCommandDefault(context, "out-lineoutput", typeof(OutLineOutputCommand));
/*
NOTE:
This is the spot where we could add new specialized handlers for
additional types. Adding a handler here would cause a new sub-pipeline
to be created.
For example, the following line would add a new handler named "out-example"
to be invoked when the incoming object type is "MyNamespace.Whatever.Example"
RegisterCommandForTypes (context, "out-example", new string[] { "MyNamespace.Whatever.Example" });
And the method can be like this:
private void RegisterCommandForTypes (ExecutionContext context, string commandName, Type commandType, string[] types)
{
CommandEntry ce = new CommandEntry ();
ce.command.Initialize (context, commandName, commandType);
ce.command.AddNamedParameter ("LineOutput", this.lo);
for (int k = 0; k < types.Length; k++)
{
ce.AddApplicableType (types[k]);
}
this.commandEntryList.Add (ce);
}
*/
}
/// <summary>
/// Register the default output command.
/// </summary>
/// <param name="context">ExecutionContext to pass to the child pipeline.</param>
/// <param name="commandName">Name of the command to execute.</param>
/// <param name="commandType">Type of the command to execute.</param>
private void RegisterCommandDefault(ExecutionContext context, string commandName, Type commandType)
{
CommandEntry ce = new CommandEntry();
ce.command.Initialize(context, commandName, commandType);
ce.command.AddNamedParameter("LineOutput", _lo);
_defaultCommandEntry = ce;
}
/// <summary>
/// Process an incoming parent pipeline object.
/// </summary>
/// <param name="so">Pipeline object to process.</param>
internal void Process(PSObject so)
{
// select which pipeline should handle the object
CommandEntry ce = this.GetActiveCommandEntry(so);
Diagnostics.Assert(ce != null, "CommandEntry ce must not be null");
// delegate the processing
ce.command.Process(so);
}
/// <summary>
/// Shut down the child pipelines.
/// </summary>
internal void ShutDown()
{
// we assume that command entries are never null
foreach (CommandEntry ce in _commandEntryList)
{
Diagnostics.Assert(ce != null, "ce != null");
ce.command.ShutDown();
ce.command = null;
}
// we assume we always have a default command entry
Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null");
_defaultCommandEntry.command.ShutDown();
_defaultCommandEntry.command = null;
}
public void Dispose()
{
// we assume that command entries are never null
foreach (CommandEntry ce in _commandEntryList)
{
Diagnostics.Assert(ce != null, "ce != null");
ce.Dispose();
}
// we assume we always have a default command entry
Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null");
_defaultCommandEntry.Dispose();
}
/// <summary>
/// It selects the applicable out command (it can be the default one)
/// to process the current pipeline object.
/// </summary>
/// <param name="so">Pipeline object to be processed.</param>
/// <returns>Applicable command entry.</returns>
private CommandEntry GetActiveCommandEntry(PSObject so)
{
string typeName = PSObjectHelper.PSObjectIsOfExactType(so.InternalTypeNames);
foreach (CommandEntry ce in _commandEntryList)
{
if (ce.AppliesToType(typeName))
return ce;
}
// failed any match: return the default handler
return _defaultCommandEntry;
}
private LineOutput _lo = null;
/// <summary>
/// List of command entries, each with a set of applicable types.
/// </summary>
private readonly List<CommandEntry> _commandEntryList = new List<CommandEntry>();
/// <summary>
/// Default command entry to be executed when all type matches fail.
/// </summary>
private CommandEntry _defaultCommandEntry = new CommandEntry();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AutoMoq;
using FizzWare.NBuilder;
using Moq;
using FluentValidation;
using FluentValidation.Results;
using Sample.Core.Models;
using Sample.Core.Services;
using Sample.Core.Validators;
using Sample.Web.ApiControllers;
namespace Sample.Tests.ApiControllers
{
[TestClass]
public class RolesControllerTests
{
#region Helpers/Test Initializers
private AutoMoqer Mocker { get; set; }
private Mock<IRoleService> MockService { get; set; }
private Mock<IValidator<Role>> MockValidator { get; set; }
private RolesController SubjectUnderTest { get; set; }
[TestInitialize]
public void TestInitialize()
{
Mocker = new AutoMoqer();
SubjectUnderTest = Mocker.Create<RolesController>();
SubjectUnderTest.Request = new HttpRequestMessage();
SubjectUnderTest.Configuration = new HttpConfiguration();
MockService = Mocker.GetMock<IRoleService>();
MockValidator = Mocker.GetMock<IValidator<Role>>();
}
#endregion
#region Tests - Get All
[TestMethod]
public void RolesController_Should_GetAll()
{
// arrange
var expected = Builder<Role>.CreateListOfSize(10).Build();
MockService.Setup(x => x.Get()).Returns(expected);
// act
var actual = SubjectUnderTest.GetAll();
// assert
CollectionAssert.AreEqual(expected as ICollection, actual as ICollection);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Get One
[TestMethod]
public void RolesController_Should_GetOne()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
// act
var result = SubjectUnderTest.Get(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Role actual = null;
Assert.IsTrue(response.Result.TryGetContentValue<Role>(out actual));
Assert.AreEqual(expected.Id, actual.Id);
Assert.AreEqual(expected.Name, actual.Name);
Assert.AreEqual(expected.CreatedAt, actual.CreatedAt);
Assert.AreEqual(expected.UpdatedAt, actual.UpdatedAt);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void RolesController_Should_GetOne_NotFound()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(null as Role);
// act
var result = SubjectUnderTest.Get(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Post One
[TestMethod]
public void RolesController_Should_PostOne()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new ValidationFailure[0]));
MockService.Setup(x => x.Insert(expected));
// act
var result = SubjectUnderTest.Post(expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void RolesController_Should_PostOne_BadRequest()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new []{ new ValidationFailure("", "") }));
// act
var result = SubjectUnderTest.Post(expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.BadRequest);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Put One
[TestMethod]
public void RolesController_Should_PutOne()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new ValidationFailure[0]));
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
MockService.Setup(x => x.Update(expected));
// act
var result = SubjectUnderTest.Put(expected.Id, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void RolesController_Should_PutOne_BadRequest()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new []{ new ValidationFailure("", "") }));
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
// act
var result = SubjectUnderTest.Put(expected.Id, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.BadRequest);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void RolesController_Should_PutOne_NotFound()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(null as Role);
// act
var result = SubjectUnderTest.Put(expected.Id, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Delete One
[TestMethod]
public void RolesController_Should_DeleteOne()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
MockService.Setup(x => x.Delete(expected));
// act
var result = SubjectUnderTest.Delete(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void RolesController_Should_DeleteOne_NotFound()
{
// arrange
var expected = Builder<Role>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(null as Role);
// act
var result = SubjectUnderTest.Delete(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
}
}
| |
namespace SandcastleBuilder.Gui.ContentEditors
{
partial class ResourceItemEditorWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ResourceItemEditorWindow));
this.editor = new SandcastleBuilder.Gui.ContentEditors.ContentEditorControl();
this.cmsDropImage = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miMediaLink = new System.Windows.Forms.ToolStripMenuItem();
this.miMediaLinkInline = new System.Windows.Forms.ToolStripMenuItem();
this.miExternalLinkMedia = new System.Windows.Forms.ToolStripMenuItem();
this.sbStatusBarText = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components);
this.tvResourceItems = new System.Windows.Forms.TreeView();
this.txtId = new System.Windows.Forms.TextBox();
this.btnRevert = new System.Windows.Forms.Button();
this.txtFilename = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.label2 = new System.Windows.Forms.Label();
this.cmsDropImage.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// editor
//
this.editor.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.editor.IsReadOnly = false;
this.editor.Location = new System.Drawing.Point(6, 66);
this.editor.Name = "editor";
this.editor.Size = new System.Drawing.Size(470, 259);
this.sbStatusBarText.SetStatusBarText(this.editor, "Item Content: Edit the resource item\'s content");
this.editor.TabIndex = 4;
//
// cmsDropImage
//
this.cmsDropImage.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miMediaLink,
this.miMediaLinkInline,
this.miExternalLinkMedia});
this.cmsDropImage.Name = "cmsDropImage";
this.cmsDropImage.ShowImageMargin = false;
this.cmsDropImage.Size = new System.Drawing.Size(218, 76);
//
// miMediaLink
//
this.miMediaLink.Name = "miMediaLink";
this.miMediaLink.Size = new System.Drawing.Size(217, 24);
this.miMediaLink.Text = "&Insert <mediaLink>";
//
// miMediaLinkInline
//
this.miMediaLinkInline.Name = "miMediaLinkInline";
this.miMediaLinkInline.Size = new System.Drawing.Size(217, 24);
this.miMediaLinkInline.Text = "I&nsert <mediaLinkInline>";
//
// miExternalLinkMedia
//
this.miExternalLinkMedia.Name = "miExternalLinkMedia";
this.miExternalLinkMedia.Size = new System.Drawing.Size(217, 24);
this.miExternalLinkMedia.Text = "In&sert <externalLink>";
//
// tvResourceItems
//
this.tvResourceItems.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvResourceItems.FullRowSelect = true;
this.tvResourceItems.HideSelection = false;
this.tvResourceItems.Location = new System.Drawing.Point(0, 0);
this.tvResourceItems.Name = "tvResourceItems";
this.tvResourceItems.ShowLines = false;
this.tvResourceItems.ShowRootLines = false;
this.tvResourceItems.Size = new System.Drawing.Size(153, 328);
this.sbStatusBarText.SetStatusBarText(this.tvResourceItems, "Resource Items: Select a resource item to edit");
this.tvResourceItems.TabIndex = 0;
this.tvResourceItems.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvResourceItems_AfterSelect);
this.tvResourceItems.BeforeSelect += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvResourceItems_BeforeSelect);
//
// txtId
//
this.txtId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtId.Location = new System.Drawing.Point(94, 10);
this.txtId.Name = "txtId";
this.txtId.ReadOnly = true;
this.txtId.Size = new System.Drawing.Size(264, 22);
this.sbStatusBarText.SetStatusBarText(this.txtId, "Item ID: The item\'s ID");
this.txtId.TabIndex = 1;
//
// btnRevert
//
this.btnRevert.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnRevert.Location = new System.Drawing.Point(12, 346);
this.btnRevert.Name = "btnRevert";
this.btnRevert.Size = new System.Drawing.Size(88, 32);
this.sbStatusBarText.SetStatusBarText(this.btnRevert, "Revert: Revert the item value to its default value");
this.btnRevert.TabIndex = 1;
this.btnRevert.Text = "&Revert";
this.toolTip1.SetToolTip(this.btnRevert, "Revert item value to its default");
this.btnRevert.UseVisualStyleBackColor = true;
this.btnRevert.Click += new System.EventHandler(this.btnRevert_Click);
//
// txtFilename
//
this.txtFilename.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtFilename.Location = new System.Drawing.Point(94, 38);
this.txtFilename.Name = "txtFilename";
this.txtFilename.ReadOnly = true;
this.txtFilename.Size = new System.Drawing.Size(382, 22);
this.sbStatusBarText.SetStatusBarText(this.txtFilename, "Source File: The source file containing the resource item");
this.txtFilename.TabIndex = 3;
//
// label1
//
this.label1.Location = new System.Drawing.Point(32, 10);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Item ID";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(12, 12);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tvResourceItems);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.label2);
this.splitContainer1.Panel2.Controls.Add(this.txtFilename);
this.splitContainer1.Panel2.Controls.Add(this.editor);
this.splitContainer1.Panel2.Controls.Add(this.label1);
this.splitContainer1.Panel2.Controls.Add(this.txtId);
this.splitContainer1.Size = new System.Drawing.Size(636, 328);
this.splitContainer1.SplitterDistance = 153;
this.splitContainer1.TabIndex = 0;
//
// label2
//
this.label2.Location = new System.Drawing.Point(3, 38);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(85, 23);
this.label2.TabIndex = 2;
this.label2.Text = "Source File";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// ResourceItemEditorWindow
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
this.ClientSize = new System.Drawing.Size(660, 390);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.btnRevert);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ResourceItemEditorWindow";
this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document;
this.ShowInTaskbar = false;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ResourceItemEditorWindow_FormClosing);
this.cmsDropImage.ResumeLayout(false);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private SandcastleBuilder.Gui.ContentEditors.ContentEditorControl editor;
private System.Windows.Forms.ContextMenuStrip cmsDropImage;
private System.Windows.Forms.ToolStripMenuItem miMediaLinkInline;
private System.Windows.Forms.ToolStripMenuItem miMediaLink;
private System.Windows.Forms.ToolStripMenuItem miExternalLinkMedia;
private SandcastleBuilder.Utils.Controls.StatusBarTextProvider sbStatusBarText;
private System.Windows.Forms.TreeView tvResourceItems;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtId;
private System.Windows.Forms.Button btnRevert;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtFilename;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
namespace NodeCanvas.DialogueTrees{
/// <summary>
/// Use DialogueTrees to create Dialogues between Actors
/// </summary>
[GraphInfo(
packageName = "NodeCanvas",
docsURL = "http://nodecanvas.paradoxnotion.com/documentation/",
resourcesURL = "http://nodecanvas.paradoxnotion.com/downloads/",
forumsURL = "http://nodecanvas.paradoxnotion.com/forums-page/"
)]
public class DialogueTree : Graph {
[System.Serializable]
public class ActorParameter {
[SerializeField]
private string _keyName;
[SerializeField]
private string _id;
[SerializeField]
private UnityEngine.Object _actorObject;
private IDialogueActor _actor;
public string name{
get {return _keyName;}
set {_keyName = value;}
}
public string ID{
get {return string.IsNullOrEmpty(_id)? _id = System.Guid.NewGuid().ToString() : _id; }
}
public IDialogueActor actor{
get
{
if (_actor == null){
_actor = _actorObject as IDialogueActor;
}
return _actor;
}
set
{
_actor = value;
_actorObject = value as UnityEngine.Object;
}
}
public ActorParameter(){}
public ActorParameter(string name){
this.name = name;
}
public ActorParameter(string name, IDialogueActor actor){
this.name = name;
this.actor = actor;
}
}
[SerializeField]
private List<ActorParameter> _actorParameters = new List<ActorParameter>();
private DTNode currentNode;
public const string INSTIGATOR_NAME = "INSTIGATOR";
public static event Action<DialogueTree> OnDialogueStarted;
public static event Action<DialogueTree> OnDialoguePaused;
public static event Action<DialogueTree> OnDialogueFinished;
public static event Action<SubtitlesRequestInfo> OnSubtitlesRequest;
public static event Action<MultipleChoiceRequestInfo> OnMultipleChoiceRequest;
public static DialogueTree currentDialogue;
public override System.Type baseNodeType{ get {return typeof(DTNode);} }
public override bool requiresAgent{ get {return false;} }
public override bool requiresPrimeNode { get {return true;} }
public override bool autoSort{ get {return true;} }
public override bool useLocalBlackboard{get {return true;}}
///The dialogue actor parameters
public List<ActorParameter> actorParameters{
get {return _actorParameters;}
}
//A list of the defined names for the involved actor parameters
public List<string> definedActorParameterNames{
get
{
var list = actorParameters.Select(r => r.name).ToList();
list.Insert(0, INSTIGATOR_NAME);
return list;
}
}
//Returns the ActorParameter by id
public ActorParameter GetParameterByID(string id){
return actorParameters.Find(p => p.ID == id);
}
//Returns the ActorParameter by name
public ActorParameter GetParameterByName(string paramName){
return actorParameters.Find(p => p.name == paramName);
}
//Returns the actor by parameter id.
public IDialogueActor GetActorReferenceByID(string id){
var param = GetParameterByID(id);
return param != null? GetActorReferenceByName(param.name) : null;
}
///Resolves and gets an actor based on the key name
public IDialogueActor GetActorReferenceByName(string paramName){
//Check for INSTIGATOR selection
if (paramName == INSTIGATOR_NAME){
//return it directly if it implements IDialogueActor
if (agent is IDialogueActor){
return (IDialogueActor)agent;
}
//Otherwise use the default actor and set name and transform from agent
if (agent != null){
return new ProxyDialogueActor(agent.gameObject.name, agent.transform);
}
return new ProxyDialogueActor("Null Instigator", null);
}
//Check for non INSTIGATOR selection. If there IS an actor reference return it
var refData = actorParameters.Find(r => r.name == paramName);
if (refData != null && refData.actor != null){
return refData.actor;
}
//Otherwise use the default actor and set the name to the key and null transform
Debug.Log(string.Format("<b>DialogueTree:</b> An actor entry '{0}' on DialogueTree has no reference. A dummy Actor will be used with the entry Key for name", paramName), this);
return new ProxyDialogueActor(paramName, null);
}
///Set the target IDialogueActor for the provided key parameter name
public void SetActorReference(string paramName, IDialogueActor actor){
var reference = actorParameters.Find(r => r.name == paramName);
if (reference == null){
Debug.LogError(string.Format("There is no defined Actor key name '{0}'", paramName));
return;
}
reference.actor = actor;
}
///Set all target IDialogueActors at once by provided dictionary
public void SetActorReferences(Dictionary<string, IDialogueActor> actors){
foreach (var pair in actors){
var reference = actorParameters.Find(r => r.name == pair.Key);
if (reference == null){
Debug.LogWarning(string.Format("There is no defined Actor key name '{0}'. Seting actor skiped", pair.Key));
continue;
}
reference.actor = pair.Value;
}
}
///Continues the DialogueTree at provided child connection index of currentNode
public void Continue(int index = 0){
if (!isRunning){
return;
}
if (index < 0 || index > currentNode.outConnections.Count-1){
Stop(true);
return;
}
EnterNode( (DTNode)currentNode.outConnections[index].targetNode );
}
///Enters the provided node
public void EnterNode(DTNode node){
currentNode = node;
currentNode.Reset(false);
if (currentNode.Execute(agent, blackboard) == Status.Error ){
Stop(false);
}
}
///Raise the OnSubtitlesRequest event
public static void RequestSubtitles(SubtitlesRequestInfo info){
if (OnSubtitlesRequest != null)
OnSubtitlesRequest(info);
else Debug.LogWarning("<b>DialogueTree:</b> Subtitle Request event has no subscribers. Make sure to add the default '@DialogueGUI' prefab or create your own GUI.");
}
///Raise the OnMultipleChoiceRequest event
public static void RequestMultipleChoices(MultipleChoiceRequestInfo info){
if (OnMultipleChoiceRequest != null)
OnMultipleChoiceRequest(info);
else Debug.LogWarning("<b>DialogueTree:</b> Multiple Choice Request event has no subscribers. Make sure to add the default '@DialogueGUI' prefab or create your own GUI.");
}
///Convenience starting Methods
///Start the DialogueTree without an Instigator
public void StartDialogue(){
StartGraph(null, localBlackboard, true, null);
}
///Start the DialogueTree with provided actor as Instigator
public void StartDialogue(IDialogueActor instigator){
StartGraph(instigator is Component? (Component)instigator : instigator.transform, localBlackboard, true, null);
}
///Start the DialogueTree with provded actor as instigator and callback
public void StartDialogue(IDialogueActor instigator, Action<bool> callback){
StartGraph(instigator is Component? (Component)instigator : instigator.transform, localBlackboard, true, callback );
}
///Start the DialogueTree with a callback for when its finished
public void StartDialogue(Action<bool> callback){
StartGraph(null, localBlackboard, true, callback);
}
////
protected override void OnGraphStarted(){
if (currentDialogue != null){
Debug.LogWarning(string.Format("<b>DialogueTree:</b> Another Dialogue Tree named '{0}' is already running and will be stoped before starting new one '{1}'", currentDialogue.name, this.name ));
currentDialogue.Stop(true);
}
currentDialogue = this;
Debug.Log(string.Format("<b>DialogueTree:</b> Dialogue Started '{0}'", this.name));
if (OnDialogueStarted != null){
OnDialogueStarted(this);
}
if ( !(agent is IDialogueActor) ){
Debug.Log("<b>DialogueTree:</b> INSTIGATOR agent used in DialogueTree does not implement IDialogueActor. A dummy actor will be used.");
}
currentNode = currentNode != null? currentNode : (DTNode)primeNode;
EnterNode( currentNode );
}
protected override void OnGraphUnpaused(){
currentNode = currentNode != null? currentNode : (DTNode)primeNode;
EnterNode( currentNode );
Debug.Log(string.Format("<b>DialogueTree:</b> Dialogue Resumed '{0}'", this.name));
if (OnDialogueStarted != null){
OnDialogueStarted(this);
}
}
protected override void OnGraphStoped(){
currentNode = null;
currentDialogue = null;
Debug.Log(string.Format("<b>DialogueTree:</b> Dialogue Finished '{0}'", this.name));
if (OnDialogueFinished != null){
OnDialogueFinished(this);
}
}
protected override void OnGraphPaused(){
Debug.Log(string.Format("<b>DialogueTree:</b> Dialogue Paused '{0}'", this.name));
if (OnDialoguePaused != null){
OnDialoguePaused(this);
}
}
////////////////////////////////////////
///////////GUI AND EDITOR STUFF/////////
////////////////////////////////////////
#if UNITY_EDITOR
[UnityEditor.MenuItem("Tools/ParadoxNotion/NodeCanvas/Create/Dialogue Tree", false, 0)]
public static void Editor_CreateGraph(){
var newGraph = EditorUtils.AddScriptableComponent<DialogueTree>( new GameObject("DialogueTree") );
UnityEditor.Selection.activeObject = newGraph;
}
/*
[UnityEditor.MenuItem("Window/NodeCanvas/Create/Graph/Dialogue Tree")]
public static void Editor_CreateGraph(){
var newGraph = EditorUtils.CreateAsset<DialogueTree>(true);
UnityEditor.Selection.activeObject = newGraph;
}
[UnityEditor.MenuItem("Assets/Create/NodeCanvas/Dialogue Tree")]
public static void Editor_CreateGraphFix(){
var path = EditorUtils.GetAssetUniquePath("DialogueTree.asset");
var newGraph = EditorUtils.CreateAsset<DialogueTree>(path);
UnityEditor.Selection.activeObject = newGraph;
}
*/
#endif
}
}
| |
// 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 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// JobOperations operations.
/// </summary>
public partial interface IJobOperations
{
/// <summary>
/// Gets statistics of the specified job.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// Job Information ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobStatistics>> GetStatisticsWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the job debug data information specified by the job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobDataPath>> GetDebugDataPathWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Builds (compiles) the specified job in the specified Data Lake
/// Analytics account for job correctness and validation.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='parameters'>
/// The parameters to build a job.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobInformation>> BuildWithHttpMessagesAsync(string accountName, BuildJobParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Cancels the running job specified by the job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to cancel.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Submits a job to the specified Data Lake Analytics account.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// The job ID (a GUID) for the job being submitted.
/// </param>
/// <param name='parameters'>
/// The parameters to submit a job.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobInformation>> CreateWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, CreateJobParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the job information for the specified job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobInformation>> GetWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake
/// Analytics account. The response includes a link to the next page of
/// results, if any.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just
/// those requested, e.g. Categories?$select=CategoryName,Description.
/// Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobInformationBasic>>> ListWithHttpMessagesAsync(string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake
/// Analytics account. The response includes a link to the next page of
/// results, if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobInformationBasic>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// A collection of <see cref="Note"/> exposed in the <see cref="Repository"/>.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class NoteCollection : IEnumerable<Note>
{
internal readonly Repository repo;
private readonly Lazy<string> defaultNamespace;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected NoteCollection()
{ }
internal NoteCollection(Repository repo)
{
this.repo = repo;
defaultNamespace = new Lazy<string>(RetrieveDefaultNamespace);
}
#region Implementation of IEnumerable
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns>
public virtual IEnumerator<Note> GetEnumerator()
{
return this[DefaultNamespace].GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// The default namespace for notes.
/// </summary>
public virtual string DefaultNamespace
{
get { return defaultNamespace.Value; }
}
/// <summary>
/// The list of canonicalized namespaces related to notes.
/// </summary>
public virtual IEnumerable<string> Namespaces
{
get
{
return NamespaceRefs.Select(UnCanonicalizeName);
}
}
internal IEnumerable<string> NamespaceRefs
{
get
{
return new[] { NormalizeToCanonicalName(DefaultNamespace) }.Concat(
from reference in repo.Refs
select reference.CanonicalName into refCanonical
where refCanonical.StartsWith(Reference.NotePrefix, StringComparison.Ordinal) && refCanonical != NormalizeToCanonicalName(DefaultNamespace)
select refCanonical);
}
}
/// <summary>
/// Gets the collection of <see cref="Note"/> associated with the specified <see cref="ObjectId"/>.
/// </summary>
public virtual IEnumerable<Note> this[ObjectId id]
{
get
{
Ensure.ArgumentNotNull(id, "id");
return NamespaceRefs
.Select(ns => this[ns, id])
.Where(n => n != null);
}
}
/// <summary>
/// Gets the collection of <see cref="Note"/> associated with the specified namespace.
/// <para>This is similar to the 'get notes list' command.</para>
/// </summary>
public virtual IEnumerable<Note> this[string @namespace]
{
get
{
Ensure.ArgumentNotNull(@namespace, "@namespace");
string canonicalNamespace = NormalizeToCanonicalName(@namespace);
return Proxy.git_note_foreach(repo.Handle, canonicalNamespace,
(blobId,annotatedObjId) => this[canonicalNamespace, annotatedObjId]);
}
}
/// <summary>
/// Gets the <see cref="Note"/> associated with the specified objectId and the specified namespace.
/// </summary>
public virtual Note this[string @namespace, ObjectId id]
{
get
{
Ensure.ArgumentNotNull(id, "id");
Ensure.ArgumentNotNull(@namespace, "@namespace");
string canonicalNamespace = NormalizeToCanonicalName(@namespace);
using (NoteSafeHandle noteHandle = Proxy.git_note_read(repo.Handle, canonicalNamespace, id))
{
return noteHandle == null
? null
: Note.BuildFromPtr(noteHandle, UnCanonicalizeName(canonicalNamespace), id);
}
}
}
private string RetrieveDefaultNamespace()
{
string notesRef = Proxy.git_note_default_ref(repo.Handle);
return UnCanonicalizeName(notesRef);
}
internal static string NormalizeToCanonicalName(string name)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
if (name.LooksLikeNote())
{
return name;
}
return string.Concat(Reference.NotePrefix, name);
}
internal string UnCanonicalizeName(string name)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
if (!name.LooksLikeNote())
{
return name;
}
return name.Substring(Reference.NotePrefix.Length);
}
/// <summary>
/// Creates or updates a <see cref="Note"/> on the specified object, and for the given namespace.
/// </summary>
/// <param name="targetId">The target <see cref="ObjectId"/>, for which the note will be created.</param>
/// <param name="message">The note message.</param>
/// <param name="author">The author.</param>
/// <param name="committer">The committer.</param>
/// <param name="namespace">The namespace on which the note will be created. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace').</param>
/// <returns>The note which was just saved.</returns>
public virtual Note Add(ObjectId targetId, string message, Signature author, Signature committer, string @namespace)
{
Ensure.ArgumentNotNull(targetId, "targetId");
Ensure.ArgumentNotNullOrEmptyString(message, "message");
Ensure.ArgumentNotNull(author, "author");
Ensure.ArgumentNotNull(committer, "committer");
Ensure.ArgumentNotNullOrEmptyString(@namespace, "@namespace");
string canonicalNamespace = NormalizeToCanonicalName(@namespace);
Remove(targetId, author, committer, @namespace);
Proxy.git_note_create(repo.Handle, author, committer, canonicalNamespace, targetId, message, true);
return this[canonicalNamespace, targetId];
}
/// <summary>
/// Deletes the note on the specified object, and for the given namespace.
/// </summary>
/// <param name="targetId">The target <see cref="ObjectId"/>, for which the note will be created.</param>
/// <param name="author">The author.</param>
/// <param name="committer">The committer.</param>
/// <param name="namespace">The namespace on which the note will be removed. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace').</param>
public virtual void Remove(ObjectId targetId, Signature author, Signature committer, string @namespace)
{
Ensure.ArgumentNotNull(targetId, "targetId");
Ensure.ArgumentNotNull(author, "author");
Ensure.ArgumentNotNull(committer, "committer");
Ensure.ArgumentNotNullOrEmptyString(@namespace, "@namespace");
string canonicalNamespace = NormalizeToCanonicalName(@namespace);
Proxy.git_note_remove(repo.Handle, canonicalNamespace, author, committer, targetId);
}
private string DebuggerDisplay
{
get
{
return string.Format(CultureInfo.InvariantCulture,
"Count = {0}", this.Count());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// Gfe2010Page
/// </summary>
public sealed partial class Gfe2010Page : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<int?>? _balloonPaymentDueInYears;
private DirtyValue<string?>? _brokerCompensationFwbc;
private DirtyValue<string?>? _brokerCompensationFwsc;
private DirtyValue<decimal?>? _curedGfeTotalTolerance;
private DirtyValue<DateTime?>? _firstArmChangeDate;
private DirtyList<Gfe2010FwbcFwsc>? _gfe2010FwbcFwscs;
private DirtyList<Gfe2010GfeCharge>? _gfe2010GfeCharges;
private DirtyValue<string?>? _gfeRecordingCharges;
private DirtyValue<decimal?>? _gfeTotalTolerance;
private DirtyValue<bool?>? _hasEscrowAccountIndicator;
private DirtyValue<bool?>? _hasEscrowCityPropertyTaxesIndicator;
private DirtyValue<bool?>? _hasEscrowFloodInsurancesIndicator;
private DirtyValue<bool?>? _hasEscrowHomeownerInsurancesIndicator;
private DirtyValue<bool?>? _hasEscrowPropertyTaxesIndicator;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator1;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator2;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator3;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator4;
private DirtyValue<decimal?>? _highestArmRate;
private DirtyValue<decimal?>? _hud1GovernmentRecordingCharge;
private DirtyValue<decimal?>? _hud1Pg1SellerPaidClosingCostsAmount;
private DirtyValue<decimal?>? _hud1Pg1TotalSettlementCharges;
private DirtyValue<decimal?>? _hud1Pg2SellerPaidClosingCostsAmount;
private DirtyValue<decimal?>? _hud1Pg2TotalSettlementCharges;
private DirtyValue<decimal?>? _hudTotalTolerance;
private DirtyValue<decimal?>? _hudTotalToleranceIncreasePercent;
private DirtyValue<string?>? _id;
private DirtyValue<decimal?>? _line1101SellerPaidTotal;
private DirtyValue<decimal?>? _line1201SellerPaidTotal;
private DirtyValue<decimal?>? _line1301SellerPaidTotal;
private DirtyValue<decimal?>? _line801BorrowerPaidTotal;
private DirtyValue<decimal?>? _line801SellerPaidTotal;
private DirtyValue<decimal?>? _line802BorrowerPaidTotal;
private DirtyValue<decimal?>? _line803BorrowerPaidTotal;
private DirtyValue<decimal?>? _line803SellerPaidTotal;
private DirtyValue<bool?>? _line818FwbcIndicator;
private DirtyValue<bool?>? _line818FwscIndicator;
private DirtyValue<bool?>? _line819FwbcIndicator;
private DirtyValue<bool?>? _line819FwscIndicator;
private DirtyValue<bool?>? _line820FwbcIndicator;
private DirtyValue<bool?>? _line820FwscIndicator;
private DirtyValue<bool?>? _line821FwbcIndicator;
private DirtyValue<bool?>? _line821FwscIndicator;
private DirtyValue<bool?>? _line822FwbcIndicator;
private DirtyValue<bool?>? _line822FwscIndicator;
private DirtyValue<bool?>? _line823FwbcIndicator;
private DirtyValue<bool?>? _line823FwscIndicator;
private DirtyValue<bool?>? _line824FwbcIndicator;
private DirtyValue<bool?>? _line824FwscIndicator;
private DirtyValue<bool?>? _line825FwbcIndicator;
private DirtyValue<bool?>? _line825FwscIndicator;
private DirtyValue<bool?>? _line826FwbcIndicator;
private DirtyValue<bool?>? _line826FwscIndicator;
private DirtyValue<bool?>? _line827FwbcIndicator;
private DirtyValue<bool?>? _line827FwscIndicator;
private DirtyValue<bool?>? _line828FwbcIndicator;
private DirtyValue<bool?>? _line828FwscIndicator;
private DirtyValue<bool?>? _line829FwbcIndicator;
private DirtyValue<bool?>? _line829FwscIndicator;
private DirtyValue<bool?>? _line830FwbcIndicator;
private DirtyValue<bool?>? _line830FwscIndicator;
private DirtyValue<bool?>? _line831FwbcIndicator;
private DirtyValue<bool?>? _line831FwscIndicator;
private DirtyValue<bool?>? _line832FwbcIndicator;
private DirtyValue<bool?>? _line832FwscIndicator;
private DirtyValue<bool?>? _line833FwbcIndicator;
private DirtyValue<bool?>? _line833FwscIndicator;
private DirtyValue<bool?>? _lineLFwbcIndicator;
private DirtyValue<bool?>? _lineLFwscIndicator;
private DirtyValue<bool?>? _lineMFwbcIndicator;
private DirtyValue<bool?>? _lineMFwscIndicator;
private DirtyValue<bool?>? _lineNFwbcIndicator;
private DirtyValue<bool?>? _lineNFwscIndicator;
private DirtyValue<bool?>? _lineOFwbcIndicator;
private DirtyValue<bool?>? _lineOFwscIndicator;
private DirtyValue<bool?>? _linePFwbcIndicator;
private DirtyValue<bool?>? _linePFwscIndicator;
private DirtyValue<bool?>? _lineQFwbcIndicator;
private DirtyValue<bool?>? _lineQFwscIndicator;
private DirtyValue<bool?>? _lineRFwbcIndicator;
private DirtyValue<bool?>? _lineRFwscIndicator;
private DirtyValue<decimal?>? _lowestArmRate;
private DirtyValue<bool?>? _monthlyAmountIncludeInterestIndicator;
private DirtyValue<bool?>? _monthlyAmountIncludeMiIndicator;
private DirtyValue<bool?>? _monthlyAmountIncludePrincipalIndicator;
private DirtyValue<decimal?>? _monthlyAmountWithEscrow;
private DirtyValue<decimal?>? _monthlyEscrowPayment;
private DirtyValue<decimal?>? _prepaidInterest;
private DirtyValue<decimal?>? _totalToleranceIncreaseAmount;
/// <summary>
/// Years Until Balloon Pymt Due [NEWHUD.X348]
/// </summary>
public int? BalloonPaymentDueInYears { get => _balloonPaymentDueInYears; set => SetField(ref _balloonPaymentDueInYears, value); }
/// <summary>
/// Fees Line Fees Line 801 Broker Compensation Borrower Checked [NEWHUD.X672]
/// </summary>
public string? BrokerCompensationFwbc { get => _brokerCompensationFwbc; set => SetField(ref _brokerCompensationFwbc, value); }
/// <summary>
/// Fees Line Fees Line 801 Broker Compensation Seller Checked [NEWHUD.X673]
/// </summary>
public string? BrokerCompensationFwsc { get => _brokerCompensationFwsc; set => SetField(ref _brokerCompensationFwsc, value); }
/// <summary>
/// Cured Total GFE Tolerance [NEWHUD.CuredX312]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? CuredGfeTotalTolerance { get => _curedGfeTotalTolerance; set => SetField(ref _curedGfeTotalTolerance, value); }
/// <summary>
/// First ARM Change Date [NEWHUD.X332]
/// </summary>
public DateTime? FirstArmChangeDate { get => _firstArmChangeDate; set => SetField(ref _firstArmChangeDate, value); }
/// <summary>
/// Gfe2010Page Gfe2010FwbcFwscs
/// </summary>
[AllowNull]
public IList<Gfe2010FwbcFwsc> Gfe2010FwbcFwscs { get => GetField(ref _gfe2010FwbcFwscs); set => SetField(ref _gfe2010FwbcFwscs, value); }
/// <summary>
/// Gfe2010Page Gfe2010GfeCharges
/// </summary>
[AllowNull]
public IList<Gfe2010GfeCharge> Gfe2010GfeCharges { get => GetField(ref _gfe2010GfeCharges); set => SetField(ref _gfe2010GfeCharges, value); }
/// <summary>
/// GFE Gov Recording Chrgs [NEWHUD.X295]
/// </summary>
public string? GfeRecordingCharges { get => _gfeRecordingCharges; set => SetField(ref _gfeRecordingCharges, value); }
/// <summary>
/// Total GFE Tolerance [NEWHUD.X312]
/// </summary>
public decimal? GfeTotalTolerance { get => _gfeTotalTolerance; set => SetField(ref _gfeTotalTolerance, value); }
/// <summary>
/// Has Escrow Acct [NEWHUD.X335]
/// </summary>
public bool? HasEscrowAccountIndicator { get => _hasEscrowAccountIndicator; set => SetField(ref _hasEscrowAccountIndicator, value); }
/// <summary>
/// Incl Escrow-City Prop Taxes [NEWHUD.X1726]
/// </summary>
public bool? HasEscrowCityPropertyTaxesIndicator { get => _hasEscrowCityPropertyTaxesIndicator; set => SetField(ref _hasEscrowCityPropertyTaxesIndicator, value); }
/// <summary>
/// Incl Escrow-Flood Ins [NEWHUD.X338]
/// </summary>
public bool? HasEscrowFloodInsurancesIndicator { get => _hasEscrowFloodInsurancesIndicator; set => SetField(ref _hasEscrowFloodInsurancesIndicator, value); }
/// <summary>
/// Incl Escrow-Homeowners Ins [NEWHUD.X339]
/// </summary>
public bool? HasEscrowHomeownerInsurancesIndicator { get => _hasEscrowHomeownerInsurancesIndicator; set => SetField(ref _hasEscrowHomeownerInsurancesIndicator, value); }
/// <summary>
/// Incl Escrow-Prop Taxes [NEWHUD.X337]
/// </summary>
public bool? HasEscrowPropertyTaxesIndicator { get => _hasEscrowPropertyTaxesIndicator; set => SetField(ref _hasEscrowPropertyTaxesIndicator, value); }
/// <summary>
/// Incl Escrow-User Defined 1 [NEWHUD.X340]
/// </summary>
public bool? HasEscrowUserDefinedIndicator1 { get => _hasEscrowUserDefinedIndicator1; set => SetField(ref _hasEscrowUserDefinedIndicator1, value); }
/// <summary>
/// Incl Escrow-User Defined 2 [NEWHUD.X341]
/// </summary>
public bool? HasEscrowUserDefinedIndicator2 { get => _hasEscrowUserDefinedIndicator2; set => SetField(ref _hasEscrowUserDefinedIndicator2, value); }
/// <summary>
/// Incl Escrow-User Defined 3 [NEWHUD.X342]
/// </summary>
public bool? HasEscrowUserDefinedIndicator3 { get => _hasEscrowUserDefinedIndicator3; set => SetField(ref _hasEscrowUserDefinedIndicator3, value); }
/// <summary>
/// New HUD-1 Page 3 Include Escrow Annual Fee [NEWHUD.X343]
/// </summary>
public bool? HasEscrowUserDefinedIndicator4 { get => _hasEscrowUserDefinedIndicator4; set => SetField(ref _hasEscrowUserDefinedIndicator4, value); }
/// <summary>
/// Highest ARM Rate [NEWHUD.X334]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? HighestArmRate { get => _highestArmRate; set => SetField(ref _highestArmRate, value); }
/// <summary>
/// 10% Tolerance Comp Chart - HUD1 Government Recording Charge [NEWHUD.X336]
/// </summary>
public decimal? Hud1GovernmentRecordingCharge { get => _hud1GovernmentRecordingCharge; set => SetField(ref _hud1GovernmentRecordingCharge, value); }
/// <summary>
/// Seller Total Closing Cost for HUD-1 Pg1 [NEWHUD.X774]
/// </summary>
public decimal? Hud1Pg1SellerPaidClosingCostsAmount { get => _hud1Pg1SellerPaidClosingCostsAmount; set => SetField(ref _hud1Pg1SellerPaidClosingCostsAmount, value); }
/// <summary>
/// Borr Total Closing Cost for HUD-1 Pg1 [NEWHUD.X773]
/// </summary>
public decimal? Hud1Pg1TotalSettlementCharges { get => _hud1Pg1TotalSettlementCharges; set => SetField(ref _hud1Pg1TotalSettlementCharges, value); }
/// <summary>
/// Seller Total Closing Costs [NEWHUD.X278]
/// </summary>
public decimal? Hud1Pg2SellerPaidClosingCostsAmount { get => _hud1Pg2SellerPaidClosingCostsAmount; set => SetField(ref _hud1Pg2SellerPaidClosingCostsAmount, value); }
/// <summary>
/// Borr Total Closing Costs [NEWHUD.X277]
/// </summary>
public decimal? Hud1Pg2TotalSettlementCharges { get => _hud1Pg2TotalSettlementCharges; set => SetField(ref _hud1Pg2TotalSettlementCharges, value); }
/// <summary>
/// Total HUD Tolerance [NEWHUD.X313]
/// </summary>
public decimal? HudTotalTolerance { get => _hudTotalTolerance; set => SetField(ref _hudTotalTolerance, value); }
/// <summary>
/// Total GFE Tolerance Increase % [NEWHUD.X315]
/// </summary>
public decimal? HudTotalToleranceIncreasePercent { get => _hudTotalToleranceIncreasePercent; set => SetField(ref _hudTotalToleranceIncreasePercent, value); }
/// <summary>
/// Gfe2010Page Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Fees Line 1101 Seller Paid Total [NEWHUD.X798]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line1101SellerPaidTotal { get => _line1101SellerPaidTotal; set => SetField(ref _line1101SellerPaidTotal, value); }
/// <summary>
/// Fees Line 1201 Seller Paid Total [NEWHUD.X799]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line1201SellerPaidTotal { get => _line1201SellerPaidTotal; set => SetField(ref _line1201SellerPaidTotal, value); }
/// <summary>
/// Fees Line 1301 Seller Paid Total [NEWHUD.X800]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line1301SellerPaidTotal { get => _line1301SellerPaidTotal; set => SetField(ref _line1301SellerPaidTotal, value); }
/// <summary>
/// Fees Line 801 Borrower Paid Total [NEWHUD.X795]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line801BorrowerPaidTotal { get => _line801BorrowerPaidTotal; set => SetField(ref _line801BorrowerPaidTotal, value); }
/// <summary>
/// Fees Line 801 Seller Paid Total [NEWHUD.X794]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line801SellerPaidTotal { get => _line801SellerPaidTotal; set => SetField(ref _line801SellerPaidTotal, value); }
/// <summary>
/// Fees Line 802 Borrower Paid Total [NEWHUD.X797]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line802BorrowerPaidTotal { get => _line802BorrowerPaidTotal; set => SetField(ref _line802BorrowerPaidTotal, value); }
/// <summary>
/// Fees Line 803 Borrower Paid Total [NEWHUD.X796]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line803BorrowerPaidTotal { get => _line803BorrowerPaidTotal; set => SetField(ref _line803BorrowerPaidTotal, value); }
/// <summary>
/// Fees Line 803 Seller Paid Total [NEWHUD.X801]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line803SellerPaidTotal { get => _line803SellerPaidTotal; set => SetField(ref _line803SellerPaidTotal, value); }
/// <summary>
/// Fees Line 820 Funding Worksheet Checkbox for Borrower [NEWHUD.X1486]
/// </summary>
public bool? Line818FwbcIndicator { get => _line818FwbcIndicator; set => SetField(ref _line818FwbcIndicator, value); }
/// <summary>
/// Fees Line 820 Funding Worksheet Checkbox for Seller [NEWHUD.X1509]
/// </summary>
public bool? Line818FwscIndicator { get => _line818FwscIndicator; set => SetField(ref _line818FwscIndicator, value); }
/// <summary>
/// Fees Line 821 Funding Worksheet Checkbox for Borrower [NEWHUD.X1487]
/// </summary>
public bool? Line819FwbcIndicator { get => _line819FwbcIndicator; set => SetField(ref _line819FwbcIndicator, value); }
/// <summary>
/// Fees Line 821 Funding Worksheet Checkbox for Seller [NEWHUD.X1510]
/// </summary>
public bool? Line819FwscIndicator { get => _line819FwscIndicator; set => SetField(ref _line819FwscIndicator, value); }
/// <summary>
/// Fees Line 822 Funding Worksheet Checkbox for Borrower [NEWHUD.X1488]
/// </summary>
public bool? Line820FwbcIndicator { get => _line820FwbcIndicator; set => SetField(ref _line820FwbcIndicator, value); }
/// <summary>
/// Fees Line 822 Funding Worksheet Checkbox for Seller [NEWHUD.X1511]
/// </summary>
public bool? Line820FwscIndicator { get => _line820FwscIndicator; set => SetField(ref _line820FwscIndicator, value); }
/// <summary>
/// Fees Line 823 Funding Worksheet Checkbox for Borrower [NEWHUD.X1489]
/// </summary>
public bool? Line821FwbcIndicator { get => _line821FwbcIndicator; set => SetField(ref _line821FwbcIndicator, value); }
/// <summary>
/// Fees Line 823 Funding Worksheet Checkbox for Seller [NEWHUD.X1512]
/// </summary>
public bool? Line821FwscIndicator { get => _line821FwscIndicator; set => SetField(ref _line821FwscIndicator, value); }
/// <summary>
/// Fees Line 824 Funding Worksheet Checkbox for Borrower [NEWHUD.X1490]
/// </summary>
public bool? Line822FwbcIndicator { get => _line822FwbcIndicator; set => SetField(ref _line822FwbcIndicator, value); }
/// <summary>
/// Fees Line 824 Funding Worksheet Checkbox for Seller [NEWHUD.X1513]
/// </summary>
public bool? Line822FwscIndicator { get => _line822FwscIndicator; set => SetField(ref _line822FwscIndicator, value); }
/// <summary>
/// Fees Line 825 Funding Worksheet Checkbox for Borrower [NEWHUD.X1491]
/// </summary>
public bool? Line823FwbcIndicator { get => _line823FwbcIndicator; set => SetField(ref _line823FwbcIndicator, value); }
/// <summary>
/// Fees Line 825 Funding Worksheet Checkbox for Seller [NEWHUD.X1514]
/// </summary>
public bool? Line823FwscIndicator { get => _line823FwscIndicator; set => SetField(ref _line823FwscIndicator, value); }
/// <summary>
/// Fees Line 826 Funding Worksheet Checkbox for Borrower [NEWHUD.X1492]
/// </summary>
public bool? Line824FwbcIndicator { get => _line824FwbcIndicator; set => SetField(ref _line824FwbcIndicator, value); }
/// <summary>
/// Fees Line 826 Funding Worksheet Checkbox for Seller [NEWHUD.X1515]
/// </summary>
public bool? Line824FwscIndicator { get => _line824FwscIndicator; set => SetField(ref _line824FwscIndicator, value); }
/// <summary>
/// Fees Line 827 Funding Worksheet Checkbox for Borrower [NEWHUD.X1493]
/// </summary>
public bool? Line825FwbcIndicator { get => _line825FwbcIndicator; set => SetField(ref _line825FwbcIndicator, value); }
/// <summary>
/// Fees Line 827 Funding Worksheet Checkbox for Seller [NEWHUD.X1516]
/// </summary>
public bool? Line825FwscIndicator { get => _line825FwscIndicator; set => SetField(ref _line825FwscIndicator, value); }
/// <summary>
/// Fees Line 828 Funding Worksheet Checkbox for Borrower [NEWHUD.X1494]
/// </summary>
public bool? Line826FwbcIndicator { get => _line826FwbcIndicator; set => SetField(ref _line826FwbcIndicator, value); }
/// <summary>
/// Fees Line 828 Funding Worksheet Checkbox for Seller [NEWHUD.X1517]
/// </summary>
public bool? Line826FwscIndicator { get => _line826FwscIndicator; set => SetField(ref _line826FwscIndicator, value); }
/// <summary>
/// Fees Line 829 Funding Worksheet Checkbox for Borrower [NEWHUD.X1495]
/// </summary>
public bool? Line827FwbcIndicator { get => _line827FwbcIndicator; set => SetField(ref _line827FwbcIndicator, value); }
/// <summary>
/// Fees Line 829 Funding Worksheet Checkbox for Seller [NEWHUD.X1518]
/// </summary>
public bool? Line827FwscIndicator { get => _line827FwscIndicator; set => SetField(ref _line827FwscIndicator, value); }
/// <summary>
/// Fees Line 830 Funding Worksheet Checkbox for Borrower [NEWHUD.X1496]
/// </summary>
public bool? Line828FwbcIndicator { get => _line828FwbcIndicator; set => SetField(ref _line828FwbcIndicator, value); }
/// <summary>
/// Fees Line 830 Funding Worksheet Checkbox for Seller [NEWHUD.X1519]
/// </summary>
public bool? Line828FwscIndicator { get => _line828FwscIndicator; set => SetField(ref _line828FwscIndicator, value); }
/// <summary>
/// Fees Line 831 Funding Worksheet Checkbox for Borrower [NEWHUD.X1497]
/// </summary>
public bool? Line829FwbcIndicator { get => _line829FwbcIndicator; set => SetField(ref _line829FwbcIndicator, value); }
/// <summary>
/// Fees Line 831 Funding Worksheet Checkbox for Seller [NEWHUD.X1520]
/// </summary>
public bool? Line829FwscIndicator { get => _line829FwscIndicator; set => SetField(ref _line829FwscIndicator, value); }
/// <summary>
/// Fees Line 832 Funding Worksheet Checkbox for Borrower [NEWHUD.X1498]
/// </summary>
public bool? Line830FwbcIndicator { get => _line830FwbcIndicator; set => SetField(ref _line830FwbcIndicator, value); }
/// <summary>
/// Fees Line 832 Funding Worksheet Checkbox for Seller [NEWHUD.X1521]
/// </summary>
public bool? Line830FwscIndicator { get => _line830FwscIndicator; set => SetField(ref _line830FwscIndicator, value); }
/// <summary>
/// Fees Line 833 Funding Worksheet Checkbox for Borrower [NEWHUD.X1499]
/// </summary>
public bool? Line831FwbcIndicator { get => _line831FwbcIndicator; set => SetField(ref _line831FwbcIndicator, value); }
/// <summary>
/// Fees Line 833 Funding Worksheet Checkbox for Seller [NEWHUD.X1522]
/// </summary>
public bool? Line831FwscIndicator { get => _line831FwscIndicator; set => SetField(ref _line831FwscIndicator, value); }
/// <summary>
/// Fees Line 834 Funding Worksheet Checkbox for Borrower [NEWHUD.X1500]
/// </summary>
public bool? Line832FwbcIndicator { get => _line832FwbcIndicator; set => SetField(ref _line832FwbcIndicator, value); }
/// <summary>
/// Fees Line 834 Funding Worksheet Checkbox for Seller [NEWHUD.X1523]
/// </summary>
public bool? Line832FwscIndicator { get => _line832FwscIndicator; set => SetField(ref _line832FwscIndicator, value); }
/// <summary>
/// Fees Line 835 Funding Worksheet Checkbox for Borrower [NEWHUD.X1501]
/// </summary>
public bool? Line833FwbcIndicator { get => _line833FwbcIndicator; set => SetField(ref _line833FwbcIndicator, value); }
/// <summary>
/// Fees Line 835 Funding Worksheet Checkbox for Seller [NEWHUD.X1524]
/// </summary>
public bool? Line833FwscIndicator { get => _line833FwscIndicator; set => SetField(ref _line833FwscIndicator, value); }
/// <summary>
/// Fees Line 801 L Funding Worksheet Checkbox for Borrower [NEWHUD.X1479]
/// </summary>
public bool? LineLFwbcIndicator { get => _lineLFwbcIndicator; set => SetField(ref _lineLFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 L Funding Worksheet Checkbox for Seller [NEWHUD.X1502]
/// </summary>
public bool? LineLFwscIndicator { get => _lineLFwscIndicator; set => SetField(ref _lineLFwscIndicator, value); }
/// <summary>
/// Fees Line 801 M Funding Worksheet Checkbox for Borrower [NEWHUD.X1480]
/// </summary>
public bool? LineMFwbcIndicator { get => _lineMFwbcIndicator; set => SetField(ref _lineMFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 M Funding Worksheet Checkbox for Seller [NEWHUD.X1503]
/// </summary>
public bool? LineMFwscIndicator { get => _lineMFwscIndicator; set => SetField(ref _lineMFwscIndicator, value); }
/// <summary>
/// Fees Line 801 N Funding Worksheet Checkbox for Borrower [NEWHUD.X1481]
/// </summary>
public bool? LineNFwbcIndicator { get => _lineNFwbcIndicator; set => SetField(ref _lineNFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 N Funding Worksheet Checkbox for Seller [NEWHUD.X1504]
/// </summary>
public bool? LineNFwscIndicator { get => _lineNFwscIndicator; set => SetField(ref _lineNFwscIndicator, value); }
/// <summary>
/// Fees Line 801 O Funding Worksheet Checkbox for Borrower [NEWHUD.X1482]
/// </summary>
public bool? LineOFwbcIndicator { get => _lineOFwbcIndicator; set => SetField(ref _lineOFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 O Funding Worksheet Checkbox for Seller [NEWHUD.X1505]
/// </summary>
public bool? LineOFwscIndicator { get => _lineOFwscIndicator; set => SetField(ref _lineOFwscIndicator, value); }
/// <summary>
/// Fees Line 801 P Funding Worksheet Checkbox for Borrower [NEWHUD.X1483]
/// </summary>
public bool? LinePFwbcIndicator { get => _linePFwbcIndicator; set => SetField(ref _linePFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 P Funding Worksheet Checkbox for Seller [NEWHUD.X1506]
/// </summary>
public bool? LinePFwscIndicator { get => _linePFwscIndicator; set => SetField(ref _linePFwscIndicator, value); }
/// <summary>
/// Fees Line 801 Q Funding Worksheet Checkbox for Borrower [NEWHUD.X1484]
/// </summary>
public bool? LineQFwbcIndicator { get => _lineQFwbcIndicator; set => SetField(ref _lineQFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 Q Funding Worksheet Checkbox for Seller [NEWHUD.X1507]
/// </summary>
public bool? LineQFwscIndicator { get => _lineQFwscIndicator; set => SetField(ref _lineQFwscIndicator, value); }
/// <summary>
/// Fees Line 801 R Funding Worksheet Checkbox for Borrower [NEWHUD.X1485]
/// </summary>
public bool? LineRFwbcIndicator { get => _lineRFwbcIndicator; set => SetField(ref _lineRFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 R Funding Worksheet Checkbox for Seller [NEWHUD.X1508]
/// </summary>
public bool? LineRFwscIndicator { get => _lineRFwscIndicator; set => SetField(ref _lineRFwscIndicator, value); }
/// <summary>
/// Lowest ARM Rate [NEWHUD.X333]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? LowestArmRate { get => _lowestArmRate; set => SetField(ref _lowestArmRate, value); }
/// <summary>
/// Mnthly Amt Includes Interest [NEWHUD.X356]
/// </summary>
public bool? MonthlyAmountIncludeInterestIndicator { get => _monthlyAmountIncludeInterestIndicator; set => SetField(ref _monthlyAmountIncludeInterestIndicator, value); }
/// <summary>
/// Mnthly Amt Includes Mortg Ins [NEWHUD.X357]
/// </summary>
public bool? MonthlyAmountIncludeMiIndicator { get => _monthlyAmountIncludeMiIndicator; set => SetField(ref _monthlyAmountIncludeMiIndicator, value); }
/// <summary>
/// Mnthly Amt Includes Principal [NEWHUD.X355]
/// </summary>
public bool? MonthlyAmountIncludePrincipalIndicator { get => _monthlyAmountIncludePrincipalIndicator; set => SetField(ref _monthlyAmountIncludePrincipalIndicator, value); }
/// <summary>
/// HUD-1 Pg 3 Initial Mthly Amt w/Escrow [NEWHUD.X802]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyAmountWithEscrow { get => _monthlyAmountWithEscrow; set => SetField(ref _monthlyAmountWithEscrow, value); }
/// <summary>
/// HUD-1 Pg 3 Mthly Escrow Pymt w/o Mrtg Ins [NEWHUD.X950]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyEscrowPayment { get => _monthlyEscrowPayment; set => SetField(ref _monthlyEscrowPayment, value); }
/// <summary>
/// New HUD HUD-1 Page 3 Prepaid Interest [NEWHUD.X949]
/// </summary>
public decimal? PrepaidInterest { get => _prepaidInterest; set => SetField(ref _prepaidInterest, value); }
/// <summary>
/// Total GFE Tolerance Increase Amt [NEWHUD.X314]
/// </summary>
public decimal? TotalToleranceIncreaseAmount { get => _totalToleranceIncreaseAmount; set => SetField(ref _totalToleranceIncreaseAmount, value); }
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ByteStorage.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Xml;
using System.Data.SqlTypes;
using System.Collections;
internal sealed class ByteStorage : DataStorage {
private const Byte defaultValue = 0;
private Byte[] values;
internal ByteStorage(DataColumn column)
: base(column, typeof(Byte), defaultValue, StorageType.Byte) {
}
override public Object Aggregate(int[] records, AggregateType kind) {
bool hasData = false;
try {
switch (kind) {
case AggregateType.Sum:
UInt64 sum = defaultValue;
foreach (int record in records) {
if (IsNull(record))
continue;
checked { sum += values[record];}
hasData = true;
}
if (hasData) {
return sum;
}
return NullValue;
case AggregateType.Mean:
Int64 meanSum = (Int64)defaultValue;
int meanCount = 0;
foreach (int record in records) {
if (IsNull(record))
continue;
checked { meanSum += (Int64)values[record];}
meanCount++;
hasData = true;
}
if (hasData) {
Byte mean;
checked {mean = (Byte)(meanSum / meanCount);}
return mean;
}
return NullValue;
case AggregateType.Var:
case AggregateType.StDev:
int count = 0;
double var = (double)defaultValue;
double prec = (double)defaultValue;
double dsum = (double)defaultValue;
double sqrsum = (double)defaultValue;
foreach (int record in records) {
if (IsNull(record))
continue;
dsum += (double)values[record];
sqrsum += (double)values[record]*(double)values[record];
count++;
}
if (count > 1) {
var = ((double)count * sqrsum - (dsum * dsum));
prec = var / (dsum * dsum);
// we are dealing with the risk of a cancellation error
// double is guaranteed only for 15 digits so a difference
// with a result less than 1e-15 should be considered as zero
if ((prec < 1e-15) || (var <0))
var = 0;
else
var = var / (count * (count -1));
if (kind == AggregateType.StDev) {
return Math.Sqrt(var);
}
return var;
}
return NullValue;
case AggregateType.Min:
Byte min = Byte.MaxValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (IsNull(record))
continue;
min=Math.Min(values[record], min);
hasData = true;
}
if (hasData) {
return min;
}
return NullValue;
case AggregateType.Max:
Byte max = Byte.MinValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (IsNull(record))
continue;
max=Math.Max(values[record], max);
hasData = true;
}
if (hasData) {
return max;
}
return NullValue;
case AggregateType.First:
if (records.Length > 0) {
return values[records[0]];
}
return null;
case AggregateType.Count:
return base.Aggregate(records, kind);
}
}
catch (OverflowException) {
throw ExprException.Overflow(typeof(Byte));
}
throw ExceptionBuilder.AggregateException(kind, DataType);
}
override public int Compare(int recordNo1, int recordNo2) {
Byte valueNo1 = values[recordNo1];
Byte valueNo2 = values[recordNo2];
if (valueNo1 == defaultValue || valueNo2 == defaultValue) {
int bitCheck = CompareBits(recordNo1, recordNo2);
if (0 != bitCheck)
return bitCheck;
}
return valueNo1.CompareTo(valueNo2);
//return(valueNo1 - valueNo2); // copied from Byte.CompareTo(Byte)
}
public override int CompareValueTo(int recordNo, object value) {
System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record");
System.Diagnostics.Debug.Assert(null != value, "null value");
if (NullValue == value) {
if (IsNull(recordNo)) {
return 0;
}
return 1;
}
Byte valueNo1 = values[recordNo];
if ((defaultValue == valueNo1) && IsNull(recordNo)) {
return -1;
}
return valueNo1.CompareTo((Byte)value);
//return(valueNo1 - valueNo2); // copied from Byte.CompareTo(Byte)
}
public override object ConvertValue(object value) {
if (NullValue != value) {
if (null != value) {
value = ((IConvertible)value).ToByte(FormatProvider);
}
else {
value = NullValue;
}
}
return value;
}
override public void Copy(int recordNo1, int recordNo2) {
CopyBits(recordNo1, recordNo2);
values[recordNo2] = values[recordNo1];
}
override public Object Get(int record) {
Byte value = values[record];
if (value != defaultValue) {
return value;
}
return GetBits(record);
}
override public void Set(int record, Object value) {
System.Diagnostics.Debug.Assert(null != value, "null value");
if (NullValue == value) {
values[record] = defaultValue;
SetNullBit(record, true);
}
else {
values[record] = ((IConvertible)value).ToByte(FormatProvider);
SetNullBit(record, false);
}
}
override public void SetCapacity(int capacity) {
Byte[] newValues = new Byte[capacity];
if (null != values) {
Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length));
}
values = newValues;
base.SetCapacity(capacity);
}
override public object ConvertXmlToObject(string s) {
return XmlConvert.ToByte(s);
}
override public string ConvertObjectToXml(object value) {
return XmlConvert.ToString((Byte) value);
}
override protected object GetEmptyStorage(int recordCount) {
return new Byte[recordCount];
}
override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) {
Byte[] typedStore = (Byte[]) store;
typedStore[storeIndex] = values[record];
nullbits.Set(storeIndex, IsNull(record));
}
override protected void SetStorage(object store, BitArray nullbits) {
values = (Byte[]) store;
SetNullStorage(nullbits);
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
namespace Irony.Parsing {
[Flags]
public enum ParseOptions {
Reserved = 0x01,
TraceParser = 0x02,
AnalyzeCode = 0x10, //run code analysis; effective only in Module mode
}
public enum ParseMode {
File, //default, continuous input file
VsLineScan, // line-by-line scanning in VS integration for syntax highlighting
CommandLine, //line-by-line from console
}
public enum ParserStatus {
Init, //initial state
Parsing,
Previewing, //previewing tokens
Recovering, //recovering from error
Accepted,
AcceptedPartial,
Error,
}
// The purpose of this class is to provide a container for information shared
// between parser, scanner and token filters.
public class ParsingContext {
public readonly Parser Parser;
public readonly LanguageData Language;
//Parser settings
public ParseOptions Options;
public ParseMode Mode = ParseMode.File;
public int MaxErrors = 20; //maximum error count to report
public CultureInfo Culture; //defaults to Grammar.DefaultCulture, might be changed by app code
#region properties and fields
//Parser fields
public ParserState CurrentParserState { get; internal set; }
public ParseTreeNode CurrentParserInput { get; internal set; }
internal readonly ParserStack ParserStack = new ParserStack();
internal readonly ParserStack ParserInputStack = new ParserStack();
public CommentBlock CurrentCommentBlock;
public ParseTree CurrentParseTree { get; internal set; }
public readonly TokenStack OpenBraces = new TokenStack();
public ParserTrace ParserTrace = new ParserTrace();
public ISourceStream Source { get { return SourceStream; } }
//list for terminals - for current parser state and current input char
public TerminalList CurrentTerminals = new TerminalList();
public Token CurrentToken; //The token just scanned by Scanner
public Token PreviousToken;
public SourceLocation PreviousLineStart; //Location of last line start
//Internal fields
internal SourceStream SourceStream;
internal TokenFilterList TokenFilters = new TokenFilterList();
internal TokenStack BufferedTokens = new TokenStack();
internal IEnumerator<Token> FilteredTokens; //stream of tokens after filter
internal TokenStack PreviewTokens = new TokenStack();
internal ParsingEventArgs SharedParsingEventArgs;
internal ValidateTokenEventArgs SharedValidateTokenEventArgs;
public VsScannerStateMap VsLineScanState; //State variable used in line scanning mode for VS integration
public ParserStatus Status {get; internal set;}
public bool HasErrors; //error flag, once set remains set
//values dictionary to use by custom language implementations to save some temporary values in parse process
public readonly Dictionary<string, object> Values = new Dictionary<string, object>();
public int TabWidth {
get { return _tabWidth; }
set {
_tabWidth = value;
if (SourceStream != null)
SourceStream.TabWidth = value;
}
} int _tabWidth = 8;
#endregion
#region constructors
public ParsingContext(Parser parser) {
this.Parser = parser;
Language = Parser.Language;
Culture = Language.Grammar.DefaultCulture;
//This might be a problem for multi-threading - if we have several contexts on parallel threads with different culture.
//Resources.Culture is static property (this is not Irony's fault, this is auto-generated file).
Resources.Culture = Culture;
SharedParsingEventArgs = new ParsingEventArgs(this);
SharedValidateTokenEventArgs = new ValidateTokenEventArgs(this);
}
#endregion
#region Events: TokenCreated
public event EventHandler<ParsingEventArgs> TokenCreated;
internal void OnTokenCreated() {
if (TokenCreated != null)
TokenCreated(this, SharedParsingEventArgs);
}
#endregion
#region Error handling and tracing
public void EnableTracing(bool value) {
if (value)
Options |= ParseOptions.TraceParser;
else
Options &= ~ParseOptions.TraceParser;
}
public void AddParserError(string message, params object[] args) {
var location = CurrentParserInput == null? Source.Location : CurrentParserInput.Span.Location;
HasErrors = true;
AddParserMessage(ParserErrorLevel.Error, location, message, args);
}
public void AddParserMessage(ParserErrorLevel level, SourceLocation location, string message, params object[] args) {
if (CurrentParseTree == null) return;
if (CurrentParseTree.ParserMessages.Count >= MaxErrors) return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
CurrentParseTree.ParserMessages.Add(new ParserMessage(level, location, message, CurrentParserState));
if (Options.IsSet(ParseOptions.TraceParser))
ParserTrace.Add( new ParserTraceEntry(CurrentParserState, ParserStack.Top, CurrentParserInput, message, true));
}
public void AddTrace(string message, params object[] args) {
if (!Options.IsSet(ParseOptions.TraceParser)) return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
ParserTrace.Add(new ParserTraceEntry(CurrentParserState, ParserStack.Top, CurrentParserInput, message, false));
}
#endregion
internal void Reset() {
CurrentParserState = Parser.InitialState;
CurrentParserInput = null;
ParserStack.Clear();
HasErrors = false;
ParserStack.Push(new ParseTreeNode(CurrentParserState));
ParserInputStack.Clear();
CurrentParseTree = null;
OpenBraces.Clear();
ParserTrace.Clear();
CurrentTerminals.Clear();
CurrentToken = null;
PreviousToken = null;
PreviousLineStart = new SourceLocation(0, -1, 0);
BufferedTokens.Clear();
PreviewTokens.Clear();
Values.Clear();
foreach (var filter in TokenFilters)
filter.Reset();
}
public void SetSourceLocation(SourceLocation location) {
foreach (var filter in TokenFilters)
filter.OnSetSourceLocation(location);
SourceStream.Location = location;
}
#region Expected term set computations
public StringSet GetExpectedTermSet() {
if (CurrentParserState == null)
return new StringSet();
//See note about multi-threading issues in ComputeReportedExpectedSet comments.
if (CurrentParserState.ReportedExpectedSet == null)
CurrentParserState.ReportedExpectedSet = CoreParser.ComputeGroupedExpectedSetForState(Language.Grammar, CurrentParserState);
//Filter out closing braces which are not expected based on previous input.
// While the closing parenthesis ")" might be expected term in a state in general,
// if there was no opening parenthesis in preceding input then we would not
// expect a closing one.
var expectedSet = FilterBracesInExpectedSet(CurrentParserState.ReportedExpectedSet);
return expectedSet;
}
private StringSet FilterBracesInExpectedSet(StringSet stateExpectedSet) {
var result = new StringSet();
result.UnionWith(stateExpectedSet);
//Find what brace we expect
var nextClosingBrace = string.Empty;
if (OpenBraces.Count > 0) {
var lastOpenBraceTerm = OpenBraces.Peek().KeyTerm;
var nextClosingBraceTerm = lastOpenBraceTerm.IsPairFor as KeyTerm;
if (nextClosingBraceTerm != null)
nextClosingBrace = nextClosingBraceTerm.Text;
}
//Now check all closing braces in result set, and leave only nextClosingBrace
foreach(var closingBrace in Language.GrammarData.ClosingBraces) {
if (result.Contains(closingBrace) && closingBrace != nextClosingBrace)
result.Remove(closingBrace);
}
return result;
}
#endregion
#region Operators handling
public ExpressionType GetOperatorExpressionType(string symbol) {
OperatorInfo opInfo;
if (Language.Grammar.OperatorMappings.TryGetValue(symbol, out opInfo))
return opInfo.ExpressionType;
return CustomExpressionTypes.NotAnExpression;
}
public ExpressionType GetUnaryOperatorExpressionType(string symbol) {
switch (symbol.ToLowerInvariant()) {
case "+": return ExpressionType.UnaryPlus;
case "-": return ExpressionType.Negate;
case "!":
case "not":
case "~" :
return ExpressionType.Not;
default:
return CustomExpressionTypes.NotAnExpression;
}
}
#endregion
}//class
// A struct used for packing/unpacking ScannerState int value; used for VS integration.
// When Terminal produces incomplete token, it sets
// this state to non-zero value; this value identifies this terminal as the one who will continue scanning when
// it resumes, and the terminal's internal state when there may be several types of multi-line tokens for one terminal.
// For ex., there maybe several types of string literal like in Python.
[StructLayout(LayoutKind.Explicit)]
public struct VsScannerStateMap {
[FieldOffset(0)]
public int Value;
[FieldOffset(0)]
public byte TerminalIndex; //1-based index of active multiline term in MultilineTerminals
[FieldOffset(1)]
public byte TokenSubType; //terminal subtype (used in StringLiteral to identify string kind)
[FieldOffset(2)]
public short TerminalFlags; //Terminal flags
}//struct
}
| |
using System;
using System.Data;
using PCSComMaterials.Inventory.BO;
using PCSComMaterials.Inventory.DS;
using PCSComProcurement.Purchase.DS;
using PCSComProduct.Items.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
namespace PCSComProcurement.Purchase.BO
{
public interface IPOReturnToVendor{}
public class POReturnToVendorBO : IPOReturnToVendor
{
#region IObjectBO Members
public void UpdateDataSet(System.Data.DataSet dstData)
{
// TODO: Add POReturnToVendor.UpdateDataSet implementation
}
public void Update(object pObjectDetail)
{
// TODO: Add POReturnToVendor.Update implementation
}
public void Delete(object pObjectVO)
{
// TODO: Add POReturnToVendor.Delete implementation
}
public void Add(object pObjectDetail)
{
// TODO: Add POReturnToVendor.Add implementation
}
public object GetObjectVO(int pintID, string VOclass)
{
PO_ReturnToVendorMasterDS dsMaster = new PO_ReturnToVendorMasterDS();
return dsMaster.GetObjectVO(pintID);
}
public object GetMasterInfo(int pintID, out DataRow odrowInfo)
{
odrowInfo = null;
PO_ReturnToVendorMasterDS dsMaster = new PO_ReturnToVendorMasterDS();
odrowInfo = dsMaster.GetReturnToVendorMasterInfo(pintID).Rows[0];
return dsMaster.GetObjectVO(pintID);
}
#endregion
public DataSet GetDetailData(int pintReturnMasterID)
{
PO_ReturnToVendorDetailDS dsDetail = new PO_ReturnToVendorDetailDS();
return dsDetail.List(pintReturnMasterID);
}
public DataRow GetVendorInfo(int pintVendorLocationID)
{
MST_PartyDS dsParty = new MST_PartyDS();
return dsParty.GetVendorInfo(pintVendorLocationID);
}
public DataTable GetListOfReceivedProductsFromPurchaseOrder(int pintPurchaseOrderMasterID)
{
PO_PurchaseOrderDetailDS objPO_PurchaseOrderDetailDS = new PO_PurchaseOrderDetailDS();
return objPO_PurchaseOrderDetailDS.GetListOfReceivedProductsFromPurchaseOrder(pintPurchaseOrderMasterID);
}
public DataSet GetDetailByInvoiceMasterID(int pintInvoiceMasterID)
{
PO_ReturnToVendorDetailDS dsDetail = new PO_ReturnToVendorDetailDS();
DataSet dstTemp = dsDetail.GetDetailByInvoiceMasterToReturn(pintInvoiceMasterID);
DataSet dstData = dstTemp.Clone();
int intLine = 0;
foreach (DataRow drowData in dstTemp.Tables[0].Rows)
{
DataRow drowNew = dstData.Tables[0].NewRow();
foreach (DataColumn dcolData in dstData.Tables[0].Columns)
drowNew[dcolData.ColumnName] = drowData[dcolData.ColumnName];
drowNew[PO_ReturnToVendorDetailTable.LINE_FLD] = ++ intLine;
dstData.Tables[0].Rows.Add(drowNew);
}
return dstData;
}
public int AddNewReturnToVendor(PO_ReturnToVendorMasterVO pobjReturnToVendorMasterVO, DataSet pdstDetail)
{
//check onhand quantity
CheckOnHandQty(pdstDetail,pobjReturnToVendorMasterVO);
//store the master first
PO_ReturnToVendorMasterDS objPO_ReturnToVendorMasterDS = new PO_ReturnToVendorMasterDS();
PO_ReturnToVendorDetailDS objPO_ReturnToVendorDetailDS = new PO_ReturnToVendorDetailDS();
//first we need to add to the master and return the latest ID
int intReturnToVendorMasterID = objPO_ReturnToVendorMasterDS.AddNewReturnToVendor(pobjReturnToVendorMasterVO);
//assign this ID into the detail
//update the dataset all of this id
for (int i=0; i<pdstDetail.Tables[0].Rows.Count;i++)
{
if (pdstDetail.Tables[0].Rows[i].RowState != DataRowState.Deleted)
{
pdstDetail.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.RETURNTOVENDORMASTERID_FLD] = intReturnToVendorMasterID;
}
}
//Add this database into database
if (pobjReturnToVendorMasterVO.PurchaseOrderMasterID != 0)
objPO_ReturnToVendorDetailDS.UpdateReturnToVendorDataSet(pdstDetail, intReturnToVendorMasterID);
else if (pobjReturnToVendorMasterVO.InvoiceMasterID != 0)
objPO_ReturnToVendorDetailDS.UpdateDataSetForInvoice(pdstDetail);
// re-load dataset
pdstDetail = objPO_ReturnToVendorDetailDS.List(intReturnToVendorMasterID);
// Add value to pobjReturnToVendorMasterVO
pobjReturnToVendorMasterVO.ReturnToVendorMasterID = intReturnToVendorMasterID;
//Update inventory data
UpdateInventoryInfor(pdstDetail,true, pobjReturnToVendorMasterVO);
// HACK: Trada 27-12-2005
//Update MST_TransactionHistory
new UtilsBO();
InventoryUtilsBO boInventoryUtils = new InventoryUtilsBO();
PO_ReturnToVendorDetailDS dsReturnToVendorDetail = new PO_ReturnToVendorDetailDS();
pdstDetail = dsReturnToVendorDetail.ListReturnToVendorDetail(intReturnToVendorMasterID);
foreach (DataRow drow in pdstDetail.Tables[0].Rows)
{
MST_TransactionHistoryVO voTransactionHistory = new MST_TransactionHistoryVO();
voTransactionHistory.CCNID = pobjReturnToVendorMasterVO.CCNID;
voTransactionHistory.MasterLocationID = pobjReturnToVendorMasterVO.MasterLocationID;
voTransactionHistory.PartyID = pobjReturnToVendorMasterVO.PartyID;
voTransactionHistory.PostDate = pobjReturnToVendorMasterVO.PostDate;
voTransactionHistory.PartyLocationID = pobjReturnToVendorMasterVO.PurchaseLocID;
//HACK: Modified by Tuan TQ: 15 June, 2006. RefMasterID must be RTV MasterID (for Stock Card report)
voTransactionHistory.RefMasterID = intReturnToVendorMasterID;
//end hack
//End Hack
voTransactionHistory.LocationID = int.Parse(drow[PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString());
if (drow[PO_ReturnToVendorDetailTable.BINID_FLD].ToString() != string.Empty)
voTransactionHistory.BinID = int.Parse(drow[PO_ReturnToVendorDetailTable.BINID_FLD].ToString());
if (drow[PO_ReturnToVendorDetailTable.RETURNTOVENDORDETAILID_FLD].ToString() != string.Empty)
voTransactionHistory.RefDetailID = int.Parse(drow[PO_ReturnToVendorDetailTable.RETURNTOVENDORDETAILID_FLD].ToString());
if (drow[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString() != string.Empty)
voTransactionHistory.ProductID = int.Parse(drow[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString());
if (drow[PO_ReturnToVendorDetailTable.STOCKUMID_FLD].ToString() != string.Empty)
voTransactionHistory.StockUMID = int.Parse(drow[PO_ReturnToVendorDetailTable.STOCKUMID_FLD].ToString());
voTransactionHistory.Quantity = Decimal.Parse(drow[PO_ReturnToVendorDetailTable.QUANTITY_FLD].ToString());
voTransactionHistory.TransDate = new UtilsBO().GetDBDate();
boInventoryUtils.SaveTransactionHistory(Constants.TRANTYPE_PORETURNTOVENDOR, (int)PurposeEnum.ReturnToVendor, voTransactionHistory);
}
// END: Trada 27-12-2005
return intReturnToVendorMasterID;
}
private void CheckOnHandQty(DataSet dstData, PO_ReturnToVendorMasterVO pobjPO_ReturnToVendorMasterVO)
{
DateTime dtmCurrentDate = new UtilsBO().GetDBDate().AddDays(1);
InventoryUtilsBO boIVUtils = new InventoryUtilsBO();
decimal dcmOnHandQty, decOnHandCurrent =0;
for (int i=0; i<dstData.Tables[0].Rows.Count;i++)
{
if (dstData.Tables[0].Rows[i].RowState != DataRowState.Deleted)
{
//get Quantity, location, bin, umrate
string strBINID = dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.BINID_FLD].ToString().Trim();
dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString().Trim();
if (strBINID != String.Empty)
{
IV_BinCacheVO objIV_BinCacheVO = new IV_BinCacheVO();
objIV_BinCacheVO.ProductID = int.Parse(dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString());
objIV_BinCacheVO.MasterLocationID = pobjPO_ReturnToVendorMasterVO.MasterLocationID;
objIV_BinCacheVO.CCNID = pobjPO_ReturnToVendorMasterVO.CCNID;
objIV_BinCacheVO.LocationID = int.Parse(dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString());
objIV_BinCacheVO.BinID = int.Parse(dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.BINID_FLD].ToString());
dcmOnHandQty = boIVUtils.GetAvailableQtyByPostDate(dtmCurrentDate, objIV_BinCacheVO.CCNID, objIV_BinCacheVO.MasterLocationID,
objIV_BinCacheVO.LocationID, objIV_BinCacheVO.BinID, objIV_BinCacheVO.ProductID);
decOnHandCurrent = boIVUtils.GetAvailableQtyByPostDate(dtmCurrentDate, objIV_BinCacheVO.CCNID, objIV_BinCacheVO.MasterLocationID,
objIV_BinCacheVO.LocationID, objIV_BinCacheVO.BinID, objIV_BinCacheVO.ProductID);
}
else
{
IV_LocationCacheVO objIV_LocationCacheVO = new IV_LocationCacheVO();
objIV_LocationCacheVO.ProductID = int.Parse(dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString());
objIV_LocationCacheVO.MasterLocationID = pobjPO_ReturnToVendorMasterVO.MasterLocationID;
objIV_LocationCacheVO.CCNID = pobjPO_ReturnToVendorMasterVO.CCNID;
objIV_LocationCacheVO.LocationID = int.Parse(dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString());
dcmOnHandQty = boIVUtils.GetAvailableQtyByPostDate(dtmCurrentDate, objIV_LocationCacheVO.CCNID, objIV_LocationCacheVO.MasterLocationID,
objIV_LocationCacheVO.LocationID, 0, objIV_LocationCacheVO.ProductID);
decOnHandCurrent = boIVUtils.GetAvailableQtyByPostDate(dtmCurrentDate, objIV_LocationCacheVO.CCNID, objIV_LocationCacheVO.MasterLocationID,
objIV_LocationCacheVO.LocationID, 0, objIV_LocationCacheVO.ProductID);
}
decimal dcmUMRate = 1;
if (pobjPO_ReturnToVendorMasterVO.PurchaseOrderMasterID != 0)
{
//get the UMRate
if (dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.UMRATE_FLD].ToString() != String.Empty)
dcmUMRate = decimal.Parse(dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.UMRATE_FLD].ToString());
else
dcmUMRate = 1;
}
decimal dcmReturnQuantity = decimal.Parse(dstData.Tables[0].Rows[i][PO_ReturnToVendorDetailTable.QUANTITY_FLD].ToString());
if ( (dcmOnHandQty - (dcmReturnQuantity * dcmUMRate)) < 0)
throw new PCSBOException(ErrorCode.MESSAGE_RGA_OVERONHANDQTY,i.ToString(),null);
else
if (decOnHandCurrent < (dcmReturnQuantity * dcmUMRate))
throw new PCSBOException(ErrorCode.MESSAGE_AVAILABLE_WAS_USED_AFTER_POSTDATE, i.ToString(),null);
}
}
}
private void UpdateInventoryInfor(DataSet dsReturnToVendorDetail,bool blnNewRecord, PO_ReturnToVendorMasterVO pobjPO_ReturnToVendorMasterVO)
{
UtilsBO boUtils = new UtilsBO();
foreach (DataRow drowReturnedGoodsDetail in dsReturnToVendorDetail.Tables[0].Rows)
{
if (blnNewRecord && drowReturnedGoodsDetail.RowState == DataRowState.Deleted)
continue;
int intStockUMID = int.Parse(drowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.STOCKUMID_FLD].ToString());
int intBuyingUMID = int.Parse(drowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.BUYINGUMID_FLD].ToString());
Decimal decUMRate = boUtils.GetUMRate(intBuyingUMID, intStockUMID);
if (decUMRate != 0)
drowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.QUANTITY_FLD] = Decimal.Parse(drowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.QUANTITY_FLD].ToString())* decUMRate;
else
throw new PCSException(ErrorCode.MESSAGE_MUST_SET_UMRATE, string.Empty, new Exception());
#region Update IV_BinCache
if (drowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.BINID_FLD].ToString().Trim() != String.Empty)
UpdateIVBinCache(drowReturnedGoodsDetail,blnNewRecord,pobjPO_ReturnToVendorMasterVO);
#endregion
#region update into the IV_locationCache
UpdateIVLocationCache(drowReturnedGoodsDetail,blnNewRecord,pobjPO_ReturnToVendorMasterVO);
#endregion
#region Update into the IV_MasterLocationCache
UpdateIVMasterLocationCache(drowReturnedGoodsDetail,blnNewRecord,pobjPO_ReturnToVendorMasterVO);
#endregion
#region Add By CanhNV: {Update add Inventory for Bom tree}
if (pobjPO_ReturnToVendorMasterVO.ProductionLineId > 0)
{
//1.Get BomDetail by ProductID
DataTable dtBomDetail = new ITM_BOMDS().ListBomDetailOfProduct((int) drowReturnedGoodsDetail[ITM_ProductTable.PRODUCTID_FLD]);
if (dtBomDetail.Rows.Count <=0)
return;
//2.Get LocationID and BinID by ProductionLineID
DataTable dtLocBin = new PO_ReturnToVendorMasterDS().GetLocationBin(pobjPO_ReturnToVendorMasterVO.ProductionLineId);
if(dtLocBin.Rows.Count == 0)
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
int intProLocationID = Convert.ToInt32(dtLocBin.Rows[0][MST_BINTable.LOCATIONID_FLD]);
int intProBinID = Convert.ToInt32(dtLocBin.Rows[0][MST_BINTable.BINID_FLD]);
//3.Scan DataTable
foreach (DataRow dataRow in dtBomDetail.Rows)
{
//3.1.Set value to voTransactionHistory
MST_TransactionHistoryVO voTransactionHistory = new MST_TransactionHistoryVO();
voTransactionHistory.TransDate = new UtilsBO().GetDBDate();
voTransactionHistory.TranTypeID = new MST_TranTypeDS().GetTranTypeID(TransactionTypeEnum.IVMiscellaneousIssue.ToString());
voTransactionHistory.InspStatus = new MST_TranTypeDS().GetTranTypeID(TransactionTypeEnum.POReturnToVendor.ToString());
voTransactionHistory.ProductID = (int) dataRow[ITM_BOMTable.COMPONENTID_FLD];
voTransactionHistory.CCNID = pobjPO_ReturnToVendorMasterVO.CCNID;
voTransactionHistory.PostDate = pobjPO_ReturnToVendorMasterVO.PostDate;
voTransactionHistory.RefMasterID = pobjPO_ReturnToVendorMasterVO.ReturnToVendorMasterID;
try
{
voTransactionHistory.RefDetailID = (int)drowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.RETURNTOVENDORDETAILID_FLD];
}
catch{}
voTransactionHistory.Quantity = (decimal)drowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.QUANTITY_FLD]*(decimal)dataRow[ITM_BOMTable.QUANTITY_FLD];
decimal decQuantity = voTransactionHistory.Quantity;
voTransactionHistory.MasterLocationID = pobjPO_ReturnToVendorMasterVO.MasterLocationID;
voTransactionHistory.LocationID = intProLocationID;
voTransactionHistory.BinID = intProBinID;
//3.2.Update Inventory
//
new InventoryUtilsBO().UpdateAddOHQuantity(voTransactionHistory.CCNID,
voTransactionHistory.MasterLocationID,
voTransactionHistory.LocationID,
voTransactionHistory.BinID,
voTransactionHistory.ProductID,
decQuantity,
string.Empty,
string.Empty);
//3.3.Update TransactionHistory
new InventoryUtilsBO().SaveTransactionHistory(TransactionTypeEnum.IVMiscellaneousIssue.ToString(), (int) PurposeEnum.ReturnToVendor, voTransactionHistory);
}
}
#endregion
}
}
private void UpdateIVBinCache(DataRow pdrowReturnedGoodsDetail,bool blnNewReturnedGood, PO_ReturnToVendorMasterVO pobjPO_ReturnToVendorMasterVO)
{
if (blnNewReturnedGood && pdrowReturnedGoodsDetail.RowState == DataRowState.Deleted)
return;
IV_BinCacheDS objIV_BinCacheDS = new IV_BinCacheDS();
bool blnHasProductID = objIV_BinCacheDS.HasProductID(int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString()),
pobjPO_ReturnToVendorMasterVO.CCNID,
pobjPO_ReturnToVendorMasterVO.MasterLocationID,
int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString()),
int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.BINID_FLD].ToString()));
//Initialize the VO for the MasLocCache object
IV_BinCacheVO objIV_BinCacheVO = new IV_BinCacheVO();
objIV_BinCacheVO.ProductID = int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString());
objIV_BinCacheVO.MasterLocationID = pobjPO_ReturnToVendorMasterVO.MasterLocationID;
objIV_BinCacheVO.CCNID = pobjPO_ReturnToVendorMasterVO.CCNID;
objIV_BinCacheVO.LocationID = int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString());
objIV_BinCacheVO.BinID = int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.BINID_FLD].ToString());
if (blnNewReturnedGood)
objIV_BinCacheVO.OHQuantity = Decimal.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.QUANTITY_FLD].ToString()) * (-1);
if (blnHasProductID)
objIV_BinCacheDS.UpdateReturnedGoods(objIV_BinCacheVO);
else
objIV_BinCacheDS.AddReturnedGoods(objIV_BinCacheVO);
}
private void UpdateIVLocationCache(DataRow pdrowReturnedGoodsDetail,bool blnNewReturnedGood, PO_ReturnToVendorMasterVO pobjPO_ReturnToVendorMasterVO)
{
if (blnNewReturnedGood && pdrowReturnedGoodsDetail.RowState == DataRowState.Deleted)
return;
IV_LocationCacheDS objIV_LocationCacheDS = new IV_LocationCacheDS();
bool blnHasProductID = objIV_LocationCacheDS.HasProductID(int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString()),
pobjPO_ReturnToVendorMasterVO.CCNID,
pobjPO_ReturnToVendorMasterVO.MasterLocationID,
int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString()));
//Initialize the VO for the MasLocCache object
IV_LocationCacheVO objIV_LocationCacheVO = new IV_LocationCacheVO();
objIV_LocationCacheVO.ProductID = int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString());
objIV_LocationCacheVO.MasterLocationID = pobjPO_ReturnToVendorMasterVO.MasterLocationID;
objIV_LocationCacheVO.CCNID = pobjPO_ReturnToVendorMasterVO.CCNID;
objIV_LocationCacheVO.LocationID = int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.LOCATIONID_FLD].ToString());
//first we implement the case of totally adding new returned goods record
//incase of updating an existing returned goods record
//according to Mr.Nguyen Manh Cuong ==> Implement later ==> because it is very very complicated
if (blnNewReturnedGood)
objIV_LocationCacheVO.OHQuantity = Decimal.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.QUANTITY_FLD].ToString()) * (-1);
if (blnHasProductID)
objIV_LocationCacheDS.UpdateReturnedGoods(objIV_LocationCacheVO);
else
objIV_LocationCacheDS.AddReturnedGoods(objIV_LocationCacheVO);
}
private void UpdateIVMasterLocationCache(DataRow pdrowReturnedGoodsDetail,bool blnNewReturnedGood, PO_ReturnToVendorMasterVO pobjPO_ReturnToVendorMasterVO)
{
if (blnNewReturnedGood && pdrowReturnedGoodsDetail.RowState == DataRowState.Deleted)
return;
IV_MasLocCacheDS objIV_MasLocCacheDS = new IV_MasLocCacheDS();
bool blnHasProductID = objIV_MasLocCacheDS.HasProductID(int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString()),
pobjPO_ReturnToVendorMasterVO.CCNID,
pobjPO_ReturnToVendorMasterVO.MasterLocationID);
//Initialize the VO for the MasLocCache object
IV_MasLocCacheVO objIV_MasLocCacheVO = new IV_MasLocCacheVO();
objIV_MasLocCacheVO.ProductID = int.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.PRODUCTID_FLD].ToString());
objIV_MasLocCacheVO.MasterLocationID = pobjPO_ReturnToVendorMasterVO.MasterLocationID;
objIV_MasLocCacheVO.CCNID = pobjPO_ReturnToVendorMasterVO.CCNID;
//objIV_MasLocCacheVO.AVGCost = (float)pintAVGCost;
//first we implement the case of totally adding new returned goods record
//incase of updating an existing returned goods record
//according to Mr.Nguyen Manh Cuong ==> Implement later ==> because it is very very complicated
if (blnNewReturnedGood)
objIV_MasLocCacheVO.OHQuantity = Decimal.Parse(pdrowReturnedGoodsDetail[PO_ReturnToVendorDetailTable.QUANTITY_FLD].ToString()) * (-1);
if (blnHasProductID)
objIV_MasLocCacheDS.UpdateReturnedGoods(objIV_MasLocCacheVO);
else
objIV_MasLocCacheDS.AddReturnedGoods(objIV_MasLocCacheVO);
}
public void DeleteReturnToVendor(int printReturnToVendorMasterID)
{
#region 1. Variable
InventoryUtilsBO boInventory = new InventoryUtilsBO();
PO_ReturnToVendorMasterDS RTVMasterDS = new PO_ReturnToVendorMasterDS();
PO_ReturnToVendorDetailDS RTVDetailDS = new PO_ReturnToVendorDetailDS();
MST_TransactionHistoryDS TransactionDS = new MST_TransactionHistoryDS();
DataSet dsRTVDetail = null;
PO_ReturnToVendorMasterVO voRTVMaster = new PO_ReturnToVendorMasterVO();
#endregion
#region 2. Get Master Infomation
voRTVMaster = (PO_ReturnToVendorMasterVO) RTVMasterDS.GetObjectVORTV(printReturnToVendorMasterID);
if (voRTVMaster == null)
{
return;
}
#endregion
#region 3. Get Detail Infomation
dsRTVDetail = RTVDetailDS.ListReturnToVendorDetail(voRTVMaster.ReturnToVendorMasterID);
#endregion
#region 4. Update Inventory
foreach (DataRow drow in dsRTVDetail.Tables[0].Rows)
{
//4.0 Variable
int LocationID = (int)drow[PO_ReturnToVendorDetailTable.LOCATIONID_FLD];
int BinID = (int)drow[PO_ReturnToVendorDetailTable.BINID_FLD];
int ProductionID = (int)drow[PO_ReturnToVendorDetailTable.PRODUCTID_FLD];
decimal decQuantity = (decimal) drow[PO_ReturnToVendorDetailTable.QUANTITY_FLD];
//4.1 Update Add Item in Detail
boInventory.UpdateAddOHQuantity(voRTVMaster.CCNID,voRTVMaster.MasterLocationID,LocationID,BinID,ProductionID,decQuantity,null,null);
#region 4.2. Update Substract Bom Item
if (voRTVMaster.ProductionLineId > 0)
{
//4.2.1.Get BomDetail by ProductID
DataTable dtBomDetail = new ITM_BOMDS().ListBomDetailOfProduct((int) drow[ITM_ProductTable.PRODUCTID_FLD]);
if (dtBomDetail.Rows.Count <=0)
{
return;
}
//4.2.2.Get LocationID and BinID by ProductionLineID
DataTable dtLocBin = new PO_ReturnToVendorMasterDS().GetLocationBin(voRTVMaster.ProductionLineId);
int intProLocationID = Convert.ToInt32(dtLocBin.Rows[0][MST_BINTable.LOCATIONID_FLD]);
int intProBinID = Convert.ToInt32(dtLocBin.Rows[0][MST_BINTable.BINID_FLD]);
//4.2.3.Scan DataTable
foreach (DataRow dataRow in dtBomDetail.Rows)
{
int intBomProductionID = (int) dataRow[ITM_BOMTable.COMPONENTID_FLD];
decimal decBomQuantity = (decimal)drow[PO_ReturnToVendorDetailTable.QUANTITY_FLD]*(decimal)dataRow[ITM_BOMTable.QUANTITY_FLD];
new InventoryUtilsBO().UpdateSubtractOHQuantity(voRTVMaster.CCNID,
voRTVMaster.MasterLocationID,
intProLocationID,
intProBinID,
intBomProductionID,
decBomQuantity,
string.Empty,
string.Empty);
}
}
#endregion
}
#endregion
#region 5. Update TransactionHistory
int OldTranTypeIDBom = new MST_TranTypeDS().GetTranTypeID(TransactionTypeEnum.IVMiscellaneousIssue.ToString());
int OldTranTypeIDDetail = new MST_TranTypeDS().GetTranTypeID(TransactionTypeEnum.POReturnToVendor.ToString());
int InspStatus=12;
//5.1 Update TransactionHistory by Item detail
TransactionDS.UpdateTranType(voRTVMaster.ReturnToVendorMasterID,OldTranTypeIDDetail,(int)TransactionTypeEnum.DeleteTransaction,InspStatus);
//5.2 Update TransactionHistory by Bom Item
TransactionDS.UpdateTranType(voRTVMaster.ReturnToVendorMasterID,OldTranTypeIDBom,(int)TransactionTypeEnum.DeleteTransaction,InspStatus);
#endregion
#region 6. Delete ReturnToVendor
RTVMasterDS.DeleteReturnToVendor(voRTVMaster.ReturnToVendorMasterID);
#endregion
}
}
}
| |
// Copyright 2020 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
//
// 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 CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example fetches the set of valid ProductBiddingCategories.
/// </summary>
public class GetProductBiddingCategoryConstant : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="GetProductBiddingCategoryConstant"/>
/// example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
return 0;
});
GetProductBiddingCategoryConstant codeExample = new GetProductBiddingCategoryConstant();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId);
}
/// <summary>
/// Node that tracks a product bidding category's id, name, and child nodes.
/// </summary>
public class CategoryNode
{
/// <summary>
/// The resource name of the category.
/// </summary>
public string ResourceName
{
get;
private set;
}
/// <summary>
/// Gets or sets the localized name of the category.
/// </summary>
public string LocalizedName
{
get;
set;
}
/// <summary>
/// Gets the list of child.
/// </summary>
public List<CategoryNode> Children
{
get;
} = new List<CategoryNode>();
/// <summary>
/// Constructor for categories first encountered as non-parent elements in the results.
/// </summary>
/// <param name="resourceName">The resource name of the category.</param>
/// <param name="localizedName">The name of the category.</param>
public CategoryNode(string resourceName, string localizedName)
{
if (string.IsNullOrEmpty(resourceName))
{
throw new ArgumentNullException();
}
this.ResourceName = resourceName;
this.LocalizedName = localizedName;
}
/// <summary>
/// Constructor for categories first encountered as a parent category, in which case
/// only the ID is available.
/// </summary>
/// <param name="resourceName">The resource name of the category.</param>
public CategoryNode(string resourceName) : this(resourceName, null) { }
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example fetches the set of valid ProductBiddingCategories.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
public void Run(GoogleAdsClient client, long customerId)
{
// Get the GoogleAdsServiceClient .
GoogleAdsServiceClient googleAdsService =
client.GetService(Services.V10.GoogleAdsService);
// Creates the query.
string query = "SELECT product_bidding_category_constant.localized_name, " +
"product_bidding_category_constant.product_bidding_category_constant_parent " +
"FROM product_bidding_category_constant WHERE " +
"product_bidding_category_constant.country_code IN ('US') ORDER BY " +
"product_bidding_category_constant.localized_name ASC";
// Creates the request.
SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
{
CustomerId = customerId.ToString(),
Query = query
};
// Creates a list of top level category nodes.
List<CategoryNode> rootCategories = new List<CategoryNode>();
// Creates a map of category ID to category node for all categories found in the
// results.
// This Map is a convenience lookup to enable fast retrieval of existing nodes.
Dictionary<string, CategoryNode> biddingCategories =
new Dictionary<string, CategoryNode>();
try
{
// Performs the search request.
foreach (GoogleAdsRow googleAdsRow in googleAdsService.Search(request))
{
ProductBiddingCategoryConstant productBiddingCategory =
googleAdsRow.ProductBiddingCategoryConstant;
string localizedName = productBiddingCategory.LocalizedName;
string resourceName = productBiddingCategory.ResourceName;
CategoryNode node = null;
if (biddingCategories.ContainsKey(resourceName))
{
node = biddingCategories[resourceName];
}
else
{
node = new CategoryNode(resourceName, localizedName);
biddingCategories[resourceName] = node;
}
if (string.IsNullOrEmpty(node.LocalizedName))
{
// Ensures that the name attribute for the node is set. Name will be null for
//nodes added to biddingCategories as a result of being a parentNode below.
node.LocalizedName = localizedName;
}
if (!string.IsNullOrEmpty(
productBiddingCategory.ProductBiddingCategoryConstantParent))
{
string parentResourceName =
productBiddingCategory.ProductBiddingCategoryConstantParent;
CategoryNode parentNode = null;
if (biddingCategories.ContainsKey(parentResourceName))
{
parentNode = biddingCategories[parentResourceName];
}
else
{
parentNode = new CategoryNode(parentResourceName);
biddingCategories[parentResourceName] = parentNode;
}
parentNode.Children.Add(node);
}
else
{
rootCategories.Add(node);
}
}
DisplayCategories(rootCategories, "");
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Recursively prints out each category node and its children.
/// </summary>
/// <param name="categories">The categories to print.</param>
/// <param name="prefix">The string to print at the beginning of each line of output.
/// </param>
private static void DisplayCategories(IEnumerable<CategoryNode> categories,
string prefix)
{
foreach (CategoryNode category in categories)
{
Console.WriteLine($"{prefix}{category.LocalizedName}" +
$" [{category.ResourceName}]");
DisplayCategories(category.Children, $"{prefix}{category.LocalizedName} > ");
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Text;
using log4net;
using WaterOneFlowImpl;
namespace WaterOneFlow.odws
{
using CuahsiBuilder = WaterOneFlowImpl.v1_0.CuahsiBuilder;
using WaterOneFlow.Schema.v1;
using WaterOneFlow.odm.v1_1;
using ValuesDataSetTableAdapters = WaterOneFlow.odm.v1_1.ValuesDataSetTableAdapters;
using DataValuesTableAdapter = WaterOneFlow.odm.v1_1.ValuesDataSetTableAdapters.DataValuesTableAdapter;
using unitsDatasetTableAdapters = WaterOneFlow.odm.v1_1.ValuesDataSetTableAdapters.UnitsTableAdapter;
using UnitsTableAdapter = WaterOneFlow.odm.v1_1.ValuesDataSetTableAdapters.UnitsTableAdapter;
using QualifiersTableAdapter = WaterOneFlow.odm.v1_1.ValuesDataSetTableAdapters.QualifiersTableAdapter;
using VariablesDataset = WaterOneFlow.odm.v1_1.VariablesDataset;
// <summary>
/// Summary description for ODValues
/// </summary>
public class ODValues
{
private static readonly ILog log = LogManager.GetLogger(typeof(ODValues));
public ODValues()
{
//
// TODO: Add constructor logic here
//
}
#region odm 1 series based
public static ValuesDataSet GetValuesDataSet(int siteID)
{
ValuesDataSet ds = basicValuesDataSet();
ValuesDataSetTableAdapters.DataValuesTableAdapter valuesTableAdapter = new DataValuesTableAdapter();
valuesTableAdapter.Connection.ConnectionString = Config.ODDB();
try
{
valuesTableAdapter.FillBySiteID(ds.DataValues, siteID);
}
catch (Exception e)
{
log.Fatal("Cannot retrieve information from database: " + e.Message); //+ valuesTableAdapter.Connection.DataSource
}
return ds;
}
public static ValuesDataSet GetValuesDataSet(int? siteID, int? VariableID)
{
ValuesDataSet ds = basicValuesDataSet();
if (!siteID.HasValue || !VariableID.HasValue) return ds;
ValuesDataSetTableAdapters.DataValuesTableAdapter valuesTableAdapter = new DataValuesTableAdapter();
valuesTableAdapter.Connection.ConnectionString = Config.ODDB();
valuesTableAdapter.FillBySiteIDVariableID(ds.DataValues, siteID.Value, VariableID.Value);
return ds;
}
public static ValuesDataSet GetValuesDataSet(int? siteID, int? VariableID, W3CDateTime BeginDateTime, W3CDateTime EndDateTime)
{
ValuesDataSet ds = basicValuesDataSet();
if (!siteID.HasValue || !VariableID.HasValue) return ds;
ValuesDataSetTableAdapters.DataValuesTableAdapter valuesTableAdapter = new DataValuesTableAdapter();
valuesTableAdapter.Connection.ConnectionString = Config.ODDB();
valuesTableAdapter.FillBySiteIdVariableIDBetweenDates(ds.DataValues, siteID.Value, VariableID.Value, BeginDateTime.DateTime, EndDateTime.DateTime);
return ds;
}
// never implemented or used. Now implemented as a filter using a passed variable parameter
//public static ValuesDataSet GetValueDataSet(int? siteID, int? VariableID, int? MethodID, int? SourceID, int? QualityControlLevelID, W3CDateTime BeginDateTime, W3CDateTime EndDateTime)
//{
// ValuesDataSet ds = basicValuesDataSet();
// if (!siteID.HasValue || !VariableID.HasValue) return ds;
// ValuesDataSetTableAdapters.DataValuesTableAdapter valuesTableAdapter = new DataValuesTableAdapter();
// valuesTableAdapter.Connection.ConnectionString = Config.ODDB();
// valuesTableAdapter.FillBySiteIdVariableIDBetweenDates(ds.DataValues, siteID.Value, VariableID.Value, BeginDateTime.DateTime, EndDateTime.DateTime);
// return ds;
//}
#endregion
// fills dataset with basic tables
private static ValuesDataSet basicValuesDataSet()
{
ValuesDataSet ds = new ValuesDataSet();
ValuesDataSetTableAdapters.UnitsTableAdapter unitsTableAdapter =
new UnitsTableAdapter();
unitsTableAdapter.Connection.ConnectionString = Config.ODDB();
ValuesDataSetTableAdapters.OffsetTypesTableAdapter offsetTypesTableAdapter =
new ValuesDataSetTableAdapters.OffsetTypesTableAdapter();
offsetTypesTableAdapter.Connection.ConnectionString = Config.ODDB();
ValuesDataSetTableAdapters.QualityControlLevelsTableAdapter qualityControlLevelsTableAdapter =
new ValuesDataSetTableAdapters.QualityControlLevelsTableAdapter();
qualityControlLevelsTableAdapter.Connection.ConnectionString = Config.ODDB();
ValuesDataSetTableAdapters.MethodsTableAdapter methodsTableAdapter =
new ValuesDataSetTableAdapters.MethodsTableAdapter();
methodsTableAdapter.Connection.ConnectionString = Config.ODDB();
ValuesDataSetTableAdapters.SamplesTableAdapter samplesTableAdapter =
new ValuesDataSetTableAdapters.SamplesTableAdapter();
samplesTableAdapter.Connection.ConnectionString = Config.ODDB();
ValuesDataSetTableAdapters.SourcesTableAdapter sourcesTableAdapter =
new ValuesDataSetTableAdapters.SourcesTableAdapter();
sourcesTableAdapter.Connection.ConnectionString = Config.ODDB();
QualifiersTableAdapter qualifiersTableAdapter =
new QualifiersTableAdapter();
qualifiersTableAdapter.Connection.ConnectionString = Config.ODDB();
unitsTableAdapter.Fill(ds.Units);
offsetTypesTableAdapter.Fill(ds.OffsetTypes);
qualityControlLevelsTableAdapter.Fill(ds.QualityControlLevels);
methodsTableAdapter.Fill(ds.Methods);
samplesTableAdapter.Fill(ds.Samples);
sourcesTableAdapter.Fill(ds.Sources);
qualifiersTableAdapter.Fill(ds.Qualifiers);
return ds;
}
/// <summary>
/// DataValue creation. Converts a ValuesDataSet to the XML schema ValueSingleVariable
/// If variable is null, it will return all
/// If variable has extra options (variable:code/Value=Key/Value=Key)
///
/// </summary>
/// <param name="ds">Dataset that you want converted</param>
/// <param name="variable">Variable that you want to use to place limits on the returned data</param>
/// <returns></returns>
public static List<ValueSingleVariable> dataset2ValuesList(ValuesDataSet ds, VariableParam variable)
{
List<ValueSingleVariable> tsTypeList = new List<ValueSingleVariable>();
/* logic
* if there is a variable that has options, then get a set of datarows
* using a select clause
* use an enumerator, since it is generic
* */
IEnumerator dataValuesEnumerator ;
ValuesDataSet.DataValuesRow[] dvRows; // if we find options, we need to use this.
String select = OdValuesCommon.CreateValuesWhereClause(variable, null);
if (select.Length > 0)
{
dvRows = (ValuesDataSet.DataValuesRow[])ds.DataValues.Select(select.ToString());
dataValuesEnumerator = dvRows.GetEnumerator();
}
else
{
dataValuesEnumerator = ds.DataValues.GetEnumerator();
}
// foreach (ValuesDataSet.DataValuesRow aRow in ds.DataValues){
while (dataValuesEnumerator.MoveNext())
{
ValuesDataSet.DataValuesRow aRow = (ValuesDataSet.DataValuesRow)dataValuesEnumerator.Current;
try
{
ValueSingleVariable tsTypeValue = new ValueSingleVariable();
#region DateTime Standard
tsTypeValue.dateTime = Convert.ToDateTime(aRow.DateTime);
//tsTypeValue.dateTimeSpecified = true;
DateTime temprealdate;
//<add key="returnUndefinedUTCorLocal" value="Undefined"/>
if (ConfigurationManager.AppSettings["returnUndefinedUTCorLocal"].Equals("Undefined"))
{
temprealdate = Convert.ToDateTime(aRow.DateTime); // not time zone shift
}
else if (ConfigurationManager.AppSettings["returnUndefinedUTCorLocal"].Equals("Local"))
{
TimeSpan zone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
Double offset = Convert.ToDouble(aRow.UTCOffset);
if (zone.TotalHours.Equals(offset))
{
// zone is the same as server. Shift
temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTime), DateTimeKind.Local);
}
else
{
//// zone is not the same. Output in UTC.
//temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTime), DateTimeKind.Utc);
//// correct time with shift.
//temprealdate = temprealdate.AddHours(offset);
// just use the DateTime UTC
temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTimeUTC), DateTimeKind.Utc);
}
}
else if (ConfigurationManager.AppSettings["returnUndefinedUTCorLocal"].Equals("UTC"))
{
temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTimeUTC), DateTimeKind.Utc);
}
else
{
temprealdate = Convert.ToDateTime(aRow.DateTime); // not time zone shift
}
temprealdate = Convert.ToDateTime(aRow.DateTime); // not time zone shift
#endregion
#region DateTimeOffset Failed
/// using XML overrides
// Attemp to use DateTimeOffset in xml Schema
//TimeSpan zone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
//Double offset = Convert.ToDouble(aRow.UTCOffset);
//DateTimeOffset temprealdate;
//temprealdate = new DateTimeOffset(Convert.ToDateTime(aRow.DateTime),
// new TimeSpan(Convert.ToInt32(offset),0,0));
//DateTimeOffset temprealdate;
//temprealdate = new DateTimeOffset(Convert.ToDateTime(aRow.DateTime),
// new TimeSpan(Convert.ToInt32(offset), 0, 0));
//tsTypeValue.dateTime = temprealdate;
//tsTypeValue.dateTimeSpecified = true;
#endregion
//tsTypeValue.censored = string.Empty;
if (string.IsNullOrEmpty(aRow.Value.ToString()))
continue;
else
tsTypeValue.Value = Convert.ToDecimal(aRow.Value);
try
{
tsTypeValue.censorCode = (CensorCodeEnum)Enum.Parse(typeof(CensorCodeEnum), aRow.CensorCode, true);
tsTypeValue.censorCodeSpecified = true;
if (!aRow.IsOffsetTypeIDNull())
{
tsTypeValue.offsetTypeID = aRow.OffsetTypeID;
tsTypeValue.offsetTypeIDSpecified = true;
// enabled to fix issue with hydroobjects
ValuesDataSet.OffsetTypesRow off = ds.OffsetTypes.FindByOffsetTypeID(aRow.OffsetTypeID);
ValuesDataSet.UnitsRow offUnit = ds.Units.FindByUnitsID(off.OffsetUnitsID);
tsTypeValue.offsetUnitsCode = offUnit.UnitsID.ToString();
tsTypeValue.offsetUnitsAbbreviation = offUnit.UnitsAbbreviation;
}
// offset value may be separate from the units... anticpating changes for USGS
if (!aRow.IsOffsetValueNull())
{
tsTypeValue.offsetValue = aRow.OffsetValue;
tsTypeValue.offsetValueSpecified = true;
}
ValuesDataSet.MethodsRow meth = ds.Methods.FindByMethodID(aRow.MethodID);
tsTypeValue.methodID = aRow.MethodID;
tsTypeValue.methodIDSpecified = true;
if (!aRow.IsQualifierIDNull())
{
ValuesDataSet.QualifiersRow qual = ds.Qualifiers.FindByQualifierID(aRow.QualifierID);
if (qual != null)
{
tsTypeValue.qualifiers = qual.QualifierCode;
}
}
ValuesDataSet.QualityControlLevelsRow qcl =
ds.QualityControlLevels.FindByQualityControlLevelID(aRow.QualityControlLevelID);
string qlName = qcl.Definition.Replace(" ", "");
if (Enum.IsDefined(typeof(QualityControlLevelEnum), qlName))
{
tsTypeValue.qualityControlLevel = (QualityControlLevelEnum)
Enum.Parse(
typeof(QualityControlLevelEnum), qlName, true);
if (tsTypeValue.qualityControlLevel != QualityControlLevelEnum.Unknown){
tsTypeValue.qualityControlLevelSpecified = true;
}
}
//}
tsTypeValue.sourceID = aRow.SourceID;
tsTypeValue.sourceIDSpecified = true;
if (!aRow.IsSampleIDNull())
{
tsTypeValue.sampleID = aRow.SampleID;
tsTypeValue.sampleIDSpecified = true;
}
}
catch (Exception e)
{
log.Debug("Error generating a value " + e.Message);
// non fatal exceptions
}
tsTypeList.Add(tsTypeValue);
}
catch (Exception e)
{
// ignore any value errors
}
}
return tsTypeList;
}
public static void addCategoricalInformation( List<ValueSingleVariable> variables, int variableID, VariablesDataset vds)
{
foreach (ValueSingleVariable variable in variables)
{
string selectquery = String.Format("VariableID = {0} AND DataValue = {1}", variableID.ToString(),
variable.Value);
DataRow[] rows = vds.Categories.Select(selectquery);
if (rows.Length >0 )
{
variable.codedVocabulary = true;
variable.codedVocabularySpecified = true;
variable.codedVocabularyTerm = (string)rows[0]["CategoryDescription"];
}
}
}
/// <summary>
/// Method to generate a list of qualifiers in a ValuesDataSet
/// This is done as a separate method since Values can could contain other VariableValue Types
///
/// </summary>
/// <param name="ds">ValuesDataSet with the values used in the timeSeries</param>
/// <returns></returns>
public static List<qualifier> datasetQualifiers(ValuesDataSet ds)
{
/* generate a list
* create a distinct DataSet
* - new data view
* - set filter (no nulls)
* - use toTable with unique to get unique list
* foreach to generate qualifiers
* */
List<qualifier> qualifiers = new List<qualifier>();
try
{
DataView qview = new DataView(ds.DataValues);
qview.RowFilter = "QualifierID is not Null";
DataTable qids = qview.ToTable("qualifiers", true, new string[] { "QualifierID" });
foreach (DataRow q in qids.Rows)
{
try
{
Object qid = q["QualifierID"];
ValuesDataSet.QualifiersRow qual = ds.Qualifiers.FindByQualifierID((int)qid);
if (qual != null)
{
qualifier qt = new qualifier();
qt.qualifierID = qual.QualifierID.ToString();
if (!qual.IsQualifierCodeNull()) qt.qualifierCode = qual.QualifierCode;
if (!String.IsNullOrEmpty(qual.QualifierDescription)) qt.Value = qual.QualifierDescription;
qualifiers.Add(qt);
}
}
catch (Exception e)
{
log.Error("Error generating a qualifier " + q.ToString() + e.Message);
}
}
return qualifiers;
}
catch (Exception e)
{
log.Error("Error generating a qualifiers " + e.Message);
// non fatal exceptions
return null;
}
}
/// <summary>
/// Method to generate a list of qualifiers in a ValuesDataSet
/// This is done as a separate method since Values can could contain other VariableValue Types
///
/// </summary>
/// <param name="ds">ValuesDataSet with the values used in the timeSeries</param>
/// <returns></returns>
public static List<MethodType> datasetMethods(ValuesDataSet ds)
{
/* generate a list
* create a distinct DataSet
* - new data view
* - set filter (no nulls)
* - use toTable with unique to get unique list
* foreach to generate qualifiers
* */
string COLUMN = "MethodID";
string TABLENAME = "methods";
List<MethodType> list = new List<MethodType>();
try
{
DataView view = new DataView(ds.DataValues);
view.RowFilter = COLUMN + " is not Null";
DataTable ids = view.ToTable(TABLENAME, true, new string[] { COLUMN });
foreach (DataRow r in ids.Rows)
{
try
{
Object aId = r[COLUMN];
// edit here
ValuesDataSet.MethodsRow method = ds.Methods.FindByMethodID((int)aId);
if (method != null)
{
MethodType t = new MethodType();
t.methodID = method.MethodID;
t.methodIDSpecified = true;
if (!String.IsNullOrEmpty(method.MethodDescription)) t.MethodDescription = method.MethodDescription;
if (!method.IsMethodLinkNull()) t.MethodLink = method.MethodLink;
list.Add(t);
}
}
catch (Exception e)
{
log.Error("Error generating a qualifier " + r.ToString() + e.Message);
}
}
return list;
}
catch (Exception e)
{
log.Error("Error generating a qualifiers " + e.Message);
// non fatal exceptions
return null;
}
}
/// <summary>
/// Method to generate a list of Sources in a ValuesDataSet
/// This is done as a separate method since Values can could contain other VariableValue Types
///
/// </summary>
/// <param name="ds">ValuesDataSet with the values used in the timeSeries</param>
/// <returns></returns>
public static List<SourceType> datasetSources(ValuesDataSet ds)
{
/* generate a list
* create a distinct DataSet
* - new data view
* - set filter (no nulls)
* - use toTable with unique to get unique list
* foreach to generate qualifiers
* */
string COLUMN = "SourceID";
string TABLENAME = "sources";
List<SourceType> list = new List<SourceType>();
try
{
DataView view = new DataView(ds.DataValues);
view.RowFilter = COLUMN + " is not Null";
DataTable ids = view.ToTable(TABLENAME, true, new string[] { COLUMN });
foreach (DataRow r in ids.Rows)
{
try
{
Object aId = r[COLUMN];
// edit here
ValuesDataSet.SourcesRow source = ds.Sources.FindBySourceID((int)aId);
if (source != null)
{
SourceType t = new SourceType();
t.sourceID = source.SourceID;
t.sourceIDSpecified = true;
if (!String.IsNullOrEmpty(source.Organization)) t.Organization = source.Organization;
t.SourceDescription = source.SourceDescription;
if (!source.IsSourceLinkNull()) t.SourceLink = source.SourceLink;
// create a contact
// only one for now
ContactInformationType contact = new ContactInformationType();
contact.TypeOfContact = "main";
if (!String.IsNullOrEmpty(source.ContactName)) contact.ContactName = source.ContactName;
if (!String.IsNullOrEmpty(source.Email)) contact.Email = source.Email;
if (!String.IsNullOrEmpty(source.Phone)) contact.Phone = source.Phone;
StringBuilder address = new StringBuilder();
if (!String.IsNullOrEmpty(source.Address)) address.Append(source.Address + System.Environment.NewLine);
if (!String.IsNullOrEmpty(source.City)
&& !String.IsNullOrEmpty(source.State)
&& !String.IsNullOrEmpty(source.ZipCode))
address.AppendFormat(",{0}, {1} {2}", source.City, source.State, source.ZipCode);
contact.Address = address.ToString();
//ContactInformationType[] contacts = new ContactInformationType[1];
// contacts[0] = contact;
// t.ContactInformation = contacts;
t.ContactInformation = contact;
list.Add(t);
}
}
catch (Exception e)
{
log.Error("Error generating a qualifier " + r.ToString() + e.Message);
}
}
return list;
}
catch (Exception e)
{
log.Error("Error generating a qualifiers " + e.Message);
// non fatal exceptions
return null;
}
}
/// <summary>
/// Method to generate a list of offset (from OD OffsetTypes table) in a ValuesDataSet
/// This is done as a separate method since Values can could contain other VariableValue Types
///
/// </summary>
/// <param name="ds">ValuesDataSet with the values used in the timeSeries</param>
/// <returns></returns>
public static List<OffsetType> datasetOffsetTypes(ValuesDataSet ds)
{
/* generate a list
* create a distinct DataSet
* - new data view
* - set filter (no nulls)
* - use toTable with unique to get unique list
* foreach to generate qualifiers
* */
string COLUMN = "OffsetTypeID";
string TABLENAME = "offsetTypes";
List<OffsetType> list = new List<OffsetType>();
try
{
DataView view = new DataView(ds.DataValues);
view.RowFilter = COLUMN + " is not Null";
DataTable ids = view.ToTable(TABLENAME, true, new string[] { COLUMN });
foreach (DataRow r in ids.Rows)
{
try
{
Object aId = r[COLUMN];
// edit here
ValuesDataSet.OffsetTypesRow offset = ds.OffsetTypes.FindByOffsetTypeID((int)aId);
if (offset != null)
{
OffsetType t = new OffsetType();
t.offsetTypeID = offset.OffsetTypeID;
t.offsetTypeIDSpecified = true;
if (!String.IsNullOrEmpty(offset.OffsetDescription)) t.offsetDescription = offset.OffsetDescription;
ValuesDataSet.UnitsRow offUnit = ds.Units.FindByUnitsID(offset.OffsetUnitsID);
string offUnitsCode;
string offUnitsName = null;
string offUnitsAbbreviation = null;
if (!String.IsNullOrEmpty(offUnit.UnitsAbbreviation)) offUnitsAbbreviation = offUnit.UnitsAbbreviation;
if (!String.IsNullOrEmpty(offUnit.UnitsName)) offUnitsName = offUnit.UnitsName;
if (offUnit != null)
t.units = CuahsiBuilder.CreateUnitsElement(
null, offUnit.UnitsID.ToString(), offUnitsAbbreviation, offUnitsName);
list.Add(t);
}
}
catch (Exception e)
{
log.Error("Error generating a qualifier " + r.ToString() + e.Message);
}
}
return list;
}
catch (Exception e)
{
log.Error("Error generating a qualifiers " + e.Message);
// non fatal exceptions
return null;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a named parameter expression.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.ParameterExpressionProxy))]
public class ParameterExpression : Expression
{
private readonly string _name;
internal ParameterExpression(string name)
{
_name = name;
}
internal static ParameterExpression Make(Type type, string name, bool isByRef)
{
if (isByRef)
{
return new ByRefParameterExpression(type, name);
}
else
{
if (!type.GetTypeInfo().IsEnum)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean: return new PrimitiveParameterExpression<Boolean>(name);
case TypeCode.Byte: return new PrimitiveParameterExpression<Byte>(name);
case TypeCode.Char: return new PrimitiveParameterExpression<Char>(name);
case TypeCode.DateTime: return new PrimitiveParameterExpression<DateTime>(name);
case TypeCode.Decimal: return new PrimitiveParameterExpression<Decimal>(name);
case TypeCode.Double: return new PrimitiveParameterExpression<Double>(name);
case TypeCode.Int16: return new PrimitiveParameterExpression<Int16>(name);
case TypeCode.Int32: return new PrimitiveParameterExpression<Int32>(name);
case TypeCode.Int64: return new PrimitiveParameterExpression<Int64>(name);
case TypeCode.Object:
// common reference types which we optimize go here. Of course object is in
// the list, the others are driven by profiling of various workloads. This list
// should be kept short.
if (type == typeof(object))
{
return new ParameterExpression(name);
}
else if (type == typeof(Exception))
{
return new PrimitiveParameterExpression<Exception>(name);
}
else if (type == typeof(object[]))
{
return new PrimitiveParameterExpression<object[]>(name);
}
break;
case TypeCode.SByte: return new PrimitiveParameterExpression<SByte>(name);
case TypeCode.Single: return new PrimitiveParameterExpression<Single>(name);
case TypeCode.String: return new PrimitiveParameterExpression<String>(name);
case TypeCode.UInt16: return new PrimitiveParameterExpression<UInt16>(name);
case TypeCode.UInt32: return new PrimitiveParameterExpression<UInt32>(name);
case TypeCode.UInt64: return new PrimitiveParameterExpression<UInt64>(name);
}
}
}
return new TypedParameterExpression(type, name);
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type
{
get { return typeof(object); }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Parameter; }
}
/// <summary>
/// The Name of the parameter or variable.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Indicates that this ParameterExpression is to be treated as a ByRef parameter.
/// </summary>
public bool IsByRef
{
get
{
return GetIsByRef();
}
}
internal virtual bool GetIsByRef()
{
return false;
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitParameter(this);
}
}
/// <summary>
/// Specialized subclass to avoid holding onto the byref flag in a
/// parameter expression. This version always holds onto the expression
/// type explicitly and therefore derives from TypedParameterExpression.
/// </summary>
internal sealed class ByRefParameterExpression : TypedParameterExpression
{
internal ByRefParameterExpression(Type type, string name)
: base(type, name)
{
}
internal override bool GetIsByRef()
{
return true;
}
}
/// <summary>
/// Specialized subclass which holds onto the type of the expression for
/// uncommon types.
/// </summary>
internal class TypedParameterExpression : ParameterExpression
{
private readonly Type _paramType;
internal TypedParameterExpression(Type type, string name)
: base(name)
{
_paramType = type;
}
public sealed override Type Type
{
get { return _paramType; }
}
}
/// <summary>
/// Generic type to avoid needing explicit storage for primitive data types
/// which are commonly used.
/// </summary>
internal sealed class PrimitiveParameterExpression<T> : ParameterExpression
{
internal PrimitiveParameterExpression(string name)
: base(name)
{
}
public sealed override Type Type
{
get { return typeof(T); }
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
/// </summary>
/// <param name="type">The type of the parameter or variable.</param>
/// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
public static ParameterExpression Parameter(Type type)
{
return Parameter(type, null);
}
/// <summary>
/// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
/// </summary>
/// <param name="type">The type of the parameter or variable.</param>
/// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
public static ParameterExpression Variable(Type type)
{
return Variable(type, null);
}
/// <summary>
/// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
/// </summary>
/// <param name="type">The type of the parameter or variable.</param>
/// <param name="name">The name of the parameter or variable, used for debugging or pretty printing purpose only.</param>
/// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
public static ParameterExpression Parameter(Type type, string name)
{
ContractUtils.RequiresNotNull(type, "type");
if (type == typeof(void))
{
throw Error.ArgumentCannotBeOfTypeVoid();
}
bool byref = type.IsByRef;
if (byref)
{
type = type.GetElementType();
}
return ParameterExpression.Make(type, name, byref);
}
/// <summary>
/// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
/// </summary>
/// <param name="type">The type of the parameter or variable.</param>
/// <param name="name">The name of the parameter or variable, used for debugging or pretty printing purpose only.</param>
/// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
public static ParameterExpression Variable(Type type, string name)
{
ContractUtils.RequiresNotNull(type, "type");
if (type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid();
if (type.IsByRef) throw Error.TypeMustNotBeByRef();
return ParameterExpression.Make(type, name, false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Security;
using System.Windows.Forms;
using Timer = System.Timers.Timer;
using IronAHK.Rusty.Common;
namespace IronAHK.Rusty
{
partial class Core
{
#region Delegates
/// <summary>
/// A function.
/// </summary>
/// <param name="args">Parameters.</param>
/// <returns>A value.</returns>
public delegate object GenericFunction(object[] args);
delegate void SimpleDelegate();
/// <summary>
///
/// </summary>
public static event EventHandler ApplicationExit;
#endregion
#region Error
[ThreadStatic]
static int error;
/// <summary>
/// Indicates the success or failure of a command.
/// </summary>
static public int ErrorLevel
{
get { return error; }
set { error = value; }
}
#endregion
#region Hooks
static Dictionary<string, object> variables;
static Dictionary<string, Keyboard.HotkeyDefinition> hotkeys;
static Dictionary<string, Keyboard.HotstringDefinition> hotstrings;
static GenericFunction keyCondition;
static Keyboard.KeyboardHook keyboardHook;
static bool suspended;
/// <summary>
/// Is the Script currently suspended?
/// </summary>
public static bool Suspended {
get { return suspended; }
}
[ThreadStatic]
static int? _KeyDelay;
[ThreadStatic]
static int? _KeyPressDuration;
[ThreadStatic]
static int? _MouseDelay;
[ThreadStatic]
static int? _DefaultMouseSpeed;
#endregion
#region Guis
[ThreadStatic]
static Form dialogOwner;
static Dictionary<long, ImageList> imageLists;
static Dictionary<string, Form> guis;
[ThreadStatic]
static string defaultGui;
static string DefaultGuiId
{
get { return defaultGui ?? "1"; }
set
{
defaultGui = value;
defaultTreeView = null;
}
}
static Form DefaultGui
{
get
{
if (guis == null)
return null;
string key = DefaultGuiId;
return guis.ContainsKey(key) ? guis[key] : null;
}
}
[ThreadStatic]
static long lastFoundForm = 0;
static long LastFoundForm
{
get
{
return lastFoundForm;
}
set
{
lastFoundForm = value;
}
}
[ThreadStatic]
static TreeView defaultTreeView;
static TreeView DefaultTreeView
{
get
{
if (defaultTreeView != null)
return defaultTreeView;
var gui = DefaultGui;
if (gui == null)
return null;
TreeView tv = null;
foreach (var control in gui.Controls)
if (control is TreeView)
tv = (TreeView)control;
return tv;
}
set { defaultTreeView = value; }
}
[ThreadStatic]
static ListView defaultListView;
static ListView DefaultListView
{
get
{
if (defaultListView != null)
return defaultListView;
var gui = DefaultGui;
if (gui == null)
return null;
ListView lv = null;
foreach (var control in gui.Controls)
if (control is ListView)
lv = (ListView)control;
return lv;
}
set { defaultListView = value; }
}
static StatusBar DefaultStatusBar
{
get
{
var gui = DefaultGui;
if (gui == null)
return null;
return ((GuiInfo)gui.Tag).StatusBar;
}
}
static NotifyIcon Tray;
#endregion
#region Dialogs
static Dictionary<int, ProgressDialog> progressDialgos;
static Dictionary<int, SplashDialog> splashDialogs;
#endregion
#region Tips
static ToolTip persistentTooltip;
static Form tooltip;
#endregion
#region RunAs
[ThreadStatic]
static string runUser;
[ThreadStatic]
static SecureString runPassword;
[ThreadStatic]
static string runDomain;
#endregion
#region Windows
[ThreadStatic]
static int? _ControlDelay;
[ThreadStatic]
static int? _WinDelay;
[ThreadStatic]
static bool? _DetectHiddenText;
[ThreadStatic]
static bool? _DetectHiddenWindows;
[ThreadStatic]
static int? _TitleMatchMode;
[ThreadStatic]
static bool? _TitleMatchModeSpeed;
#endregion
#region Strings
[ThreadStatic]
static StringComparison? _StringComparison;
[ThreadStatic]
static string _FormatNumeric;
[ThreadStatic]
static string _UserAgent;
#endregion
#region Misc
static Dictionary<string, Timer> timers;
static EventHandler onExit;
const int LoopFrequency = 50;
[ThreadStatic]
static Random randomGenerator;
#endregion
#region Coordmode
[ThreadStatic]
static CoordModes coords;
struct CoordModes
{
public CoordModeType Tooltip { get; set; }
public CoordModeType Pixel { get; set; }
public CoordModeType Mouse { get; set; }
public CoordModeType Caret { get; set; }
public CoordModeType Menu { get; set; }
}
enum CoordModeType
{
Relative = 0,
Screen
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.DataStructures;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis
{
public enum SourceLanguage { CSharp, VB }
#region ExpressionInPreState
public enum ExpressionInPreStateKind { MethodPrecondition, ObjectInvariant, Assume, Any, All = Assume, Bot = Any, Top = All }
public class ExpressionInPreStateInfo
{
public readonly bool hasAccessPath;
public readonly bool hasVariables;
public readonly bool hasOnlyImmutableVariables;
public ExpressionInPreStateKind kind { get; private set; }
public ExpressionInPreStateInfo(bool hasAccessPath, bool hasVariables, bool hasOnlyImmutableVariables, ExpressionInPreStateKind kind)
{
Contract.Ensures(this.kind == kind);
this.hasAccessPath = hasAccessPath;
this.hasVariables = hasVariables;
this.hasOnlyImmutableVariables = hasOnlyImmutableVariables;
this.kind = kind;
}
public ExpressionInPreStateInfo(ExpressionInPreStateKind kind, bool hasOnlyImmutableVariables = false)
: this(false, false, hasOnlyImmutableVariables, kind)
{ }
#region Combine
static public ExpressionInPreStateInfo Combine(ExpressionInPreStateInfo info1, ExpressionInPreStateInfo info2)
{
Contract.Requires(info1 != null);
Contract.Requires(info2 != null);
Contract.Ensures(Contract.Result<ExpressionInPreStateInfo>() != null);
ExpressionInPreStateKind kindResult = info1.kind.Join(info2.kind);
return new ExpressionInPreStateInfo(info1.hasAccessPath || info2.hasAccessPath, info1.hasVariables || info2.hasVariables, info1.hasOnlyImmutableVariables && info2.hasOnlyImmutableVariables, kindResult);
}
static public ExpressionInPreStateInfo Combine(ExpressionInPreStateInfo info1, ExpressionInPreStateInfo info2, ExpressionInPreStateInfo info3)
{
Contract.Requires(info1 != null);
Contract.Requires(info2 != null);
Contract.Requires(info3 != null);
Contract.Ensures(Contract.Result<ExpressionInPreStateInfo>() != null);
var tmp = Combine(info1, info2);
return Combine(tmp, info3);
}
#endregion
}
public enum ConditionKind
{
Requires,
ObjectInvariant,
EntryAssume,
CalleeAssume
}
[ContractClass(typeof(IInferredConditionContracts))]
public interface IInferredCondition
{
BoxedExpression Expr { get; }
ConditionKind Kind { get; }
bool IsSufficientForTheWarning { get; }
}
#region Contracts
[ContractClassFor(typeof(IInferredCondition))]
internal abstract class IInferredConditionContracts : IInferredCondition
{
public BoxedExpression Expr { get; private set; }
public ConditionKind Kind { get; private set; }
public bool IsSufficientForTheWarning { get; private set; }
[ContractInvariantMethod]
private void ContractInvariant()
{
Contract.Invariant(this.Expr != null);
}
}
#endregion
public class SimpleInferredConditionAtEntry : IInferredCondition
{
public BoxedExpression Expr { get; private set; }
public ConditionKind Kind { get; private set; }
public bool IsSufficientForTheWarning { get; private set; }
public SimpleInferredConditionAtEntry(BoxedExpression expr, ExpressionInPreStateKind kind, bool isSufficient)
{
this.Expr = expr;
this.Kind = kind.ToConditionKind();
this.IsSufficientForTheWarning = isSufficient;
}
[Pure]
public override string ToString()
{
return this.Expr != null ? this.Expr.ToString() : "null";
}
}
public class InferredCalleeCondition<Method> : IInferredCondition
{
public BoxedExpression Expr { get; private set; }
public Method Callee { get; private set; }
public APC CalleePC { get; private set; }
public InferredCalleeCondition(BoxedExpression expr, APC callePC, Method callee)
{
this.Expr = expr;
this.CalleePC = callePC;
this.Callee = callee;
}
public ConditionKind Kind
{
get { return ConditionKind.CalleeAssume; }
}
public bool IsSufficientForTheWarning
{
get { return false; }
}
}
public class InferredCalleeNecessaryConditionCandidate<Method> : IInferredCondition
{
public BoxedExpression Expr { get; private set; }
public Method Callee { get; private set; }
public APC CalleePC { get; private set; }
public InferredCalleeNecessaryConditionCandidate(BoxedExpression expr, APC callePC, Method callee)
{
Contract.Requires(expr != null);
this.Expr = expr;
this.CalleePC = callePC;
this.Callee = callee;
}
public ConditionKind Kind
{
get { return ConditionKind.CalleeAssume; }
}
public bool IsSufficientForTheWarning
{
get { return false; }
}
}
public class ExpressionInPreState : ExpressionInPreStateInfo
{
[ContractInvariantMethod]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
private void ObjectInvariant()
{
Contract.Invariant(this.expr != null);
}
public BoxedExpression expr { get; private set; }
public ExpressionInPreState(BoxedExpression expr, ExpressionInPreStateInfo info)
: base(info.hasAccessPath, info.hasVariables, info.hasOnlyImmutableVariables, info.kind)
{
Contract.Requires(expr != null);
Contract.Requires(info != null);
Contract.Ensures(this.kind == info.kind);
this.expr = expr;
}
[Pure]
public override string ToString()
{
return this.expr.ToString();
}
}
public class InferredConditions : List<IInferredCondition>
{
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(Contract.ForAll(this, pre => pre != null));
}
public InferredConditions(IEnumerable<IInferredCondition> collection)
: base(collection == null ? null : collection.Where(pre => pre != null))
{ }
#if false
public InferredPreconditions(IEnumerable<BoxedExpression> collection, ExpressionInPreStateKind kind, bool isSufficient)
: this(collection == null ? null : collection.Where(be => be != null).Select(be => new SimpleInferredPrecondition(be, kind, isSufficient)))
{ }
#endif
public bool HasASufficientCondition
{
get
{
return this.Any(c => c.IsSufficientForTheWarning);
}
}
public Set<WarningContext> PushToContractManager(ContractInferenceManager inferenceManager, bool addFalseEntryAssume, ProofObligation obl, ref ProofOutcome outcome, ILogOptions logOptions)
{
Contract.Requires(inferenceManager != null);
Contract.Requires(obl != null);
Contract.Requires(logOptions != null);
Contract.Ensures(Contract.Result<Set<WarningContext>>() != null);
IEnumerable<BoxedExpression> suggestedPreconditions, objectInvariants, entryAssumes;
IEnumerable<IInferredCondition> calleeAssumes;
this.Split(out suggestedPreconditions, out objectInvariants, out entryAssumes, out calleeAssumes);
if (addFalseEntryAssume)
{
entryAssumes = entryAssumes.Concat(new BoxedExpression[] { BoxedExpression.ConstFalse });
}
var entryOutcome = outcome;
var result = new Set<WarningContext>();
if (objectInvariants.Any())
{
outcome = inferenceManager.ObjectInvariant.AddObjectInvariants(obl, objectInvariants, logOptions.PropagateObjectInvariants
? (objectInvariants.Where(exp => this.IsSufficient(exp)).Any() ? ProofOutcome.True : outcome)
: outcome);
result.Add(new WarningContext(WarningContext.ContextType.InferredObjectInvariant, objectInvariants.Count()));
}
if (suggestedPreconditions.Any())
{
outcome = inferenceManager.AddPreconditionOrAssume(obl, suggestedPreconditions, logOptions.PropagateInferredRequires(true)
?
(suggestedPreconditions
.Where(exp => (entryOutcome != ProofOutcome.False || !exp.IsConstantFalse()) && this.IsSufficient(exp))
.Any() ? ProofOutcome.True : outcome)
:
outcome);
result.Add(new WarningContext(WarningContext.ContextType.InferredPrecondition, suggestedPreconditions.Count()));
}
if (entryAssumes.Any())
{
inferenceManager.Assumptions.AddEntryAssumes(obl, entryAssumes);
result.Add(new WarningContext(WarningContext.ContextType.InferredEntryAssume, entryAssumes.Count()));
}
if (calleeAssumes.Any())
{
var warningContexts = inferenceManager.Assumptions.AddCalleeAssumes(obl, calleeAssumes);
result.AddRange(warningContexts);
}
if (this.HasASufficientCondition && this.All(cond => !cond.Expr.IsConstantFalse()))
{
result.Add(new WarningContext(WarningContext.ContextType.InferredConditionIsSufficient));
}
if (this.Any(
cond =>
{
BinaryOperator bop; BoxedExpression dummy1, dummy2;
return cond.Expr.IsBinaryExpression(out bop, out dummy1, out dummy2) && bop == BinaryOperator.LogicalOr;
}))
{
result.Add(new WarningContext(WarningContext.ContextType.InferredConditionContainsDisjunction));
}
return result;
}
private void Split(
out IEnumerable<BoxedExpression> suggestedPreconditions,
out IEnumerable<BoxedExpression> objectInvariants,
out IEnumerable<BoxedExpression> entryAssumes,
out IEnumerable<IInferredCondition> calleeAssumes
)
{
Contract.Ensures(Contract.ValueAtReturn(out suggestedPreconditions) != null);
Contract.Ensures(Contract.ValueAtReturn(out objectInvariants) != null);
Contract.Ensures(Contract.ValueAtReturn(out entryAssumes) != null);
Contract.Ensures(Contract.ValueAtReturn(out calleeAssumes) != null);
Contract.Ensures(Contract.ForAll(Contract.ValueAtReturn(out suggestedPreconditions), be => be != null));
Contract.Ensures(Contract.ForAll(Contract.ValueAtReturn(out objectInvariants), be => be != null));
suggestedPreconditions = this.Where(cond => cond.Kind == ConditionKind.Requires).Select(cond => cond.Expr);
objectInvariants = this.Where(cond => cond.Kind == ConditionKind.ObjectInvariant).Select(cond => cond.Expr);
entryAssumes = this.Where(cond => cond.Kind == ConditionKind.EntryAssume).Select(cond => cond.Expr);
calleeAssumes = this.Where(cond => cond.Kind == ConditionKind.CalleeAssume);
}
public bool IsSufficient(BoxedExpression exp)
{
return exp != null && this.Where(pre => pre.Expr.Equals(exp)).Any(pre => pre.IsSufficientForTheWarning);
}
}
public static class ExpressionInPreStateExtensions
{
[Pure]
public static InferredConditions AsInferredPreconditions(this IEnumerable<IInferredCondition> collection)
{
Contract.Ensures(collection == null || Contract.Result<InferredConditions>() != null);
if (collection == null)
return null;
return new InferredConditions(collection);
}
[Pure]
public static InferredConditions AsInferredPreconditions(this IEnumerable<ExpressionInPreState> collection, bool isSufficient)
{
Contract.Requires(collection != null);
Contract.Ensures(Contract.Result<InferredConditions>() != null);
return new InferredConditions(collection.Select(expr => new SimpleInferredConditionAtEntry(expr.expr, expr.kind, isSufficient)));
}
/// <summary>kind1 is included in kind2 (normal domain leq)</summary>
[Pure]
static public bool IsIncludedIn(this ExpressionInPreStateKind kind1, ExpressionInPreStateKind kind2)
{
return (kind1 == ExpressionInPreStateKind.Any || kind2 == ExpressionInPreStateKind.Assume) || kind1 == kind2;
}
[Pure]
public static ExpressionInPreStateKind Join(this ExpressionInPreStateKind kind1, ExpressionInPreStateKind kind2)
{
if (kind1 == ExpressionInPreStateKind.Any) return kind2;
if (kind2 == ExpressionInPreStateKind.Any) return kind1;
if (kind2 == kind1) return kind1;
return ExpressionInPreStateKind.Assume;
}
[Pure]
public static ConditionKind ToConditionKind(this ExpressionInPreStateKind kind)
{
switch (kind)
{
case ExpressionInPreStateKind.Any:
case ExpressionInPreStateKind.MethodPrecondition:
return ConditionKind.Requires;
case ExpressionInPreStateKind.Assume:
return ConditionKind.EntryAssume;
case ExpressionInPreStateKind.ObjectInvariant:
return ConditionKind.ObjectInvariant;
default:
throw new NotImplementedException();
}
}
}
#endregion
public class PreconditionSuggestion
{
private class InvertComparison
{
private readonly bool tryInvert;
private bool hasBeenInverted;
public InvertComparison(bool tryInvert)
{
this.tryInvert = tryInvert;
}
public static InvertComparison NoInversion = new InvertComparison(false); // Thread-safe
public bool TryInvertComparison { get { return tryInvert; } }
public bool HasBeenInverted { get { return hasBeenInverted; } }
public void DischargeInversion()
{
if (tryInvert)
{
hasBeenInverted = true;
}
else
{
throw new InvalidOperationException("Can't invert what needs no inversion");
}
}
}
private class PreconditionTransformer<Local, Parameter, Method, Field, Property, Event, Expression, Type, Dest, Attribute, Assembly>
: IVisitValueExprIL<Expression, Type, Expression, Dest, InvertComparison, BoxedExpression>
where Type : IEquatable<Type>
{
private APC conditionPC;
private IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder;
private IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Dest> context;
private bool hasVariables;
public bool HasVariables { get { return hasVariables; } }
/// <summary>
/// </summary>
/// <param name="conditionPC">PC where condition is being asserted</param>
/// <param name="context"></param>
/// <param name="mdDecoder"></param>
public PreconditionTransformer(
APC conditionPC,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Dest> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder
)
{
this.conditionPC = conditionPC;
this.context = context;
this.mdDecoder = mdDecoder;
}
#region IVisitValueExprIL<Label,Type,Source,Dest,StringBuilder,bool> Members
public BoxedExpression Recurse(Expression expr)
{
return Recurse(expr, InvertComparison.NoInversion);
}
private BoxedExpression Recurse(Expression expr, InvertComparison tryInvert)
{
return context.ExpressionContext.Decode<InvertComparison, BoxedExpression, PreconditionTransformer<Local, Parameter, Method, Field, Property, Event, Expression, Type, Dest, Attribute, Assembly>>(expr, this, tryInvert);
}
public BoxedExpression SymbolicConstant(Expression pc, Dest symbol, InvertComparison tryInvert)
{
FList<PathElement> path = context.ValueContext.VisibleAccessPathListFromPre(context.MethodContext.CFG.EntryAfterRequires, symbol);
if (path != null)
{
hasVariables = true;
return BoxedExpression.Var(symbol, path);
}
path = context.ValueContext.VisibleAccessPathListFromPre(conditionPC, symbol);
if (path != null)
{
hasVariables = true;
return BoxedExpression.Var(symbol, path);
}
return null;
}
public BoxedExpression Binary(Expression pc, BinaryOperator op, Dest dest, Expression s1, Expression s2, InvertComparison tryInvert)
{
Contract.Assume(tryInvert != null);
BoxedExpression left = null;
var right = Recurse(s2);
if (right == null) return null;
switch (op)
{
case BinaryOperator.Ceq:
case BinaryOperator.Cobjeq:
if (context.ExpressionContext.IsZero(s2))
{
InvertComparison tryInvert2 = new InvertComparison(true);
BoxedExpression left2 = Recurse(s1, tryInvert2);
if (left2 == null) return null;
if (tryInvert2.HasBeenInverted)
{
// We know that left is a comparison. If outer wanted us to invert too, we cancel it here
if (tryInvert.TryInvertComparison)
{
left = Recurse(s1);
if (left == null) return null;
tryInvert.DischargeInversion();
return left;
}
return left2;
}
}
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
left = Recurse(s1);
if (left == null) return null;
return BoxedExpression.Binary(BinaryOperator.Cne_Un, left, right);
}
goto default;
case BinaryOperator.Cge:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Clt, left, right);
}
goto default;
case BinaryOperator.Cge_Un:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Clt_Un, left, right);
}
goto default;
case BinaryOperator.Cgt:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Cle, left, right);
}
goto default;
case BinaryOperator.Cgt_Un:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Cle_Un, left, right);
}
goto default;
case BinaryOperator.Cle:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Cgt, left, right);
}
goto default;
case BinaryOperator.Cle_Un:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Cgt_Un, left, right);
}
goto default;
case BinaryOperator.Clt:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Cge, left, right);
}
goto default;
case BinaryOperator.Clt_Un:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Cge_Un, left, right);
}
goto default;
case BinaryOperator.Cne_Un:
left = Recurse(s1);
if (left == null) return null;
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return BoxedExpression.Binary(BinaryOperator.Ceq, left, right);
}
goto default;
default:
if (left == null) left = Recurse(s1);
if (left == null) return null;
return BoxedExpression.Binary(op, left, right);
}
}
public BoxedExpression Isinst(Expression pc, Type type, Dest dest, Expression obj, InvertComparison data)
{
if (!mdDecoder.IsAsVisibleAs(type, context.MethodContext.CurrentMethod)) return null;
BoxedExpression arg = Recurse(obj);
if (arg == null) return null;
return ClousotExpression<Type>.MakeIsInst(type, arg);
}
public BoxedExpression Ldconst(Expression pc, object constant, Type type, Dest dest, InvertComparison data)
{
Contract.Assume(!mdDecoder.Equal(type, mdDecoder.System_Int32) || constant is Int32);
return BoxedExpression.Const(constant, type, mdDecoder);
}
public BoxedExpression Ldnull(Expression pc, Dest dest, InvertComparison data)
{
return BoxedExpression.Const(null, default(Type), mdDecoder);
}
public BoxedExpression Sizeof(Expression pc, Type type, Dest dest, InvertComparison data)
{
return ClousotExpression<Type>.MakeSizeOf(type, mdDecoder.TypeSize(type));
}
public BoxedExpression Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Dest dest, Expression source, InvertComparison data)
{
BoxedExpression arg = Recurse(source);
if (arg == null) return null;
return ClousotExpression<Type>.MakeUnary(op, arg);
}
public BoxedExpression Box(Expression pc, Type type, Dest dest, Expression source, InvertComparison data)
{
// TODO: once we have boxed expressions with Box, we can fill this in.
return null;
}
#endregion
}
private class ExpressionDecoder<Local, Parameter, Method, Field, Property, Event, Expression, Type, Dest, Attribute, Assembly>
: IVisitValueExprIL<Expression, Type, Expression, Dest, InvertComparison, string>
where Type : IEquatable<Type>
{
#region Object invariant
[ContractInvariantMethod]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
private void ObjectInvariant()
{
Contract.Invariant(mdDecoder != null);
Contract.Invariant(context != null);
}
#endregion
private readonly APC AtPC;
private readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder;
private readonly IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Dest> context;
public bool HasVariables;
public ExpressionDecoder(
APC atPC,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Dest> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder
)
{
Contract.Requires(context != null);
Contract.Requires(mdDecoder != null);
AtPC = atPC;
this.context = context;
this.mdDecoder = mdDecoder;
}
#region IVisitValueExprIL<Label,Type,Source,Dest,StringBuilder,bool> Members
private string Recurse(Expression expr)
{
return Recurse(expr, InvertComparison.NoInversion);
}
private string Recurse(Expression expr, InvertComparison tryInvert)
{
return context.ExpressionContext.Decode<InvertComparison, string, ExpressionDecoder<Local, Parameter, Method, Field, Property, Event, Expression, Type, Dest, Attribute, Assembly>>(expr, this, tryInvert);
}
public string SymbolicConstant(Expression pc, Dest symbol, InvertComparison tryInvert)
{
HasVariables = true;
string path = context.ValueContext.AccessPath(AtPC, symbol);
return path;
}
public string Binary(Expression pc, BinaryOperator op, Dest dest, Expression s1, Expression s2, InvertComparison tryInvert)
{
Contract.Assume(tryInvert != null);
string left = Recurse(s1);
if (left == null) return null;
string right = Recurse(s2);
if (right == null) return null;
switch (op)
{
case BinaryOperator.Add:
case BinaryOperator.Add_Ovf:
case BinaryOperator.Add_Ovf_Un:
return String.Format("({0} + {1})", left, right);
case BinaryOperator.And:
return String.Format("({0} & {1})", left, right);
case BinaryOperator.Ceq:
case BinaryOperator.Cobjeq:
if (right == "0")
{
InvertComparison tryInvert2 = new InvertComparison(true);
string left2 = Recurse(s1, tryInvert2);
if (tryInvert2.HasBeenInverted)
{
// We know that left is a comparison. If outer wanted us to invert too, we cancel it here
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return left;
}
return left2;
}
}
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return String.Format("({0} != {1})", left, right);
}
return String.Format("({0} == {1})", left, right);
case BinaryOperator.Cge:
case BinaryOperator.Cge_Un:
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return String.Format("({0} < {1})", left, right);
}
return String.Format("({0} >= {1})", left, right);
case BinaryOperator.Cgt:
case BinaryOperator.Cgt_Un:
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return String.Format("({0} <= {1})", left, right);
}
return String.Format("({0} > {1})", left, right);
case BinaryOperator.Cle:
case BinaryOperator.Cle_Un:
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return String.Format("({0} > {1})", left, right);
}
return String.Format("({0} <= {1})", left, right);
case BinaryOperator.Clt:
case BinaryOperator.Clt_Un:
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return String.Format("({0} >= {1})", left, right);
}
return String.Format("({0} < {1})", left, right);
case BinaryOperator.Cne_Un:
if (tryInvert.TryInvertComparison)
{
tryInvert.DischargeInversion();
return String.Format("({0} == {1})", left, right);
}
return String.Format("({0} != {1})", left, right);
case BinaryOperator.Div:
case BinaryOperator.Div_Un:
return String.Format("({0} / {1})", left, right);
case BinaryOperator.Mul:
case BinaryOperator.Mul_Ovf:
case BinaryOperator.Mul_Ovf_Un:
return String.Format("({0} * {1})", left, right);
case BinaryOperator.Or:
return String.Format("({0} | {1})", left, right);
case BinaryOperator.Rem:
case BinaryOperator.Rem_Un:
return String.Format("({0} % {1})", left, right);
case BinaryOperator.Shl:
return String.Format("({0} << {1})", left, right);
case BinaryOperator.Shr:
case BinaryOperator.Shr_Un:
return String.Format("({0} >> {1})", left, right);
case BinaryOperator.Sub:
case BinaryOperator.Sub_Ovf:
case BinaryOperator.Sub_Ovf_Un:
return String.Format("({0} - {1})", left, right);
case BinaryOperator.Xor:
return String.Format("({0} ^ {1})", left, right);
default:
throw new NotImplementedException("new binary operator?");
}
}
public string Isinst(Expression pc, Type type, Dest dest, Expression obj, InvertComparison data)
{
string arg = Recurse(obj);
if (arg == null) return null;
return String.Format("({0} as {1})", arg, mdDecoder.Name(type));
}
public string Ldconst(Expression pc, object constant, Type type, Dest dest, InvertComparison data)
{
return constant.ToString();
}
public string Ldnull(Expression pc, Dest dest, InvertComparison data)
{
return "null";
}
public string Sizeof(Expression pc, Type type, Dest dest, InvertComparison data)
{
return String.Format("sizeof({0})", mdDecoder.FullName(type));
}
[ContractVerification(true)]
public string Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Dest dest, Expression source, InvertComparison data)
{
string arg = Recurse(source);
if (arg == null) return null;
switch (op)
{
case UnaryOperator.Conv_i:
return arg;
case UnaryOperator.Conv_i1:
return String.Format("(System.Int8){0}", arg);
case UnaryOperator.Conv_i2:
return String.Format("(System.Int16){0}", arg);
case UnaryOperator.Conv_i4:
return String.Format("(System.Int32){0}", arg);
case UnaryOperator.Conv_i8:
return String.Format("(System.Int64){0}", arg);
case UnaryOperator.Conv_r_un:
return arg;
case UnaryOperator.Conv_r4:
return String.Format("(System.Single){0}", arg);
case UnaryOperator.Conv_r8:
return String.Format("(System.Double){0}", arg);
case UnaryOperator.Conv_u:
return arg;
case UnaryOperator.Conv_u1:
return String.Format("(System.UInt8){0}", arg);
case UnaryOperator.Conv_u2:
return String.Format("(System.UInt16){0}", arg);
case UnaryOperator.Conv_u4:
return String.Format("(System.UInt32){0}", arg);
case UnaryOperator.Conv_u8:
return String.Format("(System.UInt64){0}", arg);
case UnaryOperator.Neg:
return String.Format("(-{0})", arg);
case UnaryOperator.Not:
return String.Format("(!{0})", arg);
case UnaryOperator.WritableBytes:
return String.Format("System.Diagnostics.Contracts.Contract.WritableBytes({0})", arg);
default:
return "<unknown unary operator?>";
//Contract.Assert(false); // should be unreachable
//throw new NotImplementedException("new unary operator?");
}
}
public string Box(Expression pc, Type type, Dest dest, Expression source, InvertComparison data)
{
string arg = Recurse(source);
if (arg == null) return null;
return String.Format("(box {0} to {1})", arg, mdDecoder.Name(type));
}
#endregion
}
public static BoxedExpression ExpressionInPreState<Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Expression, Attribute, Assembly>
(
APC at,
Expression condition,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, SymbolicValue> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
out bool hasVariables
)
where Type : IEquatable<Type>
{
var preTrans = new PreconditionTransformer<Local, Parameter, Method, Field, Property, Event, Expression, Type, SymbolicValue, Attribute, Assembly>(at, context, mdDecoder);
var result = preTrans.Recurse(condition);
hasVariables = preTrans.HasVariables;
return result;
}
/// <summary>
/// Computes a BoxedExpression with internal accesspaths that are valid in the pre-state of the
/// current method and these paths are "visible" according to the visibility rules of pre-conditions.
/// </summary>
/// <param name="hasVariables">true if expression contains any variables at all</param>
/// <param name="conditionPC">the pc at which the condition is being tested</param>
/// <returns>null if not expressible in pre-state</returns>
public static ExpressionInPreState ExpressionInPreState<Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Expression, Attribute, Assembly>(
BoxedExpression condition,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, SymbolicValue> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
APC conditionPC,
ExpressionInPreStateKind allowedKinds
)
where Type : IEquatable<Type>
{
Contract.Requires(mdDecoder != null);
continuations = new List<Tuple<BoxedExpression, BoxedExpression, BoxedExpression>>();
ExpressionInPreStateInfo info;
var boundVariables = new Set<BoxedExpression>();
var allowObjectInvariants = ExpressionInPreStateKind.ObjectInvariant.IsIncludedIn(allowedKinds) && !mdDecoder.IsConstructor(context.MethodContext.CurrentMethod);
var result = ExpressionInPreStateInternal(condition, context, mdDecoder, out info, conditionPC, allowObjectInvariants, boundVariables);
if (result != null && continuations.Count > 0)
{
result = ApplyExistential(result);
}
continuations = null;
if (info != null && info.kind.IsIncludedIn(allowedKinds))
{
return result == null ? null : new ExpressionInPreState(result, info);
}
return null;
}
private static class BoxedExpressionsUtils // taken from BoxedExpressionsUtils, TODO: solve dependencies
{
public static List<BoxedExpression> SplitConjunctions(BoxedExpression be)
{
Contract.Requires(be != null);
Contract.Ensures(Contract.Result<List<BoxedExpression>>() != null);
var result = new List<BoxedExpression>();
return SplitConjunctionsHelper(be, result);
}
private static List<BoxedExpression> SplitConjunctionsHelper(BoxedExpression be, List<BoxedExpression> result)
{
Contract.Requires(be != null);
Contract.Requires(result != null);
Contract.Ensures(Contract.Result<List<BoxedExpression>>() != null);
if (be.IsBinary && be.BinaryOp == BinaryOperator.LogicalAnd)
{
result = SplitConjunctionsHelper(be.BinaryRight, SplitConjunctionsHelper(be.BinaryLeft, result));
}
else
{
result.Add(be);
}
return result;
}
}
public static IEnumerable<ExpressionInPreState> ExpressionsInPreState<Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Expression, Attribute, Assembly>(
BoxedExpression condition,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, SymbolicValue> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
APC conditionPC,
ExpressionInPreStateKind allowedKinds
)
where Type : IEquatable<Type>
{
Contract.Ensures(Contract.Result<IEnumerable<ExpressionInPreState>>() == null || Contract.ForAll(Contract.Result<IEnumerable<ExpressionInPreState>>(), e => e != null));
foreach (var subCondition in BoxedExpressionsUtils.SplitConjunctions(condition))
{
if (subCondition == null)
continue;
var result = ExpressionInPreState(subCondition, context, mdDecoder, conditionPC, allowedKinds);
if (result == null)
continue;
yield return result;
}
}
private static BoxedExpression ApplyExistential(BoxedExpression result)
{
Contract.Requires(result != null);
Contract.Ensures(Contract.Result<BoxedExpression>() != null);
foreach (var triple in continuations)
{
Contract.Assume(triple.Item1 != null);
Contract.Assume(triple.Item2 != null);
Contract.Assume(triple.Item3 != null);
result = new ExistsIndexedExpression(null, triple.Item1, triple.Item2, triple.Item3, result);
}
return result;
}
[ThreadStatic]
private static List<Tuple<BoxedExpression, BoxedExpression, BoxedExpression>> continuations;
[ContractVerification(false)]
private static BoxedExpression ExpressionInPreStateInternal<Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Expression, Attribute, Assembly>(
BoxedExpression condition,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, SymbolicValue> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
out ExpressionInPreStateInfo info,
APC conditionPC,
bool allowObjectInvariant, // only false if current method is a constructor!
Set<BoxedExpression> boundVariables
)
where Type : IEquatable<Type>
{
Contract.Requires(boundVariables != null);
if (boundVariables.Contains(condition))
{
Contract.Assume(condition != null);
info = new ExpressionInPreStateInfo(ExpressionInPreStateKind.Any);
return condition;
}
if (condition.IsVariable)
{
// Special case as we may have some slack variable
SymbolicValue var;
if (!condition.TryGetFrameworkVariable(out var))
{
info = null;
return null;
}
// First check if we've got a constant
Type type;
object value;
if (context.ValueContext.IsConstant(conditionPC, var, out type, out value))
{
info = new ExpressionInPreStateInfo(ExpressionInPreStateKind.Any);
return BoxedExpression.Const(value, type, mdDecoder);
}
var isConstructor = mdDecoder.IsConstructor(context.MethodContext.CurrentMethod);
FList<PathElement> accessPath;
#region Try to generate a precondition
accessPath = context.ValueContext.VisibleAccessPathListFromPre(conditionPC, var); // ConditionPC okay here, because this also checks that the path is unmodified
var headIsThis = accessPath != null ? accessPath.Head.ToString() == "this" : false;
if (accessPath != null
&& (!isConstructor || !headIsThis))
{
var resultKind = headIsThis ? ExpressionInPreStateKind.Any : ExpressionInPreStateKind.MethodPrecondition;
var hasOnlyImmutableVariables = accessPath.Length() == 1 || condition.IsArrayLength(conditionPC, context, mdDecoder);
info = new ExpressionInPreStateInfo(accessPath.Length() > 1, true, hasOnlyImmutableVariables, resultKind);
return BoxedExpression.Var(var, accessPath);
}
#endregion
#region Try to generate an Assume or an Object Invariant
accessPath = context.ValueContext.AccessPathList(conditionPC, var, false, false);
if (accessPath != null && !conditionPC.Equals(context.MethodContext.CFG.EntryAfterRequires))
{
// check that path is unmodified since entry
if (!context.ValueContext.PathUnmodifiedSinceEntry(conditionPC, accessPath))
{
accessPath = null; // can't use it
}
}
if (accessPath != null
&& accessPath.Head.IsParameter
&& accessPath.Head.ToString() == "this"
&& context.ValueContext.PathSuitableInRequires(conditionPC, accessPath))
{
var isReadOnly = mdDecoder.IsReadOnly(accessPath);
if (!isConstructor && isReadOnly && allowObjectInvariant)
{
var kind = ExpressionInPreStateKind.ObjectInvariant;
info = new ExpressionInPreStateInfo(accessPath.Length() > 1, true, false, kind);
return BoxedExpression.Var(var, accessPath);
}
}
#endregion
#region Try to generate any kind of entry assumption
//accessPath = context.ValueContext.AccessPathList(conditionPC, var, false, false);
if (accessPath != null
&& (!isConstructor || accessPath.Head.ToString() != "this"))
{
var hasOnlyImmutableVariables = accessPath.Length() == 1 || condition.IsArrayLength(conditionPC, context, mdDecoder);
info = new ExpressionInPreStateInfo(accessPath.Length() > 1, true, hasOnlyImmutableVariables, ExpressionInPreStateKind.Assume);
return BoxedExpression.Var(var, accessPath);
}
#endregion
info = null;
return null;
}
if (condition.IsConstant || condition.IsNull)
{
// no nested variables
Contract.Assume(!mdDecoder.Equal((Type)condition.ConstantType, mdDecoder.System_Int32) || condition.Constant is Int32);
info = new ExpressionInPreStateInfo(ExpressionInPreStateKind.Any, true);
return BoxedExpression.Const(condition.Constant, (Type)condition.ConstantType, mdDecoder);
}
if (condition.IsSizeOf)
{
int size;
object type;
condition.SizeOf(out type, out size);
info = new ExpressionInPreStateInfo(ExpressionInPreStateKind.Any);
return BoxedExpression.SizeOf((Type)type, size);
}
if (condition.IsUnary)
{
// Recurse
var arg = ExpressionInPreStateInternal(condition.UnaryArgument, context, mdDecoder, out info, conditionPC, allowObjectInvariant, boundVariables);
if (arg != null)
{
return BoxedExpression.Unary(condition.UnaryOp, arg);
}
return null;
}
if (condition.IsBinary)
{
ExpressionInPreStateInfo infoLeft, infoRight;
// Recurse
var left = ExpressionInPreStateInternal(condition.BinaryLeft, context, mdDecoder, out infoLeft, conditionPC, allowObjectInvariant, boundVariables);
if (left == null) { info = null; return null; }
var right = ExpressionInPreStateInternal(condition.BinaryRight, context, mdDecoder, out infoRight, conditionPC, allowObjectInvariant, boundVariables);
if (right == null) { info = null; return null; }
info = ExpressionInPreStateInfo.Combine(infoLeft, infoRight);
return BoxedExpression.Binary(condition.BinaryOp, left, right);
}
BoxedExpression arrayExp, indexExp;
object t;
if (condition.IsArrayIndexExpression(out arrayExp, out indexExp, out t) && t is Type)
{
ExpressionInPreStateInfo infoArray, infoIndex;
var newArrayExp = ExpressionInPreStateInternal(arrayExp, context, mdDecoder, out infoArray, conditionPC, allowObjectInvariant, boundVariables);
if (newArrayExp == null) { info = null; return null; }
var newIndexExp = ExpressionInPreStateInternal(indexExp, context, mdDecoder, out infoIndex, conditionPC, allowObjectInvariant, boundVariables);
if (newIndexExp == null)
{
// try to introduce the exists
SymbolicValue arrayVar, arrayLen;
if (newArrayExp.TryGetFrameworkVariable(out arrayVar)
&& context.ValueContext.TryGetArrayLength(conditionPC, arrayVar, out arrayLen))
{
var type = context.ValueContext.GetType(conditionPC, arrayVar);
var boundVar = BoxedExpression.Var(string.Format("__j{0}__", continuations.Count));
var zero = BoxedExpression.Const(0, mdDecoder.System_Int32, mdDecoder);
// TODO: the info kind computation does not seem general enough here [MAF 3/23/13]
info = new ExpressionInPreStateInfo(true, infoArray.hasVariables, false, ExpressionInPreStateKind.MethodPrecondition);
FList<PathElement> accessPath = null;
if (infoArray.kind.IsIncludedIn(ExpressionInPreStateKind.MethodPrecondition))
{
accessPath = context.ValueContext.VisibleAccessPathListFromPre(conditionPC, arrayLen);
}
if (accessPath == null && infoArray.kind.IsIncludedIn(ExpressionInPreStateKind.ObjectInvariant))
{
accessPath = context.ValueContext.AccessPathList(context.MethodContext.CFG.EntryAfterRequires, arrayLen, false, false);
info = new ExpressionInPreStateInfo(true, infoArray.hasVariables, false, ExpressionInPreStateKind.ObjectInvariant);
}
if (accessPath != null)
{
var arrayLength = BoxedExpression.Var(arrayLen, context.ValueContext.VisibleAccessPathListFromPre(conditionPC, arrayLen));
// Add the continuation
continuations.Add(
new Tuple<BoxedExpression, BoxedExpression, BoxedExpression>(boundVar, zero, arrayLength));
return new BoxedExpression.ArrayIndexExpression<Type>(newArrayExp, boundVar, type.IsNormal ? type.Value : mdDecoder.System_Object);
}
}
info = null;
return null;
}
info = ExpressionInPreStateInfo.Combine(infoArray, infoIndex);
return new BoxedExpression.ArrayIndexExpression<Type>(newArrayExp, newIndexExp, (Type)t);
}
bool isForAll;
BoxedExpression boundExp, lowerBound, upperBound, body;
if (condition.IsQuantifiedExpression(out isForAll, out boundExp, out lowerBound, out upperBound, out body))
{
ExpressionInPreStateInfo infoLowerBound, infoUpperBound, infoBody;
boundVariables.Add(boundExp);
var newLowerBound = ExpressionInPreStateInternal(lowerBound, context, mdDecoder, out infoLowerBound, conditionPC, allowObjectInvariant, boundVariables);
if (newLowerBound == null) { info = null; return null; }
var newUpperBound = ExpressionInPreStateInternal(upperBound, context, mdDecoder, out infoUpperBound, conditionPC, allowObjectInvariant, boundVariables);
if (newUpperBound == null) { info = null; return null; }
var newBody = ExpressionInPreStateInternal(body, context, mdDecoder, out infoBody, conditionPC, allowObjectInvariant, boundVariables);
if (newBody == null) { info = null; return null; }
info = ExpressionInPreStateInfo.Combine(infoLowerBound, infoUpperBound, infoBody);
if (isForAll)
{
return new ForAllIndexedExpression(null, boundExp, newLowerBound, newUpperBound, newBody);
}
else
{
return new ExistsIndexedExpression(null, boundExp, newLowerBound, newUpperBound, newBody);
}
}
object testtype;
BoxedExpression test;
if (condition.IsIsInstExpression(out test, out testtype))
{
var rec = ExpressionInPreStateInternal(test, context, mdDecoder, out info, conditionPC, allowObjectInvariant, boundVariables);
if (rec == null)
{
info = null;
return null;
}
return ClousotExpression<Type>.MakeIsInst((Type)testtype, rec);
}
info = null;
return null;
}
public static string/*?*/ ConditionAsPrecondition<Label, Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Expression, Attribute, Assembly>(
Expression condition,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, SymbolicValue> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
out bool hasVariables,
SourceLanguage slang
)
where Type : IEquatable<Type>
{
Contract.Requires(context != null);
Contract.Requires(mdDecoder != null);
return ConditionAsStringAtPC(context.MethodContext.CFG.EntryAfterRequires, condition, context, mdDecoder, out hasVariables, slang);
}
public static string/*?*/ ConditionAsStringAtPC<Local, Parameter, Method, Field, Property, Event, Type, SymbolicValue, Expression, Attribute, Assembly>(
APC atPC,
Expression condition,
IExpressionContext<Local, Parameter, Method, Field, Type, Expression, SymbolicValue> context,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
out bool hasVariables,
SourceLanguage slang
)
where Type : IEquatable<Type>
{
Contract.Requires(context != null);
Contract.Requires(mdDecoder != null);
var decoder =
new ExpressionDecoder<Local, Parameter, Method, Field, Property, Event, Expression, Type, SymbolicValue, Attribute, Assembly>(atPC, context, mdDecoder);
string result = context.ExpressionContext.Decode<InvertComparison, string, ExpressionDecoder<Local, Parameter, Method, Field, Property, Event, Expression, Type, SymbolicValue, Attribute, Assembly>>(condition, decoder, InvertComparison.NoInversion);
hasVariables = decoder.HasVariables;
return result;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B09_Region_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="B09_Region_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class B09_Region_ReChild : BusinessBase<B09_Region_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int region_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Region Child Name");
/// <summary>
/// Gets or sets the Region Child Name.
/// </summary>
/// <value>The Region Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B09_Region_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B09_Region_ReChild"/> object.</returns>
internal static B09_Region_ReChild NewB09_Region_ReChild()
{
return DataPortal.CreateChild<B09_Region_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="B09_Region_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B09_Region_ReChild"/> object.</returns>
internal static B09_Region_ReChild GetB09_Region_ReChild(SafeDataReader dr)
{
B09_Region_ReChild obj = new B09_Region_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B09_Region_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B09_Region_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B09_Region_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B09_Region_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name"));
// parent properties
region_ID2 = dr.GetInt32("Region_ID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B09_Region_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B08_Region parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddB09_Region_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID2", parent.Region_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Region_Child_Name", ReadProperty(Region_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B09_Region_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B08_Region parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateB09_Region_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID2", parent.Region_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Region_Child_Name", ReadProperty(Region_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="B09_Region_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B08_Region parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteB09_Region_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Region_ID2", parent.Region_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.App.Generate.Program;
using Encog.Engine.Network.Activation;
using Encog.ML;
using Encog.ML.Data;
using Encog.Neural.Flat;
using Encog.Neural.Networks;
using Encog.Persist;
using Encog.Util.CSV;
using Encog.Util.Simple;
namespace Encog.App.Generate.Generators.JS
{
/// <summary>
/// Generate JavaScript.
/// </summary>
public class GenerateEncogJavaScript : AbstractGenerator
{
private void EmbedNetwork(EncogProgramNode node)
{
AddBreak();
var methodFile = (FileInfo) node.Args[0].Value;
var method = (IMLMethod) EncogDirectoryPersistence
.LoadObject(methodFile);
if (!(method is IMLFactory))
{
throw new EncogError("Code generation not yet supported for: "
+ method.GetType().Name);
}
FlatNetwork flat = ((IContainsFlat) method).Flat;
// header
var line = new StringBuilder();
line.Append("public static MLMethod ");
line.Append(node.Name);
line.Append("() {");
IndentLine(line.ToString());
// create factory
line.Length = 0;
AddLine("var network = ENCOG.BasicNetwork.create( null );");
AddLine("network.inputCount = " + flat.InputCount + ";");
AddLine("network.outputCount = " + flat.OutputCount + ";");
AddLine("network.layerCounts = "
+ ToSingleLineArray(flat.LayerCounts) + ";");
AddLine("network.layerContextCount = "
+ ToSingleLineArray(flat.LayerContextCount) + ";");
AddLine("network.weightIndex = "
+ ToSingleLineArray(flat.WeightIndex) + ";");
AddLine("network.layerIndex = "
+ ToSingleLineArray(flat.LayerIndex) + ";");
AddLine("network.activationFunctions = "
+ ToSingleLineArray(flat.ActivationFunctions) + ";");
AddLine("network.layerFeedCounts = "
+ ToSingleLineArray(flat.LayerFeedCounts) + ";");
AddLine("network.contextTargetOffset = "
+ ToSingleLineArray(flat.ContextTargetOffset) + ";");
AddLine("network.contextTargetSize = "
+ ToSingleLineArray(flat.ContextTargetSize) + ";");
AddLine("network.biasActivation = "
+ ToSingleLineArray(flat.BiasActivation) + ";");
AddLine("network.beginTraining = " + flat.BeginTraining + ";");
AddLine("network.endTraining=" + flat.EndTraining + ";");
AddLine("network.weights = WEIGHTS;");
AddLine("network.layerOutput = "
+ ToSingleLineArray(flat.LayerOutput) + ";");
AddLine("network.layerSums = " + ToSingleLineArray(flat.LayerSums)
+ ";");
// return
AddLine("return network;");
UnIndentLine("}");
}
private void EmbedTraining(EncogProgramNode node)
{
var dataFile = (FileInfo) node.Args[0].Value;
IMLDataSet data = EncogUtility.LoadEGB2Memory(dataFile);
// generate the input data
IndentLine("var INPUT_DATA = [");
foreach (IMLDataPair pair in data)
{
IMLData item = pair.Input;
var line = new StringBuilder();
NumberList.ToList(CSVFormat.EgFormat, line, item);
line.Insert(0, "[ ");
line.Append(" ],");
AddLine(line.ToString());
}
UnIndentLine("];");
AddBreak();
// generate the ideal data
IndentLine("var IDEAL_DATA = [");
foreach (IMLDataPair pair in data)
{
IMLData item = pair.Ideal;
var line = new StringBuilder();
NumberList.ToList(CSVFormat.EgFormat, line, item);
line.Insert(0, "[ ");
line.Append(" ],");
AddLine(line.ToString());
}
UnIndentLine("];");
}
public override void Generate(EncogGenProgram program, bool shouldEmbed)
{
if (!shouldEmbed)
{
throw new AnalystCodeGenerationError(
"Must embed when generating Javascript");
}
GenerateForChildren(program);
}
private void GenerateArrayInit(EncogProgramNode node)
{
var line = new StringBuilder();
line.Append("var ");
line.Append(node.Name);
line.Append(" = [");
IndentLine(line.ToString());
var a = (double[]) node.Args[0].Value;
line.Length = 0;
int lineCount = 0;
for (int i = 0; i < a.Length; i++)
{
line.Append(CSVFormat.EgFormat.Format(a[i],
EncogFramework.DefaultPrecision));
if (i < (a.Length - 1))
{
line.Append(",");
}
lineCount++;
if (lineCount >= 10)
{
AddLine(line.ToString());
line.Length = 0;
lineCount = 0;
}
}
if (line.Length > 0)
{
AddLine(line.ToString());
line.Length = 0;
}
UnIndentLine("];");
}
private void GenerateClass(EncogProgramNode node)
{
AddBreak();
AddLine("<!DOCTYPE html>");
AddLine("<html>");
AddLine("<head>");
AddLine("<title>Encog Generated Javascript</title>");
AddLine("</head>");
AddLine("<body>");
AddLine("<script src=\"../encog.js\"></script>");
AddLine("<script src=\"../encog-widget.js\"></script>");
AddLine("<pre>");
AddLine("<script type=\"text/javascript\">");
GenerateForChildren(node);
AddLine("</script>");
AddLine(
"<noscript>Your browser does not support JavaScript! Note: if you are trying to view this in Encog Workbench, right-click file and choose \"Open as Text\".</noscript>");
AddLine("</pre>");
AddLine("</body>");
AddLine("</html>");
}
private void GenerateComment(EncogProgramNode commentNode)
{
AddLine("// " + commentNode.Name);
}
private void GenerateConst(EncogProgramNode node)
{
var line = new StringBuilder();
line.Append("var ");
line.Append(node.Name);
line.Append(" = \"");
line.Append(node.Args[0].Value);
line.Append("\";");
AddLine(line.ToString());
}
private void GenerateForChildren(EncogTreeNode parent)
{
foreach (EncogProgramNode node in parent.Children)
{
GenerateNode(node);
}
}
private void GenerateFunction(EncogProgramNode node)
{
AddBreak();
var line = new StringBuilder();
line.Append("function ");
line.Append(node.Name);
line.Append("() {");
IndentLine(line.ToString());
GenerateForChildren(node);
UnIndentLine("}");
}
private void GenerateFunctionCall(EncogProgramNode node)
{
AddBreak();
var line = new StringBuilder();
if (node.Args[0].Value.ToString().Length > 0)
{
line.Append("var ");
line.Append(node.Args[1].Value);
line.Append(" = ");
}
line.Append(node.Name);
line.Append("();");
AddLine(line.ToString());
}
private void GenerateMainFunction(EncogProgramNode node)
{
AddBreak();
GenerateForChildren(node);
}
private void GenerateNode(EncogProgramNode node)
{
switch (node.Type)
{
case NodeType.Comment:
GenerateComment(node);
break;
case NodeType.Class:
GenerateClass(node);
break;
case NodeType.MainFunction:
GenerateMainFunction(node);
break;
case NodeType.Const:
GenerateConst(node);
break;
case NodeType.StaticFunction:
GenerateFunction(node);
break;
case NodeType.FunctionCall:
GenerateFunctionCall(node);
break;
case NodeType.CreateNetwork:
EmbedNetwork(node);
break;
case NodeType.InitArray:
GenerateArrayInit(node);
break;
case NodeType.EmbedTraining:
EmbedTraining(node);
break;
}
}
private String ToSingleLineArray(
IActivationFunction[] activationFunctions)
{
var result = new StringBuilder();
result.Append('[');
for (int i = 0; i < activationFunctions.Length; i++)
{
if (i > 0)
{
result.Append(',');
}
IActivationFunction af = activationFunctions[i];
if (af is ActivationSigmoid)
{
result.Append("ENCOG.ActivationSigmoid.create()");
}
else if (af is ActivationTANH)
{
result.Append("ENCOG.ActivationTANH.create()");
}
else if (af is ActivationLinear)
{
result.Append("ENCOG.ActivationLinear.create()");
}
else if (af is ActivationElliott)
{
result.Append("ENCOG.ActivationElliott.create()");
}
else if (af is ActivationElliott)
{
result.Append("ENCOG.ActivationElliott.create()");
}
else
{
throw new AnalystCodeGenerationError(
"Unsupported activatoin function for code generation: "
+ af.GetType().Name);
}
}
result.Append(']');
return result.ToString();
}
private String ToSingleLineArray(double[] d)
{
var line = new StringBuilder();
line.Append("[");
for (int i = 0; i < d.Length; i++)
{
line.Append(CSVFormat.EgFormat.Format(d[i],
EncogFramework.DefaultPrecision));
if (i < (d.Length - 1))
{
line.Append(",");
}
}
line.Append("]");
return line.ToString();
}
private String ToSingleLineArray(int[] d)
{
var line = new StringBuilder();
line.Append("[");
for (int i = 0; i < d.Length; i++)
{
line.Append(d[i]);
if (i < (d.Length - 1))
{
line.Append(",");
}
}
line.Append("]");
return line.ToString();
}
}
}
| |
// 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;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Transactions;
using Microsoft.SqlServer.Server;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class TvpTest
{
private const string TvpName = "@tvp";
private static readonly IList<SteAttributeKey> BoundariesTestKeys = new List<SteAttributeKey>(
new SteAttributeKey[] {
SteAttributeKey.SqlDbType,
SteAttributeKey.MultiValued,
SteAttributeKey.MaxLength,
SteAttributeKey.Precision,
SteAttributeKey.Scale,
SteAttributeKey.LocaleId,
SteAttributeKey.CompareOptions,
SteAttributeKey.TypeName,
SteAttributeKey.Type,
SteAttributeKey.Fields,
SteAttributeKey.Value
}).AsReadOnly();
// data value and server consts
private string _connStr;
[CheckConnStrSetupFact]
public void TestMain()
{
Assert.True(RunTestCoreAndCompareWithBaseline());
}
public TvpTest()
{
_connStr = DataTestUtility.TcpConnStr;
}
private void RunTest()
{
Console.WriteLine("Starting test \'TvpTest\'");
StreamInputParam.Run(_connStr);
ColumnBoundariesTest();
QueryHintsTest();
SqlVariantParam.SendAllSqlTypesInsideVariant(_connStr);
DateTimeVariantTest.TestAllDateTimeWithDataTypeAndVariant(_connStr);
OutputParameter.Run(_connStr);
}
private bool RunTestCoreAndCompareWithBaseline()
{
string outputPath = "SqlParameterTest.out";
#if DEBUG
string baselinePath = "SqlParameterTest_DebugMode.bsl";
#else
string baselinePath = "SqlParameterTest_ReleaseMode.bsl";
#endif
var fstream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
var swriter = new StreamWriter(fstream, Encoding.UTF8);
// Convert all string writes of '\n' to '\r\n' so output files can be 'text' not 'binary'
var twriter = new CarriageReturnLineFeedReplacer(swriter);
Console.SetOut(twriter); // "redirect" Console.Out
// Run Test
RunTest();
Console.Out.Flush();
Console.Out.Dispose();
// Recover the standard output stream
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
// Compare output file
var comparisonResult = FindDiffFromBaseline(baselinePath, outputPath);
if (string.IsNullOrEmpty(comparisonResult))
{
return true;
}
Console.WriteLine("Test Failed!");
Console.WriteLine("Please compare baseline : {0} with output :{1}", Path.GetFullPath(baselinePath), Path.GetFullPath(outputPath));
Console.WriteLine("Comparison Results : ");
Console.WriteLine(comparisonResult);
return false;
}
private string FindDiffFromBaseline(string baselinePath, string outputPath)
{
var expectedLines = File.ReadAllLines(baselinePath);
var outputLines = File.ReadAllLines(outputPath);
var comparisonSb = new StringBuilder();
// Start compare results
var expectedLength = expectedLines.Length;
var outputLength = outputLines.Length;
var findDiffLength = Math.Min(expectedLength, outputLength);
// Find diff for each lines
for (var lineNo = 0; lineNo < findDiffLength; lineNo++)
{
if (!expectedLines[lineNo].Equals(outputLines[lineNo]))
{
comparisonSb.AppendFormat("** DIFF at line {0} \n", lineNo);
comparisonSb.AppendFormat("A : {0} \n", outputLines[lineNo]);
comparisonSb.AppendFormat("E : {0} \n", expectedLines[lineNo]);
}
}
var startIndex = findDiffLength - 1;
if (startIndex < 0)
startIndex = 0;
if (findDiffLength < expectedLength)
{
comparisonSb.AppendFormat("** MISSING \n");
for (var lineNo = startIndex; lineNo < expectedLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, expectedLines[lineNo]);
}
}
if (findDiffLength < outputLength)
{
comparisonSb.AppendFormat("** EXTRA \n");
for (var lineNo = startIndex; lineNo < outputLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, outputLines[lineNo]);
}
}
return comparisonSb.ToString();
}
private sealed class CarriageReturnLineFeedReplacer : TextWriter
{
private TextWriter _output;
private int _lineFeedCount;
private bool _hasCarriageReturn;
internal CarriageReturnLineFeedReplacer(TextWriter output)
{
if (output == null)
throw new ArgumentNullException("output");
_output = output;
}
public int LineFeedCount
{
get { return _lineFeedCount; }
}
public override Encoding Encoding
{
get { return _output.Encoding; }
}
public override IFormatProvider FormatProvider
{
get { return _output.FormatProvider; }
}
public override string NewLine
{
get { return _output.NewLine; }
set { _output.NewLine = value; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)_output).Dispose();
}
_output = null;
}
public override void Flush()
{
_output.Flush();
}
public override void Write(char value)
{
if ('\n' == value)
{
_lineFeedCount++;
if (!_hasCarriageReturn)
{ // X'\n'Y -> X'\r\n'Y
_output.Write('\r');
}
}
_hasCarriageReturn = '\r' == value;
_output.Write(value);
}
}
#region Main test methods
private void ColumnBoundariesTest()
{
IEnumerator<StePermutation> boundsMD = SteStructuredTypeBoundaries.AllColumnTypesExceptUdts.GetEnumerator(
BoundariesTestKeys);
TestTVPPermutations(SteStructuredTypeBoundaries.AllColumnTypesExceptUdts, false);
//Console.WriteLine("+++++++++++ UDT TVP tests ++++++++++++++");
//TestTVPPermutations(SteStructuredTypeBoundaries.UdtsOnly, true);
}
private void TestTVPPermutations(SteStructuredTypeBoundaries bounds, bool runOnlyDataRecordTest)
{
IEnumerator<StePermutation> boundsMD = bounds.GetEnumerator(BoundariesTestKeys);
object[][] baseValues = SteStructuredTypeBoundaries.GetSeparateValues(boundsMD);
IList<DataTable> dtList = GenerateDataTables(baseValues);
TransactionOptions opts = new TransactionOptions();
opts.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
// for each unique pattern of metadata
int iter = 0;
while (boundsMD.MoveNext())
{
Console.WriteLine("+++++++ Iteration {0} ++++++++", iter);
StePermutation tvpPerm = boundsMD.Current;
// Set up base command
SqlCommand cmd;
SqlParameter param;
cmd = new SqlCommand(GetProcName(tvpPerm));
cmd.CommandType = CommandType.StoredProcedure;
param = cmd.Parameters.Add(TvpName, SqlDbType.Structured);
param.TypeName = GetTypeName(tvpPerm);
// set up the server
try
{
CreateServerObjects(tvpPerm);
}
catch (SqlException se)
{
Console.WriteLine("SqlException creating objects: {0}", se.Number);
DropServerObjects(tvpPerm);
iter++;
continue;
}
// Send list of SqlDataRecords as value
Console.WriteLine("------IEnumerable<SqlDataRecord>---------");
try
{
param.Value = CreateListOfRecords(tvpPerm, baseValues);
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
if (!runOnlyDataRecordTest)
{
// send DbDataReader
Console.WriteLine("------DbDataReader---------");
try
{
param.Value = new TvpRestartableReader(CreateListOfRecords(tvpPerm, baseValues));
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
// send datasets
Console.WriteLine("------DataTables---------");
foreach (DataTable d in dtList)
{
param.Value = d;
ExecuteAndVerify(cmd, tvpPerm, null, d);
}
}
// And clean up
DropServerObjects(tvpPerm);
iter++;
}
}
public void QueryHintsTest()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
Guid randomizer = Guid.NewGuid();
string typeName = String.Format("dbo.[QHint_{0}]", randomizer);
string procName = String.Format("dbo.[QHint_Proc_{0}]", randomizer);
string createTypeSql = String.Format(
"CREATE TYPE {0} AS TABLE("
+ " c1 Int DEFAULT -1,"
+ " c2 NVarChar(40) DEFAULT N'DEFUALT',"
+ " c3 DateTime DEFAULT '1/1/2006',"
+ " c4 Int DEFAULT -1)",
typeName);
string createProcSql = String.Format(
"CREATE PROC {0}(@tvp {1} READONLY) AS SELECT TOP(2) * FROM @tvp ORDER BY c1", procName, typeName);
string dropSql = String.Format("DROP PROC {0}; DROP TYPE {1}", procName, typeName);
try
{
SqlCommand cmd = new SqlCommand(createTypeSql, conn);
cmd.ExecuteNonQuery();
cmd.CommandText = createProcSql;
cmd.ExecuteNonQuery();
cmd.CommandText = procName;
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.Add("@tvp", SqlDbType.Structured);
SqlMetaData[] columnMetadata;
List<SqlDataRecord> rows = new List<SqlDataRecord>();
SqlDataRecord record;
Console.WriteLine("------- Sort order + uniqueness #1: simple -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 0),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 1),
new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(0, "Z-value", DateTime.Parse("03/01/2000"), 5);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "Y-value", DateTime.Parse("02/01/2000"), 6);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("01/01/2000"), 7);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 8);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 4);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- Sort order + uniqueness #2: mixed order -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 0),
new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: outer subset -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: middle subset -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: all -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
SqlCommand cmd = new SqlCommand(dropSql, conn);
cmd.ExecuteNonQuery();
}
}
}
#endregion
#region Utility Methods
private bool AllowableDifference(string source, object result, StePermutation metadata)
{
object value;
bool returnValue = false;
// turn result into a string
string resultStr = null;
if (result.GetType() == typeof(string))
{
resultStr = (string)result;
}
else if (result.GetType() == typeof(char[]))
{
resultStr = new string((char[])result);
}
else if (result.GetType() == typeof(SqlChars))
{
resultStr = new string(((SqlChars)result).Value);
}
if (resultStr != null)
{
if (source.Equals(resultStr))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
if (maxLength < source.Length &&
source.Substring(0, maxLength).Equals(resultStr))
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (maxLength > source.Length &&
resultStr.Length == maxLength &&
metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Char == ((SqlDbType)value) ||
SqlDbType.NChar == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
return returnValue;
}
private bool AllowableDifference(byte[] source, object result, StePermutation metadata)
{
object value;
bool returnValue = false;
// turn result into byte array
byte[] resultBytes = null;
if (result.GetType() == typeof(byte[]))
{
resultBytes = (byte[])result;
}
else if (result.GetType() == typeof(SqlBytes))
{
resultBytes = ((SqlBytes)result).Value;
}
if (resultBytes != null)
{
if (source.Equals(resultBytes) || resultBytes.Length == source.Length)
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
// allowable max-length adjustments
if (maxLength == resultBytes.Length)
{ // a bit optimistic, but what the heck.
// truncation
if (maxLength <= source.Length)
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) && value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Binary == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool AllowableDifference(SqlDecimal source, object result, StePermutation metadata)
{
object value;
object value2;
bool returnValue = false;
// turn result into SqlDecimal
SqlDecimal resultValue = SqlDecimal.Null;
if (result.GetType() == typeof(SqlDecimal))
{
resultValue = (SqlDecimal)result;
}
else if (result.GetType() == typeof(Decimal))
{
resultValue = new SqlDecimal((Decimal)result);
}
else if (result.GetType() == typeof(SqlMoney))
{
resultValue = new SqlDecimal(((SqlMoney)result).Value);
}
if (!resultValue.IsNull)
{
if (source.Equals(resultValue))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
(SqlDbType.SmallMoney == (SqlDbType)value ||
SqlDbType.Money == (SqlDbType)value))
{
// Some server conversions seem to lose the decimal places
// TODO: Investigate and validate that this is acceptable!
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, source.Precision, 0);
if (tmp.Equals(resultValue))
{
returnValue = true;
}
else
{
tmp = SqlDecimal.ConvertToPrecScale(resultValue, resultValue.Precision, 0);
returnValue = tmp.Equals(source);
}
}
// check if value was altered by precision/scale conversion
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SqlDbType.Decimal == (SqlDbType)value)
{
if (metadata.TryGetValue(SteAttributeKey.Scale, out value) &&
metadata.TryGetValue(SteAttributeKey.Precision, out value2) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SteTypeBoundaries.s_doNotUseMarker != value2)
{
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, (byte)value2, (byte)value);
returnValue = tmp.Equals(resultValue);
}
// check if value was changed to 1 by the restartable reader
// due to exceeding size limits of System.Decimal
if (resultValue == (SqlDecimal)1M)
{
try
{
Decimal dummy = source.Value;
}
catch (OverflowException)
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool CompareValue(object result, object source, StePermutation metadata)
{
bool isMatch = false;
if (!IsNull(source))
{
if (!IsNull(result))
{
if (source.Equals(result) || result.Equals(source))
{
isMatch = true;
}
else
{
switch (Type.GetTypeCode(source.GetType()))
{
case TypeCode.String:
isMatch = AllowableDifference((string)source, result, metadata);
break;
case TypeCode.Object:
{
if (source is char[])
{
source = new String((char[])source);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is byte[])
{
isMatch = AllowableDifference((byte[])source, result, metadata);
}
else if (source is SqlBytes)
{
isMatch = AllowableDifference(((SqlBytes)source).Value, result, metadata);
}
else if (source is SqlChars)
{
source = new string(((SqlChars)source).Value);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is SqlInt64 && result is Int64)
{
isMatch = result.Equals(((SqlInt64)source).Value);
}
else if (source is SqlInt32 && result is Int32)
{
isMatch = result.Equals(((SqlInt32)source).Value);
}
else if (source is SqlInt16 && result is Int16)
{
isMatch = result.Equals(((SqlInt16)source).Value);
}
else if (source is SqlSingle && result is Single)
{
isMatch = result.Equals(((SqlSingle)source).Value);
}
else if (source is SqlDouble && result is Double)
{
isMatch = result.Equals(((SqlDouble)source).Value);
}
else if (source is SqlDateTime && result is DateTime)
{
isMatch = result.Equals(((SqlDateTime)source).Value);
}
else if (source is SqlMoney)
{
isMatch = AllowableDifference(new SqlDecimal(((SqlMoney)source).Value), result, metadata);
}
else if (source is SqlDecimal)
{
isMatch = AllowableDifference((SqlDecimal)source, result, metadata);
}
}
break;
case TypeCode.Decimal:
if (result is SqlDecimal || result is Decimal || result is SqlMoney)
{
isMatch = AllowableDifference(new SqlDecimal((Decimal)source), result, metadata);
}
break;
default:
break;
}
}
}
}
else
{
if (IsNull(result))
{
isMatch = true;
}
}
if (!isMatch)
{
ReportMismatch(source, result, metadata);
}
return isMatch;
}
private IList<SqlDataRecord> CreateListOfRecords(StePermutation tvpPerm, object[][] baseValues)
{
IList<StePermutation> fields = GetFields(tvpPerm);
SqlMetaData[] fieldMetadata = new SqlMetaData[fields.Count];
int i = 0;
foreach (StePermutation perm in fields)
{
fieldMetadata[i] = PermToSqlMetaData(perm);
i++;
}
List<SqlDataRecord> records = new List<SqlDataRecord>(baseValues.Length);
for (int rowOrd = 0; rowOrd < baseValues.Length; rowOrd++)
{
object[] row = baseValues[rowOrd];
SqlDataRecord rec = new SqlDataRecord(fieldMetadata);
records.Add(rec); // Call SetValue *after* Add to ensure record is put in list
for (int colOrd = 0; colOrd < row.Length; colOrd++)
{
// Set value in try-catch to prevent some errors from aborting run.
try
{
rec.SetValue(colOrd, row[colOrd]);
}
catch (OverflowException oe)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], oe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], ae.Message);
}
}
}
return records;
}
private DataTable CreateNewTable(object[] row, ref Type[] lastRowTypes)
{
DataTable dt = new DataTable();
for (int i = 0; i < row.Length; i++)
{
object value = row[i];
Type t;
if ((null == value || DBNull.Value == value))
{
if (lastRowTypes[i] == null)
{
return null;
}
else
{
t = lastRowTypes[i];
}
}
else
{
t = value.GetType();
}
dt.Columns.Add(new DataColumn("Col" + i + "_" + t.Name, t));
lastRowTypes[i] = t;
}
return dt;
}
// create table type and proc that uses that type at the server
private void CreateServerObjects(StePermutation tvpPerm)
{
// Create the table type tsql
StringBuilder tsql = new StringBuilder();
tsql.Append("CREATE TYPE ");
tsql.Append(GetTypeName(tvpPerm));
tsql.Append(" AS TABLE(");
bool addSeparator = false;
int colOrdinal = 1;
foreach (StePermutation perm in GetFields(tvpPerm))
{
if (addSeparator)
{
tsql.Append(", ");
}
else
{
addSeparator = true;
}
// column name
tsql.Append("column");
tsql.Append(colOrdinal);
tsql.Append(" ");
// column type
SqlDbType dbType = (SqlDbType)perm[SteAttributeKey.SqlDbType];
switch (dbType)
{
case SqlDbType.BigInt:
tsql.Append("Bigint");
break;
case SqlDbType.Binary:
tsql.Append("Binary(");
object maxLenObj = perm[SteAttributeKey.MaxLength];
int maxLen;
if (maxLenObj == SteTypeBoundaries.s_doNotUseMarker)
{
maxLen = 8000;
}
else
{
maxLen = (int)maxLenObj;
}
tsql.Append(maxLen);
tsql.Append(")");
break;
case SqlDbType.Bit:
tsql.Append("Bit");
break;
case SqlDbType.Char:
tsql.Append("Char(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.DateTime:
tsql.Append("DateTime");
break;
case SqlDbType.Decimal:
tsql.Append("Decimal(");
tsql.Append(perm[SteAttributeKey.Precision]);
tsql.Append(", ");
tsql.Append(perm[SteAttributeKey.Scale]);
tsql.Append(")");
break;
case SqlDbType.Float:
tsql.Append("Float");
break;
case SqlDbType.Image:
tsql.Append("Image");
break;
case SqlDbType.Int:
tsql.Append("Int");
break;
case SqlDbType.Money:
tsql.Append("Money");
break;
case SqlDbType.NChar:
tsql.Append("NChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.NText:
tsql.Append("NText");
break;
case SqlDbType.NVarChar:
tsql.Append("NVarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Real:
tsql.Append("Real");
break;
case SqlDbType.UniqueIdentifier:
tsql.Append("UniqueIdentifier");
break;
case SqlDbType.SmallDateTime:
tsql.Append("SmallDateTime");
break;
case SqlDbType.SmallInt:
tsql.Append("SmallInt");
break;
case SqlDbType.SmallMoney:
tsql.Append("SmallMoney");
break;
case SqlDbType.Text:
tsql.Append("Text");
break;
case SqlDbType.Timestamp:
tsql.Append("Timestamp");
break;
case SqlDbType.TinyInt:
tsql.Append("TinyInt");
break;
case SqlDbType.VarBinary:
tsql.Append("VarBinary(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.VarChar:
tsql.Append("VarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Variant:
tsql.Append("Variant");
break;
case SqlDbType.Xml:
tsql.Append("Xml");
break;
case SqlDbType.Udt:
string typeName = (string)perm[SteAttributeKey.TypeName];
tsql.Append(typeName);
break;
case SqlDbType.Structured:
throw new NotSupportedException("Not supported");
}
colOrdinal++;
}
tsql.Append(")");
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
// execute it to create the type
SqlCommand cmd = new SqlCommand(tsql.ToString(), conn);
cmd.ExecuteNonQuery();
// and create the proc that uses the type
cmd.CommandText = String.Format("CREATE PROC {0}(@tvp {1} READONLY) AS SELECT * FROM @tvp order by {2}",
GetProcName(tvpPerm), GetTypeName(tvpPerm), colOrdinal - 1);
cmd.ExecuteNonQuery();
}
}
private bool DoesRowMatchMetadata(object[] row, DataTable table)
{
bool result = true;
if (row.Length != table.Columns.Count)
{
result = false;
}
else
{
for (int i = 0; i < row.Length; i++)
{
if (null != row[i] && DBNull.Value != row[i] && row[i].GetType() != table.Columns[i].DataType)
{
result = false;
}
}
}
return result;
}
private void DropServerObjects(StePermutation tvpPerm)
{
string dropText = "DROP PROC " + GetProcName(tvpPerm) + "; DROP TYPE " + GetTypeName(tvpPerm);
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(dropText, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine("SqlException dropping objects: {0}", e.Number);
}
}
}
private void ExecuteAndVerify(SqlCommand cmd, StePermutation tvpPerm, object[][] objValues, DataTable dtValues)
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
cmd.Connection = conn;
// cmd.Transaction = conn.BeginTransaction();
// and run the command
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
VerifyColumnBoundaries(rdr, GetFields(tvpPerm), objValues, dtValues);
}
}
catch (SqlException se)
{
Console.WriteLine("SqlException: {0}", se.Message);
}
catch (InvalidOperationException ioe)
{
Console.WriteLine("InvalidOp: {0}", ioe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("ArgumentException: {0}", ae.Message);
}
// And clean up. If an error is thrown, the connection being recycled
// will roll back the transaction
if (null != cmd.Transaction)
{
// cmd.Transaction.Rollback();
}
}
}
private IList<DataTable> GenerateDataTables(object[][] values)
{
List<DataTable> dtList = new List<DataTable>();
Type[] valueTypes = new Type[values[0].Length];
foreach (object[] row in values)
{
DataTable targetTable = null;
if (0 < dtList.Count)
{
// shortcut for matching last table (most common scenario)
if (DoesRowMatchMetadata(row, dtList[dtList.Count - 1]))
{
targetTable = dtList[dtList.Count - 1];
}
else
{
foreach (DataTable candidate in dtList)
{
if (DoesRowMatchMetadata(row, candidate))
{
targetTable = candidate;
break;
}
}
}
}
if (null == targetTable)
{
targetTable = CreateNewTable(row, ref valueTypes);
if (null != targetTable)
{
dtList.Add(targetTable);
}
}
if (null != targetTable)
{
targetTable.Rows.Add(row);
}
}
return dtList;
}
private IList<StePermutation> GetFields(StePermutation tvpPerm)
{
return (IList<StePermutation>)tvpPerm[SteAttributeKey.Fields];
}
private string GetProcName(StePermutation tvpPerm)
{
return "dbo.[Proc_" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
}
private string GetTypeName(StePermutation tvpPerm)
{
return "dbo.[" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
}
private bool IsNull(object value)
{
return null == value ||
DBNull.Value == value ||
(value is INullable &&
((INullable)value).IsNull);
}
private SqlMetaData PermToSqlMetaData(StePermutation perm)
{
object attr;
SqlDbType sqlDbType;
int maxLength = 0;
byte precision = 0;
byte scale = 0;
string typeName = null;
Type type = null;
long localeId = 0;
SqlCompareOptions opts = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
if (perm.TryGetValue(SteAttributeKey.SqlDbType, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
sqlDbType = (SqlDbType)attr;
}
else
{
throw new InvalidOperationException("PermToSqlMetaData: No SqlDbType available!");
}
if (perm.TryGetValue(SteAttributeKey.MaxLength, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
maxLength = (int)attr;
}
if (perm.TryGetValue(SteAttributeKey.Precision, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
precision = (byte)attr;
}
if (perm.TryGetValue(SteAttributeKey.Scale, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
scale = (byte)attr;
}
if (perm.TryGetValue(SteAttributeKey.LocaleId, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
localeId = (int)attr;
}
if (perm.TryGetValue(SteAttributeKey.CompareOptions, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
opts = (SqlCompareOptions)attr;
}
if (perm.TryGetValue(SteAttributeKey.TypeName, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
typeName = (string)attr;
}
if (perm.TryGetValue(SteAttributeKey.Type, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
type = (Type)attr;
}
//if (SqlDbType.Udt == sqlDbType)
//{
// return new SqlMetaData("", sqlDbType, type, typeName);
//}
//else
//{
return new SqlMetaData("", sqlDbType, maxLength, precision, scale, localeId, opts, type);
//}
}
private void ReportMismatch(object source, object result, StePermutation perm)
{
if (null == source)
{
source = "(null)";
}
if (null == result)
{
result = "(null)";
}
Console.WriteLine("Mismatch: Source = {0}, result = {1}, metadata={2}", source, result, perm.ToString());
}
private void VerifyColumnBoundaries(SqlDataReader rdr, IList<StePermutation> fieldMetaData, object[][] values, DataTable dt)
{
int rowOrd = 0;
int matches = 0;
while (rdr.Read())
{
for (int columnOrd = 0; columnOrd < rdr.FieldCount; columnOrd++)
{
object value;
// Special case to handle decimal values that may be too large for GetValue
if (!rdr.IsDBNull(columnOrd) && rdr.GetFieldType(columnOrd) == typeof(Decimal))
{
value = rdr.GetSqlValue(columnOrd);
}
else
{
value = rdr.GetValue(columnOrd);
}
if (null != values)
{
if (CompareValue(value, values[rowOrd][columnOrd], fieldMetaData[columnOrd]))
{
matches++;
}
else
{
Console.WriteLine(" Row={0}, Column={1}", rowOrd, columnOrd);
}
}
else
{
if (CompareValue(value, dt.Rows[rowOrd][columnOrd], fieldMetaData[columnOrd]))
{
matches++;
}
else
{
Console.WriteLine(" Row={0}, Column={1}", rowOrd, columnOrd);
}
}
}
rowOrd++;
}
Console.WriteLine("Matches = {0}", matches);
}
private void WriteReader(SqlDataReader rdr)
{
int colCount = rdr.FieldCount;
do
{
Console.WriteLine("-------------");
while (rdr.Read())
{
for (int i = 0; i < colCount; i++)
{
Console.Write("{0} ", rdr.GetValue(i));
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("-------------");
}
while (rdr.NextResult());
}
private void DumpSqlParam(SqlParameter param)
{
Console.WriteLine("Parameter {0}", param.ParameterName);
Console.WriteLine(" IsNullable: {0}", param.IsNullable);
Console.WriteLine(" LocaleId: {0}", param.LocaleId);
Console.WriteLine(" Offset: {0}", param.Offset);
Console.WriteLine(" CompareInfo: {0}", param.CompareInfo);
Console.WriteLine(" DbType: {0}", param.DbType);
Console.WriteLine(" Direction: {0}", param.Direction);
Console.WriteLine(" Precision: {0}", param.Precision);
Console.WriteLine(" Scale: {0}", param.Scale);
Console.WriteLine(" Size: {0}", param.Size);
Console.WriteLine(" SqlDbType: {0}", param.SqlDbType);
Console.WriteLine(" TypeName: {0}", param.TypeName);
//Console.WriteLine(" UdtTypeName: {0}", param.UdtTypeName);
Console.WriteLine(" XmlSchemaCollectionDatabase: {0}", param.XmlSchemaCollectionDatabase);
Console.WriteLine(" XmlSchemaCollectionName: {0}", param.XmlSchemaCollectionName);
Console.WriteLine(" XmlSchemaCollectionSchema: {0}", param.XmlSchemaCollectionOwningSchema);
}
#endregion
}
internal class TvpRestartableReader : DbDataReader
{
private IList<SqlDataRecord> _sourceData;
int _currentRow;
internal TvpRestartableReader(IList<SqlDataRecord> source) : base()
{
_sourceData = source;
Restart();
}
public void Restart()
{
_currentRow = -1;
}
override public int Depth
{
get { return 0; }
}
override public int FieldCount
{
get { return _sourceData[_currentRow].FieldCount; }
}
override public bool HasRows
{
get { return _sourceData.Count > 0; }
}
override public bool IsClosed
{
get { return false; }
}
override public int RecordsAffected
{
get { return 0; }
}
override public object this[int ordinal]
{
get { return GetValue(ordinal); }
}
override public object this[string name]
{
get { return GetValue(GetOrdinal(name)); }
}
override public void Close()
{
_currentRow = _sourceData.Count;
}
override public string GetDataTypeName(int ordinal)
{
return _sourceData[_currentRow].GetDataTypeName(ordinal);
}
override public IEnumerator GetEnumerator()
{
return _sourceData.GetEnumerator();
}
override public Type GetFieldType(int ordinal)
{
return _sourceData[_currentRow].GetFieldType(ordinal);
}
override public string GetName(int ordinal)
{
return _sourceData[_currentRow].GetName(ordinal);
}
override public int GetOrdinal(string name)
{
return _sourceData[_currentRow].GetOrdinal(name);
}
override public DataTable GetSchemaTable()
{
SqlDataRecord rec = _sourceData[0];
DataTable schemaTable = new DataTable();
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnName, typeof(System.String)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(System.Int32)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnSize, typeof(System.Int32)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericPrecision, typeof(System.Int16)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericScale, typeof(System.Int16)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.DataType, typeof(System.Type)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NonVersionedProviderType, typeof(System.Int32)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ProviderType, typeof(System.Int32)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsLong, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.AllowDBNull, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsUnique, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsKey, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsHidden, typeof(System.Boolean)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(System.String)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(System.String)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseTableName, typeof(System.String)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseColumnName, typeof(System.String)));
for (int i = 0; i < rec.FieldCount; i++)
{
DataRow row = schemaTable.NewRow();
SqlMetaData md = rec.GetSqlMetaData(i);
row[SchemaTableColumn.ColumnName] = md.Name;
row[SchemaTableColumn.ColumnOrdinal] = i;
row[SchemaTableColumn.ColumnSize] = md.MaxLength;
row[SchemaTableColumn.NumericPrecision] = md.Precision;
row[SchemaTableColumn.NumericScale] = md.Scale;
row[SchemaTableColumn.DataType] = rec.GetFieldType(i);
row[SchemaTableOptionalColumn.ProviderSpecificDataType] = rec.GetFieldType(i);
row[SchemaTableColumn.NonVersionedProviderType] = (int)md.SqlDbType;
row[SchemaTableColumn.ProviderType] = (int)md.SqlDbType;
row[SchemaTableColumn.IsLong] = md.MaxLength == SqlMetaData.Max || md.MaxLength > 8000;
row[SchemaTableColumn.AllowDBNull] = true;
row[SchemaTableOptionalColumn.IsReadOnly] = true;
row[SchemaTableOptionalColumn.IsRowVersion] = md.SqlDbType == SqlDbType.Timestamp;
row[SchemaTableColumn.IsUnique] = false;
row[SchemaTableColumn.IsKey] = false;
row[SchemaTableOptionalColumn.IsAutoIncrement] = false;
row[SchemaTableOptionalColumn.IsHidden] = false;
row[SchemaTableOptionalColumn.BaseCatalogName] = null;
row[SchemaTableColumn.BaseSchemaName] = null;
row[SchemaTableColumn.BaseTableName] = null;
row[SchemaTableColumn.BaseColumnName] = md.Name;
schemaTable.Rows.Add(row);
}
return schemaTable;
}
override public bool GetBoolean(int ordinal)
{
return _sourceData[_currentRow].GetBoolean(ordinal);
}
override public byte GetByte(int ordinal)
{
return _sourceData[_currentRow].GetByte(ordinal);
}
override public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
return _sourceData[_currentRow].GetBytes(ordinal, dataOffset, buffer, bufferOffset, length);
}
override public char GetChar(int ordinal)
{
return _sourceData[_currentRow].GetChar(ordinal);
}
override public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
return _sourceData[_currentRow].GetChars(ordinal, dataOffset, buffer, bufferOffset, length);
}
override public DateTime GetDateTime(int ordinal)
{
return _sourceData[_currentRow].GetDateTime(ordinal);
}
override public Decimal GetDecimal(int ordinal)
{
// DataRecord may have illegal values for Decimal...
Decimal result;
try
{
result = _sourceData[_currentRow].GetDecimal(ordinal);
}
catch (OverflowException)
{
result = (Decimal)1;
}
return result;
}
override public double GetDouble(int ordinal)
{
return _sourceData[_currentRow].GetDouble(ordinal);
}
override public float GetFloat(int ordinal)
{
return _sourceData[_currentRow].GetFloat(ordinal);
}
override public Guid GetGuid(int ordinal)
{
return _sourceData[_currentRow].GetGuid(ordinal);
}
override public Int16 GetInt16(int ordinal)
{
return _sourceData[_currentRow].GetInt16(ordinal);
}
override public Int32 GetInt32(int ordinal)
{
return _sourceData[_currentRow].GetInt32(ordinal);
}
override public Int64 GetInt64(int ordinal)
{
return _sourceData[_currentRow].GetInt64(ordinal);
}
override public String GetString(int ordinal)
{
return _sourceData[_currentRow].GetString(ordinal);
}
override public Object GetValue(int ordinal)
{
return _sourceData[_currentRow].GetValue(ordinal);
}
override public int GetValues(object[] values)
{
return _sourceData[_currentRow].GetValues(values);
}
override public bool IsDBNull(int ordinal)
{
return _sourceData[_currentRow].IsDBNull(ordinal);
}
override public bool NextResult()
{
Close();
return false;
}
override public bool Read()
{
_currentRow++;
return _currentRow < _sourceData.Count;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
namespace Avro
{
public class CodeGen
{
/// <summary>
/// Object that contains all the generated types
/// </summary>
public CodeCompileUnit CompileUnit { get; private set; }
/// <summary>
/// List of schemas to generate code for
/// </summary>
public IList<Schema> Schemas { get; private set; }
/// <summary>
/// List of protocols to generate code for
/// </summary>
public IList<Protocol> Protocols { get; private set; }
/// <summary>
/// List of generated namespaces
/// </summary>
protected Dictionary<string, CodeNamespace> namespaceLookup = new Dictionary<string, CodeNamespace>(StringComparer.Ordinal);
/// <summary>
/// Default constructor
/// </summary>
public CodeGen()
{
this.Schemas = new List<Schema>();
this.Protocols = new List<Protocol>();
}
/// <summary>
/// Adds a protocol object to generate code for
/// </summary>
/// <param name="protocol">protocol object</param>
public virtual void AddProtocol(Protocol protocol)
{
Protocols.Add(protocol);
}
/// <summary>
/// Adds a schema object to generate code for
/// </summary>
/// <param name="schema">schema object</param>
public virtual void AddSchema(Schema schema)
{
Schemas.Add(schema);
}
/// <summary>
/// Adds a namespace object for the given name into the dictionary if it doesn't exist yet
/// </summary>
/// <param name="name">name of namespace</param>
/// <returns></returns>
protected virtual CodeNamespace addNamespace(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name", "name cannot be null.");
CodeNamespace ns = null;
if (!namespaceLookup.TryGetValue(name, out ns))
{
ns = new CodeNamespace(CodeGenUtil.Instance.Mangle(name));
foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports)
ns.Imports.Add(nci);
CompileUnit.Namespaces.Add(ns);
namespaceLookup.Add(name, ns);
}
return ns;
}
/// <summary>
/// Generates code for the given protocol and schema objects
/// </summary>
/// <returns>CodeCompileUnit object</returns>
public virtual CodeCompileUnit GenerateCode()
{
CompileUnit = new CodeCompileUnit();
processSchemas();
processProtocols();
return CompileUnit;
}
/// <summary>
/// Generates code for the schema objects
/// </summary>
protected virtual void processSchemas()
{
foreach (Schema schema in this.Schemas)
{
SchemaNames names = generateNames(schema);
foreach (KeyValuePair<SchemaName, NamedSchema> sn in names)
{
switch (sn.Value.Tag)
{
case Schema.Type.Enumeration: processEnum(sn.Value); break;
case Schema.Type.Fixed: processFixed(sn.Value); break;
case Schema.Type.Record: processRecord(sn.Value); break;
case Schema.Type.Error: processRecord(sn.Value); break;
default:
throw new CodeGenException("Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag);
}
}
}
}
/// <summary>
/// Generates code for the protocol objects
/// </summary>
protected virtual void processProtocols()
{
foreach (Protocol protocol in Protocols)
{
SchemaNames names = generateNames(protocol);
foreach (KeyValuePair<SchemaName, NamedSchema> sn in names)
{
switch (sn.Value.Tag)
{
case Schema.Type.Enumeration: processEnum(sn.Value); break;
case Schema.Type.Fixed: processFixed(sn.Value); break;
case Schema.Type.Record: processRecord(sn.Value); break;
case Schema.Type.Error: processRecord(sn.Value); break;
default:
throw new CodeGenException("Names in protocol should only be of type NamedSchema, type found " + sn.Value.Tag);
}
}
processInterface(protocol);
}
}
/// <summary>
/// Generate list of named schemas from given protocol
/// </summary>
/// <param name="protocol">protocol to process</param>
/// <returns></returns>
protected virtual SchemaNames generateNames(Protocol protocol)
{
var names = new SchemaNames();
foreach (Schema schema in protocol.Types)
addName(schema, names);
return names;
}
/// <summary>
/// Generate list of named schemas from given schema
/// </summary>
/// <param name="schema">schema to process</param>
/// <returns></returns>
protected virtual SchemaNames generateNames(Schema schema)
{
var names = new SchemaNames();
addName(schema, names);
return names;
}
/// <summary>
/// Recursively search the given schema for named schemas and adds them to the given container
/// </summary>
/// <param name="schema">schema object to search</param>
/// <param name="names">list of named schemas</param>
protected virtual void addName(Schema schema, SchemaNames names)
{
NamedSchema ns = schema as NamedSchema;
if (null != ns) if (names.Contains(ns.SchemaName)) return;
switch (schema.Tag)
{
case Schema.Type.Null:
case Schema.Type.Boolean:
case Schema.Type.Int:
case Schema.Type.Long:
case Schema.Type.Float:
case Schema.Type.Double:
case Schema.Type.Bytes:
case Schema.Type.String:
break;
case Schema.Type.Enumeration:
case Schema.Type.Fixed:
names.Add(ns);
break;
case Schema.Type.Record:
case Schema.Type.Error:
var rs = schema as RecordSchema;
names.Add(rs);
foreach (Field field in rs.Fields)
addName(field.Schema, names);
break;
case Schema.Type.Array:
var asc = schema as ArraySchema;
addName(asc.ItemSchema, names);
break;
case Schema.Type.Map:
var ms = schema as MapSchema;
addName(ms.ValueSchema, names);
break;
case Schema.Type.Union:
var us = schema as UnionSchema;
foreach (Schema usc in us.Schemas)
addName(usc, names);
break;
default:
throw new CodeGenException("Unable to add name for " + schema.Name + " type " + schema.Tag);
}
}
/// <summary>
/// Creates a class declaration for fixed schema
/// </summary>
/// <param name="schema">fixed schema</param>
/// <param name="ns">namespace object</param>
protected virtual void processFixed(Schema schema)
{
FixedSchema fixedSchema = schema as FixedSchema;
if (null == fixedSchema) throw new CodeGenException("Unable to cast schema into a fixed");
CodeTypeDeclaration ctd = new CodeTypeDeclaration();
ctd.Name = CodeGenUtil.Instance.Mangle(fixedSchema.Name);
ctd.IsClass = true;
ctd.IsPartial = true;
ctd.Attributes = MemberAttributes.Public;
ctd.BaseTypes.Add("SpecificFixed");
// create static schema field
createSchemaField(schema, ctd, true);
// Add Size field
string sizefname = "fixedSize";
var ctrfield = new CodeTypeReference(typeof(uint));
var codeField = new CodeMemberField(ctrfield, sizefname);
codeField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
codeField.InitExpression = new CodePrimitiveExpression(fixedSchema.Size);
ctd.Members.Add(codeField);
// Add Size property
var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), sizefname);
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Static;
property.Name = "FixedSize";
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(schema.Name + "." + sizefname)));
ctd.Members.Add(property);
// create constructor to initiate base class SpecificFixed
CodeConstructor cc = new CodeConstructor();
cc.Attributes = MemberAttributes.Public;
cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(sizefname));
ctd.Members.Add(cc);
string nspace = fixedSchema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + fixedSchema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
}
/// <summary>
/// Creates an enum declaration
/// </summary>
/// <param name="schema">enum schema</param>
/// <param name="ns">namespace</param>
protected virtual void processEnum(Schema schema)
{
EnumSchema enumschema = schema as EnumSchema;
if (null == enumschema) throw new CodeGenException("Unable to cast schema into an enum");
CodeTypeDeclaration ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(enumschema.Name));
ctd.IsEnum = true;
ctd.Attributes = MemberAttributes.Public;
foreach (string symbol in enumschema.Symbols)
{
if (CodeGenUtil.Instance.ReservedKeywords.Contains(symbol))
throw new CodeGenException("Enum symbol " + symbol + " is a C# reserved keyword");
CodeMemberField field = new CodeMemberField(typeof(int), symbol);
ctd.Members.Add(field);
}
string nspace = enumschema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + enumschema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
}
protected virtual void processInterface(Protocol protocol)
{
// Create abstract class
string protocolNameMangled = CodeGenUtil.Instance.Mangle(protocol.Name);
var ctd = new CodeTypeDeclaration(protocolNameMangled);
ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
ctd.IsClass = true;
ctd.BaseTypes.Add("Avro.Specific.ISpecificProtocol");
AddProtocolDocumentation(protocol, ctd);
// Add static protocol field.
var protocolField = new CodeMemberField();
protocolField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
protocolField.Name = "protocol";
protocolField.Type = new CodeTypeReference("readonly Avro.Protocol");
var cpe = new CodePrimitiveExpression(protocol.ToString());
var cmie = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Protocol)), "Parse"),
new CodeExpression[] { cpe });
protocolField.InitExpression = cmie;
ctd.Members.Add(protocolField);
// Add overridden Protocol method.
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
property.Name = "Protocol";
property.Type = new CodeTypeReference("Avro.Protocol");
property.HasGet = true;
property.GetStatements.Add(new CodeTypeReferenceExpression("return protocol"));
ctd.Members.Add(property);
//var requestMethod = CreateRequestMethod();
//ctd.Members.Add(requestMethod);
var requestMethod = CreateRequestMethod();
//requestMethod.Attributes |= MemberAttributes.Override;
var builder = new StringBuilder();
if (protocol.Messages.Count > 0)
{
builder.Append("switch(messageName)\n\t\t\t{");
foreach (var a in protocol.Messages)
{
builder.Append("\n\t\t\t\tcase \"").Append(a.Key).Append("\":\n");
bool unused = false;
string type = getType(a.Value.Response, false, ref unused);
builder.Append("\t\t\t\trequestor.Request<")
.Append(type)
.Append(">(messageName, args, callback);\n");
builder.Append("\t\t\t\tbreak;\n");
}
builder.Append("\t\t\t}");
}
var cseGet = new CodeSnippetExpression(builder.ToString());
requestMethod.Statements.Add(cseGet);
ctd.Members.Add(requestMethod);
AddMethods(protocol, false, ctd);
string nspace = protocol.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + nspace);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
// Create callback abstract class
ctd = new CodeTypeDeclaration(protocolNameMangled + "Callback");
ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
ctd.IsClass = true;
ctd.BaseTypes.Add(protocolNameMangled);
// Need to override
AddProtocolDocumentation(protocol, ctd);
AddMethods(protocol, true, ctd);
codens.Types.Add(ctd);
}
private static CodeMemberMethod CreateRequestMethod()
{
var requestMethod = new CodeMemberMethod();
requestMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
requestMethod.Name = "Request";
requestMethod.ReturnType = new CodeTypeReference(typeof (void));
{
var requestor = new CodeParameterDeclarationExpression(typeof (Avro.Specific.ICallbackRequestor),
"requestor");
requestMethod.Parameters.Add(requestor);
var messageName = new CodeParameterDeclarationExpression(typeof (string), "messageName");
requestMethod.Parameters.Add(messageName);
var args = new CodeParameterDeclarationExpression(typeof (object[]), "args");
requestMethod.Parameters.Add(args);
var callback = new CodeParameterDeclarationExpression(typeof (object), "callback");
requestMethod.Parameters.Add(callback);
}
return requestMethod;
}
private static void AddMethods(Protocol protocol, bool generateCallback, CodeTypeDeclaration ctd)
{
foreach (var e in protocol.Messages)
{
var name = e.Key;
var message = e.Value;
var response = message.Response;
if (generateCallback && message.Oneway.GetValueOrDefault())
continue;
var messageMember = new CodeMemberMethod();
messageMember.Name = CodeGenUtil.Instance.Mangle(name);
messageMember.Attributes = MemberAttributes.Public | MemberAttributes.Abstract;
if (message.Doc!= null && message.Doc.Trim() != string.Empty)
messageMember.Comments.Add(new CodeCommentStatement(message.Doc));
if (message.Oneway.GetValueOrDefault() || generateCallback)
{
messageMember.ReturnType = new CodeTypeReference(typeof (void));
}
else
{
bool ignored = false;
string type = getType(response, false, ref ignored);
messageMember.ReturnType = new CodeTypeReference(type);
}
foreach (Field field in message.Request.Fields)
{
bool ignored = false;
string type = getType(field.Schema, false, ref ignored);
string fieldName = CodeGenUtil.Instance.Mangle(field.Name);
var parameter = new CodeParameterDeclarationExpression(type, fieldName);
messageMember.Parameters.Add(parameter);
}
if (generateCallback)
{
bool unused = false;
var type = getType(response, false, ref unused);
var parameter = new CodeParameterDeclarationExpression("Avro.IO.ICallback<" + type + ">",
"callback");
messageMember.Parameters.Add(parameter);
}
ctd.Members.Add(messageMember);
}
}
private void AddProtocolDocumentation(Protocol protocol, CodeTypeDeclaration ctd)
{
// Add interface documentation
if (protocol.Doc != null && protocol.Doc.Trim() != string.Empty)
{
var interfaceDoc = createDocComment(protocol.Doc);
if (interfaceDoc != null)
ctd.Comments.Add(interfaceDoc);
}
}
/// <summary>
/// Creates a class declaration
/// </summary>
/// <param name="schema">record schema</param>
/// <param name="ns">namespace</param>
/// <returns></returns>
protected virtual CodeTypeDeclaration processRecord(Schema schema)
{
RecordSchema recordSchema = schema as RecordSchema;
if (null == recordSchema) throw new CodeGenException("Unable to cast schema into a record");
bool isError = recordSchema.Tag == Schema.Type.Error;
// declare the class
var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name));
ctd.BaseTypes.Add(isError ? "SpecificException" : "ISpecificRecord");
ctd.Attributes = MemberAttributes.Public;
ctd.IsClass = true;
ctd.IsPartial = true;
createSchemaField(schema, ctd, isError);
// declare Get() to be used by the Writer classes
var cmmGet = new CodeMemberMethod();
cmmGet.Name = "Get";
cmmGet.Attributes = MemberAttributes.Public;
cmmGet.ReturnType = new CodeTypeReference("System.Object");
cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");
// declare Put() to be used by the Reader classes
var cmmPut = new CodeMemberMethod();
cmmPut.Name = "Put";
cmmPut.Attributes = MemberAttributes.Public;
cmmPut.ReturnType = new CodeTypeReference(typeof(void));
cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue"));
var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");
if (isError)
{
cmmGet.Attributes |= MemberAttributes.Override;
cmmPut.Attributes |= MemberAttributes.Override;
}
foreach (Field field in recordSchema.Fields)
{
// Determine type of field
bool nullibleEnum = false;
string baseType = getType(field.Schema, false, ref nullibleEnum);
var ctrfield = new CodeTypeReference(baseType);
// Create field
string privFieldName = string.Concat("_", field.Name);
var codeField = new CodeMemberField(ctrfield, privFieldName);
codeField.Attributes = MemberAttributes.Private;
// Process field documentation if it exist and add to the field
CodeCommentStatement propertyComment = null;
if (!string.IsNullOrEmpty(field.Documentation))
{
propertyComment = createDocComment(field.Documentation);
if (null != propertyComment)
codeField.Comments.Add(propertyComment);
}
// Add field to class
ctd.Members.Add(codeField);
// Create reference to the field - this.fieldname
var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName);
var mangledName = CodeGenUtil.Instance.Mangle(field.Name);
// Create field property with get and set methods
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
property.Name = mangledName;
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression()));
if (null != propertyComment)
property.Comments.Add(propertyComment);
// Add field property to class
ctd.Members.Add(property);
// add to Get()
getFieldStmt.Append("\t\t\tcase ");
getFieldStmt.Append(field.Pos);
getFieldStmt.Append(": return this.");
getFieldStmt.Append(mangledName);
getFieldStmt.Append(";\n");
// add to Put()
putFieldStmt.Append("\t\t\tcase ");
putFieldStmt.Append(field.Pos);
putFieldStmt.Append(": this.");
putFieldStmt.Append(mangledName);
if (nullibleEnum)
{
putFieldStmt.Append(" = fieldValue == null ? (");
putFieldStmt.Append(baseType);
putFieldStmt.Append(")null : (");
string type = baseType.Remove(0, 16); // remove System.Nullable<
type = type.Remove(type.Length - 1); // remove >
putFieldStmt.Append(type);
putFieldStmt.Append(")fieldValue; break;\n");
}
else
{
putFieldStmt.Append(" = (");
putFieldStmt.Append(baseType);
putFieldStmt.Append(")fieldValue; break;\n");
}
}
// end switch block for Get()
getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}");
var cseGet = new CodeSnippetExpression(getFieldStmt.ToString());
cmmGet.Statements.Add(cseGet);
ctd.Members.Add(cmmGet);
// end switch block for Put()
putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}");
var csePut = new CodeSnippetExpression(putFieldStmt.ToString());
cmmPut.Statements.Add(csePut);
ctd.Members.Add(cmmPut);
string nspace = recordSchema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for record schema " + recordSchema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
return ctd;
}
/// <summary>
/// Gets the string representation of the schema's data type
/// </summary>
/// <param name="schema">schema</param>
/// <param name="nullible">flag to indicate union with null</param>
/// <returns></returns>
internal static string getType(Schema schema, bool nullible, ref bool nullibleEnum)
{
switch (schema.Tag)
{
case Schema.Type.Null:
return "System.Object";
case Schema.Type.Boolean:
if (nullible) return "System.Nullable<bool>";
else return typeof(bool).ToString();
case Schema.Type.Int:
if (nullible) return "System.Nullable<int>";
else return typeof(int).ToString();
case Schema.Type.Long:
if (nullible) return "System.Nullable<long>";
else return typeof(long).ToString();
case Schema.Type.Float:
if (nullible) return "System.Nullable<float>";
else return typeof(float).ToString();
case Schema.Type.Double:
if (nullible) return "System.Nullable<double>";
else return typeof(double).ToString();
case Schema.Type.Bytes:
return typeof(byte[]).ToString();
case Schema.Type.String:
return typeof(string).ToString();
case Schema.Type.Enumeration:
var namedSchema = schema as NamedSchema;
if (null == namedSchema)
throw new CodeGenException("Unable to cast schema into a named schema");
if (nullible)
{
nullibleEnum = true;
return "System.Nullable<" + CodeGenUtil.Instance.Mangle(namedSchema.Fullname) + ">";
}
else return CodeGenUtil.Instance.Mangle(namedSchema.Fullname);
case Schema.Type.Fixed:
case Schema.Type.Record:
case Schema.Type.Error:
namedSchema = schema as NamedSchema;
if (null == namedSchema)
throw new CodeGenException("Unable to cast schema into a named schema");
return CodeGenUtil.Instance.Mangle(namedSchema.Fullname);
case Schema.Type.Array:
var arraySchema = schema as ArraySchema;
if (null == arraySchema)
throw new CodeGenException("Unable to cast schema into an array schema");
return "IList<" + getType(arraySchema.ItemSchema, false, ref nullibleEnum) + ">";
case Schema.Type.Map:
var mapSchema = schema as MapSchema;
if (null == mapSchema)
throw new CodeGenException("Unable to cast schema into a map schema");
return "IDictionary<string," + getType(mapSchema.ValueSchema, false, ref nullibleEnum) + ">";
case Schema.Type.Union:
var unionSchema = schema as UnionSchema;
if (null == unionSchema)
throw new CodeGenException("Unable to cast schema into a union schema");
Schema nullibleType = getNullableType(unionSchema);
if (null == nullibleType)
return CodeGenUtil.Object;
else
return getType(nullibleType, true, ref nullibleEnum);
}
throw new CodeGenException("Unable to generate CodeTypeReference for " + schema.Name + " type " + schema.Tag);
}
/// <summary>
/// Gets the schema of a union with null
/// </summary>
/// <param name="schema">union schema</param>
/// <returns>schema that is nullible</returns>
public static Schema getNullableType(UnionSchema schema)
{
Schema ret = null;
if (schema.Count == 2)
{
bool nullable = false;
foreach (Schema childSchema in schema.Schemas)
{
if (childSchema.Tag == Schema.Type.Null)
nullable = true;
else
ret = childSchema;
}
if (!nullable)
ret = null;
}
return ret;
}
/// <summary>
/// Creates the static schema field for class types
/// </summary>
/// <param name="schema">schema</param>
/// <param name="ctd">CodeTypeDeclaration for the class</param>
protected virtual void createSchemaField(Schema schema, CodeTypeDeclaration ctd, bool overrideFlag)
{
// create schema field
var ctrfield = new CodeTypeReference("Schema");
string schemaFname = "_SCHEMA";
var codeField = new CodeMemberField(ctrfield, schemaFname);
codeField.Attributes = MemberAttributes.Public | MemberAttributes.Static;
// create function call Schema.Parse(json)
var cpe = new CodePrimitiveExpression(schema.ToString());
var cmie = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Schema)), "Parse"),
new CodeExpression[] { cpe });
codeField.InitExpression = cmie;
ctd.Members.Add(codeField);
// create property to get static schema field
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public;
if (overrideFlag) property.Attributes |= MemberAttributes.Override;
property.Name = "Schema";
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(ctd.Name + "." + schemaFname)));
ctd.Members.Add(property);
}
/// <summary>
/// Creates an XML documentation for the given comment
/// </summary>
/// <param name="comment">comment</param>
/// <returns>CodeCommentStatement object</returns>
protected virtual CodeCommentStatement createDocComment(string comment)
{
string text = string.Format("<summary>\r\n {0}\r\n </summary>", comment);
return new CodeCommentStatement(text, true);
}
/// <summary>
/// Writes the generated compile unit into one file
/// </summary>
/// <param name="outputFile">name of output file to write to</param>
public virtual void WriteCompileUnit(string outputFile)
{
var cscp = new CSharpCodeProvider();
var opts = new CodeGeneratorOptions();
opts.BracingStyle = "C";
opts.IndentString = "\t";
opts.BlankLinesBetweenMembers = false;
using (var outfile = new StreamWriter(outputFile))
{
cscp.GenerateCodeFromCompileUnit(CompileUnit, outfile, opts);
}
}
/// <summary>
/// Writes each types in each namespaces into individual files
/// </summary>
/// <param name="outputdir">name of directory to write to</param>
public virtual void WriteTypes(string outputdir)
{
var cscp = new CSharpCodeProvider();
var opts = new CodeGeneratorOptions();
opts.BracingStyle = "C";
opts.IndentString = "\t";
opts.BlankLinesBetweenMembers = false;
CodeNamespaceCollection nsc = CompileUnit.Namespaces;
for (int i = 0; i < nsc.Count; i++)
{
var ns = nsc[i];
string dir = outputdir + "\\" + CodeGenUtil.Instance.UnMangle(ns.Name).Replace('.', '\\');
Directory.CreateDirectory(dir);
var new_ns = new CodeNamespace(ns.Name);
new_ns.Comments.Add(CodeGenUtil.Instance.FileComment);
foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports)
new_ns.Imports.Add(nci);
var types = ns.Types;
for (int j = 0; j < types.Count; j++)
{
var ctd = types[j];
string file = dir + "\\" + CodeGenUtil.Instance.UnMangle(ctd.Name) + ".cs";
using (var writer = new StreamWriter(file, false))
{
new_ns.Types.Add(ctd);
cscp.GenerateCodeFromNamespace(new_ns, writer, opts);
new_ns.Types.Remove(ctd);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_TupleExpression()
{
string source = @"
class Class1
{
public void M(int x, int y)
{
var tuple = /*<bind>*/(x, x + y)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITupleExpression (OperationKind.TupleExpression, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, x + y)')
Elements(2):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
IBinaryOperatorExpression (BinaryOperatorKind.Add) (OperationKind.BinaryOperatorExpression, Type: System.Int32) (Syntax: 'x + y')
Left:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
Right:
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y')
";
var expectedDiagnostics = new[] {
// file.cs(6,13): warning CS0219: The variable 'tuple' is assigned but its value is never used
// var tuple = /*<bind>*/(x, x + y)/*</bind>*/;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "tuple").WithArguments("tuple").WithLocation(6, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_TupleDeconstruction()
{
string source = @"
class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
}
class Class1
{
public void M(Point point)
{
/*<bind>*/var (x, y) = point/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: 'var (x, y) = point')
Children(2):
ITupleExpression (OperationKind.TupleExpression, Type: (System.Int32 x, System.Int32 y)) (Syntax: 'var (x, y)')
Elements(2):
ILocalReferenceExpression: x (IsDeclaration: True) (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'x')
ILocalReferenceExpression: y (IsDeclaration: True) (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'y')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: (System.Int32 x, System.Int32 y), IsImplicit) (Syntax: 'point')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: point (OperationKind.ParameterReferenceExpression, Type: Point) (Syntax: 'point')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_AnonymousObjectCreation()
{
string source = @"
class Class1
{
public void M(int x, string y)
{
var v = /*<bind>*/new { Amount = x, Message = ""Hello"" + y }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAnonymousObjectCreationExpression (OperationKind.AnonymousObjectCreationExpression, Type: <anonymous type: System.Int32 Amount, System.String Message>) (Syntax: 'new { Amoun ... ello"" + y }')
Initializers(2):
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'Amount = x')
Left:
IPropertyReferenceExpression: System.Int32 <anonymous type: System.Int32 Amount, System.String Message>.Amount { get; } (Static) (OperationKind.PropertyReferenceExpression, Type: System.Int32) (Syntax: 'Amount')
Instance Receiver:
null
Right:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.String) (Syntax: 'Message = ""Hello"" + y')
Left:
IPropertyReferenceExpression: System.String <anonymous type: System.Int32 Amount, System.String Message>.Message { get; } (Static) (OperationKind.PropertyReferenceExpression, Type: System.String) (Syntax: 'Message')
Instance Receiver:
null
Right:
IBinaryOperatorExpression (BinaryOperatorKind.Add) (OperationKind.BinaryOperatorExpression, Type: System.String) (Syntax: '""Hello"" + y')
Left:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""Hello"") (Syntax: '""Hello""')
Right:
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.String) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AnonymousObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_QueryExpression()
{
string source = @"
using System.Linq;
using System.Collections.Generic;
struct Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
class Class1
{
public void M(List<Customer> customers)
{
var result = /*<bind>*/from cust in customers
select cust.Name/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryExpression (OperationKind.TranslatedQueryExpression, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from cust i ... t cust.Name')
Expression:
IInvocationExpression (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<Customer, System.String>(this System.Collections.Generic.IEnumerable<Customer> source, System.Func<Customer, System.String> selector)) (OperationKind.InvocationExpression, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select cust.Name')
Instance Receiver:
null
Arguments(2):
IArgument (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, IsImplicit) (Syntax: 'from cust in customers')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Collections.Generic.IEnumerable<Customer>, IsImplicit) (Syntax: 'from cust in customers')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: customers (OperationKind.ParameterReferenceExpression, Type: System.Collections.Generic.List<Customer>) (Syntax: 'customers')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgument (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, IsImplicit) (Syntax: 'cust.Name')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Func<Customer, System.String>, IsImplicit) (Syntax: 'cust.Name')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAnonymousFunctionExpression (Symbol: lambda expression) (OperationKind.AnonymousFunctionExpression, Type: null, IsImplicit) (Syntax: 'cust.Name')
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'cust.Name')
IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: 'cust.Name')
ReturnedValue:
IPropertyReferenceExpression: System.String Customer.Name { get; set; } (OperationKind.PropertyReferenceExpression, Type: System.String) (Syntax: 'cust.Name')
Instance Receiver:
IOperation: (OperationKind.None) (Syntax: 'cust')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_ObjectAndCollectionInitializer()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public int X { get; set; }
public List<int> Y { get; set; }
public Dictionary<int, int> Z { get; set; }
public Class C { get; set; }
public void M(int x, int y, int z)
{
var c = /*<bind>*/new Class() { X = x, Y = { x, y, 3 }, Z = { { x, y } }, C = { X = z } }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IObjectCreationExpression (Constructor: Class..ctor()) (OperationKind.ObjectCreationExpression, Type: Class) (Syntax: 'new Class() ... { X = z } }')
Arguments(0)
Initializer:
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: Class) (Syntax: '{ X = x, Y ... { X = z } }')
Initializers(4):
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'X = x')
Left:
IPropertyReferenceExpression: System.Int32 Class.X { get; set; } (OperationKind.PropertyReferenceExpression, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: Class) (Syntax: 'X')
Right:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
IMemberInitializerExpression (OperationKind.MemberInitializerExpression, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y = { x, y, 3 }')
InitializedMember:
IPropertyReferenceExpression: System.Collections.Generic.List<System.Int32> Class.Y { get; set; } (OperationKind.PropertyReferenceExpression, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: Class) (Syntax: 'Y')
Initializer:
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '{ x, y, 3 }')
Initializers(3):
ICollectionElementInitializerExpression (AddMethod: void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void, IsImplicit) (Syntax: 'x')
Arguments(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
ICollectionElementInitializerExpression (AddMethod: void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void, IsImplicit) (Syntax: 'y')
Arguments(1):
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y')
ICollectionElementInitializerExpression (AddMethod: void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void, IsImplicit) (Syntax: '3')
Arguments(1):
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3')
IMemberInitializerExpression (OperationKind.MemberInitializerExpression, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z = { { x, y } }')
InitializedMember:
IPropertyReferenceExpression: System.Collections.Generic.Dictionary<System.Int32, System.Int32> Class.Z { get; set; } (OperationKind.PropertyReferenceExpression, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: Class) (Syntax: 'Z')
Initializer:
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: '{ { x, y } }')
Initializers(1):
ICollectionElementInitializerExpression (AddMethod: void System.Collections.Generic.Dictionary<System.Int32, System.Int32>.Add(System.Int32 key, System.Int32 value)) (IsDynamic: False) (OperationKind.CollectionElementInitializerExpression, Type: System.Void, IsImplicit) (Syntax: '{ x, y }')
Arguments(2):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y')
IMemberInitializerExpression (OperationKind.MemberInitializerExpression, Type: Class) (Syntax: 'C = { X = z }')
InitializedMember:
IPropertyReferenceExpression: Class Class.C { get; set; } (OperationKind.PropertyReferenceExpression, Type: Class) (Syntax: 'C')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: Class) (Syntax: 'C')
Initializer:
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: Class) (Syntax: '{ X = z }')
Initializers(1):
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'X = z')
Left:
IPropertyReferenceExpression: System.Int32 Class.X { get; set; } (OperationKind.PropertyReferenceExpression, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: Class) (Syntax: 'X')
Right:
IParameterReferenceExpression: z (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'z')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DelegateCreationExpressionWithLambdaArgument()
{
string source = @"
using System;
class Class
{
// Used parameter methods
public void UsedParameterMethod1(Action a)
{
Action a2 = /*<bind>*/new Action(() =>
{
a();
})/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: 'new Action( ... })')
Children(1):
IAnonymousFunctionExpression (Symbol: lambda expression) (OperationKind.AnonymousFunctionExpression, Type: null) (Syntax: '() => ... }')
IBlockStatement (2 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'a();')
Expression:
IInvocationExpression (virtual void System.Action.Invoke()) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'a()')
Instance Receiver:
IParameterReferenceExpression: a (OperationKind.ParameterReferenceExpression, Type: System.Action) (Syntax: 'a')
Arguments(0)
IReturnStatement (OperationKind.ReturnStatement, IsImplicit) (Syntax: '{ ... }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DelegateCreationExpressionWithMethodArgument()
{
string source = @"
using System;
class Class
{
public delegate void Delegate(int x, int y);
public void Method(Delegate d)
{
var a = /*<bind>*/new Delegate(Method2)/*</bind>*/;
}
public void Method2(int x, int y)
{
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: 'new Delegate(Method2)')
Children(1):
IOperation: (OperationKind.None) (Syntax: 'Method2')
Children(1):
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: Class, IsImplicit) (Syntax: 'Method2')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DelegateCreationExpressionWithInvalidArgument()
{
string source = @"
using System;
class Class
{
public delegate void Delegate(int x, int y);
public void Method(int x)
{
var a = /*<bind>*/new Delegate(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidExpression (OperationKind.InvalidExpression, Type: Class.Delegate, IsInvalid) (Syntax: 'new Delegate(x)')
Children(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0149: Method name expected
// var a = /*<bind>*/new Delegate(x)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethodNameExpected, "x").WithLocation(10, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicCollectionInitializer()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public dynamic X { get; set; }
public void M(int x, int y)
{
var c = new Class() /*<bind>*/{ X = { { x, y } } }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: Class) (Syntax: '{ X = { { x, y } } }')
Initializers(1):
IMemberInitializerExpression (OperationKind.MemberInitializerExpression, Type: dynamic) (Syntax: 'X = { { x, y } }')
InitializedMember:
IPropertyReferenceExpression: dynamic Class.X { get; set; } (OperationKind.PropertyReferenceExpression, Type: dynamic) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: Class) (Syntax: 'X')
Initializer:
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: dynamic) (Syntax: '{ { x, y } }')
Initializers(1):
ICollectionElementInitializerExpression (IsDynamic: True) (OperationKind.CollectionElementInitializerExpression, Type: System.Void) (Syntax: '{ x, y }')
Arguments(2):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_NameOfExpression()
{
string source = @"
class Class1
{
public string M(int x)
{
return /*<bind>*/nameof(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
INameOfExpression (OperationKind.NameOfExpression, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)')
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_PointerIndirectionExpression()
{
string source = @"
class Class1
{
public unsafe int M(int *x)
{
return /*<bind>*/*x/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: '*x')
Children(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32*) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0227: Unsafe code may only appear if compiling with /unsafe
// public unsafe int M(int *x)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(4, 23)
};
VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_FixedLocalInitializer()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public unsafe void M(int[] array)
{
fixed (int* /*<bind>*/p = array/*</bind>*/)
{
*p = 1;
}
}
}
";
string expectedOperationTree = @"
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'p = array')
Variables: Local_1: System.Int32* p
Initializer:
IOperation: (OperationKind.None) (Syntax: 'array')
Children(1):
IParameterReferenceExpression: array (OperationKind.ParameterReferenceExpression, Type: System.Int32[]) (Syntax: 'array')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0227: Unsafe code may only appear if compiling with /unsafe
// public unsafe void M(int[] array)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24)
};
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_RefTypeOperator()
{
string source = @"
class Class1
{
public System.Type M(System.TypedReference x)
{
return /*<bind>*/__reftype(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: '__reftype(x)')
Children(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.TypedReference) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<RefTypeExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_MakeRefOperator()
{
string source = @"
class Class1
{
public void M(System.Type x)
{
var y = /*<bind>*/__makeref(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: '__makeref(x)')
Children(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Type) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<MakeRefExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_RefValueOperator()
{
string source = @"
class Class1
{
public void M(System.TypedReference x)
{
var y = /*<bind>*/__refvalue(x, int)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: '__refvalue(x, int)')
Children(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.TypedReference) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<RefValueExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicIndexerAccess()
{
string source = @"
class Class1
{
public void M(dynamic d, int x)
{
var /*<bind>*/y = d[x]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'y = d[x]')
Variables: Local_1: dynamic y
Initializer:
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'd[x]')
Expression:
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
Arguments(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicMemberAccess()
{
string source = @"
class Class1
{
public void M(dynamic x, int y)
{
var z = /*<bind>*/x.M(y)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'x.M(y)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: dynamic) (Syntax: 'x.M')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'x')
Arguments(1):
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicInvocation()
{
string source = @"
class Class1
{
public void M(dynamic x, int y)
{
var z = /*<bind>*/x(y)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'x(y)')
Expression:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'x')
Arguments(1):
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DynamicObjectCreation()
{
string source = @"
internal class Class
{
public Class(Class x) { }
public Class(string x) { }
public void M(dynamic x)
{
var c = /*<bind>*/new Class(x)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: Class) (Syntax: 'new Class(x)')
Arguments(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'x')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_StackAllocArrayCreation()
{
string source = @"
using System.Collections.Generic;
internal class Class
{
public unsafe void M(int x)
{
int* block = /*<bind>*/stackalloc int[x]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: 'stackalloc int[x]')
Children(1):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0227: Unsafe code may only appear if compiling with /unsafe
// public unsafe void M(int x)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24)
};
VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_InterpolatedStringExpression()
{
string source = @"
using System;
internal class Class
{
public void M(string x, int y)
{
Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/);
}
}
";
string expectedOperationTree = @"
IInterpolatedStringExpression (OperationKind.InterpolatedStringExpression, Type: System.String) (Syntax: '$""String {x ... nstant {1}""')
Parts(6):
IInterpolatedStringText (OperationKind.InterpolatedStringText) (Syntax: 'String ')
Text:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""String "") (Syntax: 'String ')
IInterpolation (OperationKind.Interpolation) (Syntax: '{x,20}')
Expression:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.String) (Syntax: 'x')
Alignment:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 20) (Syntax: '20')
FormatString:
null
IInterpolatedStringText (OperationKind.InterpolatedStringText) (Syntax: ' and ')
Text:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "" and "") (Syntax: ' and ')
IInterpolation (OperationKind.Interpolation) (Syntax: '{y:D3}')
Expression:
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'y')
Alignment:
null
FormatString:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""D3"") (Syntax: ':D3')
IInterpolatedStringText (OperationKind.InterpolatedStringText) (Syntax: ' and constant ')
Text:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: "" and constant "") (Syntax: ' and constant ')
IInterpolation (OperationKind.Interpolation) (Syntax: '{1}')
Expression:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1')
Alignment:
null
FormatString:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_ThrowExpression()
{
string source = @"
using System;
internal class Class
{
public void M(string x)
{
var y = x ?? /*<bind>*/throw new ArgumentNullException(nameof(x))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IThrowExpression (OperationKind.ThrowExpression, Type: null) (Syntax: 'throw new A ... (nameof(x))')
IObjectCreationExpression (Constructor: System.ArgumentNullException..ctor(System.String paramName)) (OperationKind.ObjectCreationExpression, Type: System.ArgumentNullException) (Syntax: 'new Argumen ... (nameof(x))')
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: paramName) (OperationKind.Argument) (Syntax: 'nameof(x)')
INameOfExpression (OperationKind.NameOfExpression, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)')
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.String) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ThrowExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_PatternSwitchStatement()
{
string source = @"
internal class Class
{
public void M(int x)
{
switch (x)
{
/*<bind>*/case var y when (x >= 10):
break;/*</bind>*/
}
}
}
";
string expectedOperationTree = @"
ISwitchCase (1 case clauses, 1 statements) (OperationKind.SwitchCase) (Syntax: 'case var y ... break;')
Clauses:
IPatternCaseClause (Label Symbol: case var y when (x >= 10):) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case var y ... (x >= 10):')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 y) (OperationKind.DeclarationPattern) (Syntax: 'var y')
Guard Expression:
IBinaryOperatorExpression (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'x >= 10')
Left:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 10) (Syntax: '10')
Body:
IBranchStatement (BranchKind.Break) (OperationKind.BranchStatement) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchSectionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_DefaultPatternSwitchStatement()
{
string source = @"
internal class Class
{
public void M(int x)
{
switch (x)
{
case var y when (x >= 10):
break;
/*<bind>*/default:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IDefaultCaseClause (CaseKind.Default) (OperationKind.CaseClause) (Syntax: 'default:')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<DefaultSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_UserDefinedLogicalConditionalOperator()
{
string source = @"
class A<T>
{
public static bool operator true(A<T> o) { return true; }
public static bool operator false(A<T> o) { return false; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static C operator |(C x, C y) { return x; }
}
class P
{
static void M(C x, C y)
{
if (/*<bind>*/x && y/*</bind>*/)
{
}
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: 'x && y')
Children(2):
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: B, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'x')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: B, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_NoPiaObjectCreation()
{
var sources0 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")]
[CoClass(typeof(C))]
public interface I
{
int P { get; set; }
}
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")]
public class C
{
public C(object o)
{
}
}
";
var sources1 = @"
struct S
{
public I F(object x)
{
return /*<bind>*/new I(x)/*</bind>*/;
}
}
";
var compilation0 = CreateStandardCompilation(sources0);
compilation0.VerifyDiagnostics();
var compilation1 = CreateStandardCompilation(
sources1,
references: new[] { MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes: true) });
string expectedOperationTree = @"
IOperation: (OperationKind.None, IsInvalid) (Syntax: 'new I(x)')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// (6,25): error CS1729: 'I' does not contain a constructor that takes 1 arguments
// return /*<bind>*/new I(x)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(x)").WithArguments("I", "1").WithLocation(6, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation1, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")]
public void ParameterReference_ArgListOperator()
{
string source = @"
using System;
class C
{
static void Method(int x, bool y)
{
M(1, /*<bind>*/__arglist(x, y)/*</bind>*/);
}
static void M(int x, __arglist)
{
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None) (Syntax: '__arglist(x, y)')
Children(2):
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'x')
IParameterReferenceExpression: y (OperationKind.ParameterReferenceExpression, Type: System.Boolean) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19790, "https://github.com/dotnet/roslyn/issues/19790")]
public void ParameterReference_IsPatternExpression()
{
string source = @"
class Class1
{
public void Method1(object x)
{
if (/*<bind>*/x is int y/*</bind>*/) { }
}
}
";
string expectedOperationTree = @"
IIsPatternExpression (OperationKind.IsPatternExpression, Type: System.Boolean) (Syntax: 'x is int y')
Expression:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'x')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 y) (OperationKind.DeclarationPattern) (Syntax: 'int y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19902, "https://github.com/dotnet/roslyn/issues/19902")]
public void ParameterReference_LocalFunctionStatement()
{
string source = @"
using System;
using System.Collections.Generic;
class Class
{
static IEnumerable<T> MyIterator<T>(IEnumerable<T> source, Func<T, bool> predicate)
{
/*<bind>*/IEnumerable<T> Iterator()
{
foreach (var element in source)
if (predicate(element))
yield return element;
}/*</bind>*/
return Iterator();
}
}
";
string expectedOperationTree = @"
ILocalFunctionStatement (Symbol: System.Collections.Generic.IEnumerable<T> Iterator()) (OperationKind.LocalFunctionStatement) (Syntax: 'IEnumerable ... }')
IBlockStatement (2 statements) (OperationKind.BlockStatement) (Syntax: '{ ... }')
IForEachLoopStatement (LoopKind.ForEach) (OperationKind.LoopStatement) (Syntax: 'foreach (va ... rn element;')
Locals: Local_1: T element
LoopControlVariable:
ILocalReferenceExpression: element (IsDeclaration: True) (OperationKind.LocalReferenceExpression, Type: T, Constant: null) (Syntax: 'foreach (va ... rn element;')
Collection:
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Collections.Generic.IEnumerable<T>, IsImplicit) (Syntax: 'source')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: source (OperationKind.ParameterReferenceExpression, Type: System.Collections.Generic.IEnumerable<T>) (Syntax: 'source')
Body:
IIfStatement (OperationKind.IfStatement) (Syntax: 'if (predica ... rn element;')
Condition:
IInvocationExpression (virtual System.Boolean System.Func<T, System.Boolean>.Invoke(T arg)) (OperationKind.InvocationExpression, Type: System.Boolean) (Syntax: 'predicate(element)')
Instance Receiver:
IParameterReferenceExpression: predicate (OperationKind.ParameterReferenceExpression, Type: System.Func<T, System.Boolean>) (Syntax: 'predicate')
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument) (Syntax: 'element')
ILocalReferenceExpression: element (OperationKind.LocalReferenceExpression, Type: T) (Syntax: 'element')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IfTrue:
IReturnStatement (OperationKind.YieldReturnStatement) (Syntax: 'yield return element;')
ReturnedValue:
ILocalReferenceExpression: element (OperationKind.LocalReferenceExpression, Type: T) (Syntax: 'element')
IfFalse:
null
NextVariables(0)
IReturnStatement (OperationKind.YieldBreakStatement, IsImplicit) (Syntax: '{ ... }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Threading;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Managed environment. Acts as a gateway for native code.
/// </summary>
internal static class ExceptionUtils
{
/** NoClassDefFoundError fully-qualified class name which is important during startup phase. */
private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError";
/** NoSuchMethodError fully-qualified class name which is important during startup phase. */
private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError";
/** InteropCachePartialUpdateException. */
private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException";
/** Map with predefined exceptions. */
private static readonly IDictionary<string, ExceptionFactoryDelegate> EXS = new Dictionary<string, ExceptionFactoryDelegate>();
/** Exception factory delegate. */
private delegate Exception ExceptionFactoryDelegate(string msg);
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability")]
static ExceptionUtils()
{
// Common Java exceptions mapped to common .Net exceptions.
EXS["java.lang.IllegalArgumentException"] = m => new ArgumentException(m);
EXS["java.lang.IllegalStateException"] = m => new InvalidOperationException(m);
EXS["java.lang.UnsupportedOperationException"] = m => new NotImplementedException(m);
EXS["java.lang.InterruptedException"] = m => new ThreadInterruptedException(m);
// Generic Ignite exceptions.
EXS["org.apache.ignite.IgniteException"] = m => new IgniteException(m);
EXS["org.apache.ignite.IgniteCheckedException"] = m => new IgniteException(m);
// Cluster exceptions.
EXS["org.apache.ignite.cluster.ClusterGroupEmptyException"] = m => new ClusterGroupEmptyException(m);
EXS["org.apache.ignite.cluster.ClusterTopologyException"] = m => new ClusterTopologyException(m);
// Compute exceptions.
EXS["org.apache.ignite.compute.ComputeExecutionRejectedException"] = m => new ComputeExecutionRejectedException(m);
EXS["org.apache.ignite.compute.ComputeJobFailoverException"] = m => new ComputeJobFailoverException(m);
EXS["org.apache.ignite.compute.ComputeTaskCancelledException"] = m => new ComputeTaskCancelledException(m);
EXS["org.apache.ignite.compute.ComputeTaskTimeoutException"] = m => new ComputeTaskTimeoutException(m);
EXS["org.apache.ignite.compute.ComputeUserUndeclaredException"] = m => new ComputeUserUndeclaredException(m);
// Cache exceptions.
EXS["javax.cache.CacheException"] = m => new CacheException(m);
EXS["javax.cache.integration.CacheLoaderException"] = m => new CacheStoreException(m);
EXS["javax.cache.integration.CacheWriterException"] = m => new CacheStoreException(m);
EXS["javax.cache.processor.EntryProcessorException"] = m => new CacheEntryProcessorException(m);
EXS["org.apache.ignite.cache.CacheAtomicUpdateTimeoutException"] = m => new CacheAtomicUpdateTimeoutException(m);
// Transaction exceptions.
EXS["org.apache.ignite.transactions.TransactionOptimisticException"] = m => new TransactionOptimisticException(m);
EXS["org.apache.ignite.transactions.TransactionTimeoutException"] = m => new TransactionTimeoutException(m);
EXS["org.apache.ignite.transactions.TransactionRollbackException"] = m => new TransactionRollbackException(m);
EXS["org.apache.ignite.transactions.TransactionHeuristicException"] = m => new TransactionHeuristicException(m);
// Security exceptions.
EXS["org.apache.ignite.IgniteAuthenticationException"] = m => new SecurityException(m);
EXS["org.apache.ignite.plugin.security.GridSecurityException"] = m => new SecurityException(m);
}
/// <summary>
/// Creates exception according to native code class and message.
/// </summary>
/// <param name="clsName">Exception class name.</param>
/// <param name="msg">Exception message.</param>
/// <param name="reader">Error data reader.</param>
public static Exception GetException(string clsName, string msg, BinaryReader reader = null)
{
ExceptionFactoryDelegate ctor;
if (EXS.TryGetValue(clsName, out ctor))
return ctor(msg);
if (ClsNoClsDefFoundErr.Equals(clsName))
return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg);
if (ClsNoSuchMthdErr.Equals(clsName))
return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg);
if (ClsCachePartialUpdateErr.Equals(clsName))
return ProcessCachePartialUpdateException(msg, reader);
return new IgniteException("Java exception occurred [class=" + clsName + ", message=" + msg + ']');
}
/// <summary>
/// Process cache partial update exception.
/// </summary>
/// <param name="msg">Message.</param>
/// <param name="reader">Reader.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Exception ProcessCachePartialUpdateException(string msg, BinaryReader reader)
{
if (reader == null)
return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available."));
bool dataExists = reader.ReadBoolean();
Debug.Assert(dataExists);
if (reader.ReadBoolean())
{
bool keepBinary = reader.ReadBoolean();
BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary);
try
{
return new CachePartialUpdateException(msg, ReadNullableList(keysReader));
}
catch (Exception e)
{
// Failed to deserialize data.
return new CachePartialUpdateException(msg, e);
}
}
// Was not able to write keys.
string innerErrCls = reader.ReadString();
string innerErrMsg = reader.ReadString();
Exception innerErr = GetException(innerErrCls, innerErrMsg);
return new CachePartialUpdateException(msg, innerErr);
}
/// <summary>
/// Create JVM initialization exception.
/// </summary>
/// <param name="clsName">Class name.</param>
/// <param name="msg">Message.</param>
/// <returns>Exception.</returns>
public static Exception GetJvmInitializeException(string clsName, string msg)
{
if (clsName != null)
return new IgniteException("Failed to initialize JVM.", GetException(clsName, msg));
if (msg != null)
return new IgniteException("Failed to initialize JVM: " + msg);
return new IgniteException("Failed to initialize JVM.");
}
/// <summary>
/// Reads nullable list.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>List.</returns>
private static List<object> ReadNullableList(BinaryReader reader)
{
if (!reader.ReadBoolean())
return null;
var size = reader.ReadInt();
var list = new List<object>(size);
for (int i = 0; i < size; i++)
list.Add(reader.ReadObject<object>());
return list;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace AnimatGuiCtrls.Controls
{
/// <summary>
/// Provides the ability to create 32-bit alpha drag images
/// using the ImageList drag functionality in .NET.
/// </summary>
public class ImageListDrag : IDisposable
{
#region Unmanaged Code
[StructLayoutAttribute(LayoutKind.Sequential)]
private struct POINTAPI
{
public int X;
public int Y;
public override string ToString()
{
return String.Format("{0} X={1},Y={2}",
this.GetType().FullName, this.X, this.Y);
}
}
/*
[StructLayoutAttribute(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public override string ToString()
{
return String.Format("{0} Left={1},Top={2},Right={3},Bottom={4}",
this.GetType().FullName, this.Left, this.Top, this.Right, this.Bottom);
}
}
*/
[DllImport("comctl32")]
private static extern int ImageList_BeginDrag(
IntPtr himlTrack,
int iTrack,
int dxHotspot,
int dyHotspot);
[DllImport("comctl32")]
private static extern void ImageList_EndDrag();
[DllImport("comctl32")]
private static extern int ImageList_DragEnter(
IntPtr hwndLock,
int X,
int Y);
[DllImport("comctl32")]
private static extern int ImageList_DragLeave (
IntPtr hwndLock );
[DllImport("comctl32")]
private static extern int ImageList_DragMove (
int X,
int Y);
[DllImport("comctl32")]
private static extern int ImageList_SetDragCursorImage (
IntPtr himlDrag,
int iDrag,
int dxHotspot,
int dyHotspot);
[DllImport("comctl32")]
private static extern int ImageList_DragShowNolock (
int fShow );
[DllImport("comctl32")]
private static extern int ImageList_GetDragImage (
ref POINTAPI ppt,
ref POINTAPI pptHotspot);
/*
[DllImport("user32")]
static extern int GetWindowRect (
IntPtr hwnd,
ref RECT rect);
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
*/
#endregion
#region Member Variables
/// <summary>
/// The <code>ImageList</code> to use to source the drag-drop image from.
/// </summary>
private System.Windows.Forms.ImageList iml = null;
/// <summary>
/// The <code>Control</code> which owns this class.
/// </summary>
private Control owner = null;
/// <summary>
/// The Window handle which we're dragging over.
/// </summary>
private IntPtr hWndLast = IntPtr.Zero;
/// <summary>
/// Whether dragging is occurring or not.
/// </summary>
private bool inDrag = false;
/// <summary>
/// Whether we have suspended image
/// dragging and need to start it again when the
/// cursor next moves.
/// </summary>
private bool startDrag = false;
/// <summary>
/// Whether this class has been disposed or not.
/// </summary>
private bool disposed = false;
#endregion
#region API
/// <summary>
/// Gets/sets the ImageList used to source drag images.
/// </summary>
public System.Windows.Forms.ImageList Imagelist
{
get
{
return this.iml;
}
set
{
this.iml = value;
}
}
/// <summary>
/// Gets/sets the Owning control or form for this object.
/// </summary>
public Control Owner
{
get
{
return this.owner;
}
set
{
this.owner = value;
}
}
/// <summary>
/// Starts a dragging operation which will use
/// an ImageList to create a drag image and defaults
/// the position of the image to the cursor's drag
/// point.
/// </summary>
/// <param name="imageIndex">The index of the image in
/// the ImageList to use for the drag image.</param>
public void StartDrag(
int imageIndex
)
{
StartDrag(imageIndex, 0, 0);
}
/// <summary>
/// Starts a dragging operation which will use
/// an ImageList to create a drag image and allows
/// the offset of the Image from the drag position
/// to be specified.
/// </summary>
/// <param name="imageIndex">The index of the image in
/// the ImageList to use for the drag image.</param>
/// <param name="xOffset">The horizontal offset of the drag image
/// from the drag position. Negative values move the image
/// to the right of the cursor, positive values move it
/// to the left.</param>
/// <param name="yOffset">The vertical offset of the drag image
/// from the drag position. Negative values move the image
/// below the cursor, positive values move it above.</param>
public void StartDrag(
int imageIndex,
int xOffset,
int yOffset
)
{
int res = 0;
CompleteDrag();
res = ImageList_BeginDrag(
iml.Handle, imageIndex, xOffset, yOffset);
if (res != 0)
{
this.inDrag = true;
this.startDrag = true;
}
}
/// <summary>
/// Shows the ImageList drag image at the current
/// dragging position.
/// </summary>
public void DragDrop()
{
IntPtr hWndParent = IntPtr.Zero;
Point dst = new Point();
if (this.inDrag)
{
dst = Cursor.Position;
if (this.owner != null)
{
// Position relative to owner:
dst = this.owner.PointToClient(dst);
}
if (this.startDrag)
{
this.hWndLast = (this.owner == null ? IntPtr.Zero : this.owner.Handle);
ImageList_DragEnter(
hWndLast,
dst.X, dst.Y);
this.startDrag = false;
}
ImageList_DragMove(dst.X, dst.Y);
}
}
/// <summary>
/// Completes a drag operation.
/// </summary>
public void CompleteDrag()
{
if (this.inDrag)
{
ImageList_EndDrag();
ImageList_DragLeave(this.hWndLast);
this.hWndLast = IntPtr.Zero;
this.inDrag = false;
}
}
/// <summary>
/// Shows or hides the drag image. This is used to prevent
/// painting problems if the area under the drag needs to
/// be repainted.
/// </summary>
/// <param name="state">True to hide the drag image and
/// allow repainting, False to show the drag image.</param>
public void HideDragImage(bool state)
{
if (this.inDrag)
{
if (state)
{
ImageList_DragLeave(this.hWndLast);
this.startDrag = true;
}
else
{
DragDrop();
}
}
}
#endregion
#region Constructor, Dispose, Finalise
/// <summary>
/// Constructs a new instance of the ImageListDrag class.
/// </summary>
public ImageListDrag()
{
// Intentionally blank
}
/// <summary>
/// Clears up any resources associated with this object.
/// Note there are only resources associated when there is
/// a drag operation in effect.
/// </summary>
public void Dispose()
{
if (!this.disposed)
{
CompleteDrag();
}
this.disposed = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalize calls Dispose if it hasn't already been called.
/// </summary>
~ImageListDrag()
{
if (!this.disposed)
{
Dispose();
}
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007-2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using FluentMigrator.Exceptions;
using FluentMigrator.Runner.Generators.SQLite;
using FluentMigrator.SqlServer;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.SQLite
{
[TestFixture]
// ReSharper disable once InconsistentNaming
public class SQLiteDataTests : BaseDataTests
{
protected SQLiteGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new SQLiteGenerator();
}
[Test]
public override void CanDeleteDataForAllRowsWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteDataAllRowsExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("DELETE FROM \"TestTable1\" WHERE 1 = 1");
}
[Test]
public override void CanDeleteDataForAllRowsWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteDataAllRowsExpression();
var result = Generator.Generate(expression);
result.ShouldBe("DELETE FROM \"TestTable1\" WHERE 1 = 1");
}
[Test]
public override void CanDeleteDataForMultipleRowsWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteDataMultipleRowsExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("DELETE FROM \"TestTable1\" WHERE \"Name\" = 'Just''in' AND \"Website\" IS NULL; DELETE FROM \"TestTable1\" WHERE \"Website\" = 'github.com'");
}
[Test]
public override void CanDeleteDataForMultipleRowsWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteDataMultipleRowsExpression();
var result = Generator.Generate(expression);
result.ShouldBe("DELETE FROM \"TestTable1\" WHERE \"Name\" = 'Just''in' AND \"Website\" IS NULL; DELETE FROM \"TestTable1\" WHERE \"Website\" = 'github.com'");
}
[Test]
public override void CanDeleteDataWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteDataExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("DELETE FROM \"TestTable1\" WHERE \"Name\" = 'Just''in' AND \"Website\" IS NULL");
}
[Test]
public override void CanDeleteDataWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteDataExpression();
var result = Generator.Generate(expression);
result.ShouldBe("DELETE FROM \"TestTable1\" WHERE \"Name\" = 'Just''in' AND \"Website\" IS NULL");
}
[Test]
public override void CanDeleteDataWithDbNullCriteria()
{
var expression = GeneratorTestHelper.GetDeleteDataExpressionWithDbNullValue();
var result = Generator.Generate(expression);
result.ShouldBe("DELETE FROM \"TestTable1\" WHERE \"Name\" = 'Just''in' AND \"Website\" IS NULL");
}
[Test]
public override void CanInsertDataWithCustomSchema()
{
var expression = GeneratorTestHelper.GetInsertDataExpression();
expression.SchemaName = "TestSchema";
var expected = "INSERT INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (1, 'Just''in', 'codethinked.com');";
expected += " INSERT INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (2, 'Na\\te', 'kohari.org')";
var result = Generator.Generate(expression);
result.ShouldBe(expected);
}
[Test]
public override void CanInsertDataWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetInsertDataExpression();
var expected = "INSERT INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (1, 'Just''in', 'codethinked.com');";
expected += " INSERT INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (2, 'Na\\te', 'kohari.org')";
var result = Generator.Generate(expression);
result.ShouldBe(expected);
}
[Test]
public override void CanInsertGuidDataWithCustomSchema()
{
var expression = GeneratorTestHelper.GetInsertGUIDExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("INSERT INTO \"TestTable1\" (\"guid\") VALUES ('{0}')", GeneratorTestHelper.TestGuid.ToString()));
}
[Test]
public override void CanInsertGuidDataWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetInsertGUIDExpression();
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("INSERT INTO \"TestTable1\" (\"guid\") VALUES ('{0}')", GeneratorTestHelper.TestGuid.ToString()));
}
[Test]
public override void CanUpdateDataForAllDataWithCustomSchema()
{
var expression = GeneratorTestHelper.GetUpdateDataExpressionWithAllRows();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("UPDATE \"TestTable1\" SET \"Name\" = 'Just''in', \"Age\" = 25 WHERE 1 = 1");
}
[Test]
public override void CanUpdateDataForAllDataWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetUpdateDataExpressionWithAllRows();
var result = Generator.Generate(expression);
result.ShouldBe("UPDATE \"TestTable1\" SET \"Name\" = 'Just''in', \"Age\" = 25 WHERE 1 = 1");
}
[Test]
public override void CanUpdateDataWithCustomSchema()
{
var expression = GeneratorTestHelper.GetUpdateDataExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("UPDATE \"TestTable1\" SET \"Name\" = 'Just''in', \"Age\" = 25 WHERE \"Id\" = 9 AND \"Homepage\" IS NULL");
}
[Test]
public override void CanUpdateDataWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetUpdateDataExpression();
var result = Generator.Generate(expression);
result.ShouldBe("UPDATE \"TestTable1\" SET \"Name\" = 'Just''in', \"Age\" = 25 WHERE \"Id\" = 9 AND \"Homepage\" IS NULL");
}
[Test]
public void CanInsertDataWithSqlServerIdentityInsertInLooseMode()
{
var expression = GeneratorTestHelper.GetInsertDataExpression();
expression.AdditionalFeatures.Add(SqlServerExtensions.IdentityInsert, true);
Generator.CompatibilityMode = Runner.CompatibilityMode.LOOSE;
var expected = "INSERT INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (1, 'Just''in', 'codethinked.com');";
expected += " INSERT INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (2, 'Na\\te', 'kohari.org')";
var result = Generator.Generate(expression);
result.ShouldBe(expected);
}
[Test]
public void CanNotInsertDataWithSqlServerIdentityInsertInStrictMode()
{
var expression = GeneratorTestHelper.GetInsertDataExpression();
expression.AdditionalFeatures.Add(SqlServerExtensions.IdentityInsert, true);
Generator.CompatibilityMode = Runner.CompatibilityMode.STRICT;
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
[Test]
public override void CanUpdateDataWithDbNullCriteria()
{
var expression = GeneratorTestHelper.GetUpdateDataExpressionWithDbNullValue();
var result = Generator.Generate(expression);
result.ShouldBe("UPDATE \"TestTable1\" SET \"Name\" = 'Just''in', \"Age\" = 25 WHERE \"Id\" = 9 AND \"Homepage\" IS NULL");
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace Northwind
{
/// <summary>
/// Strongly-typed collection for the Customer class.
/// </summary>
[Serializable]
public partial class CustomerCollection : ActiveList<Customer, CustomerCollection>
{
public CustomerCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>CustomerCollection</returns>
public CustomerCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Customer o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Customers table.
/// </summary>
[Serializable]
public partial class Customer : ActiveRecord<Customer>, IActiveRecord
{
#region .ctors and Default Settings
public Customer()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Customer(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Customer(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Customer(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Customers", TableType.Table, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.String;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = false;
colvarCustomerID.IsPrimaryKey = true;
colvarCustomerID.IsForeignKey = false;
colvarCustomerID.IsReadOnly = false;
colvarCustomerID.DefaultSetting = @"";
colvarCustomerID.ForeignKeyTableName = "";
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = false;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
colvarCompanyName.DefaultSetting = @"";
colvarCompanyName.ForeignKeyTableName = "";
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema);
colvarContactName.ColumnName = "ContactName";
colvarContactName.DataType = DbType.String;
colvarContactName.MaxLength = 30;
colvarContactName.AutoIncrement = false;
colvarContactName.IsNullable = true;
colvarContactName.IsPrimaryKey = false;
colvarContactName.IsForeignKey = false;
colvarContactName.IsReadOnly = false;
colvarContactName.DefaultSetting = @"";
colvarContactName.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactName);
TableSchema.TableColumn colvarContactTitle = new TableSchema.TableColumn(schema);
colvarContactTitle.ColumnName = "ContactTitle";
colvarContactTitle.DataType = DbType.String;
colvarContactTitle.MaxLength = 30;
colvarContactTitle.AutoIncrement = false;
colvarContactTitle.IsNullable = true;
colvarContactTitle.IsPrimaryKey = false;
colvarContactTitle.IsForeignKey = false;
colvarContactTitle.IsReadOnly = false;
colvarContactTitle.DefaultSetting = @"";
colvarContactTitle.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactTitle);
TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema);
colvarAddress.ColumnName = "Address";
colvarAddress.DataType = DbType.String;
colvarAddress.MaxLength = 60;
colvarAddress.AutoIncrement = false;
colvarAddress.IsNullable = true;
colvarAddress.IsPrimaryKey = false;
colvarAddress.IsForeignKey = false;
colvarAddress.IsReadOnly = false;
colvarAddress.DefaultSetting = @"";
colvarAddress.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddress);
TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema);
colvarCity.ColumnName = "City";
colvarCity.DataType = DbType.String;
colvarCity.MaxLength = 15;
colvarCity.AutoIncrement = false;
colvarCity.IsNullable = true;
colvarCity.IsPrimaryKey = false;
colvarCity.IsForeignKey = false;
colvarCity.IsReadOnly = false;
colvarCity.DefaultSetting = @"";
colvarCity.ForeignKeyTableName = "";
schema.Columns.Add(colvarCity);
TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema);
colvarRegion.ColumnName = "Region";
colvarRegion.DataType = DbType.String;
colvarRegion.MaxLength = 15;
colvarRegion.AutoIncrement = false;
colvarRegion.IsNullable = true;
colvarRegion.IsPrimaryKey = false;
colvarRegion.IsForeignKey = false;
colvarRegion.IsReadOnly = false;
colvarRegion.DefaultSetting = @"";
colvarRegion.ForeignKeyTableName = "";
schema.Columns.Add(colvarRegion);
TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema);
colvarPostalCode.ColumnName = "PostalCode";
colvarPostalCode.DataType = DbType.String;
colvarPostalCode.MaxLength = 10;
colvarPostalCode.AutoIncrement = false;
colvarPostalCode.IsNullable = true;
colvarPostalCode.IsPrimaryKey = false;
colvarPostalCode.IsForeignKey = false;
colvarPostalCode.IsReadOnly = false;
colvarPostalCode.DefaultSetting = @"";
colvarPostalCode.ForeignKeyTableName = "";
schema.Columns.Add(colvarPostalCode);
TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema);
colvarCountry.ColumnName = "Country";
colvarCountry.DataType = DbType.String;
colvarCountry.MaxLength = 15;
colvarCountry.AutoIncrement = false;
colvarCountry.IsNullable = true;
colvarCountry.IsPrimaryKey = false;
colvarCountry.IsForeignKey = false;
colvarCountry.IsReadOnly = false;
colvarCountry.DefaultSetting = @"";
colvarCountry.ForeignKeyTableName = "";
schema.Columns.Add(colvarCountry);
TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema);
colvarPhone.ColumnName = "Phone";
colvarPhone.DataType = DbType.String;
colvarPhone.MaxLength = 24;
colvarPhone.AutoIncrement = false;
colvarPhone.IsNullable = true;
colvarPhone.IsPrimaryKey = false;
colvarPhone.IsForeignKey = false;
colvarPhone.IsReadOnly = false;
colvarPhone.DefaultSetting = @"";
colvarPhone.ForeignKeyTableName = "";
schema.Columns.Add(colvarPhone);
TableSchema.TableColumn colvarFax = new TableSchema.TableColumn(schema);
colvarFax.ColumnName = "Fax";
colvarFax.DataType = DbType.String;
colvarFax.MaxLength = 24;
colvarFax.AutoIncrement = false;
colvarFax.IsNullable = true;
colvarFax.IsPrimaryKey = false;
colvarFax.IsForeignKey = false;
colvarFax.IsReadOnly = false;
colvarFax.DefaultSetting = @"";
colvarFax.ForeignKeyTableName = "";
schema.Columns.Add(colvarFax);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Customers",schema);
}
}
#endregion
#region Props
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get { return GetColumnValue<string>(Columns.CustomerID); }
set { SetColumnValue(Columns.CustomerID, value); }
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get { return GetColumnValue<string>(Columns.CompanyName); }
set { SetColumnValue(Columns.CompanyName, value); }
}
[XmlAttribute("ContactName")]
[Bindable(true)]
public string ContactName
{
get { return GetColumnValue<string>(Columns.ContactName); }
set { SetColumnValue(Columns.ContactName, value); }
}
[XmlAttribute("ContactTitle")]
[Bindable(true)]
public string ContactTitle
{
get { return GetColumnValue<string>(Columns.ContactTitle); }
set { SetColumnValue(Columns.ContactTitle, value); }
}
[XmlAttribute("Address")]
[Bindable(true)]
public string Address
{
get { return GetColumnValue<string>(Columns.Address); }
set { SetColumnValue(Columns.Address, value); }
}
[XmlAttribute("City")]
[Bindable(true)]
public string City
{
get { return GetColumnValue<string>(Columns.City); }
set { SetColumnValue(Columns.City, value); }
}
[XmlAttribute("Region")]
[Bindable(true)]
public string Region
{
get { return GetColumnValue<string>(Columns.Region); }
set { SetColumnValue(Columns.Region, value); }
}
[XmlAttribute("PostalCode")]
[Bindable(true)]
public string PostalCode
{
get { return GetColumnValue<string>(Columns.PostalCode); }
set { SetColumnValue(Columns.PostalCode, value); }
}
[XmlAttribute("Country")]
[Bindable(true)]
public string Country
{
get { return GetColumnValue<string>(Columns.Country); }
set { SetColumnValue(Columns.Country, value); }
}
[XmlAttribute("Phone")]
[Bindable(true)]
public string Phone
{
get { return GetColumnValue<string>(Columns.Phone); }
set { SetColumnValue(Columns.Phone, value); }
}
[XmlAttribute("Fax")]
[Bindable(true)]
public string Fax
{
get { return GetColumnValue<string>(Columns.Fax); }
set { SetColumnValue(Columns.Fax, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public Northwind.CustomerCustomerDemoCollection CustomerCustomerDemoRecords()
{
return new Northwind.CustomerCustomerDemoCollection().Where(CustomerCustomerDemo.Columns.CustomerID, CustomerID).Load();
}
public Northwind.OrderCollection Orders()
{
return new Northwind.OrderCollection().Where(Order.Columns.CustomerID, CustomerID).Load();
}
#endregion
//no foreign key tables defined (0)
#region Many To Many Helpers
public Northwind.CustomerDemographicCollection GetCustomerDemographicCollection() { return Customer.GetCustomerDemographicCollection(this.CustomerID); }
public static Northwind.CustomerDemographicCollection GetCustomerDemographicCollection(string varCustomerID)
{
SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [dbo].[CustomerDemographics] INNER JOIN [CustomerCustomerDemo] ON [CustomerDemographics].[CustomerTypeID] = [CustomerCustomerDemo].[CustomerTypeID] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmd.AddParameter("@CustomerID", varCustomerID, DbType.String);
IDataReader rdr = SubSonic.DataService.GetReader(cmd);
CustomerDemographicCollection coll = new CustomerDemographicCollection();
coll.LoadAndCloseReader(rdr);
return coll;
}
public static void SaveCustomerDemographicMap(string varCustomerID, CustomerDemographicCollection items)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (CustomerDemographic item in items)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerID", varCustomerID);
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", item.GetPrimaryKeyValue());
varCustomerCustomerDemo.Save();
}
}
public static void SaveCustomerDemographicMap(string varCustomerID, System.Web.UI.WebControls.ListItemCollection itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (System.Web.UI.WebControls.ListItem l in itemList)
{
if (l.Selected)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerID", varCustomerID);
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", l.Value);
varCustomerCustomerDemo.Save();
}
}
}
public static void SaveCustomerDemographicMap(string varCustomerID , string[] itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (string item in itemList)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerID", varCustomerID);
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", item);
varCustomerCustomerDemo.Save();
}
}
public static void DeleteCustomerDemographicMap(string varCustomerID)
{
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerID] = @CustomerID", Customer.Schema.Provider.Name);
cmdDel.AddParameter("@CustomerID", varCustomerID, DbType.String);
DataService.ExecuteQuery(cmdDel);
}
#endregion
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCustomerID,string varCompanyName,string varContactName,string varContactTitle,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varPhone,string varFax)
{
Customer item = new Customer();
item.CustomerID = varCustomerID;
item.CompanyName = varCompanyName;
item.ContactName = varContactName;
item.ContactTitle = varContactTitle;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.Phone = varPhone;
item.Fax = varFax;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varCustomerID,string varCompanyName,string varContactName,string varContactTitle,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varPhone,string varFax)
{
Customer item = new Customer();
item.CustomerID = varCustomerID;
item.CompanyName = varCompanyName;
item.ContactName = varContactName;
item.ContactTitle = varContactTitle;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.Phone = varPhone;
item.Fax = varFax;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn CustomerIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CompanyNameColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ContactNameColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ContactTitleColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn AddressColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn CityColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn RegionColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn PostalCodeColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CountryColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn PhoneColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn FaxColumn
{
get { return Schema.Columns[10]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CustomerID = @"CustomerID";
public static string CompanyName = @"CompanyName";
public static string ContactName = @"ContactName";
public static string ContactTitle = @"ContactTitle";
public static string Address = @"Address";
public static string City = @"City";
public static string Region = @"Region";
public static string PostalCode = @"PostalCode";
public static string Country = @"Country";
public static string Phone = @"Phone";
public static string Fax = @"Fax";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#endregion
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Game.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
#endregion
namespace InputSequenceSample
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class InputSequenceSampleGame : Microsoft.Xna.Framework.Game
{
#region Fields
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont spriteFont;
// This is the master list of moves in logical order. This array is kept
// around in order to draw the move list on the screen in this order.
Move[] moves;
// The move list used for move detection at runtime.
MoveList moveList;
// The move list is used to match against an input manager for each player.
InputManager[] inputManagers;
// Stores each players' most recent move and when they pressed it.
Move[] playerMoves;
TimeSpan[] playerMoveTimes;
// Time until the currently "active" move dissapears from the screen.
readonly TimeSpan MoveTimeOut = TimeSpan.FromSeconds(1.0);
// Direction textures.
Texture2D upTexture;
Texture2D downTexture;
Texture2D leftTexture;
Texture2D rightTexture;
Texture2D upLeftTexture;
Texture2D upRightTexture;
Texture2D downLeftTexture;
Texture2D downRightTexture;
// Button textures.
Texture2D aButtonTexture;
Texture2D bButtonTexture;
Texture2D xButtonTexture;
Texture2D yButtonTexture;
// Other textures.
Texture2D plusTexture;
Texture2D padFaceTexture;
#endregion
#region Initialization
public InputSequenceSampleGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// Construct the master list of moves.
moves = new Move[]
{
new Move("Jump", Buttons.A) { IsSubMove = true },
new Move("Punch", Buttons.X) { IsSubMove = true },
new Move("Double Jump", Buttons.A, Buttons.A),
new Move("Jump Kick", Buttons.A | Buttons.X),
new Move("Quad Punch", Buttons.X, Buttons.Y, Buttons.X, Buttons.Y),
new Move("Fireball", Direction.Down, Direction.DownRight,
Direction.Right | Buttons.X),
new Move("Long Jump", Direction.Up, Direction.Up, Buttons.A),
new Move("Back Flip", Direction.Down, Direction.Down | Buttons.A),
new Move("30 Lives", Direction.Up, Direction.Up,
Direction.Down, Direction.Down,
Direction.Left, Direction.Right,
Direction.Left, Direction.Right,
Buttons.B, Buttons.A),
};
// Construct a move list which will store its own copy of the moves array.
moveList = new MoveList(moves);
// Create an InputManager for each player with a sufficiently large buffer.
inputManagers = new InputManager[2];
for (int i = 0; i < inputManagers.Length; ++i)
{
inputManagers[i] =
new InputManager((PlayerIndex)i, moveList.LongestMoveLength);
}
// Give each player a location to store their most recent move.
playerMoves = new Move[inputManagers.Length];
playerMoveTimes = new TimeSpan[inputManagers.Length];
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
spriteFont = Content.Load<SpriteFont>("Font");
// Load direction textures.
upTexture = Content.Load<Texture2D>("Up");
downTexture = Content.Load<Texture2D>("Down");
leftTexture = Content.Load<Texture2D>("Left");
rightTexture = Content.Load<Texture2D>("Right");
upLeftTexture = Content.Load<Texture2D>("UpLeft");
upRightTexture = Content.Load<Texture2D>("UpRight");
downLeftTexture = Content.Load<Texture2D>("DownLeft");
downRightTexture = Content.Load<Texture2D>("DownRight");
// Load button textures.
aButtonTexture = Content.Load<Texture2D>("A");
bButtonTexture = Content.Load<Texture2D>("B");
xButtonTexture = Content.Load<Texture2D>("X");
yButtonTexture = Content.Load<Texture2D>("Y");
// Load other textures.
plusTexture = Content.Load<Texture2D>("Plus");
padFaceTexture = Content.Load<Texture2D>("PadFace");
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
for (int i = 0; i < inputManagers.Length; ++i)
{
// Expire old moves.
if (gameTime.TotalGameTime - playerMoveTimes[i] > MoveTimeOut)
{
playerMoves[i] = null;
}
// Get the updated input manager.
InputManager inputManager = inputManagers[i];
inputManager.Update(gameTime);
// Allows the game to exit.
if (inputManager.GamePadState.Buttons.Back == ButtonState.Pressed ||
inputManager.KeyboardState.IsKeyDown(Keys.Escape))
{
Exit();
}
// Detection and record the current player's most recent move.
Move newMove = moveList.DetectMove(inputManager);
if (newMove != null)
{
playerMoves[i] = newMove;
playerMoveTimes[i] = gameTime.TotalGameTime;
}
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
// Calculate some reasonable boundaries within the safe area.
Vector2 topLeft = new Vector2(50, 50);
Vector2 bottomRight = new Vector2(
GraphicsDevice.Viewport.Width - topLeft.X,
GraphicsDevice.Viewport.Height - topLeft.Y);
// Keeps track of where to draw next.
Vector2 position = topLeft;
// Draw the list of all moves.
foreach (Move move in moves)
{
Vector2 size = MeasureMove(move);
// If this move would fall off the right edge of the screen,
if (position.X + size.X > bottomRight.X)
{
// start again on the next line.
position.X = topLeft.X;
position.Y += size.Y;
}
DrawMove(move, position);
position.X += size.X + 30.0f;
}
// Skip some space.
position.Y += 90.0f;
// Draw the input from each player.
for (int i = 0; i < inputManagers.Length; ++i)
{
position.X = topLeft.X;
DrawInput(i, position);
position.Y += 80;
}
spriteBatch.End();
base.Draw(gameTime);
}
/// <summary>
/// Calculates the size of what would be drawn by a call to DrawMove.
/// </summary>
private Vector2 MeasureMove(Move move)
{
Vector2 textSize = spriteFont.MeasureString(move.Name);
Vector2 sequenceSize = MeasureSequence(move.Sequence);
return new Vector2(
Math.Max(textSize.X, sequenceSize.X),
textSize.Y + sequenceSize.Y);
}
/// <summary>
/// Draws graphical instructions on how to perform a move.
/// </summary>
private void DrawMove(Move move, Vector2 position)
{
DrawString(move.Name, position, Color.White);
position.Y += spriteFont.MeasureString(move.Name).Y;
DrawSequence(move.Sequence, position);
}
/// <summary>
/// Draws the input buffer and most recently fired action for a given player.
/// </summary>
private void DrawInput(int i, Vector2 position)
{
InputManager inputManager = inputManagers[i];
Move move = playerMoves[i];
// Draw the player's name and currently active move (if any).
string text = "Player " + inputManager.PlayerIndex + " input ";
Vector2 textSize = spriteFont.MeasureString(text);
DrawString(text, position, Color.White);
if (move != null)
{
DrawString(move.Name,
new Vector2(position.X + textSize.X, position.Y), Color.Red);
}
// Draw the player's input buffer.
position.Y += textSize.Y;
DrawSequence(inputManager.Buffer, position);
}
/// <summary>
/// Draws a string with a subtle drop shadow.
/// </summary>
private void DrawString(string text, Vector2 position, Color color)
{
spriteBatch.DrawString(spriteFont, text,
new Vector2(position.X, position.Y + 1), Color.Black);
spriteBatch.DrawString(spriteFont, text,
new Vector2(position.X, position.Y), color);
}
/// <summary>
/// Calculates the size of what would be drawn by a call to DrawSequence.
/// </summary>
private Vector2 MeasureSequence(IEnumerable<Buttons> sequence)
{
float width = 0.0f;
foreach (Buttons buttons in sequence)
{
width += MeasureButtons(buttons).X;
}
return new Vector2(width, padFaceTexture.Height);
}
/// <summary>
/// Draws a horizontal series of input steps in a sequence.
/// </summary>
private void DrawSequence(IEnumerable<Buttons> sequence, Vector2 position)
{
foreach (Buttons buttons in sequence)
{
DrawButtons(buttons, position);
position.X += MeasureButtons(buttons).X;
}
}
/// <summary>
/// Calculates the size of what would be drawn by a call to DrawButtons.
/// </summary>
private Vector2 MeasureButtons(Buttons buttons)
{
Buttons direction = Direction.FromButtons(buttons);
float width;
// If buttons has a direction,
if (direction > 0)
{
width = GetDirectionTexture(direction).Width;
// If buttons has at least one non-directional button,
if ((buttons & ~direction) > 0)
{
width += plusTexture.Width + padFaceTexture.Width;
}
}
else
{
width = padFaceTexture.Width;
}
return new Vector2(width, padFaceTexture.Height);
}
/// <summary>
/// Draws the combined state of a set of buttons flags. The rendered output
/// looks like a directional arrow, a group of buttons, or both concatenated
/// with a plus sign operator.
/// </summary>
private void DrawButtons(Buttons buttons, Vector2 position)
{
// Get the texture to draw for the direction.
Buttons direction = Direction.FromButtons(buttons);
Texture2D directionTexture = GetDirectionTexture(direction);
// If there is a direction, draw it.
if (directionTexture != null)
{
spriteBatch.Draw(directionTexture, position, Color.White);
position.X += directionTexture.Width;
}
// If any non-direction button is pressed,
if ((buttons & ~direction) > 0)
{
// Draw a plus if both a direction and one more more buttons is pressed.
if (directionTexture != null)
{
spriteBatch.Draw(plusTexture, position, Color.White);
position.X += plusTexture.Width;
}
// Draw a gamepad with all inactive buttons in the background.
spriteBatch.Draw(padFaceTexture, position, Color.White);
// Draw each active button over the inactive game pad face.
if ((buttons & Buttons.A) > 0)
{
spriteBatch.Draw(aButtonTexture, position, Color.White);
}
if ((buttons & Buttons.B) > 0)
{
spriteBatch.Draw(bButtonTexture, position, Color.White);
}
if ((buttons & Buttons.X) > 0)
{
spriteBatch.Draw(xButtonTexture, position, Color.White);
}
if ((buttons & Buttons.Y) > 0)
{
spriteBatch.Draw(yButtonTexture, position, Color.White);
}
}
}
/// <summary>
/// Gets the texture for a given direction.
/// </summary>
private Texture2D GetDirectionTexture(Buttons direction)
{
switch (direction)
{
case Direction.Up:
return upTexture;
case Direction.Down:
return downTexture;
case Direction.Left:
return leftTexture;
case Direction.Right:
return rightTexture;
case Direction.UpLeft:
return upLeftTexture;
case Direction.UpRight:
return upRightTexture;
case Direction.DownLeft:
return downLeftTexture;
case Direction.DownRight:
return downRightTexture;
default:
return null;
}
}
#endregion
}
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static class Program
{
static void Main()
{
using (InputSequenceSampleGame game = new InputSequenceSampleGame())
{
game.Run();
}
}
}
#endregion
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class NguiUtils
{
public static string FullName(GameObject go)
{
var fullName = go.name;
var p = go.transform.parent;
while (p != null)
{
fullName = p.name + "." + fullName;
p = p.parent;
}
return fullName;
}
public static NguiDataContext FindRootContext(GameObject gameObject, int depthToGo)
{
NguiDataContext lastGoodContext = null;
var p = gameObject;//.transform.parent == null ? null : gameObject.transform.parent.gameObject;
depthToGo++;
while (p != null && depthToGo > 0)
{
var context = p.GetComponent<NguiDataContext>();
if (context != null)
{
lastGoodContext = context;
depthToGo--;
}
p = (p.transform.parent == null) ? null : p.transform.parent.gameObject;
}
return lastGoodContext;
}
public const int MaxPathDepth = 100500;
public static int GetPathDepth(string path)
{
if (!path.StartsWith("#"))
return 0;
var depthString = path.Substring(1);
var dotIndex = depthString.IndexOf('.');
if (dotIndex >= 0)
depthString = depthString.Substring(0, dotIndex);
if (depthString == "#")
{
return MaxPathDepth;
}
var depth = 0;
if (int.TryParse(depthString, out depth))
{
return depth;
}
Debug.LogWarning("Failed to get binding context depth for: " + path);
return 0;
}
public static string GetCleanPath(string path)
{
if (!path.StartsWith("#"))
return path;
var dotIndex = path.IndexOf('.');
var result = (dotIndex < 0) ? path : path.Substring(dotIndex + 1);
return result;
}
public static GameObject FindParent(GameObject target, GameObject [] possibleParents)
{
foreach(var p in possibleParents)
{
if (p == target)
return p;
}
return target.transform.parent == null ? null : FindParent(target.transform.parent.gameObject, possibleParents);
}
public static T GetComponentInParents<T>(GameObject gameObject)
where T : Component
{
var p = gameObject;
T component = null;
while (p != null && component == null)
{
component = p.GetComponent<T>();
p = (p.transform.parent == null) ? null : p.transform.parent.gameObject;
}
return component;
}
public static T GetComponentInParentsExcluding<T>(GameObject gameObject)
where T : Component
{
return GetComponentInParents<T>((gameObject.transform.parent == null)
? null
: gameObject.transform.parent.gameObject);
}
public static T GetComponentAs<T>(this GameObject gameObject)
where T : class
{
var mbs = gameObject.GetComponents<Component>();
foreach(var mb in mbs)
{
if (mb is T)
return mb as T;
}
return default(T);
}
public static T[] GetComponentsAs<T>(this GameObject gameObject)
where T : class
{
var result = new List<T>();
var mbs = gameObject.GetComponents<Component>();
foreach(var mb in mbs)
{
if (mb is T)
result.Add(mb as T);
}
return result.ToArray();
}
public static T[] GetComponentsInChildrenAs<T>(this GameObject gameObject)
where T : class
{
var result = new List<T>();
var mbs = gameObject.GetComponentsInChildren<Component>();
foreach(var mb in mbs)
{
if (mb is T)
result.Add(mb as T);
}
return result.ToArray();
}
public static T GetComponentInParentsAs<T>(GameObject gameObject)
where T : class
{
T component = default(T);
var p = gameObject;
while (p != null && component == null)
{
var mbs = p.GetComponents<Component>();
foreach(var mb in mbs)
{
if (mb is T)
{
component = mb as T;
break;
}
}
p = (p.transform.parent == null) ? null : p.transform.parent.gameObject;
}
return component;
}
public static T GetComponentInParentsExcludingAs<T>(GameObject gameObject)
where T : class
{
return GetComponentInParentsAs<T>((gameObject.transform.parent == null)
? null
: gameObject.transform.parent.gameObject);
}
public delegate void ObjectAction(GameObject target);
public static void ForObjectsSubTree(GameObject root, ObjectAction action)
{
if (root == null)
return;
action(root);
for (var i = 0; i < root.transform.childCount; ++i)
{
ForObjectsSubTree(root.transform.GetChild(i).gameObject, action);
}
}
public static string LocalizeFormat(string input)
{
var output = "";
var index = 0;
const char marker = '$';
while(true)
{
var localStart = input.IndexOf(marker, index);
if (localStart < 0)
{
output += input.Substring(index);
break;
}
if (localStart > index)
{
output += input.Substring(index, localStart - index);
index = localStart;
}
var localFinish = input.IndexOf(marker, index + 1);
if (localFinish < 0)
{
break;
}
if (localFinish == localStart + 1)
{
output += marker;
}
else
{
var key = input.Substring(localStart + 1, localFinish - localStart - 1);
#if NGUI_2
output += Localization.instance.Get(key);
#else
output += Localization.Get(key);
#endif
}
index = localFinish + 1;
}
return output;
}
public static void SetVisible(GameObject gameObject, bool visible) {
if (gameObject == null) return;
SetNguiVisible(gameObject, visible);
for (var i = 0; i < gameObject.transform.childCount; ++i)
{
var child = gameObject.transform.GetChild(i).gameObject;
var childVisibilityBinding = child.GetComponentAs<IVisibilityBinding>();
if (childVisibilityBinding != null)
{
SetVisible(child, visible && childVisibilityBinding.ObjectVisible);
}
else
{
SetVisible(child, visible);
}
}
}
private static void SetNguiVisible(GameObject gameObject, bool visible) {
if (gameObject == null) return;
foreach(var collider in gameObject.GetComponents<Collider>())
{
collider.enabled = visible;
}
foreach(var widget in gameObject.GetComponents<UIWidget>())
{
widget.enabled = visible;
}
foreach (var ancher in gameObject.GetComponents<UIAnchor>()) {
ancher.enabled = visible;
}
//foreach (var scroll in gameObject.GetComponents<InfiniteScroll>()) {
// scroll.enabled = visible;
//}
foreach (var scroll in gameObject.GetComponents<UIPanel>()) {
scroll.enabled = visible;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class AppleCrypto
{
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainItemCopyKeychain(
IntPtr item,
out SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SecKeychainCreate")]
private static extern int AppleCryptoNative_SecKeychainCreateTemporary(
string path,
int utf8PassphraseLength,
byte[] utf8Passphrase,
out SafeTemporaryKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainDelete(IntPtr keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainCopyDefault(out SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainOpen(
string keychainPath,
out SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainEnumerateCerts(
SafeKeychainHandle keychain,
out SafeCFArrayHandle matches,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainEnumerateIdentities(
SafeKeychainHandle keychain,
out SafeCFArrayHandle matches,
out int pOSStatus);
internal static SafeKeychainHandle SecKeychainItemCopyKeychain(SafeKeychainItemHandle item)
{
bool addedRef = false;
try
{
item.DangerousAddRef(ref addedRef);
var handle = SecKeychainItemCopyKeychain(item.DangerousGetHandle());
return handle;
}
finally
{
if (addedRef)
{
item.DangerousRelease();
}
}
}
internal static SafeKeychainHandle SecKeychainItemCopyKeychain(IntPtr item)
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainItemCopyKeychain(item, out keychain);
// A whole lot of NULL is expected from this.
// Any key or cert which isn't keychain-backed, and this is the primary way we'd find that out.
if (keychain.IsInvalid)
{
GC.SuppressFinalize(keychain);
}
if (osStatus == 0)
{
return keychain;
}
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeKeychainHandle SecKeychainCopyDefault()
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainCopyDefault(out keychain);
if (osStatus == 0)
{
return keychain;
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeKeychainHandle SecKeychainOpen(string keychainPath)
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainOpen(keychainPath, out keychain);
if (osStatus == 0)
{
return keychain;
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeCFArrayHandle KeychainEnumerateCerts(SafeKeychainHandle keychainHandle)
{
SafeCFArrayHandle matches;
int osStatus;
int result = AppleCryptoNative_SecKeychainEnumerateCerts(keychainHandle, out matches, out osStatus);
if (result == 1)
{
return matches;
}
matches.Dispose();
if (result == 0)
throw CreateExceptionForOSStatus(osStatus);
Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}");
throw new CryptographicException();
}
internal static SafeCFArrayHandle KeychainEnumerateIdentities(SafeKeychainHandle keychainHandle)
{
SafeCFArrayHandle matches;
int osStatus;
int result = AppleCryptoNative_SecKeychainEnumerateIdentities(keychainHandle, out matches, out osStatus);
if (result == 1)
{
return matches;
}
matches.Dispose();
if (result == 0)
throw CreateExceptionForOSStatus(osStatus);
Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}");
throw new CryptographicException();
}
internal static SafeTemporaryKeychainHandle CreateTemporaryKeychain()
{
string tmpKeychainPath = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString("N") + ".keychain");
// Use a distinct GUID so that if a keychain is abandoned it isn't recoverable.
string tmpKeychainPassphrase = Guid.NewGuid().ToString("N");
byte[] utf8Passphrase = System.Text.Encoding.UTF8.GetBytes(tmpKeychainPassphrase);
SafeTemporaryKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainCreateTemporary(
tmpKeychainPath,
utf8Passphrase.Length,
utf8Passphrase,
out keychain);
SafeTemporaryKeychainHandle.TrackKeychain(keychain);
if (osStatus != 0)
{
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
return keychain;
}
internal static void SecKeychainDelete(IntPtr handle, bool throwOnError=true)
{
int osStatus = AppleCryptoNative_SecKeychainDelete(handle);
if (throwOnError && osStatus != 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
}
}
}
namespace System.Security.Cryptography.Apple
{
internal class SafeKeychainItemHandle : SafeHandle
{
internal SafeKeychainItemHandle()
: base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
SafeTemporaryKeychainHandle.UntrackItem(handle);
Interop.CoreFoundation.CFRelease(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid => handle == IntPtr.Zero;
}
internal class SafeKeychainHandle : SafeHandle
{
internal SafeKeychainHandle()
: base(IntPtr.Zero, ownsHandle: true)
{
}
internal SafeKeychainHandle(IntPtr handle)
: base(handle, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.CoreFoundation.CFRelease(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid => handle == IntPtr.Zero;
}
internal sealed class SafeTemporaryKeychainHandle : SafeKeychainHandle
{
private static readonly Dictionary<IntPtr, SafeTemporaryKeychainHandle> s_lookup =
new Dictionary<IntPtr, SafeTemporaryKeychainHandle>();
internal SafeTemporaryKeychainHandle()
{
}
protected override bool ReleaseHandle()
{
lock (s_lookup)
{
s_lookup.Remove(handle);
}
Interop.AppleCrypto.SecKeychainDelete(handle, throwOnError: false);
return base.ReleaseHandle();
}
protected override void Dispose(bool disposing)
{
if (disposing && SafeHandleCache<SafeTemporaryKeychainHandle>.IsCachedInvalidHandle(this))
{
return;
}
base.Dispose(disposing);
}
public static SafeTemporaryKeychainHandle InvalidHandle =>
SafeHandleCache<SafeTemporaryKeychainHandle>.GetInvalidHandle(() => new SafeTemporaryKeychainHandle());
internal static void TrackKeychain(SafeTemporaryKeychainHandle toTrack)
{
if (toTrack.IsInvalid)
{
return;
}
lock (s_lookup)
{
Debug.Assert(!s_lookup.ContainsKey(toTrack.handle));
s_lookup[toTrack.handle] = toTrack;
}
}
internal static void TrackItem(SafeKeychainItemHandle keychainItem)
{
if (keychainItem.IsInvalid)
return;
using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem))
{
if (keychain.IsInvalid)
{
return;
}
lock (s_lookup)
{
SafeTemporaryKeychainHandle temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
bool ignored = false;
temporaryHandle.DangerousAddRef(ref ignored);
}
}
}
}
internal static void UntrackItem(IntPtr keychainItem)
{
using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem))
{
if (keychain.IsInvalid)
{
return;
}
lock (s_lookup)
{
SafeTemporaryKeychainHandle temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
temporaryHandle.DangerousRelease();
}
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Runtime;
/// <summary>
/// Base class for common AsyncResult programming scenarios.
/// </summary>
public abstract class AsyncResult : IAsyncResult, IDisposable
{
/// <summary>
/// End should be called when the End function for the asynchronous operation is complete. It
/// ensures the asynchronous operation is complete, and does some common validation.
/// </summary>
/// <param name="result">The <see cref="IAsyncResult"/> representing the status of an asynchronous operation.</param>
public static void End(IAsyncResult result)
{
if (result == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
AsyncResult asyncResult = result as AsyncResult;
if (asyncResult == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID4001), "result"));
if (asyncResult.endCalled)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4002)));
asyncResult.endCalled = true;
if (!asyncResult.completed)
asyncResult.AsyncWaitHandle.WaitOne();
if (asyncResult.resetEvent != null)
((IDisposable)asyncResult.resetEvent).Dispose();
if (asyncResult.exception != null)
throw asyncResult.exception;
}
AsyncCallback callback;
bool completed;
bool completedSync;
bool disposed;
bool endCalled;
Exception exception;
ManualResetEvent resetEvent;
object state;
object thisLock;
/// <summary>
/// Constructor for async results that do not need a callback or state.
/// </summary>
protected AsyncResult()
: this(null, null)
{
}
/// <summary>
/// Constructor for async results that do not need a callback.
/// </summary>
/// <param name="state">A user-defined object that qualifies or contains information about an asynchronous operation.</param>
protected AsyncResult(object state)
: this(null, state)
{
}
/// <summary>
/// Constructor for async results that need a callback and a state.
/// </summary>
/// <param name="callback">The method to be called when the async operation completes.</param>
/// <param name="state">A user-defined object that qualifies or contains information about an asynchronous operation.</param>
protected AsyncResult(AsyncCallback callback, object state)
{
this.thisLock = new object();
this.callback = callback;
this.state = state;
}
/// <summary>
/// Finalizer for AsyncResult.
/// </summary>
~AsyncResult()
{
Dispose(false);
}
/// <summary>
/// Call this version of complete when your asynchronous operation is complete. This will update the state
/// of the operation and notify the callback.
/// </summary>
/// <param name="completedSynchronously">True if the asynchronous operation completed synchronously.</param>
protected void Complete(bool completedSynchronously)
{
Complete(completedSynchronously, null);
}
/// <summary>
/// Call this version of complete if you raise an exception during processing. In addition to notifying
/// the callback, it will capture the exception and store it to be thrown during AsyncResult.End.
/// </summary>
/// <param name="completedSynchronously">True if the asynchronous operation completed synchronously.</param>
/// <param name="exception">The exception during the processing of the asynchronous operation.</param>
protected void Complete(bool completedSynchronously, Exception exception)
{
if (completed == true)
{
// it is a bug to call complete twice
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AsynchronousOperationException(SR.GetString(SR.ID4005)));
}
completedSync = completedSynchronously;
this.exception = exception;
if (completedSynchronously)
{
//
// No event should be set for synchronous completion
//
completed = true;
Fx.Assert(resetEvent == null, SR.GetString(SR.ID8025));
}
else
{
//
// Complete asynchronously
//
lock (thisLock)
{
completed = true;
if (resetEvent != null)
resetEvent.Set();
}
}
//
// finally call the call back. Note, we are expecting user's callback to handle the exception
// so, if the callback throw exception, all we can do is burn and crash.
//
try
{
if (callback != null)
callback(this);
}
catch (ThreadAbortException)
{
//
// The thread running the callback is being aborted. We ignore this case.
//
}
catch (AsynchronousOperationException)
{
throw;
}
#pragma warning suppress 56500
catch (Exception unhandledException)
{
//
// The callback raising an exception is equivalent to Main raising an exception w/out a catch.
// We should just throw it back. We should log the exception somewhere.
//
// Because the stack trace gets lost on a rethrow, we're wrapping it in a generic exception
// so the stack trace is preserved.
//
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AsynchronousOperationException(SR.GetString(SR.ID4003), unhandledException));
}
}
/// <summary>
/// Disposes of unmanaged resources held by the AsyncResult.
/// </summary>
/// <param name="isExplicitDispose">True if this is an explicit call to Dispose.</param>
protected virtual void Dispose(bool isExplicitDispose)
{
if (!disposed)
{
if (isExplicitDispose)
{
lock (thisLock)
{
if (!disposed)
{
//
// Mark disposed
//
disposed = true;
//
// Called explicitly to close the object
//
if (resetEvent != null)
resetEvent.Close();
}
}
}
else
{
//
// Called for finalization
//
}
}
}
#region IAsyncResult implementation
/// <summary>
/// Gets the user-defined state information that was passed to the Begin method.
/// </summary>
public object AsyncState
{
get
{
return state;
}
}
/// <summary>
/// Gets the wait handle of the async event.
/// </summary>
public virtual WaitHandle AsyncWaitHandle
{
get
{
if (resetEvent == null)
{
bool savedCompleted = completed;
lock (thisLock)
{
if (resetEvent == null)
resetEvent = new ManualResetEvent(completed);
}
if (!savedCompleted && completed)
resetEvent.Set();
}
return resetEvent;
}
}
/// <summary>
/// Gets a value that indicates whether the asynchronous operation completed synchronously.
/// </summary>
public bool CompletedSynchronously
{
get
{
return completedSync;
}
}
/// <summary>
/// Gets a value that indicates whether the asynchronous operation has completed.
/// </summary>
public bool IsCompleted
{
get
{
return completed;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Disposes this object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Storage;
using SchoolBusCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
namespace SchoolBusAPI.Models
{
public interface IDbAppContextFactory
{
IDbAppContext Create();
}
public class DbAppContextFactory : IDbAppContextFactory
{
DbContextOptions<DbAppContext> _options;
IHttpContextAccessor _httpContextAccessor;
public DbAppContextFactory(IHttpContextAccessor httpContextAccessor, DbContextOptions<DbAppContext> options)
{
_options = options;
_httpContextAccessor = httpContextAccessor;
}
public IDbAppContext Create()
{
return new DbAppContext(_httpContextAccessor, _options);
}
}
public interface IDbAppContext
{
DbSet<CCWData> CCWDatas { get; set; }
DbSet<CCWJurisdiction> CCWJurisdictions { get; set; }
DbSet<City> Cities { get; set; }
DbSet<District> Districts { get; set; }
DbSet<Group> Groups { get; set; }
DbSet<GroupMembership> GroupMemberships { get; set; }
DbSet<Inspection> Inspections { get; set; }
DbSet<Notification> Notifications { get; set; }
DbSet<NotificationEvent> NotificationEvents { get; set; }
DbSet<Permission> Permissions { get; set; }
DbSet<Region> Regions { get; set; }
DbSet<Role> Roles { get; set; }
DbSet<RolePermission> RolePermissions { get; set; }
DbSet<SchoolBus> SchoolBuss { get; set; }
DbSet<Attachment> Attachments { get; set; }
DbSet<History> Historys { get; set; }
DbSet<Note> Notes { get; set; }
DbSet<SchoolBusOwner> SchoolBusOwners { get; set; }
DbSet<Contact> Contacts { get; set; }
DbSet<SchoolDistrict> SchoolDistricts { get; set; }
DbSet<ServiceArea> ServiceAreas { get; set; }
DbSet<User> Users { get; set; }
DbSet<UserFavourite> UserFavourites { get; set; }
DbSet<UserRole> UserRoles { get; set; }
/// <summary>
/// Starts a new transaction.
/// </summary>
/// <returns>
/// A Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction that represents
/// the started transaction.
/// </returns>
IDbContextTransaction BeginTransaction();
int SaveChanges();
}
public class DbAppContext : DbContext, IDbAppContext
{
private readonly IHttpContextAccessor _httpContextAccessor;
/// <summary>
/// Constructor for Class used for Entity Framework access.
/// </summary>
public DbAppContext(IHttpContextAccessor httpContextAccessor, DbContextOptions<DbAppContext> options)
: base(options)
{
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
/// Override for OnModelCreating - used to change the database naming convention.
/// </summary>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// add our naming convention extension
modelBuilder.UpperCaseUnderscoreSingularConvention();
}
public virtual DbSet<Audit> Audits { get; set; }
public virtual DbSet<CCWData> CCWDatas { get; set; }
public virtual DbSet<CCWJurisdiction> CCWJurisdictions { get; set; }
public virtual DbSet<City> Cities { get; set; }
public virtual DbSet<District> Districts { get; set; }
public virtual DbSet<Group> Groups { get; set; }
public virtual DbSet<GroupMembership> GroupMemberships { get; set; }
public virtual DbSet<Inspection> Inspections { get; set; }
public virtual DbSet<Notification> Notifications { get; set; }
public virtual DbSet<NotificationEvent> NotificationEvents { get; set; }
public virtual DbSet<Permission> Permissions { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<RolePermission> RolePermissions { get; set; }
public virtual DbSet<SchoolBus> SchoolBuss { get; set; }
public virtual DbSet<Attachment> Attachments { get; set; }
public virtual DbSet<History> Historys { get; set; }
public virtual DbSet<Note> Notes { get; set; }
public virtual DbSet<SchoolBusOwner> SchoolBusOwners { get; set; }
public virtual DbSet<Contact> Contacts { get; set; }
public virtual DbSet<SchoolDistrict> SchoolDistricts { get; set; }
public virtual DbSet<ServiceArea> ServiceAreas { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<UserFavourite> UserFavourites { get; set; }
public virtual DbSet<UserRole> UserRoles { get; set; }
/// <summary>
/// Starts a new transaction.
/// </summary>
/// <returns>
/// A Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction that represents
/// the started transaction.
/// </returns>
public virtual IDbContextTransaction BeginTransaction()
{
bool existingTransaction = true;
IDbContextTransaction transaction = this.Database.CurrentTransaction;
if (transaction == null)
{
existingTransaction = false;
transaction = this.Database.BeginTransaction();
}
return new DbContextTransactionWrapper(transaction, existingTransaction);
}
/// <summary>
/// Returns the current web user
/// </summary>
protected ClaimsPrincipal HttpContextUser
{
get { return _httpContextAccessor.HttpContext.User; }
}
/// <summary>
/// Returns the current user ID
/// </summary>
/// <returns></returns>
protected string GetCurrentUserId()
{
string result = null;
try
{
result = HttpContextUser.FindFirst(ClaimTypes.Name).Value;
}
catch (Exception e)
{
result = null;
}
return result;
}
protected User GetCurrentUser()
{
User result = null;
try
{
string userId = HttpContextUser.FindFirst(SchoolBusAPI.Models.User.USERID_CLAIM).Value;
int id = int.Parse(userId);
result = Users.FirstOrDefault(x => x.Id == id);
}
catch (Exception e)
{
result = null;
}
return result;
}
bool FieldHasChanged(EntityEntry entry, string fieldName)
{
bool result = false;
// first check that the property is there.
var property = entry.Metadata.FindProperty(fieldName);
if (property != null)
{
var oldValue = entry.OriginalValues[fieldName];
var newValue = entry.CurrentValues[fieldName];
if (property.ClrType == typeof(int))
{
result = oldValue != newValue;
}
else
{
result = !oldValue.Equals(newValue);
}
}
return result;
}
/// <summary>
/// Override for Save Changes to implement the audit log
/// </summary>
/// <returns></returns>
public override int SaveChanges()
{
List<Audit> auditEntries = new List<Audit>();
// update the audit fields for this item.
string smUserId = null;
User currentUser = null;
if (_httpContextAccessor != null)
{
smUserId = GetCurrentUserId();
currentUser = GetCurrentUser();
}
var modifiedEntries = ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted).ToList();
DateTime currentTime = DateTime.UtcNow;
foreach (var entry in modifiedEntries)
{
// handle the table level audit fields
if ((entry.State == EntityState.Added || entry.State == EntityState.Modified) && entry.Entity.GetType().InheritsOrImplements(typeof(AuditableEntity)))
{
var theObject = (AuditableEntity)entry.Entity;
theObject.LastUpdateUserid = smUserId;
theObject.LastUpdateTimestamp = currentTime;
if (entry.State == EntityState.Added)
{
theObject.CreateUserid = smUserId;
theObject.CreateTimestamp = currentTime;
}
}
if (currentUser != null)
{
try
{
int affectedEntityId = (int)entry.CurrentValues["Id"];
string entityName = Model.FindEntityType(entry.Entity.GetType()).Relational().TableName;
if (entry.State == EntityState.Deleted)
{
// update the Audit log for the delete record
Audit audit = new Audit();
audit.AppLastUpdateTimestamp = currentTime;
audit.AppLastUpdateUserDirectory = currentUser.SmAuthorizationDirectory;
audit.AppLastUpdateUserGuid = currentUser.Guid;
audit.AppLastUpdateUserid = smUserId;
audit.CreateTimestamp = currentTime;
audit.CreateUserid = smUserId;
audit.EntityName = entityName;
audit.EntityId = affectedEntityId;
audit.LastUpdateTimestamp = currentTime;
audit.LastUpdateUserid = smUserId;
audit.IsDelete = true;
auditEntries.Add(audit);
}
else
{
// loop through the fields and determine any changes.
foreach (var item in entry.Properties)
{
if (item.IsModified || entry.State == EntityState.Added)
{
// create an audit entry for this item.
Audit audit = new Audit();
audit.AppLastUpdateTimestamp = currentTime;
audit.AppLastUpdateUserDirectory = currentUser.SmAuthorizationDirectory;
audit.AppLastUpdateUserGuid = currentUser.Guid;
audit.AppLastUpdateUserid = smUserId;
audit.CreateTimestamp = currentTime;
audit.CreateUserid = smUserId;
audit.EntityName = entityName;
audit.EntityId = affectedEntityId;
audit.LastUpdateTimestamp = currentTime;
audit.LastUpdateUserid = smUserId;
if (entry.State == EntityState.Added)
{
audit.AppCreateTimestamp = currentTime;
audit.AppCreateUserid = smUserId;
audit.AppCreateUserGuid = currentUser.Guid;
audit.AppCreateUserDirectory = currentUser.SmAuthorizationDirectory;
}
if (item.OriginalValue != null)
{
audit.OldValue = item.OriginalValue.ToString();
}
if (item.CurrentValue != null)
{
audit.NewValue = item.CurrentValue.ToString();
}
audit.PropertyName = item.Metadata.Relational().ColumnName;
auditEntries.Add(audit);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
int result = base.SaveChanges();
// Add the audit entries.
if (auditEntries.Count > 0)
{
foreach (var item in auditEntries)
{
Audits.Add(item);
base.SaveChanges();
}
}
return result;
}
}
}
| |
using System.Text;
using GuiLabs.Editor.Blocks;
namespace GuiLabs.Editor.CSharp
{
public class PrettyPrinter : BaseVisitor
{
#region ctor
public PrettyPrinter()
{
Builder = new StringBuilder();
}
#endregion
public static string Print(CodeUnitBlock block)
{
PrettyPrinter visitor = new PrettyPrinter();
block.AcceptVisitor(visitor);
return visitor.ToString();
}
#region StringBuilder
public void Clear()
{
Builder.Remove(0, Builder.Length);
}
public override string ToString()
{
return Builder.ToString();
}
private StringBuilder mBuilder;
public StringBuilder Builder
{
get
{
return mBuilder;
}
set
{
mBuilder = value;
}
}
#endregion
#region Visit
public override void Visit(CodeUnitBlock block)
{
VisitContainer(block);
}
#region Namespace
public override void Visit(NamespaceBlock block)
{
WriteIndent();
WriteLine("namespace " + block.Name);
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(EmptyNamespaceBlock block)
{
VisitEmptyBlock(block);
}
public override void Visit(UsingBlock block)
{
foreach (UsingDirective dir in block.VMembers.Children)
{
WriteIndent();
Visit(dir);
NewLine();
}
}
public override void Visit(UsingDirective block)
{
if (string.IsNullOrEmpty(block.Text))
{
return;
}
string text = "using " + block.Text.TrimEnd(';', ' ') + ";";
Write(text);
}
#endregion
#region Types
public override void Visit(ClassBlock block)
{
WriteIndent();
Write(block.Modifiers);
WriteLine("class " + block.Name);
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(EmptyClassMember block)
{
VisitEmptyBlock(block);
}
public override void Visit(StructBlock block)
{
WriteIndent();
Write(block.Modifiers);
WriteLine("struct " + block.Name);
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
#region Interface
public override void Visit(InterfaceBlock block)
{
WriteIndent();
Write(block.Modifiers);
WriteLine("interface " + block.Name);
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(InterfaceMemberDeclarationBlock block)
{
WriteIndent();
Visit(block.Text);
if (block.Parameters != null)
{
Visit(block.Parameters);
}
if (block.ThisParameters != null)
{
Visit(block.ThisParameters);
}
if (block.PropertyAccessors != null)
{
Visit(block.PropertyAccessors);
}
else
{
if (!string.IsNullOrEmpty(block.Text.Text))
{
WriteSemicolon();
}
}
NewLine();
}
public override void Visit(InterfaceMemberTextBlock block)
{
Write(block.Text);
}
public override void Visit(InterfaceAccessorsBlock block)
{
Write(" {");
if (block.Getter != null)
{
Write(" get;");
}
if (block.Setter != null)
{
Write(" set;");
}
Write(" }");
}
#endregion
public override void Visit(EnumBlock block)
{
WriteIndent();
Write(block.Modifiers);
WriteLine("enum " + block.Name);
StartBlock();
foreach (ICSharpBlock b in block.VMembers.Children)
{
WriteIndent();
b.AcceptVisitor(this);
NewLine();
}
EndBlock();
}
public override void Visit(EnumValue block)
{
if (block.IsValue)
{
Write(block.Text);
if (!block.IsLastValue)
{
Write(",");
}
}
}
public override void Visit(DelegateBlock block)
{
WriteIndent();
Write(block.Modifiers);
Write("delegate ");
Write(block.TypeBlock.Text);
WriteSpace();
Write(block.Name);
Visit(block.Parameters);
WriteSemicolon();
NewLine();
}
#endregion
#region Members
public override void Visit(MethodBlock block)
{
WriteIndent();
Write(block.Modifiers);
Write(block.Name);
Visit(block.Parameters);
NewLine();
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(ConstructorBlock block)
{
WriteIndent();
Write(block.Modifiers);
Write(block.Name);
Visit(block.Parameters);
NewLine();
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(PropertyBlock block)
{
WriteIndent();
Write(block.Modifiers);
Write(block.Name);
NewLine();
StartBlock();
if (block.GetAccessor != null)
{
Visit(block.GetAccessor);
}
if (block.SetAccessor != null)
{
Visit(block.SetAccessor);
}
EndBlock();
}
public override void Visit(PropertyAccessorBlock block)
{
WriteIndent();
WriteLine(block.Keyword.Text);
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(FieldBlock block)
{
WriteIndent();
Write(block.Modifiers);
Write(block.Name.TrimEnd(';', ' '));
WriteSemicolon();
NewLine();
}
#endregion
#region ControlStructures
public override void Visit(ForBlock block)
{
WriteIndent();
Write(block.Keyword.Text);
Write("(");
Write(block.ForInitializer.Text);
Write("; ");
Write(block.ForCondition.Text);
Write("; ");
Write(block.ForIncrementStep.Text);
WriteLine(")");
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(ForeachBlock block)
{
WriteIndent();
Write(block.Keyword.Text);
Write("(");
Write(block.IteratorType.Text);
Write(" ");
Write(block.IteratorName.Text);
Write(" in ");
Write(block.EnumeratedExpression.Text);
WriteLine(")");
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(IfBlock block)
{
WriteControlStructureWithString(block, block.Condition.Text);
}
public override void Visit(ElseBlock block)
{
WriteIndent();
Write(block.Keyword.Text);
if (!string.IsNullOrEmpty(block.Condition))
{
Write(" if (");
Write(block.Condition);
Write(")");
}
NewLine();
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(WhileBlock block)
{
WriteControlStructureWithString(block, block.Condition.Text);
}
public override void Visit(DoWhileBlock block)
{
WriteIndent();
WriteLine("do");
StartBlock();
VisitContainer(block.DoPart.VMembers);
EndBlock();
WriteIndent();
Write("while (");
Write(block.Condition.Text);
WriteLine(");");
}
public override void Visit(UsingStatementBlock block)
{
WriteControlStructureWithString(block, block.Resource.Text.TrimEnd(' ', ';'));
}
public override void Visit(TryBlock block)
{
WriteControlStructure(block);
}
public override void Visit(CatchBlock block)
{
WriteIndent();
Write(block.Keyword.Text);
if (!string.IsNullOrEmpty(block.ExceptionBlock.Text))
{
Write("(");
Write(block.ExceptionBlock.Text);
Write(")");
}
NewLine();
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(FinallyBlock block)
{
WriteControlStructure(block);
}
public override void Visit(BreakStatement block)
{
WriteIndent();
WriteLine("break;");
}
public override void Visit(ContinueStatement block)
{
WriteIndent();
WriteLine("continue;");
}
public override void Visit(LockBlock block)
{
WriteControlStructureWithString(block, block.LockObject.Text);
}
public void WriteControlStructure(ControlStructureBlock block)
{
WriteIndent();
WriteLine(block.Keyword.Text);
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public void WriteControlStructureWithString(ControlStructureBlock block, string title)
{
WriteIndent();
Write(block.Keyword.Text);
Write("(");
Write(title);
WriteLine(")");
StartBlock();
VisitContainer(block.VMembers);
EndBlock();
}
public override void Visit(BlockStatementBlock block)
{
StartBlock();
VisitContainer(block);
EndBlock();
}
#endregion
public override void Visit(CodeLine block)
{
if (!string.IsNullOrEmpty(block.Text))
{
WriteIndent();
string text = block.Text.TrimEnd(';', ' ');
Write(text + ";");
}
NewLine();
}
public override void Visit(ParameterListBlock block)
{
Write(block.OpeningBrace + block.Text + block.ClosingBrace);
}
private void VisitEmptyBlock(EmptyBlock block)
{
if (block.Prev != null && block.Next != null)
{
NewLine();
}
}
#endregion
#region Write
public void WriteSpace()
{
Write(" ");
}
public void WriteSemicolon()
{
Write(";");
}
public void Write(ModifierContainer modifiers)
{
string mods = modifiers.ToString();
if (!string.IsNullOrEmpty(mods))
{
Write(mods);
WriteSpace();
}
}
public void Write(string s)
{
Builder.Append(s);
}
public void WriteLine(string s)
{
Builder.AppendLine(s);
}
public void NewLine()
{
Builder.AppendLine();
}
public void WriteFormat(string s, params object[] parameters)
{
Builder.AppendFormat(s, parameters);
}
public void WriteIndent()
{
Write(CurrentIndentString);
}
public void Tab()
{
Write(IndentString);
}
public void StartBlock()
{
WriteIndent();
WriteLine("{");
Indent();
}
public void EndBlock()
{
UnIndent();
WriteIndent();
WriteLine("}");
}
#endregion
#region Indent
private string mIndentString = "\t";
public string IndentString
{
get
{
return mIndentString;
}
set
{
mIndentString = value;
}
}
private string mCurrentIndentString = "";
public string CurrentIndentString
{
get
{
return mCurrentIndentString;
}
set
{
mCurrentIndentString = value;
}
}
public string GetIndents(int timesToIndent)
{
int lengthOfASingleSegment = IndentString.Length;
StringBuilder sb = new StringBuilder(timesToIndent * lengthOfASingleSegment);
for (int i = 0; i < lengthOfASingleSegment; i++)
{
sb.Append(IndentString);
}
return sb.ToString();
}
public void Indent()
{
CurrentIndentString += IndentString;
}
public void UnIndent()
{
CurrentIndentString = CurrentIndentString.Substring(0, CurrentIndentString.Length - IndentString.Length);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebApiSample.Mvvm.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AnonymousIdentificationSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration {
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Security;
using System.ComponentModel;
using System.Security.Permissions;
// <!--
// anonymousIdentification configuration:
// enabled="[true|false]" Feature is enabled?
// cookieName=".ASPXANONYMOUS" Cookie Name
// cookieTimeout="100000" Cookie Timeout in minutes
// cookiePath="/" Cookie Path
// cookieRequireSSL="[true|false]" Set Secure bit in Cookie
// cookieSlidingExpiration="[true|false]" Reissue expiring cookies?
// cookieProtection="[None|Validation|Encryption|All]" How to protect cookies from being read/tampered
// cookieless="[UseCookies|UseUri|AutoDetect|UseDeviceProfile]" - Use Cookies or the URL path to store the id
// domain="[domain]" Enables output of the "domain" cookie attribute set to the specified value
// -->
//
// <anonymousIdentification enabled="false" cookieName=".ASPXANONYMOUS" cookieTimeout="100000"
// cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true"
// cookieProtection="None" cookieless="UseDeviceProfile" domain="" />
// [SectionComment(
// " anonymousIdentification configuration:" + "\r\n" +
// " enabled=\"[true|false]\" Feature is enabled?" + "\r\n" +
// " cookieName=\".ASPXANONYMOUS\" Cookie Name" + "\r\n" +
// " cookieTimeout=\"100000\" Cookie Timeout in minutes" + "\r\n" +
// " cookiePath=\"/\" Cookie Path" + "\r\n" +
// " cookieRequireSSL=\"[true|false]\" Set Secure bit in Cookie" + "\r\n" +
// " cookieSlidingExpiration=\"[true|false]\" Reissue expiring cookies?" + "\r\n" +
// " cookieProtection=\"[None|Validation|Encryption|All]\" How to protect cookies from being read/tampered" + "\r\n" +
// " cookieless=\"[UseCookies|UseUri|AutoDetect|UseDeviceProfile]\" - Use Cookies or the URL path to store the id" + "\r\n" +
// " domain=\"[domain]\" Enables output of the "domain" cookie attribute set to the specified value" + "\r\n" +
// " -->" + "\r\n" +
// )]
public sealed class AnonymousIdentificationSection : ConfigurationSection {
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propEnabled =
new ConfigurationProperty("enabled", typeof(bool), false, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieName =
new ConfigurationProperty("cookieName",
typeof(string),
".ASPXANONYMOUS",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieTimeout =
new ConfigurationProperty("cookieTimeout",
typeof(TimeSpan),
TimeSpan.FromMinutes(100000.0),
StdValidatorsAndConverters.TimeSpanMinutesOrInfiniteConverter,
StdValidatorsAndConverters.PositiveTimeSpanValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookiePath =
new ConfigurationProperty("cookiePath",
typeof(string),
"/",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieRequireSSL =
new ConfigurationProperty("cookieRequireSSL", typeof(bool), false, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieSlidingExpiration =
new ConfigurationProperty("cookieSlidingExpiration", typeof(bool), true, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieProtection =
new ConfigurationProperty("cookieProtection", typeof(CookieProtection), CookieProtection.Validation, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieless =
new ConfigurationProperty("cookieless", typeof(HttpCookieMode), HttpCookieMode.UseCookies, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDomain =
new ConfigurationProperty("domain", typeof(string), null, ConfigurationPropertyOptions.None);
static AnonymousIdentificationSection() {
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propEnabled);
_properties.Add(_propCookieName);
_properties.Add(_propCookieTimeout);
_properties.Add(_propCookiePath);
_properties.Add(_propCookieRequireSSL);
_properties.Add(_propCookieSlidingExpiration);
_properties.Add(_propCookieProtection);
_properties.Add(_propCookieless);
_properties.Add(_propDomain);
}
public AnonymousIdentificationSection() {
}
protected override ConfigurationPropertyCollection Properties {
get {
return _properties;
}
}
[ConfigurationProperty("enabled", DefaultValue = false)]
public bool Enabled {
get {
return (bool)base[_propEnabled];
}
set {
base[_propEnabled] = value;
}
}
[ConfigurationProperty("cookieName", DefaultValue = ".ASPXANONYMOUS")]
[StringValidator(MinLength = 1)]
public string CookieName {
get {
return (string)base[_propCookieName];
}
set {
base[_propCookieName] = value;
}
}
[ConfigurationProperty("cookieTimeout", DefaultValue = "69.10:40:00")]
[TimeSpanValidator(MinValueString="00:00:00", MaxValueString=TimeSpanValidatorAttribute.TimeSpanMaxValue)]
[TypeConverter(typeof(TimeSpanMinutesOrInfiniteConverter))]
public TimeSpan CookieTimeout {
get {
return (TimeSpan)base[_propCookieTimeout];
}
set {
base[_propCookieTimeout] = value;
}
}
[ConfigurationProperty("cookiePath", DefaultValue = "/")]
[StringValidator(MinLength = 1)]
public string CookiePath {
get {
return (string)base[_propCookiePath];
}
set {
base[_propCookiePath] = value;
}
}
[ConfigurationProperty("cookieRequireSSL", DefaultValue = false)]
public bool CookieRequireSSL {
get {
return (bool)base[_propCookieRequireSSL];
}
set {
base[_propCookieRequireSSL] = value;
}
}
[ConfigurationProperty("cookieSlidingExpiration", DefaultValue = true)]
public bool CookieSlidingExpiration {
get {
return (bool)base[_propCookieSlidingExpiration];
}
set {
base[_propCookieSlidingExpiration] = value;
}
}
[ConfigurationProperty("cookieProtection", DefaultValue = CookieProtection.Validation)]
public CookieProtection CookieProtection {
get {
return (CookieProtection)base[_propCookieProtection];
}
set {
base[_propCookieProtection] = value;
}
}
[ConfigurationProperty("cookieless", DefaultValue = HttpCookieMode.UseCookies)]
public HttpCookieMode Cookieless {
get {
return (HttpCookieMode)base[_propCookieless];
}
set {
base[_propCookieless] = value;
}
}
[ConfigurationProperty("domain")]
public string Domain {
get {
return (string)base[_propDomain];
}
set {
base[_propDomain] = value;
}
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using Sensus.Shared.Anonymization;
using Sensus.Shared.Anonymization.Anonymizers;
using Sensus.Shared.Probes.User.Scripts.ProbeTriggerProperties;
using Sensus.Shared.UI.Inputs;
namespace Sensus.Shared.Probes.User.Scripts
{
public class ScriptDatum : Datum
{
private string _scriptId;
private string _scriptName;
private string _groupId;
private string _inputId;
private string _runId;
private object _response;
private string _triggerDatumId;
private double? _latitude;
private double? _longitude;
private DateTimeOffset _runTimestamp;
private DateTimeOffset? _locationTimestamp;
private List<InputCompletionRecord> _completionRecords;
private DateTimeOffset _submissionTimestamp;
public string ScriptId
{
get
{
return _scriptId;
}
set
{
_scriptId = value;
}
}
public string ScriptName
{
get
{
return _scriptName;
}
set
{
_scriptName = value;
}
}
public string GroupId
{
get
{
return _groupId;
}
set
{
_groupId = value;
}
}
public string InputId
{
get
{
return _inputId;
}
set
{
_inputId = value;
}
}
public string RunId
{
get
{
return _runId;
}
set
{
_runId = value;
}
}
public object Response
{
get { return _response; }
set { _response = value; }
}
[Anonymizable("Triggering Datum ID:", typeof(StringHashAnonymizer), false)]
public string TriggerDatumId
{
get { return _triggerDatumId; }
set { _triggerDatumId = value; }
}
[DoubleProbeTriggerProperty]
[Anonymizable(null, new Type[] { typeof(DoubleRoundingTenthsAnonymizer), typeof(DoubleRoundingHundredthsAnonymizer), typeof(DoubleRoundingThousandthsAnonymizer) }, -1)]
public double? Latitude
{
get { return _latitude; }
set { _latitude = value; }
}
[DoubleProbeTriggerProperty]
[Anonymizable(null, new Type[] { typeof(DoubleRoundingTenthsAnonymizer), typeof(DoubleRoundingHundredthsAnonymizer), typeof(DoubleRoundingThousandthsAnonymizer) }, -1)]
public double? Longitude
{
get { return _longitude; }
set { _longitude = value; }
}
public DateTimeOffset RunTimestamp
{
get
{
return _runTimestamp;
}
set
{
_runTimestamp = value;
}
}
public DateTimeOffset? LocationTimestamp
{
get
{
return _locationTimestamp;
}
set
{
_locationTimestamp = value;
}
}
public List<InputCompletionRecord> CompletionRecords
{
get
{
return _completionRecords;
}
// need setter in order for anonymizer to pick up the property (only includes writable properties)
set
{
_completionRecords = value;
}
}
public override string DisplayDetail
{
get
{
if (_response == null)
return "No response.";
else
{
if (_response is IList)
{
IList responseList = _response as IList;
return responseList.Count + " response" + (responseList.Count == 1 ? "" : "s") + ".";
}
else
return _response.ToString();
}
}
}
public DateTimeOffset SubmissionTimestamp
{
get
{
return _submissionTimestamp;
}
set
{
_submissionTimestamp = value;
}
}
/// <summary>
/// For JSON deserialization.
/// </summary>
private ScriptDatum()
{
_completionRecords = new List<InputCompletionRecord>();
}
public ScriptDatum(DateTimeOffset timestamp, string scriptId, string scriptName, string groupId, string inputId, string runId, object response, string triggerDatumId, double? latitude, double? longitude, DateTimeOffset? locationTimestamp, DateTimeOffset runTimestamp, List<InputCompletionRecord> completionRecords, DateTimeOffset submissionTimestamp)
: base(timestamp)
{
_scriptId = scriptId;
_scriptName = scriptName;
_groupId = groupId;
_inputId = inputId;
_runId = runId;
_response = response;
_triggerDatumId = triggerDatumId == null ? "" : triggerDatumId;
_latitude = latitude;
_longitude = longitude;
_locationTimestamp = locationTimestamp;
_runTimestamp = runTimestamp;
_completionRecords = completionRecords;
_submissionTimestamp = submissionTimestamp;
}
public override string ToString()
{
return base.ToString() + Environment.NewLine +
"Script: " + _scriptId + Environment.NewLine +
"Group: " + _groupId + Environment.NewLine +
"Input: " + _inputId + Environment.NewLine +
"Run: " + _runId + Environment.NewLine +
"Response: " + _response + Environment.NewLine +
"Latitude: " + _latitude + Environment.NewLine +
"Longitude: " + _longitude + Environment.NewLine +
"Location Timestamp: " + _locationTimestamp + Environment.NewLine +
"Run Timestamp: " + _runTimestamp + Environment.NewLine +
"Submission Timestamp: " + _submissionTimestamp;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel
{
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.ServiceModel.Security;
static class CryptoHelper
{
static byte[] emptyBuffer;
static RandomNumberGenerator random;
static Rijndael rijndael;
static TripleDES tripleDES;
static Dictionary<string, Func<object>> algorithmDelegateDictionary = new Dictionary<string, Func<object>>();
static object AlgorithmDictionaryLock = new object();
public const int WindowsVistaMajorNumber = 6;
const string SHAString = "SHA";
const string SHA1String = "SHA1";
const string SHA256String = "SHA256";
const string SystemSecurityCryptographySha1String = "System.Security.Cryptography.SHA1";
/// <summary>
/// The helper class which helps user to compute the combined entropy as well as the session
/// key
/// </summary>
public static class KeyGenerator
{
static RandomNumberGenerator _random = CryptoHelper.RandomNumberGenerator;
//
// 1/(2^32) keys will be weak. 20 random keys will never happen by chance without the RNG being messed up.
//
const int _maxKeyIterations = 20;
/// <summary>
/// Computes the session key based on PSHA1 algorithm.
/// </summary>
/// <param name="requestorEntropy">The entropy from the requestor side.</param>
/// <param name="issuerEntropy">The entropy from the token issuer side.</param>
/// <param name="keySizeInBits">The desired key size in bits.</param>
/// <returns>The computed session key.</returns>
public static byte[] ComputeCombinedKey( byte[] requestorEntropy, byte[] issuerEntropy, int keySizeInBits )
{
if ( null == requestorEntropy )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "requestorEntropy" );
}
if ( null == issuerEntropy )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "issuerEntropy" );
}
int keySizeInBytes = ValidateKeySizeInBytes( keySizeInBits );
byte[] key = new byte[keySizeInBytes]; // Final key
// The symmetric key generation chosen is
// http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1
// which per the WS-Trust specification is defined as follows:
//
// The key is computed using P_SHA1
// from the TLS specification to generate
// a bit stream using entropy from both
// sides. The exact form is:
//
// key = P_SHA1 (EntREQ, EntRES)
//
// where P_SHA1 is defined per http://www.ietf.org/rfc/rfc2246.txt
// and EntREQ is the entropy supplied by the requestor and EntRES
// is the entrophy supplied by the issuer.
//
// From http://www.faqs.org/rfcs/rfc2246.html:
//
// 8<------------------------------------------------------------>8
// First, we define a data expansion function, P_hash(secret, data)
// which uses a single hash function to expand a secret and seed
// into an arbitrary quantity of output:
//
// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
// HMAC_hash(secret, A(2) + seed) +
// HMAC_hash(secret, A(3) + seed) + ...
//
// Where + indicates concatenation.
//
// A() is defined as:
// A(0) = seed
// A(i) = HMAC_hash(secret, A(i-1))
//
// P_hash can be iterated as many times as is necessary to produce
// the required quantity of data. For example, if P_SHA-1 was
// being used to create 64 bytes of data, it would have to be
// iterated 4 times (through A(4)), creating 80 bytes of output
// data; the last 16 bytes of the final iteration would then be
// discarded, leaving 64 bytes of output data.
// 8<------------------------------------------------------------>8
// Note that requestorEntrophy is considered the 'secret'.
using ( KeyedHashAlgorithm kha = CryptoHelper.NewHmacSha1KeyedHashAlgorithm() )
{
kha.Key = requestorEntropy;
byte[] a = issuerEntropy; // A(0), the 'seed'.
byte[] b = new byte[kha.HashSize / 8 + a.Length]; // Buffer for A(i) + seed
byte[] result = null;
try
{
for ( int i = 0; i < keySizeInBytes; )
{
// Calculate A(i+1).
kha.Initialize();
a = kha.ComputeHash( a );
// Calculate A(i) + seed
a.CopyTo( b, 0 );
issuerEntropy.CopyTo( b, a.Length );
kha.Initialize();
result = kha.ComputeHash( b );
for ( int j = 0; j < result.Length; j++ )
{
if ( i < keySizeInBytes )
{
key[i++] = result[j];
}
else
{
break;
}
}
}
}
catch
{
Array.Clear( key, 0, key.Length );
throw;
}
finally
{
if ( result != null )
{
Array.Clear( result, 0, result.Length );
}
Array.Clear( b, 0, b.Length );
kha.Clear();
}
}
return key;
}
/// <summary>
/// Generates a symmetric key with a given size.
/// </summary>
/// <remarks>This function should not be used to generate DES keys because it does not perform an IsWeakKey check.
/// Use GenerateDESKey() instead.</remarks>
/// <param name="keySizeInBits">The key size in bits.</param>
/// <returns>The symmetric key.</returns>
/// <exception cref="ArgumentException">When keySizeInBits is not a whole number of bytes.</exception>
public static byte[] GenerateSymmetricKey( int keySizeInBits )
{
int keySizeInBytes = ValidateKeySizeInBytes( keySizeInBits );
byte[] key = new byte[keySizeInBytes];
CryptoHelper.GenerateRandomBytes( key );
return key;
}
/// <summary>
/// Generates a combined-entropy key.
/// </summary>
/// <remarks>This function should not be used to generate DES keys because it does not perform an IsWeakKey check.
/// Use GenerateDESKey() instead.</remarks>
/// <param name="keySizeInBits">The key size in bits.</param>
/// <param name="senderEntropy">Requestor's entropy.</param>
/// <param name="receiverEntropy">The issuer's entropy.</param>
/// <returns>The computed symmetric key based on PSHA1 algorithm.</returns>
/// <exception cref="ArgumentException">When keySizeInBits is not a whole number of bytes.</exception>
public static byte[] GenerateSymmetricKey( int keySizeInBits, byte[] senderEntropy, out byte[] receiverEntropy )
{
if ( senderEntropy == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "senderEntropy" );
}
int keySizeInBytes = ValidateKeySizeInBytes( keySizeInBits );
//
// Generate proof key using sender entropy and receiver entropy
//
receiverEntropy = new byte[keySizeInBytes];
_random.GetNonZeroBytes( receiverEntropy );
return ComputeCombinedKey( senderEntropy, receiverEntropy, keySizeInBits );
}
/// <summary>
/// Generates a symmetric key for use with the DES or Triple-DES algorithms. This function will always return a key that is
/// not considered weak by TripleDES.IsWeakKey().
/// </summary>
/// <param name="keySizeInBits">The key size in bits.</param>
/// <returns>The symmetric key.</returns>
/// <exception cref="ArgumentException">When keySizeInBits is not a proper DES key size.</exception>
public static byte[] GenerateDESKey( int keySizeInBits )
{
int keySizeInBytes = ValidateKeySizeInBytes( keySizeInBits );
byte[] key = new byte[keySizeInBytes];
int tries = 0;
do
{
if ( tries > _maxKeyIterations )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CryptographicException( SR.GetString( SR.ID6048, _maxKeyIterations ) ) );
}
CryptoHelper.GenerateRandomBytes( key );
++tries;
} while ( TripleDES.IsWeakKey( key ) );
return key;
}
/// <summary>
/// Generates a combined-entropy key for use with the DES or Triple-DES algorithms. This function will always return a key that is
/// not considered weak by TripleDES.IsWeakKey().
/// </summary>
/// <param name="keySizeInBits">The key size in bits.</param>
/// <param name="senderEntropy">Requestor's entropy.</param>
/// <param name="receiverEntropy">The issuer's entropy.</param>
/// <returns>The computed symmetric key based on PSHA1 algorithm.</returns>
/// <exception cref="ArgumentException">When keySizeInBits is not a proper DES key size.</exception>
public static byte[] GenerateDESKey( int keySizeInBits, byte[] senderEntropy, out byte[] receiverEntropy )
{
int keySizeInBytes = ValidateKeySizeInBytes( keySizeInBits );
byte[] key = new byte[keySizeInBytes];
int tries = 0;
do
{
if ( tries > _maxKeyIterations )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CryptographicException( SR.GetString( SR.ID6048, _maxKeyIterations ) ) );
}
receiverEntropy = new byte[keySizeInBytes];
_random.GetNonZeroBytes( receiverEntropy );
key = ComputeCombinedKey( senderEntropy, receiverEntropy, keySizeInBits );
++tries;
} while ( TripleDES.IsWeakKey( key ) );
return key;
}
static int ValidateKeySizeInBytes( int keySizeInBits )
{
int keySizeInBytes = keySizeInBits / 8;
if ( keySizeInBits <= 0 )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException( "keySizeInBits", SR.GetString( SR.ID6033, keySizeInBits ) ) );
}
else if ( keySizeInBytes * 8 != keySizeInBits )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException( SR.GetString( SR.ID6002, keySizeInBits ), "keySizeInBits" ) );
}
return keySizeInBytes;
}
/// <summary>
/// Gets a security key identifier which contains the BinarySecretKeyIdentifierClause or
/// EncryptedKeyIdentifierClause if the wrapping credentials is available.
/// </summary>
public static SecurityKeyIdentifier GetSecurityKeyIdentifier(byte[] secret, EncryptingCredentials wrappingCredentials)
{
if (secret == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("secret");
}
if (secret.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("secret", SR.GetString(SR.ID6031));
}
if (wrappingCredentials == null || wrappingCredentials.SecurityKey == null)
{
//
// BinarySecret case
//
return new SecurityKeyIdentifier(new BinarySecretKeyIdentifierClause(secret));
}
else
{
//
// EncryptedKey case
//
byte[] wrappedKey = wrappingCredentials.SecurityKey.EncryptKey(wrappingCredentials.Algorithm, secret);
return new SecurityKeyIdentifier(new EncryptedKeyIdentifierClause(wrappedKey, wrappingCredentials.Algorithm, wrappingCredentials.SecurityKeyIdentifier));
}
}
}
/// <summary>
/// Provides an integer-domain mathematical operation for
/// Ceiling( dividend / divisor ).
/// </summary>
/// <param name="dividend"></param>
/// <param name="divisor"></param>
/// <returns></returns>
public static int CeilingDivide( int dividend, int divisor )
{
int remainder, quotient;
remainder = dividend % divisor;
quotient = dividend / divisor;
if ( remainder > 0 )
{
quotient++;
}
return quotient;
}
internal static byte[] EmptyBuffer
{
get
{
if (emptyBuffer == null)
{
byte[] tmp = new byte[0];
emptyBuffer = tmp;
}
return emptyBuffer;
}
}
internal static Rijndael Rijndael
{
get
{
if (rijndael == null)
{
Rijndael tmp = SecurityUtils.RequiresFipsCompliance ? (Rijndael)new RijndaelCryptoServiceProvider() : new RijndaelManaged();
tmp.Padding = PaddingMode.ISO10126;
rijndael = tmp;
}
return rijndael;
}
}
internal static TripleDES TripleDES
{
get
{
if (tripleDES == null)
{
TripleDESCryptoServiceProvider tmp = new TripleDESCryptoServiceProvider();
tmp.Padding = PaddingMode.ISO10126;
tripleDES = tmp;
}
return tripleDES;
}
}
internal static RandomNumberGenerator RandomNumberGenerator
{
get
{
if (random == null)
{
random = new RNGCryptoServiceProvider();
}
return random;
}
}
/// <summary>
/// Creates the default encryption algorithm.
/// </summary>
/// <returns>A SymmetricAlgorithm instance that must be disposed by the caller after use.</returns>
internal static SymmetricAlgorithm NewDefaultEncryption()
{
return GetSymmetricAlgorithm(null, SecurityAlgorithms.DefaultEncryptionAlgorithm );
}
internal static HashAlgorithm NewSha1HashAlgorithm()
{
return CryptoHelper.CreateHashAlgorithm(SecurityAlgorithms.Sha1Digest);
}
internal static HashAlgorithm NewSha256HashAlgorithm()
{
return CryptoHelper.CreateHashAlgorithm(SecurityAlgorithms.Sha256Digest);
}
internal static KeyedHashAlgorithm NewHmacSha1KeyedHashAlgorithm()
{
KeyedHashAlgorithm algorithm = GetAlgorithmFromConfig( SecurityAlgorithms.HmacSha1Signature ) as KeyedHashAlgorithm;
if ( algorithm == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "algorithm", SR.GetString( SR.ID6037, SecurityAlgorithms.HmacSha1Signature ) );
}
return algorithm;
}
internal static KeyedHashAlgorithm NewHmacSha1KeyedHashAlgorithm(byte[] key)
{
return CryptoHelper.CreateKeyedHashAlgorithm(key, SecurityAlgorithms.HmacSha1Signature);
}
internal static KeyedHashAlgorithm NewHmacSha256KeyedHashAlgorithm(byte[] key)
{
return CryptoHelper.CreateKeyedHashAlgorithm(key, SecurityAlgorithms.HmacSha256Signature);
}
internal static Rijndael NewRijndaelSymmetricAlgorithm()
{
Rijndael rijndael = (GetSymmetricAlgorithm(null, SecurityAlgorithms.Aes128Encryption) as Rijndael);
if (rijndael != null)
return rijndael;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidSymmetricAlgorithm, SecurityAlgorithms.Aes128Encryption)));
}
internal static ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, string algorithm)
{
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
if (symmetricAlgorithm != null)
{
return symmetricAlgorithm.CreateDecryptor(key, iv);
}
//NOTE: KeyedHashAlgorithms are symmetric in nature but we still throw if it is passed as an argument.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidSymmetricAlgorithm, algorithm)));
}
switch (algorithm)
{
case SecurityAlgorithms.TripleDesEncryption:
return TripleDES.CreateDecryptor(key, iv);
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes256Encryption:
return Rijndael.CreateDecryptor(key, iv);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedEncryptionAlgorithm, algorithm)));
}
}
internal static ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, string algorithm)
{
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
if (symmetricAlgorithm != null)
{
return symmetricAlgorithm.CreateEncryptor(key, iv);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidSymmetricAlgorithm, algorithm)));
}
switch (algorithm)
{
case SecurityAlgorithms.TripleDesEncryption:
return TripleDES.CreateEncryptor(key, iv);
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes256Encryption:
return Rijndael.CreateEncryptor(key, iv);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedEncryptionAlgorithm, algorithm)));
}
}
internal static HashAlgorithm CreateHashAlgorithm(string algorithm)
{
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
HashAlgorithm hashAlgorithm = algorithmObject as HashAlgorithm;
if (hashAlgorithm != null)
{
return hashAlgorithm;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidHashAlgorithm, algorithm)));
}
switch (algorithm)
{
case SHAString:
case SHA1String:
case SystemSecurityCryptographySha1String:
case SecurityAlgorithms.Sha1Digest:
if (SecurityUtils.RequiresFipsCompliance)
return new SHA1CryptoServiceProvider();
else
return new SHA1Managed();
case SHA256String:
case SecurityAlgorithms.Sha256Digest:
if (SecurityUtils.RequiresFipsCompliance)
return new SHA256CryptoServiceProvider();
else
return new SHA256Managed();
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedCryptoAlgorithm, algorithm)));
}
}
internal static KeyedHashAlgorithm CreateKeyedHashAlgorithm(byte[] key, string algorithm)
{
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm;
if (keyedHashAlgorithm != null)
{
keyedHashAlgorithm.Key = key;
return keyedHashAlgorithm;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidKeyedHashAlgorithm, algorithm)));
}
switch (algorithm)
{
case SecurityAlgorithms.HmacSha1Signature:
return new HMACSHA1(key, !SecurityUtils.RequiresFipsCompliance);
case SecurityAlgorithms.HmacSha256Signature:
if (!SecurityUtils.RequiresFipsCompliance)
return new HMACSHA256(key);
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CryptoAlgorithmIsNotFipsCompliant, algorithm)));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedCryptoAlgorithm, algorithm)));
}
}
internal static byte[] ComputeHash(byte[] buffer)
{
using (HashAlgorithm hasher = CryptoHelper.NewSha1HashAlgorithm())
{
return hasher.ComputeHash(buffer);
}
}
internal static byte[] GenerateDerivedKey(byte[] key, string algorithm, byte[] label, byte[] nonce, int derivedKeySize, int position)
{
if ((algorithm != SecurityAlgorithms.Psha1KeyDerivation) && (algorithm != SecurityAlgorithms.Psha1KeyDerivationDec2005))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedKeyDerivationAlgorithm, algorithm)));
}
return new Psha1DerivedKeyGenerator(key).GenerateDerivedKey(label, nonce, derivedKeySize, position);
}
internal static int GetIVSize(string algorithm)
{
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
if (symmetricAlgorithm != null)
{
return symmetricAlgorithm.BlockSize;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidSymmetricAlgorithm, algorithm)));
}
switch (algorithm)
{
case SecurityAlgorithms.TripleDesEncryption:
return TripleDES.BlockSize;
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes256Encryption:
return Rijndael.BlockSize;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedEncryptionAlgorithm, algorithm)));
}
}
internal static void FillRandomBytes( byte[] buffer )
{
RandomNumberGenerator.GetBytes( buffer );
}
/// <summary>
/// This generates the entropy using random number. This is usually used on the sending
/// side to generate the requestor's entropy.
/// </summary>
/// <param name="data">The array to fill with cryptographically strong random nonzero bytes.</param>
public static void GenerateRandomBytes( byte[] data )
{
RandomNumberGenerator.GetNonZeroBytes( data );
}
/// <summary>
/// This method generates a random byte array used as entropy with the given size.
/// </summary>
/// <param name="sizeInBits"></param>
/// <returns></returns>
public static byte[] GenerateRandomBytes( int sizeInBits )
{
int sizeInBytes = sizeInBits / 8;
if ( sizeInBits <= 0 )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException( "sizeInBits", SR.GetString( SR.ID6033, sizeInBits ) ) );
}
else if ( sizeInBytes * 8 != sizeInBits )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException( SR.GetString( SR.ID6002, sizeInBits ), "sizeInBits" ) );
}
byte[] data = new byte[sizeInBytes];
GenerateRandomBytes( data );
return data;
}
internal static SymmetricAlgorithm GetSymmetricAlgorithm(byte[] key, string algorithm)
{
SymmetricAlgorithm symmetricAlgorithm;
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
if (symmetricAlgorithm != null)
{
if (key != null)
{
symmetricAlgorithm.Key = key;
}
return symmetricAlgorithm;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.CustomCryptoAlgorithmIsNotValidSymmetricAlgorithm, algorithm)));
}
// NOTE: HMACSHA1 and HMACSHA256 ( KeyedHashAlgorithms ) are symmetric algorithms but they do not extend Symmetric class.
// Hence the function throws when they are passed as arguments.
switch (algorithm)
{
case SecurityAlgorithms.TripleDesEncryption:
case SecurityAlgorithms.TripleDesKeyWrap:
symmetricAlgorithm = new TripleDESCryptoServiceProvider();
break;
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes256Encryption:
case SecurityAlgorithms.Aes128KeyWrap:
case SecurityAlgorithms.Aes192KeyWrap:
case SecurityAlgorithms.Aes256KeyWrap:
symmetricAlgorithm = SecurityUtils.RequiresFipsCompliance ? (Rijndael)new RijndaelCryptoServiceProvider() : new RijndaelManaged();
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedEncryptionAlgorithm, algorithm)));
}
if (key != null)
{
symmetricAlgorithm.Key = key;
}
return symmetricAlgorithm;
}
/// <summary>
/// Wrapper that creates a signature for SHA256 taking into consideration the special logic required for FIPS compliance
/// </summary>
/// <param name="formatter">the signature formatter</param>
/// <param name="hash">the hash algorithm</param>
/// <returns>byte array representing the signature</returns>
internal static byte[] CreateSignatureForSha256( AsymmetricSignatureFormatter formatter, HashAlgorithm hash )
{
if ( SecurityUtils.RequiresFipsCompliance )
{
//
// When FIPS is turned ON. We need to set the hash algorithm specifically
// as we need to pass the pre-computed buffer to CreateSignature, else
// for SHA256 and FIPS turned ON, the underlying formatter does not understand the
// OID for the hashing algorithm.
//
formatter.SetHashAlgorithm( "SHA256" );
return formatter.CreateSignature( hash.Hash );
}
else
{
//
// Calling the formatter with the object allows us to be Crypto-Agile
//
return formatter.CreateSignature( hash );
}
}
/// <summary>
/// Wrapper that verifies the signature for SHA256 taking into consideration the special logic for FIPS compliance
/// </summary>
/// <param name="deformatter">the signature deformatter</param>
/// <param name="hash">the hash algorithm</param>
/// <param name="signatureValue">the byte array for the signature value</param>
/// <returns>true/false indicating if signature was verified or not</returns>
internal static bool VerifySignatureForSha256( AsymmetricSignatureDeformatter deformatter, HashAlgorithm hash, byte[] signatureValue )
{
if ( SecurityUtils.RequiresFipsCompliance )
{
//
// When FIPS is turned ON. We need to set the hash algorithm specifically
// else for SHA256 and FIPS turned ON, the underlying deformatter does not understand the
// OID for the hashing algorithm.
//
deformatter.SetHashAlgorithm( "SHA256" );
return deformatter.VerifySignature( hash.Hash, signatureValue );
}
else
{
return deformatter.VerifySignature( hash, signatureValue );
}
}
/// <summary>
/// This method returns an AsymmetricSignatureFormatter capable of supporting Sha256 signatures.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
internal static AsymmetricSignatureFormatter GetSignatureFormatterForSha256( AsymmetricSecurityKey key )
{
AsymmetricAlgorithm algorithm = key.GetAsymmetricAlgorithm( SecurityAlgorithms.RsaSha256Signature, true );
RSACryptoServiceProvider rsaProvider = algorithm as RSACryptoServiceProvider;
if ( null != rsaProvider )
{
return GetSignatureFormatterForSha256( rsaProvider );
}
else
{
//
// If not an RSaCryptoServiceProvider, we can only hope that
// the derived imlementation does the correct thing thing WRT Sha256.
//
return new RSAPKCS1SignatureFormatter( algorithm );
}
}
/// <summary>
/// This method returns an AsymmetricSignatureFormatter capable of supporting Sha256 signatures.
/// </summary>
internal static AsymmetricSignatureFormatter GetSignatureFormatterForSha256( RSACryptoServiceProvider rsaProvider )
{
const int PROV_RSA_AES = 24; // CryptoApi provider type for an RSA provider supporting sha-256 digital signatures
AsymmetricSignatureFormatter formatter = null;
CspParameters csp = new CspParameters();
csp.ProviderType = PROV_RSA_AES;
if ( PROV_RSA_AES == rsaProvider.CspKeyContainerInfo.ProviderType )
{
csp.ProviderName = rsaProvider.CspKeyContainerInfo.ProviderName;
}
csp.KeyContainerName = rsaProvider.CspKeyContainerInfo.KeyContainerName;
csp.KeyNumber = (int)rsaProvider.CspKeyContainerInfo.KeyNumber;
if ( rsaProvider.CspKeyContainerInfo.MachineKeyStore )
{
csp.Flags = CspProviderFlags.UseMachineKeyStore;
}
csp.Flags |= CspProviderFlags.UseExistingKey;
rsaProvider = new RSACryptoServiceProvider( csp );
formatter = new RSAPKCS1SignatureFormatter( rsaProvider );
return formatter;
}
/// <summary>
/// This method returns an AsymmetricSignatureDeFormatter capable of supporting Sha256 signatures.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
internal static AsymmetricSignatureDeformatter GetSignatureDeFormatterForSha256( AsymmetricSecurityKey key )
{
RSAPKCS1SignatureDeformatter deformatter;
AsymmetricAlgorithm algorithm = key.GetAsymmetricAlgorithm( SecurityAlgorithms.RsaSha256Signature, false );
RSACryptoServiceProvider rsaProvider = algorithm as RSACryptoServiceProvider;
if ( null != rsaProvider )
{
return GetSignatureDeFormatterForSha256( rsaProvider );
}
else
{
//
// If not an RSaCryptoServiceProvider, we can only hope that
// the derived imlementation does the correct thing WRT Sha256.
//
deformatter = new RSAPKCS1SignatureDeformatter( algorithm );
}
return deformatter;
}
/// <summary>
/// This method returns an AsymmetricSignatureDeFormatter capable of supporting Sha256 signatures.
/// </summary>
internal static AsymmetricSignatureDeformatter GetSignatureDeFormatterForSha256( RSACryptoServiceProvider rsaProvider )
{
const int PROV_RSA_AES = 24; // CryptoApi provider type for an RSA provider supporting sha-256 digital signatures
AsymmetricSignatureDeformatter deformatter = null;
CspParameters csp = new CspParameters();
csp.ProviderType = PROV_RSA_AES;
if ( PROV_RSA_AES == rsaProvider.CspKeyContainerInfo.ProviderType )
{
csp.ProviderName = rsaProvider.CspKeyContainerInfo.ProviderName;
}
csp.KeyNumber = (int)rsaProvider.CspKeyContainerInfo.KeyNumber;
if ( rsaProvider.CspKeyContainerInfo.MachineKeyStore )
{
csp.Flags = CspProviderFlags.UseMachineKeyStore;
}
csp.Flags |= CspProviderFlags.UseExistingKey;
RSACryptoServiceProvider rsaPublicProvider = new RSACryptoServiceProvider( csp );
rsaPublicProvider.ImportCspBlob( rsaProvider.ExportCspBlob( false ) );
deformatter = new RSAPKCS1SignatureDeformatter( rsaPublicProvider );
return deformatter;
}
internal static bool IsAsymmetricAlgorithm(string algorithm)
{
object algorithmObject = null;
try
{
algorithmObject = GetAlgorithmFromConfig(algorithm);
}
catch (InvalidOperationException)
{
algorithmObject = null;
// We ---- the exception and continue.
}
if (algorithmObject != null)
{
AsymmetricAlgorithm asymmetricAlgorithm = algorithmObject as AsymmetricAlgorithm;
SignatureDescription signatureDescription = algorithmObject as SignatureDescription;
if (asymmetricAlgorithm != null || signatureDescription != null)
return true;
return false;
}
switch (algorithm)
{
case SecurityAlgorithms.DsaSha1Signature:
case SecurityAlgorithms.RsaSha1Signature:
case SecurityAlgorithms.RsaSha256Signature:
case SecurityAlgorithms.RsaOaepKeyWrap:
case SecurityAlgorithms.RsaV15KeyWrap:
return true;
default:
return false;
}
}
internal static bool IsSymmetricAlgorithm(string algorithm)
{
object algorithmObject = null;
try
{
algorithmObject = GetAlgorithmFromConfig(algorithm);
}
catch (InvalidOperationException)
{
algorithmObject = null;
// We ---- the exception and continue.
}
if (algorithmObject != null)
{
SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm;
if (symmetricAlgorithm != null || keyedHashAlgorithm != null)
return true;
return false;
}
// NOTE: A KeyedHashAlgorithm is symmetric in nature.
switch (algorithm)
{
case SecurityAlgorithms.DsaSha1Signature:
case SecurityAlgorithms.RsaSha1Signature:
case SecurityAlgorithms.RsaSha256Signature:
case SecurityAlgorithms.RsaOaepKeyWrap:
case SecurityAlgorithms.RsaV15KeyWrap:
return false;
case SecurityAlgorithms.HmacSha1Signature:
case SecurityAlgorithms.HmacSha256Signature:
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.DesEncryption:
case SecurityAlgorithms.Aes256Encryption:
case SecurityAlgorithms.TripleDesEncryption:
case SecurityAlgorithms.Aes128KeyWrap:
case SecurityAlgorithms.Aes192KeyWrap:
case SecurityAlgorithms.Aes256KeyWrap:
case SecurityAlgorithms.TripleDesKeyWrap:
case SecurityAlgorithms.Psha1KeyDerivation:
case SecurityAlgorithms.Psha1KeyDerivationDec2005:
return true;
default:
return false;
}
}
internal static bool IsSymmetricSupportedAlgorithm(string algorithm, int keySize)
{
bool found = false;
object algorithmObject = null;
try
{
algorithmObject = GetAlgorithmFromConfig(algorithm);
}
catch (InvalidOperationException)
{
// We ---- the exception and continue.
}
if (algorithmObject != null)
{
SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm;
if (symmetricAlgorithm != null || keyedHashAlgorithm != null)
found = true;
// The reason we do not return here even when the user has provided a custom algorithm in machine.config
// is because we need to check if the user has overwritten an existing standard URI.
}
switch (algorithm)
{
case SecurityAlgorithms.DsaSha1Signature:
case SecurityAlgorithms.RsaSha1Signature:
case SecurityAlgorithms.RsaSha256Signature:
case SecurityAlgorithms.RsaOaepKeyWrap:
case SecurityAlgorithms.RsaV15KeyWrap:
return false;
case SecurityAlgorithms.HmacSha1Signature:
case SecurityAlgorithms.HmacSha256Signature:
case SecurityAlgorithms.Psha1KeyDerivation:
case SecurityAlgorithms.Psha1KeyDerivationDec2005:
return true;
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes128KeyWrap:
return keySize >= 128 && keySize <= 256;
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes192KeyWrap:
return keySize >= 192 && keySize <= 256;
case SecurityAlgorithms.Aes256Encryption:
case SecurityAlgorithms.Aes256KeyWrap:
return keySize == 256;
case SecurityAlgorithms.TripleDesEncryption:
case SecurityAlgorithms.TripleDesKeyWrap:
return keySize == 128 || keySize == 192;
default:
if (found)
return true;
return false;
// We do not expect the user to map the uri of an existing standrad algorithm with say key size 128 bit
// to a custom algorithm with keySize 192 bits. If he does that, we anyways make sure that we return false.
}
}
// We currently call the CLR APIs to do symmetric key wrap.
// This ends up causing a triple cloning of the byte arrays.
// However, the symmetric key wrap exists now primarily for
// the feature completeness of cryptos and tokens. That is,
// it is never encountered in any Indigo AuthenticationMode.
// The performance of this should be reviewed if this gets hit
// in any mainline scenario.
internal static byte[] UnwrapKey(byte[] wrappingKey, byte[] wrappedKey, string algorithm)
{
SymmetricAlgorithm symmetricAlgorithm;
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
if (symmetricAlgorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.InvalidCustomKeyWrapAlgorithm, algorithm)));
}
using (symmetricAlgorithm)
{
symmetricAlgorithm.Key = wrappingKey;
return EncryptedXml.DecryptKey(wrappedKey, symmetricAlgorithm);
}
}
switch (algorithm)
{
case SecurityAlgorithms.TripleDesKeyWrap:
symmetricAlgorithm = new TripleDESCryptoServiceProvider();
break;
case SecurityAlgorithms.Aes128KeyWrap:
case SecurityAlgorithms.Aes192KeyWrap:
case SecurityAlgorithms.Aes256KeyWrap:
symmetricAlgorithm = SecurityUtils.RequiresFipsCompliance ? (Rijndael)new RijndaelCryptoServiceProvider() : new RijndaelManaged();
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedKeyWrapAlgorithm, algorithm)));
}
using (symmetricAlgorithm)
{
symmetricAlgorithm.Key = wrappingKey;
return EncryptedXml.DecryptKey(wrappedKey, symmetricAlgorithm);
}
}
internal static byte[] WrapKey(byte[] wrappingKey, byte[] keyToBeWrapped, string algorithm)
{
SymmetricAlgorithm symmetricAlgorithm;
object algorithmObject = GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
symmetricAlgorithm = algorithmObject as SymmetricAlgorithm;
if (symmetricAlgorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.InvalidCustomKeyWrapAlgorithm, algorithm)));
}
using (symmetricAlgorithm)
{
symmetricAlgorithm.Key = wrappingKey;
return EncryptedXml.EncryptKey(keyToBeWrapped, symmetricAlgorithm);
}
}
switch (algorithm)
{
case SecurityAlgorithms.TripleDesKeyWrap:
symmetricAlgorithm = new TripleDESCryptoServiceProvider();
break;
case SecurityAlgorithms.Aes128KeyWrap:
case SecurityAlgorithms.Aes192KeyWrap:
case SecurityAlgorithms.Aes256KeyWrap:
symmetricAlgorithm = SecurityUtils.RequiresFipsCompliance ? (Rijndael)new RijndaelCryptoServiceProvider() : new RijndaelManaged();
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.GetString(SR.UnsupportedKeyWrapAlgorithm, algorithm)));
}
using (symmetricAlgorithm)
{
symmetricAlgorithm.Key = wrappingKey;
return EncryptedXml.EncryptKey(keyToBeWrapped, symmetricAlgorithm);
}
}
internal static void ValidateBufferBounds(Array buffer, int offset, int count)
{
if (buffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer"));
}
if (count < 0 || count > buffer.Length)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeInRange, 0, buffer.Length)));
}
if (offset < 0 || offset > buffer.Length - count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeInRange, 0, buffer.Length - count)));
}
}
internal static bool IsEqual(byte[] a, byte[] b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (a == null || b == null || a.Length != b.Length)
{
return false;
}
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}
private static object GetDefaultAlgorithm(string algorithm)
{
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("algorithm"));
}
switch (algorithm)
{
//case SecurityAlgorithms.RsaSha1Signature:
//case SecurityAlgorithms.DsaSha1Signature:
// For these algorithms above, crypto config returns internal objects.
// As we cannot create those internal objects, we are returning null.
// If no custom algorithm is plugged-in, at least these two algorithms
// will be inside the delegate dictionary.
case SecurityAlgorithms.Sha1Digest:
if (SecurityUtils.RequiresFipsCompliance)
return new SHA1CryptoServiceProvider();
else
return new SHA1Managed();
case SecurityAlgorithms.ExclusiveC14n:
return new XmlDsigExcC14NTransform();
case SHA256String:
case SecurityAlgorithms.Sha256Digest:
if (SecurityUtils.RequiresFipsCompliance)
return new SHA256CryptoServiceProvider();
else
return new SHA256Managed();
case SecurityAlgorithms.Sha512Digest:
if (SecurityUtils.RequiresFipsCompliance)
return new SHA512CryptoServiceProvider();
else
return new SHA512Managed();
case SecurityAlgorithms.Aes128Encryption:
case SecurityAlgorithms.Aes192Encryption:
case SecurityAlgorithms.Aes256Encryption:
case SecurityAlgorithms.Aes128KeyWrap:
case SecurityAlgorithms.Aes192KeyWrap:
case SecurityAlgorithms.Aes256KeyWrap:
if (SecurityUtils.RequiresFipsCompliance)
return new RijndaelCryptoServiceProvider();
else
return new RijndaelManaged();
case SecurityAlgorithms.TripleDesEncryption:
case SecurityAlgorithms.TripleDesKeyWrap:
return new TripleDESCryptoServiceProvider();
case SecurityAlgorithms.HmacSha1Signature:
byte[] key = new byte[64];
new RNGCryptoServiceProvider().GetBytes(key);
return new HMACSHA1(key, !SecurityUtils.RequiresFipsCompliance);
case SecurityAlgorithms.HmacSha256Signature:
if (!SecurityUtils.RequiresFipsCompliance)
return new HMACSHA256();
return null;
case SecurityAlgorithms.ExclusiveC14nWithComments:
return new XmlDsigExcC14NWithCommentsTransform();
case SecurityAlgorithms.Ripemd160Digest:
if (!SecurityUtils.RequiresFipsCompliance)
return new RIPEMD160Managed();
return null;
case SecurityAlgorithms.DesEncryption:
return new DESCryptoServiceProvider();
default:
return null;
}
}
internal static object GetAlgorithmFromConfig(string algorithm)
{
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("algorithm"));
}
object algorithmObject = null;
object defaultObject = null;
Func<object> delegateFunction = null;
if (!algorithmDelegateDictionary.TryGetValue(algorithm, out delegateFunction))
{
lock (AlgorithmDictionaryLock)
{
if (!algorithmDelegateDictionary.ContainsKey(algorithm))
{
try
{
algorithmObject = CryptoConfig.CreateFromName(algorithm);
}
catch (TargetInvocationException)
{
algorithmDelegateDictionary[algorithm] = null;
}
if (algorithmObject == null)
{
algorithmDelegateDictionary[algorithm] = null;
}
else
{
defaultObject = GetDefaultAlgorithm(algorithm);
if ((!SecurityUtils.RequiresFipsCompliance && algorithmObject is SHA1CryptoServiceProvider)
|| (defaultObject != null && defaultObject.GetType() == algorithmObject.GetType()))
{
algorithmDelegateDictionary[algorithm] = null;
}
else
{
// Create a factory delegate which returns new instances of the algorithm type for later calls.
Type algorithmType = algorithmObject.GetType();
System.Linq.Expressions.NewExpression algorithmCreationExpression = System.Linq.Expressions.Expression.New(algorithmType);
System.Linq.Expressions.LambdaExpression creationFunction = System.Linq.Expressions.Expression.Lambda<Func<object>>(algorithmCreationExpression);
delegateFunction = creationFunction.Compile() as Func<object>;
if (delegateFunction != null)
{
algorithmDelegateDictionary[algorithm] = delegateFunction;
}
return algorithmObject;
}
}
}
}
}
else
{
if (delegateFunction != null)
{
return delegateFunction.Invoke();
}
}
//
// This is a fallback in case CryptoConfig fails to return a valid
// algorithm object. CrytoConfig does not understand all the uri's and
// can return a null in that case, in which case it is our responsibility
// to fallback and create the right algorithm if it is a uri we understand
//
switch (algorithm)
{
case SHA256String:
case SecurityAlgorithms.Sha256Digest:
if (SecurityUtils.RequiresFipsCompliance)
{
return new SHA256CryptoServiceProvider();
}
else
{
return new SHA256Managed();
}
case SecurityAlgorithms.Sha1Digest:
if (SecurityUtils.RequiresFipsCompliance)
{
return new SHA1CryptoServiceProvider();
}
else
{
return new SHA1Managed();
}
case SecurityAlgorithms.HmacSha1Signature:
return new HMACSHA1(GenerateRandomBytes(64),
!SecurityUtils.RequiresFipsCompliance /* indicates the managed version of the algortithm */ );
default:
break;
}
return null;
}
public static void ResetAllCertificates(X509Certificate2Collection certificates)
{
if (certificates != null)
{
for (int i = 0; i < certificates.Count; ++i)
{
certificates[i].Reset();
}
}
}
}
}
| |
#region Using Directives
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.Text;
using Xunit;
#endregion
namespace System.CommandLine.Tests
{
/// <summary>
/// Represents a set of unit tests for the command line parser.
/// </summary>
public class ParserTests
{
#region Unit Tests
/// <summary>
/// Tests whether the command line parser correctly handles situations where multiple arguments are declared with the same name and/or alias.
/// </summary>
[Fact]
public void TestDuplicateArgumentReferences()
{
// Adding two arguments with the same name results in an exception
Parser parser = new Parser(new ParserOptions { IgnoreCase = true });
parser.AddFlagArgument<bool>("show-warnings");
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<bool>("show-warnings"));
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<bool>("Show-Warnings"));
// Adding two arguments with the same alias results in an exception
parser = new Parser(new ParserOptions { IgnoreCase = true });
parser.AddNamedArgument<string>("file-name", "f");
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<float>("factor", "f"));
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<StringBuilder>("filter", "F"));
// Adding two arguments with different names that both map to the same destination name results in an exception
parser = new Parser(new ParserOptions { IgnoreCase = true });
parser.AddPositionalArgument<string>("file-name");
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<StringBuilder>("fileName"));
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<StringBuilder>("FileName"));
// When unsetting the ignore case option, then two names that differ in casing should be accepted
parser = new Parser(new ParserOptions { IgnoreCase = false });
parser.AddFlagArgument<bool>("show-warnings");
parser.AddNamedArgument<bool>("Show-Warnings", null, "Warnings", null);
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<bool>("show-warnings"));
// When unsetting the ignore case option, then two aliases that differ in casing should be accepted
parser = new Parser(new ParserOptions { IgnoreCase = false });
parser.AddNamedArgument<string>("file-name", "f");
parser.AddNamedArgument<float>("factor", "F");
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<StringBuilder>("filter", "f"));
// When unsetting the ignore case option, then two destinations that differ in casing should be accepted
parser = new Parser(new ParserOptions { IgnoreCase = false });
parser.AddNamedArgument<bool>("show-warnings", null, "ShowWarnings", null);
parser.AddNamedArgument<bool>("Show-Warnings", null, "Showwarnings", null);
Assert.Throws<InvalidOperationException>(() => parser.AddNamedArgument<bool>("show-warnings"));
}
/// <summary>
/// Tests whether the command line parser correctly handles situations where multiple commands are declared with the same name.
/// </summary>
[Fact]
public void TestDuplicateCommandNames()
{
// Adding two commands with the same name results in an exception
Parser parser = new Parser(new ParserOptions { IgnoreCase = true });
parser.AddCommand("create");
Assert.Throws<InvalidOperationException>(() => parser.AddCommand("Create"));
Assert.Throws<InvalidOperationException>(() => parser.AddCommand("create"));
// Adding two commands with the same alias results in an exception
parser = new Parser(new ParserOptions { IgnoreCase = true });
parser.AddCommand("create", "c", "Creates a new entity.");
Assert.Throws<InvalidOperationException>(() => parser.AddCommand("combine", "c", "Combines two entities."));
Assert.Throws<InvalidOperationException>(() => parser.AddCommand("calibrate", "C", "Calibrates the entity."));
// When unsetting the ignore case option, then two names that differ in casing should be accepted
parser = new Parser(new ParserOptions { IgnoreCase = false });
parser.AddCommand("create");
parser.AddCommand("Create");
Assert.Throws<InvalidOperationException>(() => parser.AddCommand("create"));
// When unsetting the ignore case option, then two aliases that differ in casing should be accepted
parser = new Parser(new ParserOptions { IgnoreCase = false });
parser.AddCommand("create", "c", "Creates a new entity.");
parser.AddCommand("combine", "C", "Combines two entities.");
Assert.Throws<InvalidOperationException>(() => parser.AddCommand("calibrate", "C", "Calibrates the entity."));
}
/// <summary>
/// Tests whether the parser can handle one positional argument.
/// </summary>
[Fact]
public void TestOnePositionalArgument()
{
// Sets up the parser
Parser parser = new Parser();
parser.AddPositionalArgument<string>("file-name");
// Parses the command line arguments
ParsingResults parsingResults = parser.Parse(new string[] { "test.exe", @"C:\test" });
// Validates that the parsed values are correct
Assert.Equal(@"C:\test", parsingResults.GetParsedValue<string>("FileName"));
}
/// <summary>
/// Tests whether the parser can handle multiple positional arguments.
/// </summary>
[Fact]
public void TestMultiplePositionalArgument()
{
// Sets up the parser
Parser parser = new Parser();
parser
.AddPositionalArgument<string>("file-name")
.AddPositionalArgument<double>("factor")
.AddPositionalArgument<DayOfWeek>("day-of-week");
// Parses the command line arguments
ParsingResults parsingResults = parser.Parse(new string[] { "test.exe", @"C:\test", "8.45e9", "friday" });
// Validates that the parsed values are correct
Assert.Equal(@"C:\test", parsingResults.GetParsedValue<string>("FileName"));
Assert.Equal(8.45e9, parsingResults.GetParsedValue<double>("Factor"));
Assert.Equal(DayOfWeek.Friday, parsingResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
}
/// <summary>
/// Tests how the parser handles if a position argument is missing.
/// </summary>
[Fact]
public void TestMissingPositionalArguments()
{
// Sets up the parser
Parser parser = new Parser();
parser
.AddPositionalArgument<string>("file-name")
.AddPositionalArgument<double>("factor");
// Parses the command line arguments, since there are two positional arguments declared and only one value was supplied, an exception should be raised
Assert.Throws<InvalidOperationException>(() => parser.Parse(new string[] { "test.exe", @"C:\test" }));
}
/// <summary>
/// Tests whether the parser can handle one named argument.
/// </summary>
[Fact]
public void TestOneNamedArgument()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddNamedArgument<string>("file-name", "f");
// Parses the command line arguments
ParsingResults parsingResultsWithName = parser.Parse(new string[] { "test.exe", "--file-name", @"C:\test" });
ParsingResults parsingResultsWithAlias = parser.Parse(new string[] { "test.exe", "-f", @"C:\test" });
// Validates that the parsed values are correct
Assert.Equal(@"C:\test", parsingResultsWithName.GetParsedValue<string>("FileName"));
Assert.Equal(@"C:\test", parsingResultsWithAlias.GetParsedValue<string>("FileName"));
}
/// <summary>
/// Tests whether the parser can handle multiple named arguments.
/// </summary>
[Fact]
public void TestMultipleNamedArgument()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "/",
ArgumentAliasPrefix = "/"
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i")
.AddNamedArgument<DayOfWeek>("day-of-week", "d");
// Parses the command line arguments
ParsingResults parsingResultsWithName = parser.Parse(new string[] { "test.exe", "/feature", "false", "/number-of-iterations", "72", "/day-of-week", "wednesday" });
ParsingResults parsingResultsWithAlias = parser.Parse(new string[] { "test.exe", "/f", "off", "/i", "72", "/d", "wednesday" });
ParsingResults parsingResultsMixed = parser.Parse(new string[] { "test.exe", "/f", "no", "/number-of-iterations", "72", "/d", "wednesday" });
// Validates that the parsed values are correct
Assert.False(parsingResultsWithName.GetParsedValue<bool>("Feature"));
Assert.Equal(72, parsingResultsWithName.GetParsedValue<int>("NumberOfIterations"));
Assert.Equal(DayOfWeek.Wednesday, parsingResultsWithName.GetParsedValue<DayOfWeek>("DayOfWeek"));
Assert.False(parsingResultsWithAlias.GetParsedValue<bool>("Feature"));
Assert.Equal(72, parsingResultsWithAlias.GetParsedValue<int>("NumberOfIterations"));
Assert.Equal(DayOfWeek.Wednesday, parsingResultsWithAlias.GetParsedValue<DayOfWeek>("DayOfWeek"));
Assert.False(parsingResultsMixed.GetParsedValue<bool>("Feature"));
Assert.Equal(72, parsingResultsMixed.GetParsedValue<int>("NumberOfIterations"));
Assert.Equal(DayOfWeek.Wednesday, parsingResultsMixed.GetParsedValue<DayOfWeek>("DayOfWeek"));
}
/// <summary>
/// Tests whether the parser correctly handles default values.
/// </summary>
[Fact]
public void TestNamedArgumentDefaultValues()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser
.AddNamedArgument<bool>("feature", "f", "Feature", null, true)
.AddNamedArgument<int>("number-of-iterations", "i", "NumberOfIterations", null, 123)
.AddNamedArgument<DayOfWeek>("day-of-week", "d", "DayOfWeek");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "--number-of-iterations", "72" });
ParsingResults thirdParsingResults = parser.Parse(new string[] { "test.exe", "--feature", "false", "-i", "72", "-d", "wednesday" });
// Validates that the parsed values are correct
Assert.True(firstParsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(123, firstParsingResults.GetParsedValue<int>("NumberOfIterations"));
Assert.Equal(DayOfWeek.Sunday, firstParsingResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
Assert.True(secondParsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(72, secondParsingResults.GetParsedValue<int>("NumberOfIterations"));
Assert.Equal(DayOfWeek.Sunday, secondParsingResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
Assert.False(thirdParsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(72, thirdParsingResults.GetParsedValue<int>("NumberOfIterations"));
Assert.Equal(DayOfWeek.Wednesday, thirdParsingResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
}
/// <summary>
/// Tests whether the parser can handle one flag argument.
/// </summary>
[Fact]
public void TestOneFlagArgument()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddFlagArgument<int>("number", "n");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "--number" });
ParsingResults thirdParsingResults = parser.Parse(new string[] { "test.exe", "--number", "--number" });
ParsingResults fourthParsingResults = parser.Parse(new string[] { "test.exe", "-n", "-n", "-n" });
// Validates that the parsed values are correct
Assert.Equal(0, firstParsingResults.GetParsedValue<int>("Number"));
Assert.Equal(1, secondParsingResults.GetParsedValue<int>("Number"));
Assert.Equal(2, thirdParsingResults.GetParsedValue<int>("Number"));
Assert.Equal(3, fourthParsingResults.GetParsedValue<int>("Number"));
}
/// <summary>
/// Tests whether the parser can handle multiple flag arguments.
/// </summary>
[Fact]
public void TestMultipleFlagArgument()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddFlagArgument<DayOfWeek>("day", "d");
parser.AddFlagArgument<bool>("verbose", "v");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "--verbose", "--day" });
ParsingResults thirdParsingResults = parser.Parse(new string[] { "test.exe", "--day", "--day" });
ParsingResults fourthParsingResults = parser.Parse(new string[] { "test.exe", "-d", "-v", "-d", "-v", "-d" });
// Validates that the parsed values are correct
Assert.Equal(DayOfWeek.Sunday, firstParsingResults.GetParsedValue<DayOfWeek>("Day"));
Assert.False(firstParsingResults.GetParsedValue<bool>("Verbose"));
Assert.Equal(DayOfWeek.Monday, secondParsingResults.GetParsedValue<DayOfWeek>("Day"));
Assert.True(secondParsingResults.GetParsedValue<bool>("Verbose"));
Assert.Equal(DayOfWeek.Tuesday, thirdParsingResults.GetParsedValue<DayOfWeek>("Day"));
Assert.False(thirdParsingResults.GetParsedValue<bool>("Verbose"));
Assert.Equal(DayOfWeek.Wednesday, fourthParsingResults.GetParsedValue<DayOfWeek>("Day"));
Assert.True(fourthParsingResults.GetParsedValue<bool>("Verbose"));
}
/// <summary>
/// Represents an enumeration used for testing the multi-character flags.
/// </summary>
private enum VerbosityLevel { Quiet, Minimal, Normal, Detailed, Diagnostic }
/// <summary>
/// Tests how the parser handles multi-character flags.
/// </summary>
[Fact]
public void TestMultiCharacterFlagArguments()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddFlagArgument<VerbosityLevel>("verbosity", "v");
parser.AddFlagArgument<int>("count", "c");
parser.AddFlagArgument<bool>("activate", "a");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "-vca" });
ParsingResults thirdParsingResults = parser.Parse(new string[] { "test.exe", "-vvv", "-ccc", "-aaa" });
ParsingResults fourthParsingResults = parser.Parse(new string[] { "test.exe", "-vvvcccaaa" });
// Validates that the parsed values are correct
Assert.Equal(VerbosityLevel.Quiet, firstParsingResults.GetParsedValue<VerbosityLevel>("Verbosity"));
Assert.Equal(0, firstParsingResults.GetParsedValue<int>("Count"));
Assert.False(firstParsingResults.GetParsedValue<bool>("Activate"));
Assert.Equal(VerbosityLevel.Minimal, secondParsingResults.GetParsedValue<VerbosityLevel>("Verbosity"));
Assert.Equal(1, secondParsingResults.GetParsedValue<int>("Count"));
Assert.True(secondParsingResults.GetParsedValue<bool>("Activate"));
Assert.Equal(VerbosityLevel.Detailed, thirdParsingResults.GetParsedValue<VerbosityLevel>("Verbosity"));
Assert.Equal(3, thirdParsingResults.GetParsedValue<int>("Count"));
Assert.True(thirdParsingResults.GetParsedValue<bool>("Activate"));
Assert.Equal(VerbosityLevel.Detailed, fourthParsingResults.GetParsedValue<VerbosityLevel>("Verbosity"));
Assert.Equal(3, fourthParsingResults.GetParsedValue<int>("Count"));
Assert.True(fourthParsingResults.GetParsedValue<bool>("Activate"));
}
/// <summary>
/// Tests how the parser handles a situation where it parses a named argument that was not declared.
/// </summary>
[Fact]
public void TestUnknownNamedArgument()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
// Parses the command line arguments, since there is are only two named arguments declared but three are supplied, an exception should be raised
Assert.Throws<InvalidOperationException>(() => parser.Parse(new string[] { "test.exe", "--feature", "on", "--number-of-iterations", "72", "--day-of-week", "wednesday" }));
}
/// <summary>
/// Tests how the parser handles a situation where it parses a named argument and its value is missing.
/// </summary>
[Fact]
public void TestMissingNamedArgumentValue()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "/",
ArgumentAliasPrefix = "/"
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i")
.AddNamedArgument<DayOfWeek>("day-of-week", "d");
// Parses the command line arguments, there are three declared arguments and only two are supplied, but since named arguments are optional, nothing should happen
ParsingResults parsingResults = parser.Parse(new string[] { "test.exe", "/feature", "yes", "/number-of-iterations", "72" });
// Validates that the parsed values are correct
Assert.True(parsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(72, parsingResults.GetParsedValue<int>("NumberOfIterations"));
}
/// <summary>
/// Tests whether the parser can handle multiple positional arguments and named arguments.
/// </summary>
[Fact]
public void TestPositionalAndNamedArguments()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser
.AddPositionalArgument<string>("file-name")
.AddPositionalArgument<float>("factor")
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i")
.AddNamedArgument<DayOfWeek>("day-of-week", "d");
// Parses the command line arguments
ParsingResults parsingResults = parser.Parse(new string[] { "test.exe", "/home/test.txt", "123.5", "-f", "true", "--number-of-iterations", "123", "-d", "Sunday" });
// Validates that the parsed values are correct
Assert.Equal("/home/test.txt", parsingResults.GetParsedValue<string>("FileName"));
Assert.Equal(123.5, parsingResults.GetParsedValue<float>("Factor"));
Assert.True(parsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(123, parsingResults.GetParsedValue<int>("NumberOfIterations"));
Assert.Equal(DayOfWeek.Sunday, parsingResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
}
/// <summary>
/// Tests how the parser handles different prefix styles (e.g. the UNIX "--" style and the Windows "/" style).
/// </summary>
[Fact]
public void TestArgumentPrefixStyles()
{
// Sets up the parser with the usual UNIX style argument prefixes
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
// Parses the command line arguments with the UNIX style argument prefixes
ParsingResults parsingResults = parser.Parse(new string[] { "test.exe", "--feature", "off", "-i", "987" });
// Validates that the parsed values with the UNIX style argument prefixes are correct
Assert.False(parsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(987, parsingResults.GetParsedValue<int>("NumberOfIterations"));
// Sets up the parser with the usual Windows style argument prefixes
parser = new Parser(new ParserOptions
{
ArgumentPrefix = "/",
ArgumentAliasPrefix = "/"
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
// Parses the command line arguments with the Windows style argument prefixes
parsingResults = parser.Parse(new string[] { "test.exe", "/feature", "off", "/i", "987" });
// Validates that the parsed values with the Windows style argument prefixes are correct
Assert.False(parsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(987, parsingResults.GetParsedValue<int>("NumberOfIterations"));
// Sets up the parser with some non-standard argument prefixes, with different prefixes for arguments and their aliases
parser = new Parser(new ParserOptions
{
ArgumentPrefix = "@",
ArgumentAliasPrefix = "&"
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
// Parses the command line arguments with non-standard argument prefixes
parsingResults = parser.Parse(new string[] { "test.exe", "@feature", "off", "&i", "987" });
// Validates that the parsed values with non-standard argument prefixes are correct
Assert.False(parsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(987, parsingResults.GetParsedValue<int>("NumberOfIterations"));
// Sets up the parser with some non-standard argument prefixes, with the same prefixes for arguments and their aliases
parser = new Parser(new ParserOptions
{
ArgumentPrefix = "=",
ArgumentAliasPrefix = "="
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
// Parses the command line arguments with non-standard argument prefixes
parsingResults = parser.Parse(new string[] { "test.exe", "=feature", "off", "=i", "987" });
// Validates that the parsed values with non-standard argument prefixes are correct
Assert.False(parsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(987, parsingResults.GetParsedValue<int>("NumberOfIterations"));
// Sets up the parser with switched UNIX style argument prefixes
parser = new Parser(new ParserOptions
{
ArgumentPrefix = "-",
ArgumentAliasPrefix = "--"
});
parser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
// Parses the command line arguments with the switched UNIX style argument prefixes
parsingResults = parser.Parse(new string[] { "test.exe", "-feature", "off", "--i", "987" });
// Validates that the parsed values with the switched UNIX style argument prefixes are correct
Assert.False(parsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(987, parsingResults.GetParsedValue<int>("NumberOfIterations"));
}
/// <summary>
/// Tests how the parser handles named arguments that are using the key value separator syntax (e.g. "--age=18" instead of "--age 18").
/// </summary>
[Fact]
public void TestKeyValueSeparator()
{
// Sets up the parser
Parser unixStyleParser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-",
KeyValueSeparator = "="
});
unixStyleParser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
Parser windowsStyleParser = new Parser(new ParserOptions
{
ArgumentPrefix = "/",
ArgumentAliasPrefix = "/",
KeyValueSeparator = ":"
});
windowsStyleParser
.AddNamedArgument<bool>("feature", "f")
.AddNamedArgument<int>("number-of-iterations", "i");
// Parses the command line arguments
ParsingResults firstUnixStyleParsingResults = unixStyleParser.Parse(new string[] { "test.exe", "--feature=true", "-i=34" });
ParsingResults secondUnixStyleParsingResults = unixStyleParser.Parse(new string[] { "test.exe", "-f", "off", "--number-of-iterations", "78" });
ParsingResults firstWindowStyleParsingResults = windowsStyleParser.Parse(new string[] { "test.exe", "/feature:no", "/i:49" });
ParsingResults secondWindowsStyleParsingResults = windowsStyleParser.Parse(new string[] { "test.exe", "/f", "yes", "/number-of-iterations", "20" });
// Validates that the parsed values are correct
Assert.True(firstUnixStyleParsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(34, firstUnixStyleParsingResults.GetParsedValue<int>("NumberOfIterations"));
Assert.False(secondUnixStyleParsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(78, secondUnixStyleParsingResults.GetParsedValue<int>("NumberOfIterations"));
Assert.False(firstWindowStyleParsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(49, firstWindowStyleParsingResults.GetParsedValue<int>("NumberOfIterations"));
Assert.True(secondWindowsStyleParsingResults.GetParsedValue<bool>("Feature"));
Assert.Equal(20, secondWindowsStyleParsingResults.GetParsedValue<int>("NumberOfIterations"));
}
/// <summary>
/// Tests how the parser handles the parsing of arguments of a collection type and especially how it handles a situation where a single named argument is provided multiple times.
/// </summary>
[Fact]
public void TestCollectionArguments()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddNamedArgument<List<string>>("names", "n");
parser.AddNamedArgument<string>("car", "c");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe", "--names", "Alice", "-n", "Bob", "--car", "blue car", "--names", "Eve" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "-n", "Alice", "Bob", "Eve", "-c", "red car" });
// Validates that the parsed values are correct
Assert.Equal(new List<string> { "Alice", "Bob", "Eve" }, firstParsingResults.GetParsedValue<List<string>>("Names"));
Assert.Equal("blue car", firstParsingResults.GetParsedValue<string>("Car"));
Assert.Equal(new List<string> { "Alice", "Bob", "Eve" }, secondParsingResults.GetParsedValue<List<string>>("Names"));
Assert.Equal("red car", secondParsingResults.GetParsedValue<string>("Car"));
}
/// <summary>
/// Tests whether the default duplicate resolution policy works, which is used if a single named argument is provided more than once.
/// </summary>
[Fact]
public void TestDuplicateResolutionPolicy()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddNamedArgument<int>("age", "a");
// Parses the command line arguments
ParsingResults parsingResults = parser.Parse(new string[] { "test.exe", "--age", "18", "-a", "17", "--age", "16" });
// Validates that the parsed values are correct
Assert.Equal(16, parsingResults.GetParsedValue<int>("Age"));
}
/// <summary>
/// Tests whether a custom duplicate resolution policy works, which is used if a single named argument is provided more than once.
/// </summary>
[Fact]
public void TestCustomDuplicateResolutionPolicy()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddNamedArgument<int>("add", "a", "Add", "Adds numbers together", 0, (a, b) => a + b);
parser.AddNamedArgument<int>("multiply", "m", "Multiply", "Multiplies numbers together", 0, (a, b) => a * b);
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe", "--add", "1", "-a", "2", "--add", "3" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "--multiply", "4", "5", "-m", "6" });
// Validates that the parsed values are correct
Assert.Equal(6, firstParsingResults.GetParsedValue<int>("Add"));
Assert.Equal(120, secondParsingResults.GetParsedValue<int>("Multiply"));
}
/// <summary>
/// Tests how the parser handles the parsing of a single commands.
/// </summary>
[Fact]
public void TestSingleCommand()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
parser.AddNamedArgument<bool>("verbose", "v");
Parser commandParser = parser.AddCommand("restart", "r", string.Empty);
commandParser.AddPositionalArgument<string>("time");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe", "-v", "no" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "restart", "now" });
ParsingResults thirdParsingResults = parser.Parse(new string[] { "test.exe", "--verbose", "yes", "r", "later" });
// Validates that the parsed values are correct
Assert.False(firstParsingResults.GetParsedValue<bool>("Verbose"));
Assert.True(secondParsingResults.HasSubResults);
Assert.NotNull(secondParsingResults.SubResults);
Assert.Equal("restart", secondParsingResults.SubResults.Command);
Assert.Equal("now", secondParsingResults.SubResults.GetParsedValue<string>("Time"));
Assert.True(thirdParsingResults.GetParsedValue<bool>("Verbose"));
Assert.True(thirdParsingResults.HasSubResults);
Assert.NotNull(thirdParsingResults.SubResults);
Assert.Equal("restart", thirdParsingResults.SubResults.Command);
Assert.Equal("later", thirdParsingResults.SubResults.GetParsedValue<string>("Time"));
}
/// <summary>
/// Tests how the parser handles the parsing of a command when having the a choice between multiple commands.
/// </summary>
[Fact]
public void TestMultipleCommands()
{
// Sets up the parser
Parser parser = new Parser();
parser.AddCommand("test", "t", string.Empty);
parser.AddCommand("run", "r", string.Empty);
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe", "test" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "t" });
ParsingResults thirdParsingResults = parser.Parse(new string[] { "test.exe", "run" });
ParsingResults fourthParsingResults = parser.Parse(new string[] { "test.exe", "r" });
// Validates that the parsed values are correct
Assert.Equal("test", firstParsingResults.SubResults.Command);
Assert.Equal("test", secondParsingResults.SubResults.Command);
Assert.Equal("run", thirdParsingResults.SubResults.Command);
Assert.Equal("run", fourthParsingResults.SubResults.Command);
}
/// <summary>
/// Tests how the parser handles the parsing of multiple nested commands.
/// </summary>
[Fact]
public void TestNestedCommands()
{
// Sets up the parser
Parser parser = new Parser(new ParserOptions
{
ArgumentPrefix = "--",
ArgumentAliasPrefix = "-"
});
Parser subParser = parser.AddCommand("add");
Parser subSubParser = subParser.AddCommand("package");
subSubParser.AddCommand("to-project");
subSubParser.AddCommand("to-solution");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "add" });
ParsingResults thirdParsingResults = parser.Parse(new string[] { "test.exe", "add", "package" });
ParsingResults fourthParsingResults = parser.Parse(new string[] { "test.exe", "add", "package", "to-project" });
ParsingResults fifthParsingResults = parser.Parse(new string[] { "test.exe", "add", "package", "to-solution" });
// Validates that the parsed values are correct
Assert.False(firstParsingResults.HasSubResults);
Assert.Equal("add", secondParsingResults.SubResults.Command);
Assert.False(secondParsingResults.SubResults.HasSubResults);
Assert.Equal("add", thirdParsingResults.SubResults.Command);
Assert.Equal("package", thirdParsingResults.SubResults.SubResults.Command);
Assert.False(thirdParsingResults.SubResults.SubResults.HasSubResults);
Assert.Equal("add", fourthParsingResults.SubResults.Command);
Assert.Equal("package", fourthParsingResults.SubResults.SubResults.Command);
Assert.Equal("to-project", fourthParsingResults.SubResults.SubResults.SubResults.Command);
Assert.False(fourthParsingResults.SubResults.SubResults.SubResults.HasSubResults);
Assert.Equal("add", fifthParsingResults.SubResults.Command);
Assert.Equal("package", fifthParsingResults.SubResults.SubResults.Command);
Assert.Equal("to-solution", fifthParsingResults.SubResults.SubResults.SubResults.Command);
Assert.False(fifthParsingResults.SubResults.SubResults.SubResults.HasSubResults);
}
/// <summary>
/// Tests how the parser handles situations where arguments have the same names or aliases as commands.
/// </summary>
[Fact]
public void TestArgumentCommandNameCollision()
{
// Sets up the parser
Parser parser = new Parser();
parser.AddNamedArgument<string>("test", "t");
parser.AddCommand("test", "t", string.Empty);
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe", "--test", "test", "test" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "-t", "t", "t" });
// Validates that the parsed values are correct
Assert.Equal("test", firstParsingResults.GetParsedValue<string>("Test"));
Assert.True(firstParsingResults.HasSubResults);
Assert.Equal("test", firstParsingResults.SubResults.Command);
Assert.Equal("t", secondParsingResults.GetParsedValue<string>("Test"));
Assert.True(secondParsingResults.HasSubResults);
Assert.Equal("test", secondParsingResults.SubResults.Command);
}
/// <summary>
/// Tests how the parser handles name collisions in a parser and a sub parser.
/// </summary>
[Fact]
public void TestArgumentNameCollisionInCommands()
{
// Sets up the parser
Parser parser = new Parser();
parser.AddNamedArgument<DayOfWeek>("day-of-week", "d");
Parser subParser = parser.AddCommand("test", "t", string.Empty);
subParser.AddNamedArgument<DayOfWeek>("day-of-week", "d");
// Parses the command line arguments
ParsingResults firstParsingResults = parser.Parse(new string[] { "test.exe", "--day-of-week", "thursday", "test", "--day-of-week", "wednesday" });
ParsingResults secondParsingResults = parser.Parse(new string[] { "test.exe", "-d", "Tuesday", "t", "-d", "Saturday" });
// Validates that the parsed values are correct
Assert.Equal(DayOfWeek.Thursday, firstParsingResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
Assert.True(firstParsingResults.HasSubResults);
Assert.Equal("test", firstParsingResults.SubResults.Command);
Assert.Equal(DayOfWeek.Wednesday, firstParsingResults.SubResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
Assert.Equal(DayOfWeek.Tuesday, secondParsingResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
Assert.True(secondParsingResults.HasSubResults);
Assert.Equal("test", secondParsingResults.SubResults.Command);
Assert.Equal(DayOfWeek.Saturday, secondParsingResults.SubResults.GetParsedValue<DayOfWeek>("DayOfWeek"));
}
/// <summary>
/// Tests how the parser handles a very complex scenario with many different kinds of parameters and multiple commands.
/// </summary>
[Fact]
public void TestComplexScenario()
{
// Creates the main parser and adds all the necessary arguments
Parser parser = new Parser("A simple version of the .NET CLI.", new ParserOptions(false, "--", "-", "=", true));
parser.AddFlagArgument<bool>("help", "h", "Show command line help.");
// Creates the parser for the add command
Parser addCommandParser = parser.AddCommand("add", "Add a new package or reference to a .NET project.");
addCommandParser.AddPositionalArgument<string>("project", "The project file to operate on.");
addCommandParser.AddFlagArgument<bool>("help", "h", "Show command line help.");
// Creates the parser for the add package command
Parser addPackageCommandParser = addCommandParser.AddCommand("package", "Add a NuGet package reference to the project.");
addPackageCommandParser.AddPositionalArgument<string>("package-name", "The package reference to add.");
addPackageCommandParser.AddFlagArgument<bool>("help", "h", "Show command line help.");
addPackageCommandParser.AddNamedArgument<string>("version", "v", "The version of the package to add.");
addPackageCommandParser.AddFlagArgument<bool>("interactive", null, "Show command line help.");
// Creates the parser for the add reference command
Parser addReferenceCommandParser = addCommandParser.AddCommand("reference", "Add a project-to-project reference to the project.");
addReferenceCommandParser.AddPositionalArgument<string>("project-path", "The paths to the projects to add as references.");
addReferenceCommandParser.AddFlagArgument<bool>("help", "h", "Show command line help.");
addReferenceCommandParser.AddNamedArgument<string>("framework", "f", "Add the reference only when targeting a specific framework.");
// Creates the parser for the build command
Parser buildCommandParser = parser.AddCommand("build", "Add a new package or reference to a .NET project.");
buildCommandParser.AddPositionalArgument<string>("project", "The project file to operate on.");
buildCommandParser.AddFlagArgument<bool>("help", "h", "Show command line help.");
buildCommandParser.AddNamedArgument<VerbosityLevel>("verbosity", "v", "Set the MSBuild verbosity level. Allowed values are quiet, minimal, normal, detailed, and diagnostic.");
buildCommandParser.AddNamedArgument<string>("framework", "f", "The target framework to build for. The target framework must also be specified in the project file.");
// Creates the parser for the new command
Parser newCommandParser = parser.AddCommand("new", "Create a new .NET project or file.");
newCommandParser.AddPositionalArgument<string>("template", "The project template to use.");
newCommandParser.AddFlagArgument<bool>("help", "h", "Show command line help.");
newCommandParser.AddNamedArgument<string>("name", "n", "The name for the output being created. If no name is specified, the name of the current directory is used.");
newCommandParser.AddNamedArgument<string>("output", "o", "Location to place the generated output.");
// Creates the parser for the run command
Parser runCommandParser = parser.AddCommand("run", "Build and run a .NET project output.");
runCommandParser.AddFlagArgument<bool>("help", "h", "Show command line help.");
runCommandParser.AddNamedArgument<string>("project", "p", "Project", "The path to the project file to run (defaults to the current directory if there is only one project).", "./");
runCommandParser.AddNamedArgument<string>("framework", "f", "The target framework to run for. The target framework must also be specified in the project file.");
// Tests how the parser handles no command line arguments at all
ParsingResults parsingResults = parser.Parse(new string[] { "dotnet" });
Assert.False(parsingResults.GetParsedValue<bool>("Help"));
Assert.False(parsingResults.HasSubResults);
Assert.Null(parsingResults.SubResults);
// Tests how the parser handles the add command
parsingResults = parser.Parse(new string[] { "dotnet", "add", "./test.csproj", "--help" });
Assert.False(parsingResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.HasSubResults);
Assert.Equal("add", parsingResults.SubResults.Command);
Assert.Equal("./test.csproj", parsingResults.SubResults.GetParsedValue<string>("Project"));
Assert.True(parsingResults.SubResults.GetParsedValue<bool>("Help"));
Assert.False(parsingResults.SubResults.HasSubResults);
// Tests how the parser handles the add package command
parsingResults = parser.Parse(new string[] { "dotnet", "add", "./test.csproj", "package", "Newtonsoft.Json", "--version", "11.0.2" });
Assert.False(parsingResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.HasSubResults);
Assert.Equal("add", parsingResults.SubResults.Command);
Assert.Equal("./test.csproj", parsingResults.SubResults.GetParsedValue<string>("Project"));
Assert.False(parsingResults.SubResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.SubResults.HasSubResults);
Assert.Equal("package", parsingResults.SubResults.SubResults.Command);
Assert.Equal("Newtonsoft.Json", parsingResults.SubResults.SubResults.GetParsedValue<string>("PackageName"));
Assert.Equal("11.0.2", parsingResults.SubResults.SubResults.GetParsedValue<string>("Version"));
Assert.False(parsingResults.SubResults.SubResults.GetParsedValue<bool>("Help"));
Assert.False(parsingResults.SubResults.SubResults.GetParsedValue<bool>("Interactive"));
Assert.False(parsingResults.SubResults.SubResults.HasSubResults);
// Tests how the parser handles the missing package name in the add package command
Assert.Throws<InvalidOperationException>(() => parser.Parse(new string[] { "dotnet", "add", "./test.csproj", "package" }));
// Tests how the parser handles the add reference command
parsingResults = parser.Parse(new string[] { "dotnet", "add", "./test.csproj", "reference", "../foo/bar.csproj", "--framework", "netcoreapp2.1", "-h" });
Assert.False(parsingResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.HasSubResults);
Assert.Equal("add", parsingResults.SubResults.Command);
Assert.Equal("./test.csproj", parsingResults.SubResults.GetParsedValue<string>("Project"));
Assert.False(parsingResults.SubResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.SubResults.HasSubResults);
Assert.Equal("reference", parsingResults.SubResults.SubResults.Command);
Assert.Equal("../foo/bar.csproj", parsingResults.SubResults.SubResults.GetParsedValue<string>("ProjectPath"));
Assert.Equal("netcoreapp2.1", parsingResults.SubResults.SubResults.GetParsedValue<string>("Framework"));
Assert.True(parsingResults.SubResults.SubResults.GetParsedValue<bool>("Help"));
Assert.False(parsingResults.SubResults.SubResults.HasSubResults);
// Tests how the parser handles the missing project path in the add reference command
Assert.Throws<InvalidOperationException>(() => parser.Parse(new string[] { "dotnet", "add", "./test.csproj", "reference" }));
// Tests how the parser handles the build command
parsingResults = parser.Parse(new string[] { "dotnet", "build", "./test.csproj", "--verbosity", "detailed" });
Assert.False(parsingResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.HasSubResults);
Assert.Equal("build", parsingResults.SubResults.Command);
Assert.Equal("./test.csproj", parsingResults.SubResults.GetParsedValue<string>("Project"));
Assert.Equal(VerbosityLevel.Detailed, parsingResults.SubResults.GetParsedValue<VerbosityLevel>("Verbosity"));
Assert.False(parsingResults.SubResults.GetParsedValue<bool>("Help"));
Assert.False(parsingResults.SubResults.HasSubResults);
// Tests how the parser handles the new command
parsingResults = parser.Parse(new string[] { "dotnet", "new", "console", "-n", "test", "--output", "./test" });
Assert.False(parsingResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.HasSubResults);
Assert.Equal("new", parsingResults.SubResults.Command);
Assert.Equal("console", parsingResults.SubResults.GetParsedValue<string>("Template"));
Assert.Equal("test", parsingResults.SubResults.GetParsedValue<string>("Name"));
Assert.Equal("./test", parsingResults.SubResults.GetParsedValue<string>("Output"));
Assert.False(parsingResults.SubResults.GetParsedValue<bool>("Help"));
Assert.False(parsingResults.SubResults.HasSubResults);
// Tests how the parser handles the run command
parsingResults = parser.Parse(new string[] { "dotnet", "run", "--project", "./test.csproj", "-f", "netcoreapp2.0", "-h" });
Assert.False(parsingResults.GetParsedValue<bool>("Help"));
Assert.True(parsingResults.HasSubResults);
Assert.Equal("run", parsingResults.SubResults.Command);
Assert.Equal("./test.csproj", parsingResults.SubResults.GetParsedValue<string>("Project"));
Assert.Equal("netcoreapp2.0", parsingResults.SubResults.GetParsedValue<string>("Framework"));
Assert.True(parsingResults.SubResults.GetParsedValue<bool>("Help"));
Assert.False(parsingResults.SubResults.HasSubResults);
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>KeywordPlanCampaign</c> resource.</summary>
public sealed partial class KeywordPlanCampaignName : gax::IResourceName, sys::IEquatable<KeywordPlanCampaignName>
{
/// <summary>The possible contents of <see cref="KeywordPlanCampaignName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c>
/// .
/// </summary>
CustomerKeywordPlanCampaign = 1,
}
private static gax::PathTemplate s_customerKeywordPlanCampaign = new gax::PathTemplate("customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}");
/// <summary>Creates a <see cref="KeywordPlanCampaignName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="KeywordPlanCampaignName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static KeywordPlanCampaignName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new KeywordPlanCampaignName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignName"/> with the pattern
/// <c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignId">
/// The <c>KeywordPlanCampaign</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="KeywordPlanCampaignName"/> constructed from the provided ids.
/// </returns>
public static KeywordPlanCampaignName FromCustomerKeywordPlanCampaign(string customerId, string keywordPlanCampaignId) =>
new KeywordPlanCampaignName(ResourceNameType.CustomerKeywordPlanCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanCampaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignId, nameof(keywordPlanCampaignId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanCampaignName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignId">
/// The <c>KeywordPlanCampaign</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanCampaignName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c>.
/// </returns>
public static string Format(string customerId, string keywordPlanCampaignId) =>
FormatCustomerKeywordPlanCampaign(customerId, keywordPlanCampaignId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordPlanCampaignName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignId">
/// The <c>KeywordPlanCampaign</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="KeywordPlanCampaignName"/> with pattern
/// <c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c>.
/// </returns>
public static string FormatCustomerKeywordPlanCampaign(string customerId, string keywordPlanCampaignId) =>
s_customerKeywordPlanCampaign.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignId, nameof(keywordPlanCampaignId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanCampaignName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordPlanCampaignName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="KeywordPlanCampaignName"/> if successful.</returns>
public static KeywordPlanCampaignName Parse(string keywordPlanCampaignName) => Parse(keywordPlanCampaignName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordPlanCampaignName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanCampaignName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="KeywordPlanCampaignName"/> if successful.</returns>
public static KeywordPlanCampaignName Parse(string keywordPlanCampaignName, bool allowUnparsed) =>
TryParse(keywordPlanCampaignName, allowUnparsed, out KeywordPlanCampaignName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanCampaignName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordPlanCampaignName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanCampaignName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanCampaignName, out KeywordPlanCampaignName result) =>
TryParse(keywordPlanCampaignName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordPlanCampaignName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordPlanCampaignName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordPlanCampaignName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordPlanCampaignName, bool allowUnparsed, out KeywordPlanCampaignName result)
{
gax::GaxPreconditions.CheckNotNull(keywordPlanCampaignName, nameof(keywordPlanCampaignName));
gax::TemplatedResourceName resourceName;
if (s_customerKeywordPlanCampaign.TryParseName(keywordPlanCampaignName, out resourceName))
{
result = FromCustomerKeywordPlanCampaign(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(keywordPlanCampaignName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private KeywordPlanCampaignName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string keywordPlanCampaignId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
KeywordPlanCampaignId = keywordPlanCampaignId;
}
/// <summary>
/// Constructs a new instance of a <see cref="KeywordPlanCampaignName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/keywordPlanCampaigns/{keyword_plan_campaign_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keywordPlanCampaignId">
/// The <c>KeywordPlanCampaign</c> ID. Must not be <c>null</c> or empty.
/// </param>
public KeywordPlanCampaignName(string customerId, string keywordPlanCampaignId) : this(ResourceNameType.CustomerKeywordPlanCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), keywordPlanCampaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(keywordPlanCampaignId, nameof(keywordPlanCampaignId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>KeywordPlanCampaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string KeywordPlanCampaignId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerKeywordPlanCampaign: return s_customerKeywordPlanCampaign.Expand(CustomerId, KeywordPlanCampaignId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as KeywordPlanCampaignName);
/// <inheritdoc/>
public bool Equals(KeywordPlanCampaignName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(KeywordPlanCampaignName a, KeywordPlanCampaignName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(KeywordPlanCampaignName a, KeywordPlanCampaignName b) => !(a == b);
}
public partial class KeywordPlanCampaign
{
/// <summary>
/// <see cref="gagvr::KeywordPlanCampaignName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal KeywordPlanCampaignName ResourceNameAsKeywordPlanCampaignName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::KeywordPlanCampaignName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="KeywordPlanName"/>-typed view over the <see cref="KeywordPlan"/> resource name property.
/// </summary>
internal KeywordPlanName KeywordPlanAsKeywordPlanName
{
get => string.IsNullOrEmpty(KeywordPlan) ? null : KeywordPlanName.Parse(KeywordPlan, allowUnparsed: true);
set => KeywordPlan = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::KeywordPlanCampaignName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal KeywordPlanCampaignName KeywordPlanCampaignName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::KeywordPlanCampaignName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="LanguageConstantName"/>-typed view over the <see cref="LanguageConstants"/> resource name
/// property.
/// </summary>
internal gax::ResourceNameList<LanguageConstantName> LanguageConstantsAsLanguageConstantNames
{
get => new gax::ResourceNameList<LanguageConstantName>(LanguageConstants, s => string.IsNullOrEmpty(s) ? null : LanguageConstantName.Parse(s, allowUnparsed: true));
}
}
public partial class KeywordPlanGeoTarget
{
/// <summary>
/// <see cref="GeoTargetConstantName"/>-typed view over the <see cref="GeoTargetConstant"/> resource name
/// property.
/// </summary>
internal GeoTargetConstantName GeoTargetConstantAsGeoTargetConstantName
{
get => string.IsNullOrEmpty(GeoTargetConstant) ? null : GeoTargetConstantName.Parse(GeoTargetConstant, allowUnparsed: true);
set => GeoTargetConstant = value?.ToString() ?? "";
}
}
}
| |
// 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.
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
public sealed class DataContractSerializer : XmlObjectSerializer
{
private Type _rootType;
private DataContract _rootContract; // post-surrogate
private bool _needsContractNsAtRoot;
private XmlDictionaryString _rootName;
private XmlDictionaryString _rootNamespace;
private int _maxItemsInObjectGraph;
private bool _ignoreExtensionDataObject;
private bool _preserveObjectReferences;
private ReadOnlyCollection<Type> _knownTypeCollection;
internal IList<Type> knownTypeList;
internal DataContractDictionary knownDataContracts;
private DataContractResolver _dataContractResolver;
private ISerializationSurrogateProvider _serializationSurrogateProvider;
private bool _serializeReadOnlyTypes;
private static SerializationOption _option = IsReflectionBackupAllowed() ? SerializationOption.ReflectionAsBackup : SerializationOption.CodeGenOnly;
private static bool _optionAlreadySet;
internal static SerializationOption Option
{
get { return _option; }
set
{
if (_optionAlreadySet)
{
throw new InvalidOperationException("Can only set once");
}
_optionAlreadySet = true;
_option = value;
}
}
private static bool IsReflectionBackupAllowed()
{
return true;
}
public DataContractSerializer(Type type)
: this(type, (IEnumerable<Type>)null)
{
}
public DataContractSerializer(Type type, IEnumerable<Type> knownTypes)
{
Initialize(type, knownTypes, int.MaxValue, false, false, null, false);
}
public DataContractSerializer(Type type, string rootName, string rootNamespace)
: this(type, rootName, rootNamespace, null)
{
}
public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type> knownTypes)
{
XmlDictionary dictionary = new XmlDictionary(2);
Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false);
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace)
: this(type, rootName, rootNamespace, null)
{
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes)
{
Initialize(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, false);
}
internal DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences)
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, null, false);
}
public DataContractSerializer(Type type, DataContractSerializerSettings settings)
{
if (settings == null)
{
settings = new DataContractSerializerSettings();
}
Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, false,
settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes);
}
private void Initialize(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
DataContractResolver dataContractResolver,
bool serializeReadOnlyTypes)
{
CheckNull(type, nameof(type));
_rootType = type;
if (knownTypes != null)
{
this.knownTypeList = new List<Type>();
foreach (Type knownType in knownTypes)
{
this.knownTypeList.Add(knownType);
}
}
if (maxItemsInObjectGraph < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxItemsInObjectGraph), SR.ValueMustBeNonNegative));
_maxItemsInObjectGraph = maxItemsInObjectGraph;
_ignoreExtensionDataObject = ignoreExtensionDataObject;
_preserveObjectReferences = preserveObjectReferences;
_dataContractResolver = dataContractResolver;
_serializeReadOnlyTypes = serializeReadOnlyTypes;
}
private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
DataContractResolver dataContractResolver,
bool serializeReadOnlyTypes)
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractResolver, serializeReadOnlyTypes);
// validate root name and namespace are both non-null
_rootName = rootName;
_rootNamespace = rootNamespace;
}
public ReadOnlyCollection<Type> KnownTypes
{
get
{
if (_knownTypeCollection == null)
{
if (knownTypeList != null)
{
_knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList);
}
else
{
_knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>());
}
}
return _knownTypeCollection;
}
}
internal override DataContractDictionary KnownDataContracts
{
get
{
if (this.knownDataContracts == null && this.knownTypeList != null)
{
// This assignment may be performed concurrently and thus is a race condition.
// It's safe, however, because at worse a new (and identical) dictionary of
// data contracts will be created and re-assigned to this field. Introduction
// of a lock here could lead to deadlocks.
this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList);
}
return this.knownDataContracts;
}
}
public int MaxItemsInObjectGraph
{
get { return _maxItemsInObjectGraph; }
}
internal ISerializationSurrogateProvider SerializationSurrogateProvider
{
get { return _serializationSurrogateProvider; }
set { _serializationSurrogateProvider = value; }
}
public bool PreserveObjectReferences
{
get { return _preserveObjectReferences; }
}
public bool IgnoreExtensionDataObject
{
get { return _ignoreExtensionDataObject; }
}
public DataContractResolver DataContractResolver
{
get { return _dataContractResolver; }
}
public bool SerializeReadOnlyTypes
{
get { return _serializeReadOnlyTypes; }
}
private DataContract RootContract
{
get
{
if (_rootContract == null)
{
_rootContract = DataContract.GetDataContract((_serializationSurrogateProvider == null) ? _rootType : GetSurrogatedType(_serializationSurrogateProvider, _rootType));
_needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(_rootName, _rootNamespace, _rootContract);
}
return _rootContract;
}
}
internal override void InternalWriteObject(XmlWriterDelegator writer, object graph)
{
InternalWriteObject(writer, graph, null);
}
internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
InternalWriteStartObject(writer, graph);
InternalWriteObjectContent(writer, graph, dataContractResolver);
InternalWriteEndObject(writer);
}
public override void WriteObject(XmlWriter writer, object graph)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteStartObject(XmlWriter writer, object graph)
{
WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteObjectContent(XmlWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteEndObject(XmlWriter writer)
{
WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
}
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteEndObject(XmlDictionaryWriter writer)
{
WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
}
public void WriteObject(XmlDictionaryWriter writer, object graph, DataContractResolver dataContractResolver)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph, dataContractResolver);
}
public override object ReadObject(XmlReader reader)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/);
}
public override object ReadObject(XmlReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
}
public override bool IsStartObject(XmlReader reader)
{
return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
}
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
}
public override bool IsStartObject(XmlDictionaryReader reader)
{
return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
}
public object ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName, dataContractResolver);
}
internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
{
WriteRootElement(writer, RootContract, _rootName, _rootNamespace, _needsContractNsAtRoot);
}
internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
{
InternalWriteObjectContent(writer, graph, null);
}
internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
if (MaxItemsInObjectGraph == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
DataContract contract = RootContract;
Type declaredType = contract.UnderlyingType;
Type graphType = (graph == null) ? declaredType : graph.GetType();
if (_serializationSurrogateProvider != null)
{
graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType);
}
if (dataContractResolver == null)
dataContractResolver = this.DataContractResolver;
if (graph == null)
{
if (IsRootXmlAny(_rootName, contract))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeNull, declaredType)));
WriteNull(writer);
}
else
{
if (declaredType == graphType)
{
if (contract.CanContainReferences)
{
XmlObjectSerializerWriteContext context = XmlObjectSerializerWriteContext.CreateContext(this, contract, dataContractResolver);
context.HandleGraphAtTopLevel(writer, graph, contract);
context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
}
else
{
contract.WriteXmlValue(writer, graph, null);
}
}
else
{
XmlObjectSerializerWriteContext context = null;
if (IsRootXmlAny(_rootName, contract))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType)));
contract = GetDataContract(contract, declaredType, graphType);
context = XmlObjectSerializerWriteContext.CreateContext(this, RootContract, dataContractResolver);
if (contract.CanContainReferences)
{
context.HandleGraphAtTopLevel(writer, graph, contract);
}
context.OnHandleIsReference(writer, contract, graph);
context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
}
}
}
internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType)
{
if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
return declaredTypeContract;
}
else if (declaredType.IsArray)//Array covariance is not supported in XSD
{
return declaredTypeContract;
}
else
{
return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract);
}
}
internal override void InternalWriteEndObject(XmlWriterDelegator writer)
{
if (!IsRootXmlAny(_rootName, RootContract))
{
writer.WriteEndElement();
}
}
internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
{
return InternalReadObject(xmlReader, verifyObjectName, null);
}
internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
if (MaxItemsInObjectGraph == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
if (dataContractResolver == null)
dataContractResolver = this.DataContractResolver;
if (verifyObjectName)
{
if (!InternalIsStartObject(xmlReader))
{
XmlDictionaryString expectedName;
XmlDictionaryString expectedNs;
if (_rootName == null)
{
expectedName = RootContract.TopLevelElementName;
expectedNs = RootContract.TopLevelElementNamespace;
}
else
{
expectedName = _rootName;
expectedNs = _rootNamespace;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElement, expectedNs, expectedName), xmlReader));
}
}
else if (!IsStartElement(xmlReader))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader));
}
DataContract contract = RootContract;
if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, _rootType) /*handle Nullable<T> differently*/)
{
return contract.ReadXmlValue(xmlReader, null);
}
if (IsRootXmlAny(_rootName, contract))
{
return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/);
}
XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver);
return context.InternalDeserialize(xmlReader, _rootType, contract, null, null);
}
internal override bool InternalIsStartObject(XmlReaderDelegator reader)
{
return IsRootElement(reader, RootContract, _rootName, _rootNamespace);
}
internal override Type GetSerializeType(object graph)
{
return (graph == null) ? _rootType : graph.GetType();
}
internal override Type GetDeserializeType()
{
return _rootType;
}
internal static object SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object oldObj, Type surrogatedDeclaredType, ref Type objType)
{
object obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType);
if (obj != oldObj)
{
objType = obj != null ? obj.GetType() : Globals.TypeOfObject;
}
return obj;
}
internal static Type GetSurrogatedType(ISerializationSurrogateProvider serializationSurrogateProvider, Type type)
{
return DataContractSurrogateCaller.GetDataContractType(serializationSurrogateProvider, DataContract.UnwrapNullableType(type));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
namespace Microsoft.AspNetCore.Components
{
public static partial class BindConverter
{
public static bool FormatValue(bool value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTime value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTime value, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTimeOffset value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTimeOffset value, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(decimal value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(double value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(int value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(long value, System.Globalization.CultureInfo culture = null) { throw null; }
public static bool? FormatValue(bool? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTimeOffset? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTimeOffset? value, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTime? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(System.DateTime? value, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(decimal? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(double? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(int? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(long? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(float? value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(float value, System.Globalization.CultureInfo culture = null) { throw null; }
public static string FormatValue(string value, System.Globalization.CultureInfo culture = null) { throw null; }
public static object FormatValue<T>(T value, System.Globalization.CultureInfo culture = null) { throw null; }
public static bool TryConvertToBool(object obj, System.Globalization.CultureInfo culture, out bool value) { throw null; }
public static bool TryConvertToDateTime(object obj, System.Globalization.CultureInfo culture, out System.DateTime value) { throw null; }
public static bool TryConvertToDateTime(object obj, System.Globalization.CultureInfo culture, string format, out System.DateTime value) { throw null; }
public static bool TryConvertToDateTimeOffset(object obj, System.Globalization.CultureInfo culture, out System.DateTimeOffset value) { throw null; }
public static bool TryConvertToDateTimeOffset(object obj, System.Globalization.CultureInfo culture, string format, out System.DateTimeOffset value) { throw null; }
public static bool TryConvertToDecimal(object obj, System.Globalization.CultureInfo culture, out decimal value) { throw null; }
public static bool TryConvertToDouble(object obj, System.Globalization.CultureInfo culture, out double value) { throw null; }
public static bool TryConvertToFloat(object obj, System.Globalization.CultureInfo culture, out float value) { throw null; }
public static bool TryConvertToInt(object obj, System.Globalization.CultureInfo culture, out int value) { throw null; }
public static bool TryConvertToLong(object obj, System.Globalization.CultureInfo culture, out long value) { throw null; }
public static bool TryConvertToNullableBool(object obj, System.Globalization.CultureInfo culture, out bool? value) { throw null; }
public static bool TryConvertToNullableDateTime(object obj, System.Globalization.CultureInfo culture, out System.DateTime? value) { throw null; }
public static bool TryConvertToNullableDateTime(object obj, System.Globalization.CultureInfo culture, string format, out System.DateTime? value) { throw null; }
public static bool TryConvertToNullableDateTimeOffset(object obj, System.Globalization.CultureInfo culture, out System.DateTimeOffset? value) { throw null; }
public static bool TryConvertToNullableDateTimeOffset(object obj, System.Globalization.CultureInfo culture, string format, out System.DateTimeOffset? value) { throw null; }
public static bool TryConvertToNullableDecimal(object obj, System.Globalization.CultureInfo culture, out decimal? value) { throw null; }
public static bool TryConvertToNullableDouble(object obj, System.Globalization.CultureInfo culture, out double? value) { throw null; }
public static bool TryConvertToNullableFloat(object obj, System.Globalization.CultureInfo culture, out float? value) { throw null; }
public static bool TryConvertToNullableInt(object obj, System.Globalization.CultureInfo culture, out int? value) { throw null; }
public static bool TryConvertToNullableLong(object obj, System.Globalization.CultureInfo culture, out long? value) { throw null; }
public static bool TryConvertToString(object obj, System.Globalization.CultureInfo culture, out string value) { throw null; }
public static bool TryConvertTo<T>(object obj, System.Globalization.CultureInfo culture, out T value) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=true)]
public sealed partial class BindElementAttribute : System.Attribute
{
public BindElementAttribute(string element, string suffix, string valueAttribute, string changeAttribute) { }
public string ChangeAttribute { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string Element { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string Suffix { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string ValueAttribute { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
public sealed partial class CascadingParameterAttribute : System.Attribute
{
public CascadingParameterAttribute() { }
public string Name { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed partial class CascadingTypeParameterAttribute : System.Attribute
{
public CascadingTypeParameterAttribute(string name) { }
public string Name { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public partial class CascadingValue<TValue> : Microsoft.AspNetCore.Components.IComponent
{
public CascadingValue() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment ChildContent { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public bool IsFixed { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public string Name { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public TValue Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public void Attach(Microsoft.AspNetCore.Components.RenderHandle renderHandle) { }
public System.Threading.Tasks.Task SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters) { throw null; }
}
public partial class ChangeEventArgs : System.EventArgs
{
public ChangeEventArgs() { }
public object Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public abstract partial class ComponentBase : Microsoft.AspNetCore.Components.IComponent, Microsoft.AspNetCore.Components.IHandleAfterRender, Microsoft.AspNetCore.Components.IHandleEvent
{
public ComponentBase() { }
protected virtual void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected System.Threading.Tasks.Task InvokeAsync(System.Action workItem) { throw null; }
protected System.Threading.Tasks.Task InvokeAsync(System.Func<System.Threading.Tasks.Task> workItem) { throw null; }
void Microsoft.AspNetCore.Components.IComponent.Attach(Microsoft.AspNetCore.Components.RenderHandle renderHandle) { }
System.Threading.Tasks.Task Microsoft.AspNetCore.Components.IHandleAfterRender.OnAfterRenderAsync() { throw null; }
System.Threading.Tasks.Task Microsoft.AspNetCore.Components.IHandleEvent.HandleEventAsync(Microsoft.AspNetCore.Components.EventCallbackWorkItem callback, object arg) { throw null; }
protected virtual void OnAfterRender(bool firstRender) { }
protected virtual System.Threading.Tasks.Task OnAfterRenderAsync(bool firstRender) { throw null; }
protected virtual void OnInitialized() { }
protected virtual System.Threading.Tasks.Task OnInitializedAsync() { throw null; }
protected virtual void OnParametersSet() { }
protected virtual System.Threading.Tasks.Task OnParametersSetAsync() { throw null; }
public virtual System.Threading.Tasks.Task SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters) { throw null; }
protected virtual bool ShouldRender() { throw null; }
protected void StateHasChanged() { }
}
public abstract partial class Dispatcher
{
protected Dispatcher() { }
public void AssertAccess() { }
public abstract bool CheckAccess();
public static Microsoft.AspNetCore.Components.Dispatcher CreateDefault() { throw null; }
public abstract System.Threading.Tasks.Task InvokeAsync(System.Action workItem);
public abstract System.Threading.Tasks.Task InvokeAsync(System.Func<System.Threading.Tasks.Task> workItem);
public abstract System.Threading.Tasks.Task<TResult> InvokeAsync<TResult>(System.Func<System.Threading.Tasks.Task<TResult>> workItem);
public abstract System.Threading.Tasks.Task<TResult> InvokeAsync<TResult>(System.Func<TResult> workItem);
protected void OnUnhandledException(System.UnhandledExceptionEventArgs e) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ElementReference
{
private readonly object _dummy;
public ElementReference(string id) { throw null; }
public string Id { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct EventCallback
{
private readonly object _dummy;
public static readonly Microsoft.AspNetCore.Components.EventCallback Empty;
public static readonly Microsoft.AspNetCore.Components.EventCallbackFactory Factory;
public EventCallback(Microsoft.AspNetCore.Components.IHandleEvent receiver, System.MulticastDelegate @delegate) { throw null; }
public bool HasDelegate { get { throw null; } }
public System.Threading.Tasks.Task InvokeAsync(object arg) { throw null; }
}
public sealed partial class EventCallbackFactory
{
public EventCallbackFactory() { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Microsoft.AspNetCore.Components.EventCallback Create(object receiver, Microsoft.AspNetCore.Components.EventCallback callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback Create(object receiver, System.Action callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback Create(object receiver, System.Action<object> callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback Create(object receiver, System.Func<object, System.Threading.Tasks.Task> callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback Create(object receiver, System.Func<System.Threading.Tasks.Task> callback) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Microsoft.AspNetCore.Components.EventCallback<TValue> CreateInferred<TValue>(object receiver, System.Action<TValue> callback, TValue value) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Microsoft.AspNetCore.Components.EventCallback<TValue> CreateInferred<TValue>(object receiver, System.Func<TValue, System.Threading.Tasks.Task> callback, TValue value) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Microsoft.AspNetCore.Components.EventCallback<TValue> Create<TValue>(object receiver, Microsoft.AspNetCore.Components.EventCallback callback) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Microsoft.AspNetCore.Components.EventCallback<TValue> Create<TValue>(object receiver, Microsoft.AspNetCore.Components.EventCallback<TValue> callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback<TValue> Create<TValue>(object receiver, System.Action callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback<TValue> Create<TValue>(object receiver, System.Action<TValue> callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback<TValue> Create<TValue>(object receiver, System.Func<System.Threading.Tasks.Task> callback) { throw null; }
public Microsoft.AspNetCore.Components.EventCallback<TValue> Create<TValue>(object receiver, System.Func<TValue, System.Threading.Tasks.Task> callback) { throw null; }
}
public static partial class EventCallbackFactoryBinderExtensions
{
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<bool> setter, bool existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTimeOffset> setter, System.DateTimeOffset existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTimeOffset> setter, System.DateTimeOffset existingValue, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTime> setter, System.DateTime existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTime> setter, System.DateTime existingValue, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<decimal> setter, decimal existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<double> setter, double existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<int> setter, int existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<long> setter, long existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<bool?> setter, bool? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTimeOffset?> setter, System.DateTimeOffset? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTimeOffset?> setter, System.DateTimeOffset? existingValue, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTime?> setter, System.DateTime? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.DateTime?> setter, System.DateTime? existingValue, string format, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<decimal?> setter, decimal? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<double?> setter, double? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<int?> setter, int? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<long?> setter, long? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<float?> setter, float? existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<float> setter, float existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<string> setter, string existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> CreateBinder<T>(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<T> setter, T existingValue, System.Globalization.CultureInfo culture = null) { throw null; }
}
public static partial class EventCallbackFactoryEventArgsExtensions
{
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.ChangeEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<System.EventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<System.EventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.ChangeEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.ChangeEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<System.EventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<System.EventArgs, System.Threading.Tasks.Task> callback) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct EventCallbackWorkItem
{
private readonly object _dummy;
public static readonly Microsoft.AspNetCore.Components.EventCallbackWorkItem Empty;
public EventCallbackWorkItem(System.MulticastDelegate @delegate) { throw null; }
public System.Threading.Tasks.Task InvokeAsync(object arg) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct EventCallback<TValue>
{
private readonly object _dummy;
public static readonly Microsoft.AspNetCore.Components.EventCallback<TValue> Empty;
public EventCallback(Microsoft.AspNetCore.Components.IHandleEvent receiver, System.MulticastDelegate @delegate) { throw null; }
public bool HasDelegate { get { throw null; } }
public System.Threading.Tasks.Task InvokeAsync(TValue arg) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=true)]
public sealed partial class EventHandlerAttribute : System.Attribute
{
public EventHandlerAttribute(string attributeName, System.Type eventArgsType) { }
public EventHandlerAttribute(string attributeName, System.Type eventArgsType, bool enablestopPropagation, bool enablePreventDefault) { }
public string AttributeName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public System.Type EventArgsType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public bool EnableStopPropagation { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public bool EnablePreventDefault { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public partial interface IComponent
{
void Attach(Microsoft.AspNetCore.Components.RenderHandle renderHandle);
System.Threading.Tasks.Task SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters);
}
public partial interface IHandleAfterRender
{
System.Threading.Tasks.Task OnAfterRenderAsync();
}
public partial interface IHandleEvent
{
System.Threading.Tasks.Task HandleEventAsync(Microsoft.AspNetCore.Components.EventCallbackWorkItem item, object arg);
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
public sealed partial class InjectAttribute : System.Attribute
{
public InjectAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public sealed partial class LayoutAttribute : System.Attribute
{
public LayoutAttribute(System.Type layoutType) { }
public System.Type LayoutType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public abstract partial class LayoutComponentBase : Microsoft.AspNetCore.Components.ComponentBase
{
protected LayoutComponentBase() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment Body { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class LayoutView : Microsoft.AspNetCore.Components.IComponent
{
public LayoutView() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment ChildContent { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public System.Type Layout { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public void Attach(Microsoft.AspNetCore.Components.RenderHandle renderHandle) { }
public System.Threading.Tasks.Task SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters) { throw null; }
}
public sealed partial class LocationChangeException : System.Exception
{
public LocationChangeException(string message, System.Exception innerException) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct MarkupString
{
private readonly object _dummy;
public MarkupString(string value) { throw null; }
public string Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public static explicit operator Microsoft.AspNetCore.Components.MarkupString (string value) { throw null; }
public override string ToString() { throw null; }
}
public partial class NavigationException : System.Exception
{
public NavigationException(string uri) { }
public string Location { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public abstract partial class NavigationManager
{
protected NavigationManager() { }
public string BaseUri { get { throw null; } protected set { } }
public string Uri { get { throw null; } protected set { } }
public event System.EventHandler<Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs> LocationChanged { add { } remove { } }
protected virtual void EnsureInitialized() { }
protected void Initialize(string baseUri, string uri) { }
public void NavigateTo(string uri, bool forceLoad = false) { }
protected abstract void NavigateToCore(string uri, bool forceLoad);
protected void NotifyLocationChanged(bool isInterceptedLink) { }
public System.Uri ToAbsoluteUri(string relativeUri) { throw null; }
public string ToBaseRelativePath(string uri) { throw null; }
}
public abstract partial class OwningComponentBase : Microsoft.AspNetCore.Components.ComponentBase, System.IDisposable
{
protected OwningComponentBase() { }
protected bool IsDisposed { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
protected System.IServiceProvider ScopedServices { get { throw null; } }
protected virtual void Dispose(bool disposing) { }
void System.IDisposable.Dispose() { }
}
public abstract partial class OwningComponentBase<TService> : Microsoft.AspNetCore.Components.OwningComponentBase, System.IDisposable
{
protected OwningComponentBase() { }
protected TService Service { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
public sealed partial class ParameterAttribute : System.Attribute
{
public ParameterAttribute() { }
public bool CaptureUnmatchedValues { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ParameterValue
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public bool Cascading { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string Name { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public object Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ParameterView
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public static Microsoft.AspNetCore.Components.ParameterView Empty { get { throw null; } }
public static Microsoft.AspNetCore.Components.ParameterView FromDictionary(System.Collections.Generic.IDictionary<string, object> parameters) { throw null; }
public Microsoft.AspNetCore.Components.ParameterView.Enumerator GetEnumerator() { throw null; }
public TValue GetValueOrDefault<TValue>(string parameterName) { throw null; }
public TValue GetValueOrDefault<TValue>(string parameterName, TValue defaultValue) { throw null; }
public void SetParameterProperties(object target) { }
public System.Collections.Generic.IReadOnlyDictionary<string, object> ToDictionary() { throw null; }
public bool TryGetValue<TValue>(string parameterName, out TValue result) { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public Microsoft.AspNetCore.Components.ParameterValue Current { get { throw null; } }
public bool MoveNext() { throw null; }
}
}
public delegate void RenderFragment(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder);
public delegate Microsoft.AspNetCore.Components.RenderFragment RenderFragment<TValue>(TValue value);
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct RenderHandle
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public Microsoft.AspNetCore.Components.Dispatcher Dispatcher { get { throw null; } }
public bool IsInitialized { get { throw null; } }
public void Render(Microsoft.AspNetCore.Components.RenderFragment renderFragment) { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)]
public sealed partial class RouteAttribute : System.Attribute
{
public RouteAttribute(string template) { }
public string Template { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public sealed partial class RouteData
{
public RouteData(System.Type pageType, System.Collections.Generic.IReadOnlyDictionary<string, object> routeValues) { }
public System.Type PageType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, object> RouteValues { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public partial class RouteView : Microsoft.AspNetCore.Components.IComponent
{
public RouteView() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public System.Type DefaultLayout { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RouteData RouteData { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public void Attach(Microsoft.AspNetCore.Components.RenderHandle renderHandle) { }
protected virtual void Render(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
public System.Threading.Tasks.Task SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters) { throw null; }
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public partial class EditorRequiredAttribute : Attribute
{
public EditorRequiredAttribute() { }
}
}
namespace Microsoft.AspNetCore.Components.CompilerServices
{
public static partial class RuntimeHelpers
{
public static Microsoft.AspNetCore.Components.EventCallback<T> CreateInferredEventCallback<T>(object receiver, System.Action<T> callback, T value) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<T> CreateInferredEventCallback<T>(object receiver, System.Func<T, System.Threading.Tasks.Task> callback, T value) { throw null; }
public static T TypeCheck<T>(T value) { throw null; }
}
}
namespace Microsoft.AspNetCore.Components.Rendering
{
public sealed partial class RenderTreeBuilder : System.IDisposable
{
public RenderTreeBuilder() { }
public void AddAttribute(int sequence, in Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame frame) { }
public void AddAttribute(int sequence, string name) { }
public void AddAttribute(int sequence, string name, Microsoft.AspNetCore.Components.EventCallback value) { }
public void AddAttribute(int sequence, string name, bool value) { }
public void AddAttribute(int sequence, string name, System.MulticastDelegate value) { }
public void AddAttribute(int sequence, string name, object value) { }
public void AddAttribute(int sequence, string name, string value) { }
public void AddAttribute<TArgument>(int sequence, string name, Microsoft.AspNetCore.Components.EventCallback<TArgument> value) { }
public void AddComponentReferenceCapture(int sequence, System.Action<object> componentReferenceCaptureAction) { }
public void AddContent(int sequence, Microsoft.AspNetCore.Components.MarkupString markupContent) { }
public void AddContent(int sequence, Microsoft.AspNetCore.Components.RenderFragment fragment) { }
public void AddContent(int sequence, object textContent) { }
public void AddContent(int sequence, string textContent) { }
public void AddContent<TValue>(int sequence, Microsoft.AspNetCore.Components.RenderFragment<TValue> fragment, TValue value) { }
public void AddElementReferenceCapture(int sequence, System.Action<Microsoft.AspNetCore.Components.ElementReference> elementReferenceCaptureAction) { }
public void AddMarkupContent(int sequence, string markupContent) { }
public void AddMultipleAttributes(int sequence, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>> attributes) { }
public void Clear() { }
public void CloseComponent() { }
public void CloseElement() { }
public void CloseRegion() { }
public Microsoft.AspNetCore.Components.RenderTree.ArrayRange<Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame> GetFrames() { throw null; }
public void OpenComponent(int sequence, System.Type componentType) { }
public void OpenComponent<TComponent>(int sequence) where TComponent : Microsoft.AspNetCore.Components.IComponent { }
public void OpenElement(int sequence, string elementName) { }
public void OpenRegion(int sequence) { }
public void SetKey(object value) { }
public void SetUpdatesAttributeName(string updatesAttributeName) { }
void System.IDisposable.Dispose() { }
}
}
namespace Microsoft.AspNetCore.Components.RenderTree
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ArrayBuilderSegment<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public T[] Array { get { throw null; } }
public int Count { get { throw null; } }
public T this[int index] { get { throw null; } }
public int Offset { get { throw null; } }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ArrayRange<T>
{
public readonly T[] Array;
public readonly int Count;
public ArrayRange(T[] array, int count) { throw null; }
public Microsoft.AspNetCore.Components.RenderTree.ArrayRange<T> Clone() { throw null; }
}
public partial class EventFieldInfo
{
public EventFieldInfo() { }
public int ComponentId { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public object FieldValue { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct RenderBatch
{
private readonly object _dummy;
public Microsoft.AspNetCore.Components.RenderTree.ArrayRange<int> DisposedComponentIDs { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public Microsoft.AspNetCore.Components.RenderTree.ArrayRange<ulong> DisposedEventHandlerIDs { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public Microsoft.AspNetCore.Components.RenderTree.ArrayRange<Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame> ReferenceFrames { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public Microsoft.AspNetCore.Components.RenderTree.ArrayRange<Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiff> UpdatedComponents { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct RenderTreeDiff
{
public readonly int ComponentId;
public readonly Microsoft.AspNetCore.Components.RenderTree.ArrayBuilderSegment<Microsoft.AspNetCore.Components.RenderTree.RenderTreeEdit> Edits;
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Explicit)]
public readonly partial struct RenderTreeEdit
{
[System.Runtime.InteropServices.FieldOffsetAttribute(8)]
public readonly int MoveToSiblingIndex;
[System.Runtime.InteropServices.FieldOffsetAttribute(8)]
public readonly int ReferenceFrameIndex;
[System.Runtime.InteropServices.FieldOffsetAttribute(16)]
public readonly string RemovedAttributeName;
[System.Runtime.InteropServices.FieldOffsetAttribute(4)]
public readonly int SiblingIndex;
[System.Runtime.InteropServices.FieldOffsetAttribute(0)]
public readonly Microsoft.AspNetCore.Components.RenderTree.RenderTreeEditType Type;
}
public enum RenderTreeEditType
{
PrependFrame = 1,
RemoveFrame = 2,
SetAttribute = 3,
RemoveAttribute = 4,
UpdateText = 5,
StepIn = 6,
StepOut = 7,
UpdateMarkup = 8,
PermutationListEntry = 9,
PermutationListEnd = 10,
}
public enum RenderTreeFrameType : short
{
None = (short)0,
Element = (short)1,
Text = (short)2,
Attribute = (short)3,
Component = (short)4,
Region = (short)5,
ElementReferenceCapture = (short)6,
ComponentReferenceCapture = (short)7,
Markup = (short)8,
}
}
namespace Microsoft.AspNetCore.Components.Routing
{
public partial interface IHostEnvironmentNavigationManager
{
void Initialize(string baseUri, string uri);
}
public partial interface INavigationInterception
{
System.Threading.Tasks.Task EnableNavigationInterceptionAsync();
}
public partial class LocationChangedEventArgs : System.EventArgs
{
public LocationChangedEventArgs(string location, bool isNavigationIntercepted) { }
public bool IsNavigationIntercepted { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string Location { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public partial class Router : Microsoft.AspNetCore.Components.IComponent, Microsoft.AspNetCore.Components.IHandleAfterRender, System.IDisposable
{
public Router() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public System.Collections.Generic.IEnumerable<System.Reflection.Assembly> AdditionalAssemblies { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public System.Reflection.Assembly AppAssembly { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment<Microsoft.AspNetCore.Components.RouteData> Found { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment NotFound { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public void Attach(Microsoft.AspNetCore.Components.RenderHandle renderHandle) { }
public void Dispose() { }
System.Threading.Tasks.Task Microsoft.AspNetCore.Components.IHandleAfterRender.OnAfterRenderAsync() { throw null; }
public System.Threading.Tasks.Task SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters) { throw null; }
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Localization;
using System.Diagnostics;
using OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl;
namespace OpenLiveWriter.PostEditor.PostPropertyEditing
{
using Localization.Bidi;
// TODO: Page Parent won't clear properly on switching blogs (does that even work? or do pages get converted to posts on switch?)
internal partial class PostPropertiesForm : ApplicationDialog, IBlogPostEditor, INewCategoryContext
{
private SharedPropertiesController controller;
private string _blogId;
private List<PropertyField> fields = new List<PropertyField>();
private readonly CommandManager commandManager;
internal PostPropertiesForm(CommandManager commandManager, CategoryContext categoryContext)
{
this.commandManager = commandManager;
InitializeComponent();
this.Name = "PostPropertiesForm";
Text = Res.Get(StringId.PostProperties);
AccessibleName = Text;
buttonClose.Text = Res.Get(StringId.CloseButtonNoMnemonic);
this.labelPageOrder.Text = Res.Get(StringId.PropertiesPageOrder);
this.labelPageParent.Text = Res.Get(StringId.PropertiesPageParent);
this.labelCategories.Text = Res.Get(StringId.PropertiesCategories);
this.labelPublishDate.Text = Res.Get(StringId.PropertiesPublishDate);
this.labelSlug.Text = Res.Get(StringId.PropertiesSlug);
this.labelComments.Text = Res.Get(StringId.PropertiesComments);
this.labelPings.Text = Res.Get(StringId.PropertiesPings);
this.labelTags.Text = Res.Get(StringId.PropertiesKeywords);
this.labelAuthor.Text = Res.Get(StringId.PropertiesAuthor);
this.labelPassword.Text = Res.Get(StringId.PropertiesPassword);
this.labelTrackbacks.Text = Res.Get(StringId.PropertiesTrackbacks);
this.labelExcerpt.Text = Res.Get(StringId.PropertiesExcerpt);
this.textPassword.PasswordChar = Res.PasswordChar;
ControlHelper.SetCueBanner(textTrackbacks, Res.Get(StringId.PropertiesCommaSeparated));
SuppressAutoRtlFixup = true;
comboComments.Items.AddRange(new[] {
new CommentComboItem(BlogCommentPolicy.Unspecified),
new CommentComboItem(BlogCommentPolicy.None),
new CommentComboItem(BlogCommentPolicy.Open),
new CommentComboItem(BlogCommentPolicy.Closed),
});
comboPings.Items.AddRange(new[] {
new TrackbackComboItem(BlogTrackbackPolicy.Unspecified),
new TrackbackComboItem(BlogTrackbackPolicy.Allow),
new TrackbackComboItem(BlogTrackbackPolicy.Deny),
});
InitializePropertyFields();
controller = new SharedPropertiesController(
this, labelCategories, categoryDropDown, labelTags, textTags, labelPageOrder, textPageOrder,
labelPageParent, comboPageParent, labelPublishDate, datePublishDate, fields, categoryContext);
this.comboComments.SelectedIndexChanged += controller.MakeDirty;
this.comboPings.SelectedIndexChanged += controller.MakeDirty;
this.textSlug.TextChanged += controller.MakeDirty;
this.textPassword.TextChanged += controller.MakeDirty;
this.textExcerpt.TextChanged += controller.MakeDirty;
this.textTrackbacks.TextChanged += controller.MakeDirty;
SimpleTextEditorCommandHelper.UseNativeBehaviors(commandManager,
textExcerpt, textPageOrder, textPassword,
textSlug, textTags, textTrackbacks);
}
public void DisplayCategoryForm()
{
categoryDropDown.DisplayCategoryForm();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (commandManager.ProcessCmdKeyShortcut(keyData))
return true;
return base.ProcessCmdKey(ref msg, keyData);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// WinLive 53092: Avoid horizontal scrolling for languages with long label names.
int maxLabelWidth = panel1.Width;
foreach (Control control in flowLayoutPanel.Controls)
{
maxLabelWidth = Math.Max(maxLabelWidth, control.PreferredSize.Width);
}
this.Width += maxLabelWidth - panel1.Width;
// WinLive 52981: Avoid clipping the author combobox for languages with tall comboboxes.
this.panelComboAuthorIsolate.Height = this.comboAuthor.PreferredSize.Height;
DisplayHelper.AutoFitSystemButton(buttonClose);
if (Owner != null)
{
this.Left = BidiHelper.IsRightToLeft
? this.Owner.Left + SystemInformation.VerticalScrollBarWidth * 2
: this.Owner.Right - this.Width - SystemInformation.VerticalScrollBarWidth * 2;
Top = Owner.Top + 100;
}
}
private void InitializePropertyFields()
{
RegisterField(PropertyType.Both, labelComments, comboComments,
opts => opts.SupportsCommentPolicy,
post => comboComments.SelectedItem = new CommentComboItem(post.CommentPolicy),
post => post.CommentPolicy = ((CommentComboItem)comboComments.SelectedItem).Value);
RegisterField(PropertyType.Both, labelPings, comboPings,
opts => opts.SupportsPingPolicy,
post => comboPings.SelectedItem = new TrackbackComboItem(post.TrackbackPolicy),
post => post.TrackbackPolicy = ((TrackbackComboItem)comboPings.SelectedItem).Value);
RegisterField(PropertyType.Both, labelAuthor, panelComboAuthorIsolate,
opts => opts.SupportsAuthor,
post => SetAuthor(post.Author),
post => post.Author = (PostIdAndNameField)comboAuthor.SelectedItem);
RegisterField(PropertyType.Both, labelSlug, textSlug,
opts => opts.SupportsSlug,
post => textSlug.Text = post.Slug,
post => post.Slug = textSlug.Text);
RegisterField(PropertyType.Both, labelPassword, textPassword,
opts => opts.SupportsPassword,
post => textPassword.Text = post.Password,
post => post.Password = textPassword.Text);
RegisterField(PropertyType.Post, labelExcerpt, textExcerpt,
opts => opts.SupportsExcerpt,
post => textExcerpt.Text = post.Excerpt,
post => post.Excerpt = textExcerpt.Text);
RegisterField(PropertyType.Post, labelTrackbacks, textTrackbacks,
opts => opts.SupportsTrackbacks,
post =>
textTrackbacks.Text = StringHelper.Join(ArrayHelper.Union(post.PingUrlsPending, post.PingUrlsSent), ", "),
post =>
{
List<string> sent = new List<string>(post.PingUrlsSent);
List<string> pending = new List<string>();
string[] pingUrls = StringHelper.Split(textTrackbacks.Text.Trim(), ",");
foreach (string url in pingUrls)
if (!sent.Contains(url))
pending.Add(url);
post.PingUrlsPending = pending.ToArray();
});
}
private void PostPropertiesForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing || e.CloseReason == CloseReason.None)
{
e.Cancel = true;
Hide();
if (Owner != null && Owner.Visible)
Owner.Activate();
}
}
private void flowLayoutPanel_ClientSizeChanged(object sender, EventArgs e)
{
// panel1 is used to make all the other controls stretch to fill the width of the flowLayoutPanel. See
// the MSDN article "How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control" at
// http://msdn.microsoft.com/en-us/library/ms171633(VS.80).aspx
if (flowLayoutPanel.VerticalScroll.Visible)
// The DisplayHelper.ScaleX(12) call is used to add horizontal padding between the controls in the
// flowLayoutPanel and the vertical scroll bar.
panel1.Width = flowLayoutPanel.ClientSize.Width - Convert.ToInt32(DisplayHelper.ScaleX(12));
else
panel1.Width = flowLayoutPanel.ClientSize.Width;
}
private void RegisterField(PropertyType type, Control label, Control editor, PropertyField.ShouldShow shouldShow, PropertyField.Populate populate, PropertyField.Save save)
{
PropertyField field = new PropertyField(type, new[] { label, editor }, shouldShow, populate, save);
fields.Add(field);
}
private void SetAuthor(PostIdAndNameField author)
{
if (author != null)
{
BlogAuthorFetcher authorFetcher = new BlogAuthorFetcher(_blogId, 10000);
if (!author.IsEmpty)
comboAuthor.Initialize(new object[] { new PostIdAndNameField(Res.Get(StringId.PropertiesDefault)), author }, author, authorFetcher);
else
comboAuthor.Initialize(new PostIdAndNameField(Res.Get(StringId.PropertiesDefault)), authorFetcher);
}
}
private class BlogAuthorFetcher : BlogDelayedFetchHandler
{
public BlogAuthorFetcher(string blogId, int timeoutMs)
: base(blogId, Res.Get(StringId.PropertiesAuthorsFetchingText), timeoutMs)
{
}
protected override object BlogFetchOperation(Blog blog)
{
// refresh our author list
blog.RefreshAuthors();
// return what we've got
return ConvertAuthors(blog.Authors);
}
protected override object[] GetDefaultItems(Blog blog)
{
return ConvertAuthors(blog.Authors);
}
private object[] ConvertAuthors(AuthorInfo[] authorList)
{
List<PostIdAndNameField> authors = new List<PostIdAndNameField>();
foreach (AuthorInfo author in authorList)
authors.Add(new PostIdAndNameField(author.Id, author.Name));
return authors.ToArray();
}
}
#region Implementation of IBlogPostEditor
void IBlogPostEditor.Initialize(IBlogPostEditingContext context, IBlogClientOptions clientOptions)
{
Text = context.BlogPost.IsPage ? Res.Get(StringId.PageProperties) : Res.Get(StringId.PostProperties);
controller.Initialize(context, clientOptions);
}
void IBlogPostEditor.OnBlogChanged(Blog newBlog)
{
// preserve dirty state
using (controller.SuspendLogic())
{
_blogId = newBlog.Id;
controller.OnBlogChanged(newBlog);
// Clear out author whenever blog changes
SetAuthor(PostIdAndNameField.Empty);
// Comment policy hackery
BlogCommentPolicy? commentPolicy = null;
if (comboComments.SelectedIndex >= 0)
commentPolicy = ((CommentComboItem)comboComments.SelectedItem).Value;
comboComments.Items.Remove(new CommentComboItem(BlogCommentPolicy.None));
if (!newBlog.ClientOptions.CommentPolicyAsBoolean)
comboComments.Items.Insert(1, new CommentComboItem(BlogCommentPolicy.None));
if (commentPolicy != null)
comboComments.SelectedItem = new CommentComboItem(commentPolicy.Value);
if (comboComments.SelectedIndex == -1) // In no case should there be no selection at all
comboComments.SelectedIndex = 0;
labelTags.Text = newBlog.ClientOptions.KeywordsAsTags
? Res.Get(StringId.PropertiesTags)
: Res.Get(StringId.PropertiesKeywords);
}
}
void IBlogPostEditor.OnBlogSettingsChanged(bool templateChanged)
{
// preserve dirty state
using (controller.SuspendLogic())
controller.OnBlogSettingsChanged(templateChanged);
}
bool IBlogPostEditor.IsDirty
{
get
{
return controller.IsDirty;
}
}
public bool HasKeywords
{
get { return textTags.TextValue.Trim().Length > 0; }
}
void IBlogPostEditor.SaveChanges(BlogPost post, BlogPostSaveOptions options)
{
controller.SaveChanges(post, options);
}
bool IBlogPostEditor.ValidatePublish()
{
return controller.ValidatePublish();
}
void IBlogPostEditor.OnPublishSucceeded(BlogPost blogPost, PostResult postResult)
{
using (controller.SuspendLogic())
{
controller.OnPublishSucceeded(blogPost, postResult);
// slug can be modified by the service
textSlug.Text = blogPost.Slug;
}
}
void IBlogPostEditor.OnClosing(CancelEventArgs e)
{
controller.OnPostClosing(e);
}
void IBlogPostEditor.OnPostClosing(CancelEventArgs e)
{
controller.OnPostClosing(e);
}
void IBlogPostEditor.OnClosed()
{
controller.OnClosed();
}
void IBlogPostEditor.OnPostClosed()
{
controller.OnPostClosed();
}
#endregion
#region Implementation of INewCategoryContext
public void NewCategoryAdded(BlogPostCategory category)
{
controller.NewCategoryAdded(category);
}
#endregion
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
internal void Synchronize(SharedPropertiesController anotherController)
{
Debug.Assert(!ReferenceEquals(controller, anotherController));
anotherController.Other = controller;
controller.Other = anotherController;
}
}
internal abstract class EnumComboItem<TEnum>
{
protected readonly TEnum value;
protected EnumComboItem(TEnum value)
{
this.value = value;
}
public TEnum Value { get { return value; } }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return value.Equals(((EnumComboItem<TEnum>)obj).value);
}
public override int GetHashCode()
{
return value.GetHashCode();
}
public override string ToString()
{
return DisplayName;
}
protected abstract string DisplayName { get; }
}
internal class CommentComboItem : EnumComboItem<BlogCommentPolicy>
{
public CommentComboItem(BlogCommentPolicy value) : base(value)
{
}
protected override string DisplayName
{
get
{
switch (value)
{
case BlogCommentPolicy.Unspecified:
return Res.Get(StringId.PropertiesDefault);
case BlogCommentPolicy.None:
return Res.Get(StringId.PropertiesCommentPolicyNone);
case BlogCommentPolicy.Open:
return Res.Get(StringId.PropertiesCommentPolicyOpen);
case BlogCommentPolicy.Closed:
return Res.Get(StringId.PropertiesCommentPolicyClosed);
default:
Debug.Fail("Unexpected enum value");
return Res.Get(StringId.PropertiesDefault);
}
}
}
}
internal class TrackbackComboItem : EnumComboItem<BlogTrackbackPolicy>
{
public TrackbackComboItem(BlogTrackbackPolicy value) : base(value)
{
}
protected override string DisplayName
{
get
{
switch (value)
{
case BlogTrackbackPolicy.Unspecified:
return Res.Get(StringId.PropertiesDefault);
case BlogTrackbackPolicy.Allow:
return Res.Get(StringId.PropertiesTrackbackPolicyAllow);
case BlogTrackbackPolicy.Deny:
return Res.Get(StringId.PropertiesTrackbackPolicyDeny);
default:
Debug.Fail("Unexpected enum value");
return Res.Get(StringId.PropertiesDefault);
}
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitPeeringsOperations operations.
/// </summary>
public partial interface IExpressRouteCircuitPeeringsOperations
{
/// <summary>
/// Deletes the specified peering from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified express route
/// circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit
/// peering operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified peering from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified express route
/// circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit
/// peering operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Syndication
{
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Xml;
using System.Runtime.CompilerServices;
[TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
[DataContract]
public abstract class ServiceDocumentFormatter
{
ServiceDocument document;
protected ServiceDocumentFormatter()
{
}
protected ServiceDocumentFormatter(ServiceDocument documentToWrite)
{
if (documentToWrite == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("documentToWrite");
}
this.document = documentToWrite;
}
public ServiceDocument Document
{
get { return this.document; }
}
public abstract string Version
{ get; }
public abstract bool CanRead(XmlReader reader);
public abstract void ReadFrom(XmlReader reader);
public abstract void WriteTo(XmlWriter writer);
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, CategoriesDocument categories)
{
if (categories == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("categories");
}
Atom10FeedFormatter.CloseBuffer(buffer, writer);
categories.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ResourceCollectionInfo collection)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
Atom10FeedFormatter.CloseBuffer(buffer, writer);
collection.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, Workspace workspace)
{
if (workspace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workspace");
}
Atom10FeedFormatter.CloseBuffer(buffer, writer);
workspace.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
Atom10FeedFormatter.CloseBuffer(buffer, writer);
document.LoadElementExtensions(buffer);
}
protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories)
{
if (inlineCategories == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inlineCategories");
}
return inlineCategories.CreateCategory();
}
protected static ResourceCollectionInfo CreateCollection(Workspace workspace)
{
if (workspace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workspace");
}
return workspace.CreateResourceCollection();
}
protected static InlineCategoriesDocument CreateInlineCategories(ResourceCollectionInfo collection)
{
return collection.CreateInlineCategoriesDocument();
}
protected static ReferencedCategoriesDocument CreateReferencedCategories(ResourceCollectionInfo collection)
{
return collection.CreateReferencedCategoriesDocument();
}
protected static Workspace CreateWorkspace(ServiceDocument document)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
return document.CreateWorkspace();
}
protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories, int maxExtensionSize)
{
if (categories == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("categories");
}
categories.LoadElementExtensions(reader, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection, int maxExtensionSize)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
collection.LoadElementExtensions(reader, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, Workspace workspace, int maxExtensionSize)
{
if (workspace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workspace");
}
workspace.LoadElementExtensions(reader, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document, int maxExtensionSize)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
document.LoadElementExtensions(reader, maxExtensionSize);
}
protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document, string version)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
return document.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
return collection.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("categories");
}
return categories.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace, string version)
{
if (workspace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workspace");
}
return workspace.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
return collection.TryParseElement(reader, version);
}
protected static bool TryParseElement(XmlReader reader, ServiceDocument document, string version)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
return document.TryParseElement(reader, version);
}
protected static bool TryParseElement(XmlReader reader, Workspace workspace, string version)
{
if (workspace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workspace");
}
return workspace.TryParseElement(reader, version);
}
protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("categories");
}
return categories.TryParseElement(reader, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document, string version)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
document.WriteAttributeExtensions(writer, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace, string version)
{
if (workspace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workspace");
}
workspace.WriteAttributeExtensions(writer, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
collection.WriteAttributeExtensions(writer, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("categories");
}
categories.WriteAttributeExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument document, string version)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
document.WriteElementExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, Workspace workspace, string version)
{
if (workspace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workspace");
}
workspace.WriteElementExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
collection.WriteElementExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("categories");
}
categories.WriteElementExtensions(writer, version);
}
protected virtual ServiceDocument CreateDocumentInstance()
{
return new ServiceDocument();
}
protected virtual void SetDocument(ServiceDocument document)
{
this.document = document;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
namespace BasicTests
{
public class Disjunctions
{
public int[] Arr(int[] a, int len)
{
Contract.Requires(a != null);
Contract.Requires(len >= 0);
Contract.Ensures(a.Length != len || Contract.Result<int[]>().Length == a.Length);
Contract.Ensures(a.Length == len || Contract.Result<int[]>().Length == len);
if (a.Length == len)
return a;
else
return new int[len];
}
// ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Array creation : ok", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 11, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message="valid non-null reference (as array)", PrimaryILOffset=18, MethodILOffset=0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 11)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 11)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 23, MethodILOffset = 0)]
public void Use1()
{
var a = new int[10];
var call = Arr(a, 3);
// Simplify the postconditions to call.Length == 3
Contract.Assert(call.Length == 3);
}
// ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Array creation : ok", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 31, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'call'", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 31)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 31)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 43, MethodILOffset = 0)]
public void Use2(int len, int newSize)
{
Contract.Requires(newSize >= 0);
Contract.Requires(len > newSize);
var a = new int[len];
var call = Arr(a, newSize);
// Simplify the postconditions to call.Length == newSize
Contract.Assert(call.Length == newSize);
}
// ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Array creation : ok", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 31, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'call'", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 31)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 31)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 43, MethodILOffset = 0)]
public void Use3(int len, int newSize)
{
Contract.Requires(len >= 0);
Contract.Requires(newSize > len);
var a = new int[len];
var call = Arr(a, newSize);
// Simplify the postconditions to call.Length == newSize
Contract.Assert(call.Length == newSize);
}
// ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"Array creation : ok", PrimaryILOffset = 25, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 34, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 'call'", PrimaryILOffset = 41, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 7, MethodILOffset = 34)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 34)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 46, MethodILOffset = 0)]
public void Use4(int len, int newSize)
{
Contract.Requires(len >= 0);
Contract.Requires(newSize >= 0);
var a = new int[len];
var call = Arr(a, newSize);
// Cannot simplify the postcondition
Contract.Assert(call.Length == newSize);
}
}
public class StateMachine
{
public enum States { A, B, C }
public States State;
private void RotateState()
{
Contract.Ensures(Contract.OldValue(State) != States.A || State == States.B);
Contract.Ensures(Contract.OldValue(State) != States.B || State == States.C);
Contract.Ensures(Contract.OldValue(State) != States.C || State == States.A);
// bla bla
}
// Ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 14, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 22, MethodILOffset = 0)]
public void TestOK()
{
this.State = States.A;
RotateState();
Contract.Assert(this.State == States.B);
}
// ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as field receiver)", PrimaryILOffset = 14, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = @"assert is false", PrimaryILOffset = 22, MethodILOffset = 0)]
public void TestNOTOK()
{
this.State = States.A;
RotateState();
Contract.Assert(this.State == States.C);
}
}
public class LoopExample
{
public int RandomValue(int x)
{
Contract.Ensures(x <= 123 || Contract.Result<int>() >= 0);
//Contract.Ensures(x > 123 || Contract.Result<int>() <= 0);
if (x > 123)
return 134;
else
return -12;
}
// ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as receiver)",PrimaryILOffset=21,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"assert is valid",PrimaryILOffset=46,MethodILOffset=0)]
public void Loop(int seed, int counts)
{
Contract.Requires(seed > 200);
var sum = 0;
for (int i = 0; i < counts; i++)
{
var x = RandomValue(seed);
// We refine the postcondition to "seed > 123 ==> x >= 0", hence x >= 0 by modus ponens
sum += x;
}
Contract.Assert(sum >= 0);
}
}
public class String
{
[Pure]
private static bool IsHexDigit(char c)
{
Contract.Ensures(Contract.Result<bool>() == ('0' <= c && c <= '9' || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f'));
return '0' <= c && c <= '9' || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f';
}
// F: TODO once we will have disjunctions of intervals
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven. The static checker determined that the condition 'c != 36' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add a precondition to document it: Contract.Requires(c != 36);", PrimaryILOffset = 16, MethodILOffset = 0)]
public static void TestIsHexDigit(char c)
{
if(IsHexDigit(c))
{
Contract.Assert(c != '$');
}
}
}
}
namespace RefinementOfRequires
{
class SimpleTest
{
[ClousotRegressionTest]
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="method Requires (including invariants) are unsatisfiable: RefinementOfRequires.SimpleTest.Foo(System.Int32)",PrimaryILOffset=26,MethodILOffset=0)]
#else
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"method Requires (including invariants) are unsatisfiable: RefinementOfRequires.SimpleTest.Foo(System.Int32)",PrimaryILOffset=27,MethodILOffset=0)]
#endif
public void Foo(int state)
{
Contract.Requires(state == -3 || state == 1);
Contract.Requires(state == 2);
Contract.Assert(false); // Unreachable
}
}
}
namespace UserRepro
{
public class AlexeyR
{
static bool SimpleDisjunction(out int x)
{
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out x) > 100);
x = 123;
return true;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"assert is valid",PrimaryILOffset=14,MethodILOffset=0)]
static void UseSimpledisjunction(int z)
{
if (SimpleDisjunction(out z))
{
Contract.Assert(z > 100);
}
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as receiver)",PrimaryILOffset=7,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"assert is valid",PrimaryILOffset=41,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=13,MethodILOffset=7)]
static void Test(/*out*/ int index)
{
int count = new Random().Next(100);
if (count < 2)
count = 2;
index = 0;
if (GetIndex(1, count - 2, out index))
{
Contract.Assert(index < count - 1); // proven, needs modus ponens and subpolyhedra
}
}
static bool GetIndex(int start, int count, out int index)
{
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out index) < start + count);
index = start;
return false;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as receiver)",PrimaryILOffset=7,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=7,MethodILOffset=28)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=19,MethodILOffset=28)]
#if CLOUSOT2
// In clousot2, we need the -wp=true option to prove the precondition. In Clousot1, we have slightly different IL which allows us to prove it without using WP
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="requires unproven: count <= 100",PrimaryILOffset=32,MethodILOffset=28)]
#else
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=32,MethodILOffset=28)]
#endif
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"assert is valid",PrimaryILOffset=41,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=13,MethodILOffset=7)]
static void Test2(/*out*/ int index)
{
int count = new Random().Next(100);
if (count < 2)
count = 2;
index = 0;
if (GetIndex2(1, count - 2, out index))
{
Contract.Assert(index < count - 1); // proven: needs modus ponens, simplification and subpolyhedra
}
}
static bool GetIndex2(int start, int count, out int index)
{
Contract.Requires(start >= 0);
Contract.Requires(count >= 0);
Contract.Requires(count <= 100);
Contract.Ensures(Contract.ValueAtReturn(out index) >= start);
Contract.Ensures(Contract.ValueAtReturn(out index) <= start + count);
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out index) < start + count);
index = start;
return false;
}
}
public class ForAllTest
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=77,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=77,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=8,MethodILOffset=0)]
#if !CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=14,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=23,MethodILOffset=0)]
#endif
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=28,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=58,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=91,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=96,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=71,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=77,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as receiver)",PrimaryILOffset=78,MethodILOffset=0)]
public int SumLengths(string[] input)
{
Contract.Requires(input == null || Contract.ForAll(0, input.Length, j => input[j] != null));
var c = 0;
if (input != null)
{
for (var i = 0; i < input.Length; i++)
{
c += input[i].Length;
}
}
return c;
}
}
}
| |
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
namespace AVDump3Lib.Misc;
public static class NtfsAlternateStreamsNativeMethods {
#region Constants and flags
public const int MaxPath = 256;
private const string LongPathPrefix = @"\\?\";
public const char StreamSeparator = ':';
public const int DefaultBufferSize = 0x1000;
private const int ErrorFileNotFound = 2;
// "Characters whose integer representations are in the range from 1 through 31,
// except for alternate streams where these characters are allowed"
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
//private static readonly char[] InvalidStreamNameChars = Path.GetInvalidFileNameChars().Where(c => c < 1 || c > 31).ToArray();
[Flags]
public enum NativeFileFlags : uint {
WriteThrough = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x8000000,
DeleteOnClose = 0x4000000,
BackupSemantics = 0x2000000,
PosixSemantics = 0x1000000,
OpenReparsePoint = 0x200000,
OpenNoRecall = 0x100000
}
[Flags]
public enum NativeFileAccess : uint {
GenericRead = 0x80000000,
GenericWrite = 0x40000000
}
#endregion
#region P/Invoke Methods
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern int FormatMessage(
int dwFlags,
IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
StringBuilder lpBuffer,
int nSize,
IntPtr vaListArguments);
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetFileSizeEx(SafeFileHandle handle, out long size);
[DllImport("kernel32.dll")]
private static extern int GetFileType(SafeFileHandle handle);
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFile(
string name,
NativeFileAccess access,
FileShare share,
IntPtr security,
FileMode mode,
NativeFileFlags flags,
IntPtr template);
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeleteFile(string name);
#endregion
#region Utility Methods
private static int MakeHRFromErrorCode(int errorCode) {
return (-2147024896 | errorCode);
}
private static string GetErrorMessage(int errorCode) {
var lpBuffer = new StringBuilder(0x200);
if(0 != FormatMessage(0x3200, IntPtr.Zero, errorCode, 0, lpBuffer, lpBuffer.Capacity, IntPtr.Zero)) {
return lpBuffer.ToString();
}
return "UnknownError: " + errorCode;
}
private static void ThrowIOError(int errorCode, string path) {
switch(errorCode) {
case 0: {
break;
}
case 2: // File not found
{
if(string.IsNullOrEmpty(path)) throw new FileNotFoundException();
throw new FileNotFoundException(null, path);
}
case 3: // Directory not found
{
if(string.IsNullOrEmpty(path)) throw new DirectoryNotFoundException();
throw new DirectoryNotFoundException("DirectoryNotFound: " + path);
}
case 5: // Access denied
{
if(string.IsNullOrEmpty(path)) throw new UnauthorizedAccessException();
throw new UnauthorizedAccessException("AccessDenied_Path: " + path);
}
case 15: // Drive not found
{
if(string.IsNullOrEmpty(path)) throw new DriveNotFoundException();
throw new DriveNotFoundException("DriveNotFound: " + path);
}
case 32: // Sharing violation
{
if(string.IsNullOrEmpty(path)) throw new IOException(GetErrorMessage(errorCode), MakeHRFromErrorCode(errorCode));
throw new IOException("SharingViolation: " + path, MakeHRFromErrorCode(errorCode));
}
case 80: // File already exists
{
if(!string.IsNullOrEmpty(path)) {
throw new IOException("FileAlreadyExists: " + path, MakeHRFromErrorCode(errorCode));
}
break;
}
case 87: // Invalid parameter
{
throw new IOException(GetErrorMessage(errorCode), MakeHRFromErrorCode(errorCode));
}
case 183: // File or directory already exists
{
if(!string.IsNullOrEmpty(path)) {
throw new IOException("AlreadyExists: " + path, MakeHRFromErrorCode(errorCode));
}
break;
}
case 206: // Path too long
{
throw new PathTooLongException();
}
case 995: // Operation cancelled
{
throw new OperationCanceledException();
}
default: {
Marshal.ThrowExceptionForHR(MakeHRFromErrorCode(errorCode));
break;
}
}
}
public static void ThrowLastIOError(string path) {
var errorCode = Marshal.GetLastWin32Error();
if(0 != errorCode) {
var hr = Marshal.GetHRForLastWin32Error();
if(0 <= hr) throw new Win32Exception(errorCode);
ThrowIOError(errorCode, path);
}
}
public static NativeFileAccess ToNative(this FileAccess access) {
NativeFileAccess result = 0;
if(FileAccess.Read == (FileAccess.Read & access)) result |= NativeFileAccess.GenericRead;
if(FileAccess.Write == (FileAccess.Write & access)) result |= NativeFileAccess.GenericWrite;
return result;
}
public static string BuildStreamPath(string filePath, string streamName) {
var result = filePath;
if(!string.IsNullOrEmpty(filePath)) {
if(1 == result.Length) result = ".\\" + result;
result += StreamSeparator + streamName + StreamSeparator + "$DATA";
if(MaxPath <= result.Length) result = LongPathPrefix + result;
}
return result;
}
public static bool SafeDeleteFile(string name) {
if(string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
var result = DeleteFile(name);
if(!result) {
var errorCode = Marshal.GetLastWin32Error();
if(ErrorFileNotFound != errorCode) ThrowLastIOError(name);
}
return result;
}
public static SafeFileHandle SafeCreateFile(string path, NativeFileAccess access, FileShare share, IntPtr security, FileMode mode, NativeFileFlags flags, IntPtr template) {
var result = CreateFile(path, access, share, security, mode, flags, template);
if(!result.IsInvalid && 1 != GetFileType(result)) {
result.Dispose();
throw new NotSupportedException("NonFile: " + path);
}
return result;
}
private static long GetFileSize(string path, SafeFileHandle handle) {
var result = 0L;
if(null != handle && !handle.IsInvalid) {
if(GetFileSizeEx(handle, out long value)) {
result = value;
} else {
ThrowLastIOError(path);
}
}
return result;
}
public static long GetFileSize(string path) {
var result = 0L;
if(!string.IsNullOrEmpty(path)) {
using var handle = SafeCreateFile(path, NativeFileAccess.GenericRead, FileShare.Read, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
result = GetFileSize(path, handle);
}
return result;
}
#endregion
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Globalization.GregorianCalendar.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Globalization
{
public partial class GregorianCalendar : Calendar
{
#region Methods and constructors
public override DateTime AddMonths(DateTime time, int months)
{
return default(DateTime);
}
public override DateTime AddYears(DateTime time, int years)
{
return default(DateTime);
}
public override int GetDayOfMonth(DateTime time)
{
return default(int);
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return default(DayOfWeek);
}
public override int GetDayOfYear(DateTime time)
{
return default(int);
}
public override int GetDaysInMonth(int year, int month, int era)
{
return default(int);
}
public override int GetDaysInYear(int year, int era)
{
return default(int);
}
public override int GetEra(DateTime time)
{
return default(int);
}
public override int GetLeapMonth(int year, int era)
{
return default(int);
}
public override int GetMonth(DateTime time)
{
return default(int);
}
public override int GetMonthsInYear(int year, int era)
{
return default(int);
}
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return default(int);
}
public override int GetYear(DateTime time)
{
return default(int);
}
public GregorianCalendar()
{
}
public GregorianCalendar(GregorianCalendarTypes type)
{
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return default(bool);
}
public override bool IsLeapMonth(int year, int month, int era)
{
return default(bool);
}
public override bool IsLeapYear(int year, int era)
{
return default(bool);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return default(DateTime);
}
public override int ToFourDigitYear(int year)
{
return default(int);
}
#endregion
#region Properties and indexers
public override CalendarAlgorithmType AlgorithmType
{
get
{
return default(CalendarAlgorithmType);
}
}
public virtual new GregorianCalendarTypes CalendarType
{
get
{
return default(GregorianCalendarTypes);
}
set
{
}
}
public override int[] Eras
{
get
{
return default(int[]);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return default(DateTime);
}
}
public override DateTime MinSupportedDateTime
{
get
{
return default(DateTime);
}
}
public override int TwoDigitYearMax
{
get
{
return default(int);
}
set
{
}
}
#endregion
#region Fields
public static int ADEra;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web.Models;
namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
/// <summary>
/// Represents an IPublishedContent which is created based on an Xml structure.
/// </summary>
[Serializable]
[XmlType(Namespace = "http://umbraco.org/webservices/")]
internal class XmlPublishedContent : PublishedContentWithKeyBase
{
/// <summary>
/// Initializes a new instance of the <c>XmlPublishedContent</c> class with an Xml node.
/// </summary>
/// <param name="xmlNode">The Xml node.</param>
/// <param name="isPreviewing">A value indicating whether the published content is being previewed.</param>
private XmlPublishedContent(XmlNode xmlNode, bool isPreviewing)
{
_xmlNode = xmlNode;
_isPreviewing = isPreviewing;
}
private readonly XmlNode _xmlNode;
private readonly bool _isPreviewing;
private bool _nodeInitialized;
private bool _parentInitialized;
private bool _childrenInitialized;
private IEnumerable<IPublishedContent> _children = Enumerable.Empty<IPublishedContent>();
private IPublishedContent _parent;
private PublishedContentType _contentType;
private Dictionary<string, IPublishedProperty> _properties;
private int _id;
private Guid _key;
private int _template;
private string _name;
private string _docTypeAlias;
private int _docTypeId;
private string _writerName;
private string _creatorName;
private int _writerId;
private int _creatorId;
private string _urlName;
private string _path;
private DateTime _createDate;
private DateTime _updateDate;
private Guid _version;
private int _sortOrder;
private int _level;
private bool _isDraft;
public override IEnumerable<IPublishedContent> Children
{
get
{
if (_nodeInitialized == false) InitializeNode();
if (_childrenInitialized == false) InitializeChildren();
return _children;
}
}
public override IPublishedProperty GetProperty(string alias)
{
if (_nodeInitialized == false) InitializeNode();
IPublishedProperty property;
return _properties.TryGetValue(alias, out property) ? property : null;
}
// override to implement cache
// cache at context level, ie once for the whole request
// but cache is not shared by requests because we wouldn't know how to clear it
public override IPublishedProperty GetProperty(string alias, bool recurse)
{
if (recurse == false) return GetProperty(alias);
var cache = UmbracoContextCache.Current;
if (cache == null)
return base.GetProperty(alias, true);
var key = string.Format("RECURSIVE_PROPERTY::{0}::{1}", Id, alias.ToLowerInvariant());
var value = cache.GetOrAdd(key, k => base.GetProperty(alias, true));
if (value == null)
return null;
var property = value as IPublishedProperty;
if (property == null)
throw new InvalidOperationException("Corrupted cache.");
return property;
}
public override PublishedItemType ItemType
{
get { return PublishedItemType.Content; }
}
public override IPublishedContent Parent
{
get
{
if (_nodeInitialized == false) InitializeNode();
if (_parentInitialized == false) InitializeParent();
return _parent;
}
}
public override int Id
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _id;
}
}
public override Guid Key
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _key;
}
}
public override int TemplateId
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _template;
}
}
public override int SortOrder
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _sortOrder;
}
}
public override string Name
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _name;
}
}
public override string DocumentTypeAlias
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _docTypeAlias;
}
}
public override int DocumentTypeId
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _docTypeId;
}
}
public override string WriterName
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _writerName;
}
}
public override string CreatorName
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _creatorName;
}
}
public override int WriterId
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _writerId;
}
}
public override int CreatorId
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _creatorId;
}
}
public override string Path
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _path;
}
}
public override DateTime CreateDate
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _createDate;
}
}
public override DateTime UpdateDate
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _updateDate;
}
}
public override Guid Version
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _version;
}
}
public override string UrlName
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _urlName;
}
}
public override int Level
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _level;
}
}
public override bool IsDraft
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _isDraft;
}
}
public override ICollection<IPublishedProperty> Properties
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _properties.Values;
}
}
public override PublishedContentType ContentType
{
get
{
if (_nodeInitialized == false) InitializeNode();
return _contentType;
}
}
private void InitializeParent()
{
if (_xmlNode == null) return;
var parent = _xmlNode.ParentNode;
if (parent == null) return;
if (parent.Name == "node" || (parent.Attributes != null && parent.Attributes.GetNamedItem("isDoc") != null))
_parent = Get(parent, _isPreviewing);
// warn: this is not thread-safe...
_parentInitialized = true;
}
private void InitializeNode()
{
if (_xmlNode == null) return;
if (_xmlNode.Attributes != null)
{
_id = int.Parse(_xmlNode.Attributes.GetNamedItem("id").Value);
if (_xmlNode.Attributes.GetNamedItem("key") != null) // because, migration
_key = Guid.Parse(_xmlNode.Attributes.GetNamedItem("key").Value);
if (_xmlNode.Attributes.GetNamedItem("template") != null)
_template = int.Parse(_xmlNode.Attributes.GetNamedItem("template").Value);
if (_xmlNode.Attributes.GetNamedItem("sortOrder") != null)
_sortOrder = int.Parse(_xmlNode.Attributes.GetNamedItem("sortOrder").Value);
if (_xmlNode.Attributes.GetNamedItem("nodeName") != null)
_name = _xmlNode.Attributes.GetNamedItem("nodeName").Value;
if (_xmlNode.Attributes.GetNamedItem("writerName") != null)
_writerName = _xmlNode.Attributes.GetNamedItem("writerName").Value;
if (_xmlNode.Attributes.GetNamedItem("urlName") != null)
_urlName = _xmlNode.Attributes.GetNamedItem("urlName").Value;
// Creatorname is new in 2.1, so published xml might not have it!
try
{
_creatorName = _xmlNode.Attributes.GetNamedItem("creatorName").Value;
}
catch
{
_creatorName = _writerName;
}
//Added the actual userID, as a user cannot be looked up via full name only...
if (_xmlNode.Attributes.GetNamedItem("creatorID") != null)
_creatorId = int.Parse(_xmlNode.Attributes.GetNamedItem("creatorID").Value);
if (_xmlNode.Attributes.GetNamedItem("writerID") != null)
_writerId = int.Parse(_xmlNode.Attributes.GetNamedItem("writerID").Value);
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
if (_xmlNode.Attributes.GetNamedItem("nodeTypeAlias") != null)
_docTypeAlias = _xmlNode.Attributes.GetNamedItem("nodeTypeAlias").Value;
}
else
{
_docTypeAlias = _xmlNode.Name;
}
if (_xmlNode.Attributes.GetNamedItem("nodeType") != null)
_docTypeId = int.Parse(_xmlNode.Attributes.GetNamedItem("nodeType").Value);
if (_xmlNode.Attributes.GetNamedItem("path") != null)
_path = _xmlNode.Attributes.GetNamedItem("path").Value;
if (_xmlNode.Attributes.GetNamedItem("version") != null)
_version = new Guid(_xmlNode.Attributes.GetNamedItem("version").Value);
if (_xmlNode.Attributes.GetNamedItem("createDate") != null)
_createDate = DateTime.Parse(_xmlNode.Attributes.GetNamedItem("createDate").Value);
if (_xmlNode.Attributes.GetNamedItem("updateDate") != null)
_updateDate = DateTime.Parse(_xmlNode.Attributes.GetNamedItem("updateDate").Value);
if (_xmlNode.Attributes.GetNamedItem("level") != null)
_level = int.Parse(_xmlNode.Attributes.GetNamedItem("level").Value);
_isDraft = (_xmlNode.Attributes.GetNamedItem("isDraft") != null);
}
// load data
var dataXPath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "data" : "* [not(@isDoc)]";
var nodes = _xmlNode.SelectNodes(dataXPath);
_contentType = PublishedContentType.Get(PublishedItemType.Content, _docTypeAlias);
var propertyNodes = new Dictionary<string, XmlNode>();
if (nodes != null)
foreach (XmlNode n in nodes)
{
var attrs = n.Attributes;
if (attrs == null) continue;
var alias = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema
? attrs.GetNamedItem("alias").Value
: n.Name;
propertyNodes[alias.ToLowerInvariant()] = n;
}
_properties = _contentType.PropertyTypes.Select(p =>
{
XmlNode n;
return propertyNodes.TryGetValue(p.PropertyTypeAlias.ToLowerInvariant(), out n)
? new XmlPublishedProperty(p, _isPreviewing, n)
: new XmlPublishedProperty(p, _isPreviewing);
}).Cast<IPublishedProperty>().ToDictionary(
x => x.PropertyTypeAlias,
x => x,
StringComparer.OrdinalIgnoreCase);
// warn: this is not thread-safe...
_nodeInitialized = true;
}
private void InitializeChildren()
{
if (_xmlNode == null) return;
// load children
var childXPath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : "* [@isDoc]";
var nav = _xmlNode.CreateNavigator();
var expr = nav.Compile(childXPath);
//expr.AddSort("@sortOrder", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
var iterator = nav.Select(expr);
_children = iterator.Cast<XPathNavigator>()
.Select(n => Get(((IHasXmlNode) n).GetNode(), _isPreviewing))
.OrderBy(x => x.SortOrder)
.ToList();
// warn: this is not thread-safe
_childrenInitialized = true;
}
/// <summary>
/// Gets an IPublishedContent corresponding to an Xml cache node.
/// </summary>
/// <param name="node">The Xml node.</param>
/// <param name="isPreviewing">A value indicating whether we are previewing or not.</param>
/// <returns>The IPublishedContent corresponding to the Xml cache node.</returns>
/// <remarks>Maintains a per-request cache of IPublishedContent items in order to make
/// sure that we create only one instance of each for the duration of a request. The
/// returned IPublishedContent is a model, if models are enabled.</remarks>
public static IPublishedContent Get(XmlNode node, bool isPreviewing)
{
// only 1 per request
var attrs = node.Attributes;
var id = attrs == null ? null : attrs.GetNamedItem("id").Value;
if (id.IsNullOrWhiteSpace()) throw new InvalidOperationException("Node has no ID attribute.");
var cache = ApplicationContext.Current.ApplicationCache.RequestCache;
var key = CacheKeyPrefix + id; // dont bother with preview, wont change during request in v7
return (IPublishedContent) cache.GetCacheItem(key, () => (new XmlPublishedContent(node, isPreviewing)).CreateModel());
}
public static void ClearRequest()
{
ApplicationContext.Current.ApplicationCache.RequestCache.ClearCacheByKeySearch(CacheKeyPrefix);
}
private const string CacheKeyPrefix = "CONTENTCACHE_XMLPUBLISHEDCONTENT_";
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.ServiceBus.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Formatting = Newtonsoft.Json.Formatting;
namespace GaboG.ServiceBusRelayUtil
{
[ServiceContract(Namespace = "http://samples.microsoft.com/ServiceModel/Relay/")]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
internal class DispatcherService
{
private static readonly HashSet<string> _httpContentHeaders = new HashSet<string>
{
"Allow",
"Content-Encoding",
"Content-Language",
"Content-Length",
"Content-Location",
"Content-MD5",
"Content-Range",
"Content-Type",
"Expires",
"Last-Modified"
};
private readonly ServiceBusRelayUtilConfig _config;
public DispatcherService(ServiceBusRelayUtilConfig config)
{
_config = config;
}
[WebGet(UriTemplate = "*")]
[OperationContract(AsyncPattern = true)]
public async Task<Message> GetAsync()
{
try
{
var ti0 = DateTime.Now;
Console.WriteLine("In GetAsync:");
var context = WebOperationContext.Current;
var request = BuildForwardedRequest(context, null);
Console.WriteLine("...calling {0}...", request.RequestUri);
HttpResponseMessage response;
using (var client = new HttpClient())
{
response = await client.SendAsync(request, CancellationToken.None);
}
Console.WriteLine("...and back {0:N0} ms...", DateTime.Now.Subtract(ti0).TotalMilliseconds);
Console.WriteLine("");
Console.WriteLine("...reading and creating response...");
CopyHttpResponseMessageToOutgoingResponse(response, context.OutgoingResponse);
var stream = response.Content != null ? await response.Content.ReadAsStreamAsync() : null;
var message = StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream());
Console.WriteLine("...and done (total time: {0:N0} ms).", DateTime.Now.Subtract(ti0).TotalMilliseconds);
Console.WriteLine("");
return message;
}
catch (Exception ex)
{
WriteException(ex);
throw;
}
}
[WebInvoke(UriTemplate = "*", Method = "*")]
[OperationContract(AsyncPattern = true)]
public async Task<Message> InvokeAsync(Message msg)
{
try
{
var ti0 = DateTime.Now;
WriteFlowerLine();
Console.WriteLine("In InvokeAsync:");
var context = WebOperationContext.Current;
var request = BuildForwardedRequest(context, msg);
Console.WriteLine("...calling {0}", request.RequestUri);
HttpResponseMessage response;
using (var client = new HttpClient())
{
response = await client.SendAsync(request, CancellationToken.None);
}
Console.WriteLine("...and done {0:N0} ms...", DateTime.Now.Subtract(ti0).TotalMilliseconds);
Console.WriteLine("...reading and creating response...");
CopyHttpResponseMessageToOutgoingResponse(response, context.OutgoingResponse);
var stream = response.Content != null ? await response.Content.ReadAsStreamAsync() : null;
var message = StreamMessageHelper.CreateMessage(MessageVersion.None, "GETRESPONSE", stream ?? new MemoryStream());
Console.WriteLine("...and done (total time: {0:N0} ms).", DateTime.Now.Subtract(ti0).TotalMilliseconds);
return message;
}
catch (Exception ex)
{
WriteException(ex);
throw;
}
}
private HttpRequestMessage BuildForwardedRequest(WebOperationContext context, Message msg)
{
var incomingRequest = context.IncomingRequest;
var mappedUri = new Uri(incomingRequest.UriTemplateMatch.RequestUri.ToString().Replace(_config.RelayAddress.ToString(), _config.TargetAddress.ToString()));
var newRequest = new HttpRequestMessage(new HttpMethod(incomingRequest.Method), mappedUri);
// Copy headers
var hostHeader = _config.TargetAddress.Host + (_config.TargetAddress.Port != 80 || _config.TargetAddress.Port != 443 ? ":" + _config.TargetAddress.Port : "");
foreach (var name in incomingRequest.Headers.AllKeys.Where(name => !_httpContentHeaders.Contains(name)))
{
newRequest.Headers.TryAddWithoutValidation(name, name == "Host" ? hostHeader : incomingRequest.Headers.Get(name));
}
if (msg != null)
{
Stream messageStream = null;
if (msg.Properties.TryGetValue("WebBodyFormatMessageProperty", out var value))
{
if (value is WebBodyFormatMessageProperty prop && (prop.Format == WebContentFormat.Json || prop.Format == WebContentFormat.Raw))
{
messageStream = StreamMessageHelper.GetStream(msg);
}
}
else
{
var ms = new MemoryStream();
using (var xw = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false))
{
msg.WriteBodyContents(xw);
}
ms.Seek(0, SeekOrigin.Begin);
messageStream = ms;
}
if (messageStream != null)
{
if (_config.BufferRequestContent)
{
var ms1 = new MemoryStream();
messageStream.CopyTo(ms1);
ms1.Seek(0, SeekOrigin.Begin);
newRequest.Content = new StreamContent(ms1);
}
else
{
var ms1 = new MemoryStream();
messageStream.CopyTo(ms1);
ms1.Seek(0, SeekOrigin.Begin);
var debugMs = new MemoryStream();
ms1.CopyTo(debugMs);
debugMs.Seek(0, SeekOrigin.Begin);
var result = Encoding.UTF8.GetString(debugMs.ToArray());
WriteJsonObject(result);
ms1.Seek(0, SeekOrigin.Begin);
newRequest.Content = new StreamContent(ms1);
}
foreach (var name in incomingRequest.Headers.AllKeys.Where(name => _httpContentHeaders.Contains(name)))
{
newRequest.Content.Headers.TryAddWithoutValidation(name, incomingRequest.Headers.Get(name));
}
}
}
return newRequest;
}
private static void WriteException(Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex);
Console.WriteLine("");
Console.ResetColor();
}
private static void WriteJsonObject(string result)
{
Console.ForegroundColor = ConsoleColor.Yellow;
var formatted = result;
if (IsValidJson(result))
{
var s = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
dynamic o = JsonConvert.DeserializeObject(result);
formatted = JsonConvert.SerializeObject(o, s);
}
Console.WriteLine(formatted);
Console.ResetColor();
}
private static void WriteFlowerLine()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\r\n=> {0:MM/dd/yyyy hh:mm:ss.fff tt} {1}", DateTime.Now, new string('*', 80));
Console.ResetColor();
}
private static void CopyHttpResponseMessageToOutgoingResponse(HttpResponseMessage response, OutgoingWebResponseContext outgoingResponse)
{
outgoingResponse.StatusCode = response.StatusCode;
outgoingResponse.StatusDescription = response.ReasonPhrase;
if (response.Content == null)
{
outgoingResponse.SuppressEntityBody = true;
}
foreach (var kvp in response.Headers)
{
foreach (var value in kvp.Value)
{
outgoingResponse.Headers.Add(kvp.Key, value);
}
}
if (response.Content != null)
{
foreach (var kvp in response.Content.Headers)
{
foreach (var value in kvp.Value)
{
outgoingResponse.Headers.Add(kvp.Key, value);
}
}
}
}
private static bool IsValidJson(string strInput)
{
strInput = strInput.Trim();
if ((!strInput.StartsWith("{") || !strInput.EndsWith("}")) && (!strInput.StartsWith("[") || !strInput.EndsWith("]")))
{
return false;
}
try
{
JToken.Parse(strInput);
return true;
}
catch //some other exception
{
return false;
}
}
}
}
| |
//
// PlayerInterface.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena.Gui;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Widgets;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Database;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.MediaEngine;
using Banshee.Configuration;
using Banshee.Preferences;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Gui.Dialogs;
using Banshee.Widgets;
using Banshee.Collection.Gui;
using Banshee.Sources.Gui;
using Banshee.PlayQueue;
namespace Muinshee
{
public class PlayerInterface : BaseClientWindow, IClientWindow, IDBusObjectName, IService, IDisposable
{
const string CONFIG_NAMESPACE = "muinshee";
const int DEFAULT_WIDTH = -1;
const int DEFAULT_HEIGHT = 450;
static readonly SchemaEntry<int> WidthSchema = WindowConfiguration.NewWidthSchema (CONFIG_NAMESPACE, DEFAULT_WIDTH);
static readonly SchemaEntry<int> HeightSchema = WindowConfiguration.NewHeightSchema (CONFIG_NAMESPACE, DEFAULT_HEIGHT);
static readonly SchemaEntry<int> XPosSchema = WindowConfiguration.NewXPosSchema (CONFIG_NAMESPACE);
static readonly SchemaEntry<int> YPosSchema = WindowConfiguration.NewYPosSchema (CONFIG_NAMESPACE);
static readonly SchemaEntry<bool> MaximizedSchema = WindowConfiguration.NewMaximizedSchema (CONFIG_NAMESPACE);
// Major Layout Components
private VBox content_vbox;
private VBox main_vbox;
private Toolbar header_toolbar;
private MuinsheeActions actions;
// Major Interaction Components
private TerseTrackListView track_view;
private Label list_label;
private int played_songs_number = -1;
private SchemaPreference<int> played_songs_number_pref;
public PlayerInterface () :
base (Catalog.GetString ("Banshee Media Player"),
new WindowConfiguration (WidthSchema, HeightSchema, XPosSchema, YPosSchema, MaximizedSchema))
{
}
protected override void Initialize ()
{
FindPlayQueue ();
}
private void FindPlayQueue ()
{
Banshee.ServiceStack.ServiceManager.SourceManager.SourceAdded += delegate (SourceAddedArgs args) {
if (args.Source is Banshee.PlayQueue.PlayQueueSource) {
InitPlayQueue (args.Source as Banshee.PlayQueue.PlayQueueSource);
}
};
foreach (Source src in ServiceManager.SourceManager.Sources) {
if (src is Banshee.PlayQueue.PlayQueueSource) {
InitPlayQueue (src as Banshee.PlayQueue.PlayQueueSource);
}
}
}
private void InitPlayQueue (PlayQueueSource play_queue)
{
if (actions == null) {
play_queue.Populate = false;
played_songs_number = PlayQueueSource.PlayedSongsNumberSchema.Get ();
var service = ServiceManager.Get<PreferenceService> ();
var section = service["source-specific"].ChildPages[play_queue.PreferencesPageId][null];
played_songs_number_pref = (SchemaPreference<int>) section[PlayQueueSource.PlayedSongsNumberSchema.Key];
played_songs_number_pref.Value = 0;
actions = new MuinsheeActions (play_queue);
actions.Actions.AddActionGroup (actions);
ServiceManager.SourceManager.SetActiveSource (play_queue);
play_queue.TrackModel.Reloaded += HandleTrackModelReloaded;
BuildPrimaryLayout ();
ConnectEvents ();
track_view.SetModel (play_queue.TrackModel);
InitialShowPresent ();
}
}
#region System Overrides
protected override void Dispose (bool disposing)
{
lock (this) {
if (disposing) {
Hide ();
if (played_songs_number >= 0) {
played_songs_number_pref.Value = played_songs_number;
}
if (actions != null) {
actions.Dispose ();
}
}
base.Dispose (disposing);
Gtk.Application.Quit ();
}
}
#endregion
#region Interface Construction
private void BuildPrimaryLayout ()
{
main_vbox = new VBox ();
Widget menu = new MainMenu ();
menu.Show ();
main_vbox.PackStart (menu, false, false, 0);
BuildHeader ();
content_vbox = new VBox ();
content_vbox.Spacing = 6;
Alignment content_align = new Alignment (0f, 0f, 1f, 1f);
content_align.LeftPadding = content_align.RightPadding = 6;
content_align.Child = content_vbox;
main_vbox.PackStart (content_align, true, true, 0);
BuildTrackInfo ();
BuildViews ();
main_vbox.ShowAll ();
Add (main_vbox);
}
private void BuildHeader ()
{
Alignment toolbar_alignment = new Alignment (0.0f, 0.0f, 1.0f, 1.0f);
toolbar_alignment.TopPadding = 3;
toolbar_alignment.BottomPadding = 3;
header_toolbar = (Toolbar)ActionService.UIManager.GetWidget ("/MuinsheeHeaderToolbar");
header_toolbar.ShowArrow = false;
header_toolbar.ToolbarStyle = ToolbarStyle.BothHoriz;
toolbar_alignment.Add (header_toolbar);
toolbar_alignment.ShowAll ();
main_vbox.PackStart (toolbar_alignment, false, false, 0);
Widget next_button = new NextButton (ActionService);
next_button.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/MuinsheeHeaderToolbar/NextArrowButton", next_button);
ConnectedVolumeButton volume_button = new ConnectedVolumeButton ();
volume_button.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/MuinsheeHeaderToolbar/VolumeButton", volume_button);
}
private const int info_height = 64;
private void BuildTrackInfo ()
{
TrackInfoDisplay track_info_display = new MuinsheeTrackInfoDisplay ();
if (track_info_display.HeightRequest < info_height) {
track_info_display.HeightRequest = info_height;
}
track_info_display.Show ();
content_vbox.PackStart (track_info_display, false, false, 0);
ConnectedSeekSlider seek_slider = new ConnectedSeekSlider (SeekSliderLayout.Horizontal);
seek_slider.LeftPadding = seek_slider.RightPadding = 0;
content_vbox.PackStart (seek_slider, false, false, 0);
}
private void BuildViews ()
{
track_view = new TerseTrackListView ();
track_view.HasFocus = true;
track_view.IsReorderable = true;
track_view.ColumnController.Insert (new Column (null, "indicator", new ColumnCellStatusIndicator (null), 0.05, true, 20, 20), 0);
Hyena.Widgets.ScrolledWindow sw = new Hyena.Widgets.ScrolledWindow ();
sw.Add (track_view);
/*window.Add (view);
window.HscrollbarPolicy = PolicyType.Automatic;
window.VscrollbarPolicy = PolicyType.Automatic;*/
list_label = new Label ();
list_label.Xalign = 0f;
content_vbox.PackStart (list_label, false, false, 0);
content_vbox.PackStart (sw, true, true, 0);
content_vbox.PackStart (new UserJobTileHost (), false, false, 0);
track_view.SetSizeRequest (425, -1);
}
#endregion
#region Events and Logic Setup
protected override void ConnectEvents ()
{
base.ConnectEvents ();
ServiceManager.SourceManager.SourceUpdated += OnSourceUpdated;
// FIXME: confirm that this is not needed anymore
//header_toolbar.ExposeEvent += OnToolbarExposeEvent;
}
#endregion
#region Service Event Handlers
private void OnSourceUpdated (SourceEventArgs args)
{
if (args.Source == ServiceManager.SourceManager.ActiveSource) {
UpdateSourceInformation ();
}
}
#endregion
#region Helper Functions
private void HandleTrackModelReloaded (object sender, EventArgs args)
{
UpdateSourceInformation ();
}
private void UpdateSourceInformation ()
{
DatabaseSource source = ServiceManager.SourceManager.ActiveSource as DatabaseSource;
if (source != null) {
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
Source.DurationStatusFormatters[source.CurrentStatusFormat] (sb, source.Duration);
list_label.Markup = String.Format ("<b>{0}</b> ({1})",
source.Name, String.Format (Catalog.GetString ("{0} remaining"), sb.ToString ())
);
}
}
#endregion
#region Configuration Schemas
#endregion
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
string IDBusObjectName.ExportObjectName {
get { return "MuinsheeClientWindow"; }
}
string IService.ServiceName {
get { return "MuinsheePlayerInterface"; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Specifies global messaging configuration that are common to client and silo.
/// </summary>
public interface IMessagingConfiguration
{
/// <summary>
/// The ResponseTimeout attribute specifies the default timeout before a request is assumed to have failed.
/// </summary>
TimeSpan ResponseTimeout { get; set; }
/// <summary>
/// The MaxResendCount attribute specifies the maximal number of resends of the same message.
/// </summary>
int MaxResendCount { get; set; }
/// <summary>
/// The ResendOnTimeout attribute specifies whether the message should be automaticaly resend by the runtime when it times out on the sender.
/// Default is false.
/// </summary>
bool ResendOnTimeout { get; set; }
/// <summary>
/// The MaxSocketAge attribute specifies how long to keep an open socket before it is closed.
/// Default is TimeSpan.MaxValue (never close sockets automatically, unles they were broken).
/// </summary>
TimeSpan MaxSocketAge { get; set; }
/// <summary>
/// The DropExpiredMessages attribute specifies whether the message should be dropped if it has expired, that is if it was not delivered
/// to the destination before it has timed out on the sender.
/// Default is true.
/// </summary>
bool DropExpiredMessages { get; set; }
/// <summary>
/// The SiloSenderQueues attribute specifies the number of parallel queues and attendant threads used by the silo to send outbound
/// messages (requests, responses, and notifications) to other silos.
/// If this attribute is not specified, then System.Environment.ProcessorCount is used.
/// </summary>
int SiloSenderQueues { get; set; }
/// <summary>
/// The GatewaySenderQueues attribute specifies the number of parallel queues and attendant threads used by the silo Gateway to send outbound
/// messages (requests, responses, and notifications) to clients that are connected to it.
/// If this attribute is not specified, then System.Environment.ProcessorCount is used.
/// </summary>
int GatewaySenderQueues { get; set; }
/// <summary>
/// The ClientSenderBuckets attribute specifies the total number of grain buckets used by the client in client-to-gateway communication
/// protocol. In this protocol, grains are mapped to buckets and buckets are mapped to gateway connections, in order to enable stickiness
/// of grain to gateway (messages to the same grain go to the same gateway, while evenly spreading grains across gateways).
/// This number should be about 10 to 100 times larger than the expected number of gateway connections.
/// If this attribute is not specified, then Math.Pow(2, 13) is used.
/// </summary>
int ClientSenderBuckets { get; set; }
/// <summary>
/// This is the period of time a gateway will wait before dropping a disconnected client.
/// </summary>
TimeSpan ClientDropTimeout { get; set; }
/// <summary>
/// The UseStandardSerializer attribute, if provided and set to "true", forces the use of the standard .NET serializer instead
/// of the custom Orleans serializer.
/// This parameter is intended for use only for testing and troubleshooting.
/// In production, the custom Orleans serializer should always be used because it performs significantly better.
/// </summary>
bool UseStandardSerializer { get; set; }
/// <summary>
/// The size of a buffer in the messaging buffer pool.
/// </summary>
int BufferPoolBufferSize { get; set; }
/// <summary>
/// The maximum size of the messaging buffer pool.
/// </summary>
int BufferPoolMaxSize { get; set; }
/// <summary>
/// The initial size of the messaging buffer pool that is pre-allocated.
/// </summary>
int BufferPoolPreallocationSize { get; set; }
/// <summary>
/// Whether to use automatic batching of messages. Default is false.
/// </summary>
bool UseMessageBatching { get; set; }
/// <summary>
/// The maximum batch size for automatic batching of messages, when message batching is used.
/// </summary>
int MaxMessageBatchingSize { get; set; }
/// <summary>
/// The list of serialization providers
/// </summary>
List<TypeInfo> SerializationProviders { get; }
}
/// <summary>
/// Messaging configuration that are common to client and silo.
/// </summary>
[Serializable]
public class MessagingConfiguration : IMessagingConfiguration
{
public TimeSpan ResponseTimeout { get; set; }
public int MaxResendCount { get; set; }
public bool ResendOnTimeout { get; set; }
public TimeSpan MaxSocketAge { get; set; }
public bool DropExpiredMessages { get; set; }
public int SiloSenderQueues { get; set; }
public int GatewaySenderQueues { get; set; }
public int ClientSenderBuckets { get; set; }
public TimeSpan ClientDropTimeout { get; set; }
public bool UseStandardSerializer { get; set; }
public bool UseJsonFallbackSerializer { get; set; }
public int BufferPoolBufferSize { get; set; }
public int BufferPoolMaxSize { get; set; }
public int BufferPoolPreallocationSize { get; set; }
public bool UseMessageBatching { get; set; }
public int MaxMessageBatchingSize { get; set; }
/// <summary>
/// The MaxForwardCount attribute specifies the maximal number of times a message is being forwared from one silo to another.
/// Forwarding is used internally by the tuntime as a recovery mechanism when silos fail and the membership is unstable.
/// In such times the messages might not be routed correctly to destination, and runtime attempts to forward such messages a number of times before rejecting them.
/// </summary>
public int MaxForwardCount { get; set; }
public List<TypeInfo> SerializationProviders { get; private set; }
internal double RejectionInjectionRate { get; set; }
internal double MessageLossInjectionRate { get; set; }
private static readonly TimeSpan DEFAULT_MAX_SOCKET_AGE = TimeSpan.MaxValue;
internal const int DEFAULT_MAX_FORWARD_COUNT = 2;
private const bool DEFAULT_RESEND_ON_TIMEOUT = false;
private const bool DEFAULT_USE_STANDARD_SERIALIZER = false;
private static readonly int DEFAULT_SILO_SENDER_QUEUES = Environment.ProcessorCount;
private static readonly int DEFAULT_GATEWAY_SENDER_QUEUES = Environment.ProcessorCount;
private static readonly int DEFAULT_CLIENT_SENDER_BUCKETS = (int)Math.Pow(2, 13);
private const int DEFAULT_BUFFER_POOL_BUFFER_SIZE = 4 * 1024;
private const int DEFAULT_BUFFER_POOL_MAX_SIZE = 10000;
private const int DEFAULT_BUFFER_POOL_PREALLOCATION_SIZE = 250;
private const bool DEFAULT_DROP_EXPIRED_MESSAGES = true;
private const double DEFAULT_ERROR_INJECTION_RATE = 0.0;
private const bool DEFAULT_USE_MESSAGE_BATCHING = false;
private const int DEFAULT_MAX_MESSAGE_BATCH_SIZE = 10;
private readonly bool isSiloConfig;
internal MessagingConfiguration(bool isSilo)
{
isSiloConfig = isSilo;
ResponseTimeout = Constants.DEFAULT_RESPONSE_TIMEOUT;
MaxResendCount = 0;
ResendOnTimeout = DEFAULT_RESEND_ON_TIMEOUT;
MaxSocketAge = DEFAULT_MAX_SOCKET_AGE;
DropExpiredMessages = DEFAULT_DROP_EXPIRED_MESSAGES;
SiloSenderQueues = DEFAULT_SILO_SENDER_QUEUES;
GatewaySenderQueues = DEFAULT_GATEWAY_SENDER_QUEUES;
ClientSenderBuckets = DEFAULT_CLIENT_SENDER_BUCKETS;
ClientDropTimeout = Constants.DEFAULT_CLIENT_DROP_TIMEOUT;
UseStandardSerializer = DEFAULT_USE_STANDARD_SERIALIZER;
BufferPoolBufferSize = DEFAULT_BUFFER_POOL_BUFFER_SIZE;
BufferPoolMaxSize = DEFAULT_BUFFER_POOL_MAX_SIZE;
BufferPoolPreallocationSize = DEFAULT_BUFFER_POOL_PREALLOCATION_SIZE;
if (isSiloConfig)
{
MaxForwardCount = DEFAULT_MAX_FORWARD_COUNT;
RejectionInjectionRate = DEFAULT_ERROR_INJECTION_RATE;
MessageLossInjectionRate = DEFAULT_ERROR_INJECTION_RATE;
}
else
{
MaxForwardCount = 0;
RejectionInjectionRate = 0.0;
MessageLossInjectionRate = 0.0;
}
UseMessageBatching = DEFAULT_USE_MESSAGE_BATCHING;
MaxMessageBatchingSize = DEFAULT_MAX_MESSAGE_BATCH_SIZE;
SerializationProviders = new List<TypeInfo>();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat(" Messaging:").AppendLine();
sb.AppendFormat(" Response timeout: {0}", ResponseTimeout).AppendLine();
sb.AppendFormat(" Maximum resend count: {0}", MaxResendCount).AppendLine();
sb.AppendFormat(" Resend On Timeout: {0}", ResendOnTimeout).AppendLine();
sb.AppendFormat(" Maximum Socket Age: {0}", MaxSocketAge).AppendLine();
sb.AppendFormat(" Drop Expired Messages: {0}", DropExpiredMessages).AppendLine();
if (isSiloConfig)
{
sb.AppendFormat(" Silo Sender queues: {0}", SiloSenderQueues).AppendLine();
sb.AppendFormat(" Gateway Sender queues: {0}", GatewaySenderQueues).AppendLine();
sb.AppendFormat(" Client Drop Timeout: {0}", ClientDropTimeout).AppendLine();
}
else
{
sb.AppendFormat(" Client Sender Buckets: {0}", ClientSenderBuckets).AppendLine();
}
sb.AppendFormat(" Use standard (.NET) serializer: {0}", UseStandardSerializer)
.AppendLine(isSiloConfig ? "" : " [NOTE: This *MUST* match the setting on the server or nothing will work!]");
sb.AppendFormat(" Use fallback json serializer: {0}", UseJsonFallbackSerializer)
.AppendLine(isSiloConfig ? "" : " [NOTE: This *MUST* match the setting on the server or nothing will work!]");
sb.AppendFormat(" Buffer Pool Buffer Size: {0}", BufferPoolBufferSize).AppendLine();
sb.AppendFormat(" Buffer Pool Max Size: {0}", BufferPoolMaxSize).AppendLine();
sb.AppendFormat(" Buffer Pool Preallocation Size: {0}", BufferPoolPreallocationSize).AppendLine();
sb.AppendFormat(" Use Message Batching: {0}", UseMessageBatching).AppendLine();
sb.AppendFormat(" Max Message Batching Size: {0}", MaxMessageBatchingSize).AppendLine();
if (isSiloConfig)
{
sb.AppendFormat(" Maximum forward count: {0}", MaxForwardCount).AppendLine();
}
SerializationProviders.ForEach(sp =>
sb.AppendFormat(" Serialization provider: {0}", sp.FullName).AppendLine());
return sb.ToString();
}
internal virtual void Load(XmlElement child)
{
ResponseTimeout = child.HasAttribute("ResponseTimeout")
? ConfigUtilities.ParseTimeSpan(child.GetAttribute("ResponseTimeout"),
"Invalid ResponseTimeout")
: Constants.DEFAULT_RESPONSE_TIMEOUT;
if (child.HasAttribute("MaxResendCount"))
{
MaxResendCount = ConfigUtilities.ParseInt(child.GetAttribute("MaxResendCount"),
"Invalid integer value for the MaxResendCount attribute on the Messaging element");
}
if (child.HasAttribute("ResendOnTimeout"))
{
ResendOnTimeout = ConfigUtilities.ParseBool(child.GetAttribute("ResendOnTimeout"),
"Invalid Boolean value for the ResendOnTimeout attribute on the Messaging element");
}
if (child.HasAttribute("MaxSocketAge"))
{
MaxSocketAge = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxSocketAge"),
"Invalid time span set for the MaxSocketAge attribute on the Messaging element");
}
if (child.HasAttribute("DropExpiredMessages"))
{
DropExpiredMessages = ConfigUtilities.ParseBool(child.GetAttribute("DropExpiredMessages"),
"Invalid integer value for the DropExpiredMessages attribute on the Messaging element");
}
//--
if (isSiloConfig)
{
if (child.HasAttribute("SiloSenderQueues"))
{
SiloSenderQueues = ConfigUtilities.ParseInt(child.GetAttribute("SiloSenderQueues"),
"Invalid integer value for the SiloSenderQueues attribute on the Messaging element");
}
if (child.HasAttribute("GatewaySenderQueues"))
{
GatewaySenderQueues = ConfigUtilities.ParseInt(child.GetAttribute("GatewaySenderQueues"),
"Invalid integer value for the GatewaySenderQueues attribute on the Messaging element");
}
ClientDropTimeout = child.HasAttribute("ClientDropTimeout")
? ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientDropTimeout"),
"Invalid ClientDropTimeout")
: Constants.DEFAULT_CLIENT_DROP_TIMEOUT;
}
else
{
if (child.HasAttribute("ClientSenderBuckets"))
{
ClientSenderBuckets = ConfigUtilities.ParseInt(child.GetAttribute("ClientSenderBuckets"),
"Invalid integer value for the ClientSenderBuckets attribute on the Messaging element");
}
}
if (child.HasAttribute("UseStandardSerializer"))
{
UseStandardSerializer =
ConfigUtilities.ParseBool(child.GetAttribute("UseStandardSerializer"),
"invalid boolean value for the UseStandardSerializer attribute on the Messaging element");
}
if (child.HasAttribute("UseJsonFallbackSerializer"))
{
UseJsonFallbackSerializer =
ConfigUtilities.ParseBool(child.GetAttribute("UseJsonFallbackSerializer"),
"invalid boolean value for the UseJsonFallbackSerializer attribute on the Messaging element");
}
//--
if (child.HasAttribute("BufferPoolBufferSize"))
{
BufferPoolBufferSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolBufferSize"),
"Invalid integer value for the BufferPoolBufferSize attribute on the Messaging element");
}
if (child.HasAttribute("BufferPoolMaxSize"))
{
BufferPoolMaxSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolMaxSize"),
"Invalid integer value for the BufferPoolMaxSize attribute on the Messaging element");
}
if (child.HasAttribute("BufferPoolPreallocationSize"))
{
BufferPoolPreallocationSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolPreallocationSize"),
"Invalid integer value for the BufferPoolPreallocationSize attribute on the Messaging element");
}
if (child.HasAttribute("UseMessageBatching"))
{
UseMessageBatching = ConfigUtilities.ParseBool(child.GetAttribute("UseMessageBatching"),
"Invalid boolean value for the UseMessageBatching attribute on the Messaging element");
}
if (child.HasAttribute("MaxMessageBatchingSize"))
{
MaxMessageBatchingSize = ConfigUtilities.ParseInt(child.GetAttribute("MaxMessageBatchingSize"),
"Invalid integer value for the MaxMessageBatchingSize attribute on the Messaging element");
}
//--
if (isSiloConfig)
{
if (child.HasAttribute("MaxForwardCount"))
{
MaxForwardCount = ConfigUtilities.ParseInt(child.GetAttribute("MaxForwardCount"),
"Invalid integer value for the MaxForwardCount attribute on the Messaging element");
}
}
if (child.HasChildNodes)
{
var serializerNode = child.ChildNodes.Cast<XmlElement>().FirstOrDefault(n => n.Name == "SerializationProviders");
if (serializerNode != null && serializerNode.HasChildNodes)
{
var typeNames = serializerNode.ChildNodes.Cast<XmlElement>()
.Where(n => n.Name == "Provider")
.Select(e => e.Attributes["type"])
.Where(a => a != null)
.Select(a => a.Value);
var types = typeNames.Select(t => ConfigUtilities.ParseFullyQualifiedType(t, "The type specification for the 'type' attribute of the Provider element could not be loaded"));
foreach (var type in types)
{
ConfigUtilities.ValidateSerializationProvider(type);
var typeinfo = type.GetTypeInfo();
if (SerializationProviders.Contains(typeinfo) == false)
{
SerializationProviders.Add(typeinfo);
}
}
}
}
}
}
}
| |
// 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.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class Read_char_int_int_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the read method and the testcase fails.
private const double maxPercentageDifference = .15;
//The number of random bytes to receive for parity testing
private const int numRndBytesPairty = 8;
//The number of characters to read at a time for parity testing
private const int numBytesReadPairty = 2;
//The number of random bytes to receive for BytesToRead testing
private const int numRndBytesToRead = 16;
//When we test Read and do not care about actually reading anything we must still
//create an byte array to pass into the method the following is the size of the
//byte array used in this situation
private const int defaultCharArraySize = 1;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void ReadWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying read method throws exception without a call to Open()");
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying read method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a read method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void Timeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout);
com.Open();
VerifyTimeout(com);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void SuccessiveReadTimeoutNoData()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout);
com.Open();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void SuccessiveReadTimeoutSomeData()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
var t = new Task(WriteToCom1);
com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout);
com1.Open();
//Call WriteToCom1 asynchronously this will write to com1 some time before the following call
//to a read method times out
t.Start();
try
{
com1.Read(new char[defaultCharArraySize], 0, defaultCharArraySize);
}
catch (TimeoutException)
{
}
TCSupport.WaitForTaskCompletion(t);
//Make sure there is no bytes in the buffer so the next call to read will timeout
com1.DiscardInBuffer();
VerifyTimeout(com1);
}
}
private void WriteToCom1()
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndBytesPairty - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1));
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0);
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(15);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
char[] actualChars = new char[numRndBytesPairty + 1];
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
//Create a parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace;
// Set the last expected char to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1);
com1.Read(actualChars, 0, actualChars.Length);
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != actualChars[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]);
}
}
if (1 < com1.BytesToRead)
{
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
//Clear the parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedChars, expectedChars.Length / 2);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_RND_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead));
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_1_Buffer_Size()
{
VerifyBytesToRead(1);
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_Equal_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(numRndBytesToRead);
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.ReadTimeout;
int actualTime = 0;
double percentageDifference;
//Warm up read method
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void VerifyReadException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
byte expectedByte;
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
if (-1 == parityReplace)
{
//If parityReplace is -1 and we should just use the default value
expectedByte = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
//If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedByte = bytesToWrite[parityErrorIndex];
}
else
{
//Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedByte = (byte)parityReplace;
}
//Create an parity error by setting the highest order bit to true
bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80);
expectedChars[parityErrorIndex] = (char)expectedByte;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesReadPairty);
}
}
private void VerifyBytesToRead(int numBytesRead)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesToRead];
char[] expectedChars;
ASCIIEncoding encoding = new ASCIIEncoding();
//Genrate random characters
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesRead);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, int rcvBufferSize)
{
char[] rcvBuffer = new char[rcvBufferSize];
char[] buffer = new char[expectedChars.Length];
int totalBytesRead;
int totalCharsRead;
int bytesToRead;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
totalBytesRead = 0;
totalCharsRead = 0;
bytesToRead = com1.BytesToRead;
while (true)
{
int charsRead;
try
{
charsRead = com1.Read(rcvBuffer, 0, rcvBufferSize);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead);
if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) ||
(bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
//If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (expectedChars.Length < totalCharsRead + charsRead)
{
//If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
}
Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead);
totalBytesRead += bytesRead;
totalCharsRead += charsRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead,
com1.BytesToRead);
}
bytesToRead = com1.BytesToRead;
}
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)buffer[i]);
}
}
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography {
/// <summary>
/// Native interop with CNG's BCrypt layer. Native definitions can be found in bcrypt.h
/// </summary>
internal static class BCryptNative {
/// <summary>
/// Well known algorithm names
/// </summary>
internal static class AlgorithmName {
public const string ECDHP256 = "ECDH_P256"; // BCRYPT_ECDH_P256_ALGORITHM
public const string ECDHP384 = "ECDH_P384"; // BCRYPT_ECDH_P384_ALGORITHM
public const string ECDHP521 = "ECDH_P521"; // BCRYPT_ECDH_P521_ALGORITHM
public const string ECDsaP256 = "ECDSA_P256"; // BCRYPT_ECDSA_P256_ALGORITHM
public const string ECDsaP384 = "ECDSA_P384"; // BCRYPT_ECDSA_P384_ALGORITHM
public const string ECDsaP521 = "ECDSA_P521"; // BCRYPT_ECDSA_P521_ALGORITHM
public const string MD5 = "MD5"; // BCRYPT_MD5_ALGORITHM
public const string Sha1 = "SHA1"; // BCRYPT_SHA1_ALGORITHM
public const string Sha256 = "SHA256"; // BCRYPT_SHA256_ALGORITHM
public const string Sha384 = "SHA384"; // BCRYPT_SHA384_ALGORITHM
public const string Sha512 = "SHA512"; // BCRYPT_SHA512_ALGORITHM
}
/// <summary>
/// Result codes from BCrypt APIs
/// </summary>
internal enum ErrorCode {
Success = 0x00000000, // STATUS_SUCCESS
BufferToSmall = unchecked((int)0xC0000023), // STATUS_BUFFER_TOO_SMALL
ObjectNameNotFound = unchecked((int)0xC0000034) // SATUS_OBJECT_NAME_NOT_FOUND
}
/// <summary>
/// Well known BCrypt hash property names
/// </summary>
internal static class HashPropertyName {
public const string HashLength = "HashDigestLength"; // BCRYPT_HASH_LENGTH
}
/// <summary>
/// Magic numbers identifying blob types
/// </summary>
internal enum KeyBlobMagicNumber {
ECDHPublicP256 = 0x314B4345, // BCRYPT_ECDH_PUBLIC_P256_MAGIC
ECDHPublicP384 = 0x334B4345, // BCRYPT_ECDH_PUBLIC_P384_MAGIC
ECDHPublicP521 = 0x354B4345, // BCRYPT_ECDH_PUBLIC_P521_MAGIC
ECDsaPublicP256 = 0x31534345, // BCRYPT_ECDSA_PUBLIC_P256_MAGIC
ECDsaPublicP384 = 0x33534345, // BCRYPT_ECDSA_PUBLIC_P384_MAGIC
ECDsaPublicP521 = 0x35534345 // BCRYPT_ECDSA_PUBLIC_P521_MAGIC
}
/// <summary>
/// Well known KDF names
/// </summary>
internal static class KeyDerivationFunction {
public const string Hash = "HASH"; // BCRYPT_KDF_HASH
public const string Hmac = "HMAC"; // BCRYPT_KDF_HMAC
public const string Tls = "TLS_PRF"; // BCRYPT_KDF_TLS_PRF
}
/// <summary>
/// Well known BCrypt provider names
/// </summary>
internal static class ProviderName {
public const string MicrosoftPrimitiveProvider = "Microsoft Primitive Provider"; // MS_PRIMITIVE_PROVIDER
}
/// <summary>
/// Well known BCrypt object property names
/// </summary>
internal static class ObjectPropertyName {
public const string ObjectLength = "ObjectLength"; // BCRYPT_OBJECT_LENGTH
}
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
[SuppressUnmanagedCodeSecurity]
internal static class UnsafeNativeMethods {
/// <summary>
/// Create a hash object
/// </summary>
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptCreateHash(SafeBCryptAlgorithmHandle hAlgorithm,
[Out] out SafeBCryptHashHandle phHash,
IntPtr pbHashObject,
int cbHashObject,
IntPtr pbSecret,
int cbSecret,
int dwFlags);
/// <summary>
/// Get a property from a BCrypt algorithm object
/// </summary>
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptGetProperty(SafeBCryptAlgorithmHandle hObject,
string pszProperty,
[MarshalAs(UnmanagedType.LPArray), In, Out] byte[] pbOutput,
int cbOutput,
[In, Out] ref int pcbResult,
int flags);
/// <summary>
/// Get a property from a BCrypt algorithm object
/// </summary>
[DllImport("bcrypt.dll", EntryPoint = "BCryptGetProperty", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptGetAlgorithmProperty(SafeBCryptAlgorithmHandle hObject,
string pszProperty,
[MarshalAs(UnmanagedType.LPArray), In, Out] byte[] pbOutput,
int cbOutput,
[In, Out] ref int pcbResult,
int flags);
/// <summary>
/// Get a property from a BCrypt hash object
/// </summary>
[DllImport("bcrypt.dll", EntryPoint = "BCryptGetProperty", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptGetHashProperty(SafeBCryptHashHandle hObject,
string pszProperty,
[MarshalAs(UnmanagedType.LPArray), In, Out] byte[] pbOutput,
int cbOutput,
[In, Out] ref int pcbResult,
int flags);
/// <summary>
/// Get the hash value of the data
/// </summary>
[DllImport("bcrypt.dll")]
internal static extern ErrorCode BCryptFinishHash(SafeBCryptHashHandle hHash,
[MarshalAs(UnmanagedType.LPArray), Out] byte[] pbInput,
int cbInput,
int dwFlags);
/// <summary>
/// Hash a block of data
/// </summary>
[DllImport("bcrypt.dll")]
internal static extern ErrorCode BCryptHashData(SafeBCryptHashHandle hHash,
[MarshalAs(UnmanagedType.LPArray), In] byte[] pbInput,
int cbInput,
int dwFlags);
/// <summary>
/// Get a handle to an algorithm provider
/// </summary>
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptOpenAlgorithmProvider([Out] out SafeBCryptAlgorithmHandle phAlgorithm,
string pszAlgId, // BCryptAlgorithm
string pszImplementation, // ProviderNames
int dwFlags);
}
//
// Wrapper and utility functions
//
/// <summary>
/// Adapter to wrap specific BCryptGetProperty P/Invokes with a generic handle type
/// </summary>
#pragma warning disable 618 // System.Core.dll still uses SecurityRuleSet.Level1
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
private delegate ErrorCode BCryptPropertyGetter<T>(T hObject,
string pszProperty,
byte[] pbOutput,
int cbOutput,
ref int pcbResult,
int dwFlags) where T : SafeHandle;
private static volatile bool s_haveBcryptSupported;
private static volatile bool s_bcryptSupported;
/// <summary>
/// Determine if BCrypt is supported on the current machine
/// </summary>
internal static bool BCryptSupported {
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")]
get {
if (!s_haveBcryptSupported)
{
// Attempt to load bcrypt.dll to see if the BCrypt CNG APIs are available on the machine
using (SafeLibraryHandle bcrypt = Microsoft.Win32.UnsafeNativeMethods.LoadLibraryEx("bcrypt", IntPtr.Zero, 0)) {
s_bcryptSupported = !bcrypt.IsInvalid;
s_haveBcryptSupported = true;
}
}
return s_bcryptSupported;
}
}
/// <summary>
/// Get the value of a DWORD property of a BCrypt object
/// </summary>
[System.Security.SecurityCritical]
internal static int GetInt32Property<T>(T algorithm, string property) where T : SafeHandle {
Contract.Requires(algorithm != null);
Contract.Requires(property == HashPropertyName.HashLength ||
property == ObjectPropertyName.ObjectLength);
return BitConverter.ToInt32(GetProperty(algorithm, property), 0);
}
/// <summary>
/// Get the value of a property of a BCrypt object
/// </summary>
[System.Security.SecurityCritical]
internal static byte[] GetProperty<T>(T algorithm, string property) where T : SafeHandle {
Contract.Requires(algorithm != null);
Contract.Requires(!String.IsNullOrEmpty(property));
Contract.Ensures(Contract.Result<byte[]>() != null);
BCryptPropertyGetter<T> getter = null;
if (typeof(T) == typeof(SafeBCryptAlgorithmHandle)) {
getter = new BCryptPropertyGetter<SafeBCryptAlgorithmHandle>(UnsafeNativeMethods.BCryptGetAlgorithmProperty)
as BCryptPropertyGetter<T>;
}
else if (typeof(T) == typeof(SafeBCryptHashHandle)) {
getter = new BCryptPropertyGetter<SafeBCryptHashHandle>(UnsafeNativeMethods.BCryptGetHashProperty)
as BCryptPropertyGetter<T>;
}
Debug.Assert(getter != null, "Unknown handle type");
// Figure out how big the property is
int bufferSize = 0;
ErrorCode error = getter(algorithm, property, null, 0, ref bufferSize, 0);
if (error != ErrorCode.BufferToSmall && error != ErrorCode.Success) {
throw new CryptographicException((int)error);
}
// Allocate the buffer, and return the property
Debug.Assert(bufferSize > 0, "bufferSize > 0");
byte[] buffer = new byte[bufferSize];
error = getter(algorithm, property, buffer, buffer.Length, ref bufferSize, 0);
if (error != ErrorCode.Success) {
throw new CryptographicException((int)error);
}
return buffer;
}
/// <summary>
/// Map an algorithm identifier to a key size and magic number
/// </summary>
internal static void MapAlgorithmIdToMagic(string algorithm,
out KeyBlobMagicNumber algorithmMagic,
out int keySize) {
Contract.Requires(!String.IsNullOrEmpty(algorithm));
switch (algorithm) {
case AlgorithmName.ECDHP256:
algorithmMagic = KeyBlobMagicNumber.ECDHPublicP256;
keySize = 256;
break;
case AlgorithmName.ECDHP384:
algorithmMagic = KeyBlobMagicNumber.ECDHPublicP384;
keySize = 384;
break;
case AlgorithmName.ECDHP521:
algorithmMagic = KeyBlobMagicNumber.ECDHPublicP521;
keySize = 521;
break;
case AlgorithmName.ECDsaP256:
algorithmMagic = KeyBlobMagicNumber.ECDsaPublicP256;
keySize = 256;
break;
case AlgorithmName.ECDsaP384:
algorithmMagic = KeyBlobMagicNumber.ECDsaPublicP384;
keySize = 384;
break;
case AlgorithmName.ECDsaP521:
algorithmMagic = KeyBlobMagicNumber.ECDsaPublicP521;
keySize = 521;
break;
default:
throw new ArgumentException(SR.GetString(SR.Cryptography_UnknownEllipticCurveAlgorithm));
}
}
/// <summary>
/// Open a handle to an algorithm provider
/// </summary>
[System.Security.SecurityCritical]
internal static SafeBCryptAlgorithmHandle OpenAlgorithm(string algorithm, string implementation) {
Contract.Requires(!String.IsNullOrEmpty(algorithm));
Contract.Requires(!String.IsNullOrEmpty(implementation));
Contract.Ensures(Contract.Result<SafeBCryptAlgorithmHandle>() != null &&
!Contract.Result<SafeBCryptAlgorithmHandle>().IsInvalid &&
!Contract.Result<SafeBCryptAlgorithmHandle>().IsClosed);
SafeBCryptAlgorithmHandle algorithmHandle = null;
ErrorCode error = UnsafeNativeMethods.BCryptOpenAlgorithmProvider(out algorithmHandle,
algorithm,
implementation,
0);
if (error != ErrorCode.Success) {
throw new CryptographicException((int)error);
}
return algorithmHandle;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.