context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SyncAgentsOperations operations.
/// </summary>
public partial interface ISyncAgentsOperations
{
/// <summary>
/// Gets a sync agent.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </param>
/// <param name='syncAgentName'>
/// The name of the sync agent.
/// </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<SyncAgent>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string syncAgentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a sync agent.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </param>
/// <param name='syncAgentName'>
/// The name of the sync agent.
/// </param>
/// <param name='parameters'>
/// The requested sync agent resource state.
/// </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<SyncAgent>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string syncAgentName, SyncAgent parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a sync agent.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </param>
/// <param name='syncAgentName'>
/// The name of the sync agent.
/// </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 serverName, string syncAgentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists sync agents in a server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </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<SyncAgent>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates a sync agent key.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </param>
/// <param name='syncAgentName'>
/// The name of the sync agent.
/// </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<SyncAgentKeyProperties>> GenerateKeyWithHttpMessagesAsync(string resourceGroupName, string serverName, string syncAgentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists databases linked to a sync agent.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </param>
/// <param name='syncAgentName'>
/// The name of the sync agent.
/// </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<SyncAgentLinkedDatabase>>> ListLinkedDatabasesWithHttpMessagesAsync(string resourceGroupName, string serverName, string syncAgentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a sync agent.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </param>
/// <param name='syncAgentName'>
/// The name of the sync agent.
/// </param>
/// <param name='parameters'>
/// The requested sync agent resource state.
/// </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<SyncAgent>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string syncAgentName, SyncAgent parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a sync agent.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can
/// obtain this value from the Azure Resource Manager API or the
/// portal.
/// </param>
/// <param name='serverName'>
/// The name of the server on which the sync agent is hosted.
/// </param>
/// <param name='syncAgentName'>
/// The name of the sync agent.
/// </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 serverName, string syncAgentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists sync agents in a server.
/// </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<SyncAgent>>> ListByServerNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists databases linked to a sync agent.
/// </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<SyncAgentLinkedDatabase>>> ListLinkedDatabasesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* Copyright (c) 2006-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Drawing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace GridAccountant
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class frmGridAccountant : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox grpLogin;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.TextBox txtLastName;
private System.Windows.Forms.Button cmdConnect;
private System.Windows.Forms.TextBox txtFirstName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.Label lblBalance;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtFind;
private System.Windows.Forms.Button cmdFind;
private System.Windows.Forms.TextBox txtTransfer;
private System.Windows.Forms.Button cmdTransfer;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ListView lstFind;
private System.Windows.Forms.ColumnHeader colName;
private System.Windows.Forms.ColumnHeader colOnline;
private System.Windows.Forms.ColumnHeader colUuid;
private GridClient Client;
public frmGridAccountant()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
Client.Network.Logout();
if( disposing )
{
if (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.grpLogin = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.txtPassword = new System.Windows.Forms.TextBox();
this.txtLastName = new System.Windows.Forms.TextBox();
this.cmdConnect = new System.Windows.Forms.Button();
this.txtFirstName = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.lblName = new System.Windows.Forms.Label();
this.lblBalance = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.txtFind = new System.Windows.Forms.TextBox();
this.cmdFind = new System.Windows.Forms.Button();
this.txtTransfer = new System.Windows.Forms.TextBox();
this.cmdTransfer = new System.Windows.Forms.Button();
this.label7 = new System.Windows.Forms.Label();
this.lstFind = new System.Windows.Forms.ListView();
this.colName = new System.Windows.Forms.ColumnHeader();
this.colOnline = new System.Windows.Forms.ColumnHeader();
this.colUuid = new System.Windows.Forms.ColumnHeader();
this.grpLogin.SuspendLayout();
this.SuspendLayout();
//
// grpLogin
//
this.grpLogin.Controls.Add(this.label3);
this.grpLogin.Controls.Add(this.label2);
this.grpLogin.Controls.Add(this.label1);
this.grpLogin.Controls.Add(this.txtPassword);
this.grpLogin.Controls.Add(this.txtLastName);
this.grpLogin.Controls.Add(this.cmdConnect);
this.grpLogin.Controls.Add(this.txtFirstName);
this.grpLogin.Enabled = false;
this.grpLogin.Location = new System.Drawing.Point(16, 344);
this.grpLogin.Name = "grpLogin";
this.grpLogin.Size = new System.Drawing.Size(560, 80);
this.grpLogin.TabIndex = 50;
this.grpLogin.TabStop = false;
//
// label3
//
this.label3.Location = new System.Drawing.Point(280, 24);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(120, 16);
this.label3.TabIndex = 50;
this.label3.Text = "Password";
//
// label2
//
this.label2.Location = new System.Drawing.Point(152, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 16);
this.label2.TabIndex = 50;
this.label2.Text = "Last Name";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(120, 16);
this.label1.TabIndex = 50;
this.label1.Text = "First Name";
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(280, 40);
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(120, 20);
this.txtPassword.TabIndex = 2;
this.txtPassword.Text = "";
//
// txtLastName
//
this.txtLastName.Location = new System.Drawing.Point(152, 40);
this.txtLastName.Name = "txtLastName";
this.txtLastName.Size = new System.Drawing.Size(112, 20);
this.txtLastName.TabIndex = 1;
this.txtLastName.Text = "";
//
// cmdConnect
//
this.cmdConnect.Location = new System.Drawing.Point(424, 40);
this.cmdConnect.Name = "cmdConnect";
this.cmdConnect.Size = new System.Drawing.Size(120, 24);
this.cmdConnect.TabIndex = 3;
this.cmdConnect.Text = "Connect";
this.cmdConnect.Click += new System.EventHandler(this.cmdConnect_Click);
//
// txtFirstName
//
this.txtFirstName.Location = new System.Drawing.Point(16, 40);
this.txtFirstName.Name = "txtFirstName";
this.txtFirstName.Size = new System.Drawing.Size(120, 20);
this.txtFirstName.TabIndex = 0;
this.txtFirstName.Text = "";
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 8);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(48, 16);
this.label4.TabIndex = 50;
this.label4.Text = "Name:";
//
// lblName
//
this.lblName.Location = new System.Drawing.Point(64, 8);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(184, 16);
this.lblName.TabIndex = 50;
//
// lblBalance
//
this.lblBalance.Location = new System.Drawing.Point(512, 8);
this.lblBalance.Name = "lblBalance";
this.lblBalance.Size = new System.Drawing.Size(64, 16);
this.lblBalance.TabIndex = 50;
this.lblBalance.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label6
//
this.label6.Location = new System.Drawing.Point(456, 8);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(56, 16);
this.label6.TabIndex = 50;
this.label6.Text = "Balance:";
//
// label5
//
this.label5.Location = new System.Drawing.Point(16, 40);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(88, 16);
this.label5.TabIndex = 50;
this.label5.Text = "People Search";
//
// txtFind
//
this.txtFind.Enabled = false;
this.txtFind.Location = new System.Drawing.Point(16, 56);
this.txtFind.Name = "txtFind";
this.txtFind.Size = new System.Drawing.Size(184, 20);
this.txtFind.TabIndex = 4;
this.txtFind.Text = "";
//
// cmdFind
//
this.cmdFind.Enabled = false;
this.cmdFind.Location = new System.Drawing.Point(208, 56);
this.cmdFind.Name = "cmdFind";
this.cmdFind.Size = new System.Drawing.Size(48, 24);
this.cmdFind.TabIndex = 5;
this.cmdFind.Text = "Find";
this.cmdFind.Click += new System.EventHandler(this.cmdFind_Click);
//
// txtTransfer
//
this.txtTransfer.Enabled = false;
this.txtTransfer.Location = new System.Drawing.Point(360, 192);
this.txtTransfer.MaxLength = 7;
this.txtTransfer.Name = "txtTransfer";
this.txtTransfer.Size = new System.Drawing.Size(104, 20);
this.txtTransfer.TabIndex = 7;
this.txtTransfer.Text = "";
//
// cmdTransfer
//
this.cmdTransfer.Enabled = false;
this.cmdTransfer.Location = new System.Drawing.Point(472, 192);
this.cmdTransfer.Name = "cmdTransfer";
this.cmdTransfer.Size = new System.Drawing.Size(104, 24);
this.cmdTransfer.TabIndex = 8;
this.cmdTransfer.Text = "Transfer Lindens";
this.cmdTransfer.Click += new System.EventHandler(this.cmdTransfer_Click);
//
// label7
//
this.label7.Location = new System.Drawing.Point(360, 176);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(88, 16);
this.label7.TabIndex = 17;
this.label7.Text = "Amount:";
//
// lstFind
//
this.lstFind.Activation = System.Windows.Forms.ItemActivation.OneClick;
this.lstFind.AllowColumnReorder = true;
this.lstFind.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colName,
this.colOnline,
this.colUuid});
this.lstFind.FullRowSelect = true;
this.lstFind.HideSelection = false;
this.lstFind.Location = new System.Drawing.Point(16, 88);
this.lstFind.Name = "lstFind";
this.lstFind.Size = new System.Drawing.Size(336, 248);
this.lstFind.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.lstFind.TabIndex = 6;
this.lstFind.View = System.Windows.Forms.View.Details;
//
// colName
//
this.colName.Text = "Name";
this.colName.Width = 120;
//
// colOnline
//
this.colOnline.Text = "Online";
this.colOnline.Width = 50;
//
// colUuid
//
this.colUuid.Text = "UUID";
this.colUuid.Width = 150;
//
// frmGridAccountant
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(592, 437);
this.Controls.Add(this.lstFind);
this.Controls.Add(this.label7);
this.Controls.Add(this.cmdTransfer);
this.Controls.Add(this.txtTransfer);
this.Controls.Add(this.txtFind);
this.Controls.Add(this.cmdFind);
this.Controls.Add(this.label5);
this.Controls.Add(this.lblBalance);
this.Controls.Add(this.label6);
this.Controls.Add(this.lblName);
this.Controls.Add(this.label4);
this.Controls.Add(this.grpLogin);
this.Name = "frmGridAccountant";
this.Text = "Grid Accountant";
this.Load += new System.EventHandler(this.frmGridAccountant_Load);
this.grpLogin.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
frmGridAccountant frm = new frmGridAccountant();
frm.ShowDialog();
}
private delegate void StringParamInvoker(string value);
private delegate void ListViewItemParamInvoker(ListViewItem item);
private void UpdateBalance(string value)
{
lblBalance.Text = value;
}
private void AddFindItem(ListViewItem item)
{
lock (lstFind)
{
lstFind.Items.Add(item);
}
}
protected void BalanceHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
string value = ((MoneyBalanceReplyPacket)packet).MoneyData.MoneyBalance.ToString();
this.BeginInvoke(new StringParamInvoker(UpdateBalance), new object[] { value });
}
private void DirPeopleHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
DirPeopleReplyPacket reply = (DirPeopleReplyPacket)packet;
foreach (DirPeopleReplyPacket.QueryRepliesBlock block in reply.QueryReplies)
{
ListViewItem listItem = new ListViewItem(new string[] {
Utils.BytesToString(block.FirstName) + " " + Utils.BytesToString(block.LastName),
(block.Online ? "Yes" : "No"), block.AgentID.ToString() });
this.BeginInvoke(new ListViewItemParamInvoker(AddFindItem), new object[] { listItem });
}
}
private void frmGridAccountant_Load(object sender, System.EventArgs e)
{
Client = new GridClient();
Client.Settings.MULTIPLE_SIMS = false;
Client.Network.LoginProgress += Network_OnLogin;
// Install our packet handlers
Client.Network.RegisterCallback(PacketType.MoneyBalanceReply, BalanceHandler);
Client.Network.RegisterCallback(PacketType.DirPeopleReply, DirPeopleHandler);
grpLogin.Enabled = true;
}
private void Network_OnLogin(object sender, LoginProgressEventArgs e)
{
if (e.Status == LoginStatus.Success)
{
Random rand = new Random();
// AgentSetAppearance
AgentSetAppearancePacket appearance = new AgentSetAppearancePacket();
appearance.VisualParam = new AgentSetAppearancePacket.VisualParamBlock[251];
// Setup some random appearance values
for (int i = 0; i < 251; i++)
{
appearance.VisualParam[i] = new AgentSetAppearancePacket.VisualParamBlock();
appearance.VisualParam[i].ParamValue = (byte)rand.Next(255);
}
appearance.AgentData.AgentID = Client.Self.AgentID;
appearance.AgentData.SessionID = Client.Self.SessionID;
appearance.AgentData.SerialNum = 1;
appearance.AgentData.Size = new Vector3(0.45F, 0.6F, 1.831094F);
appearance.ObjectData.TextureEntry = Utils.EmptyBytes;
Client.Network.SendPacket(appearance);
// Request our balance
Client.Self.RequestBalance();
BeginInvoke(
(MethodInvoker)delegate()
{
lblName.Text = Client.ToString();
txtFind.Enabled = cmdFind.Enabled = true;
txtTransfer.Enabled = cmdTransfer.Enabled = true;
});
}
else if (e.Status == LoginStatus.Failed)
{
BeginInvoke(
(MethodInvoker)delegate()
{
MessageBox.Show(this, "Error logging in: " + Client.Network.LoginMessage);
cmdConnect.Text = "Connect";
txtFirstName.Enabled = txtLastName.Enabled = txtPassword.Enabled = true;
txtFind.Enabled = cmdFind.Enabled = false;
lblName.Text = lblBalance.Text = String.Empty;
txtTransfer.Enabled = cmdTransfer.Enabled = false;
});
}
}
private void cmdConnect_Click(object sender, System.EventArgs e)
{
if (cmdConnect.Text == "Connect")
{
cmdConnect.Text = "Disconnect";
txtFirstName.Enabled = txtLastName.Enabled = txtPassword.Enabled = false;
LoginParams loginParams = Client.Network.DefaultLoginParams(txtFirstName.Text, txtLastName.Text,
txtPassword.Text, "GridAccountant", "1.0.0");
Client.Network.BeginLogin(loginParams);
}
else
{
Client.Network.Logout();
cmdConnect.Text = "Connect";
txtFirstName.Enabled = txtLastName.Enabled = txtPassword.Enabled = true;
txtFind.Enabled = cmdFind.Enabled = false;
lblName.Text = lblBalance.Text = "";
txtTransfer.Enabled = cmdTransfer.Enabled = false;
}
}
private void cmdFind_Click(object sender, System.EventArgs e)
{
lstFind.Items.Clear();
DirFindQueryPacket query = new DirFindQueryPacket();
query.AgentData.AgentID = Client.Self.AgentID;
query.AgentData.SessionID = Client.Self.SessionID;
query.QueryData.QueryFlags = 1;
query.QueryData.QueryID = UUID.Random();
query.QueryData.QueryStart = 0;
query.QueryData.QueryText = Utils.StringToBytes(txtFind.Text);
query.Header.Reliable = true;
Client.Network.SendPacket(query);
}
private void cmdTransfer_Click(object sender, System.EventArgs e)
{
int amount = 0;
try
{
amount = System.Convert.ToInt32(txtTransfer.Text);
}
catch (Exception)
{
MessageBox.Show(txtTransfer.Text + " is not a valid amount");
return;
}
if (lstFind.SelectedItems.Count != 1)
{
MessageBox.Show("Find an avatar using the directory search and select " +
"their name to transfer money");
return;
}
Client.Self.GiveAvatarMoney(new UUID(lstFind.SelectedItems[0].SubItems[2].Text),
amount, "GridAccountant payment");
}
}
}
| |
// 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.Text;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.DeriveBytesTests
{
public class Rfc2898Tests
{
// 8 bytes is the minimum accepted value, by using it we've already assured that the minimum is acceptable.
private static readonly byte[] s_testSalt = new byte[] { 9, 5, 5, 5, 1, 2, 1, 2 };
private static readonly byte[] s_testSaltB = new byte[] { 0, 4, 0, 4, 1, 9, 7, 5 };
private const string TestPassword = "PasswordGoesHere";
private const string TestPasswordB = "FakePasswordsAreHard";
private const int DefaultIterationCount = 1000;
[Fact]
public static void Ctor_NullPasswordBytes()
{
Assert.Throws<NullReferenceException>(() => new Rfc2898DeriveBytes((byte[])null, s_testSalt, DefaultIterationCount));
}
[Fact]
public static void Ctor_NullPasswordString()
{
Assert.Throws<ArgumentNullException>(() => new Rfc2898DeriveBytes((string)null, s_testSalt, DefaultIterationCount));
}
[Fact]
public static void Ctor_NullSalt()
{
Assert.Throws<ArgumentNullException>(() => new Rfc2898DeriveBytes(TestPassword, null, DefaultIterationCount));
}
[Fact]
public static void Ctor_EmptySalt()
{
AssertExtensions.Throws<ArgumentException>("salt", null, () => new Rfc2898DeriveBytes(TestPassword, Array.Empty<byte>(), DefaultIterationCount));
}
[Fact]
public static void Ctor_DiminishedSalt()
{
AssertExtensions.Throws<ArgumentException>("salt", null, () => new Rfc2898DeriveBytes(TestPassword, new byte[7], DefaultIterationCount));
}
[Fact]
public static void Ctor_GenerateZeroSalt()
{
AssertExtensions.Throws<ArgumentException>("saltSize", null, () => new Rfc2898DeriveBytes(TestPassword, 0));
}
[Fact]
public static void Ctor_GenerateNegativeSalt()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, int.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, int.MinValue / 2));
}
[Fact]
public static void Ctor_GenerateDiminishedSalt()
{
AssertExtensions.Throws<ArgumentException>("saltSize", null, () => new Rfc2898DeriveBytes(TestPassword, 7));
}
[Fact]
public static void Ctor_TooFewIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, 0));
}
[Fact]
public static void Ctor_NegativeIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, int.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, int.MinValue / 2));
}
#if netcoreapp
[Fact]
public static void Ctor_EmptyAlgorithm()
{
HashAlgorithmName alg = default(HashAlgorithmName);
// (byte[], byte[], int, HashAlgorithmName)
Assert.Throws<CryptographicException>(() => new Rfc2898DeriveBytes(s_testSalt, s_testSalt, DefaultIterationCount, alg));
// (string, byte[], int, HashAlgorithmName)
Assert.Throws<CryptographicException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, alg));
// (string, int, int, HashAlgorithmName)
Assert.Throws<CryptographicException>(() => new Rfc2898DeriveBytes(TestPassword, 8, DefaultIterationCount, alg));
}
[Fact]
public static void Ctor_MD5NotSupported()
{
Assert.Throws<CryptographicException>(
() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, HashAlgorithmName.MD5));
}
[Fact]
public static void Ctor_UnknownAlgorithm()
{
Assert.Throws<CryptographicException>(
() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, new HashAlgorithmName("PotatoLemming")));
}
#endif
[Fact]
public static void Ctor_SaltCopied()
{
byte[] saltIn = (byte[])s_testSalt.Clone();
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, saltIn, DefaultIterationCount))
{
byte[] saltOut = deriveBytes.Salt;
Assert.NotSame(saltIn, saltOut);
Assert.Equal(saltIn, saltOut);
// Right now we know that at least one of the constructor and get_Salt made a copy, if it was
// only get_Salt then this next part would fail.
saltIn[0] = unchecked((byte)~saltIn[0]);
// Have to read the property again to prove it's detached.
Assert.NotEqual(saltIn, deriveBytes.Salt);
}
}
[Fact]
public static void Ctor_DefaultIterations()
{
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt))
{
Assert.Equal(DefaultIterationCount, deriveBytes.IterationCount);
}
}
[Fact]
public static void Ctor_IterationsRespected()
{
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt, 1))
{
Assert.Equal(1, deriveBytes.IterationCount);
}
}
[Fact]
public static void GetSaltCopies()
{
byte[] first;
byte[] second;
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount))
{
first = deriveBytes.Salt;
second = deriveBytes.Salt;
}
Assert.NotSame(first, second);
Assert.Equal(first, second);
}
[Fact]
public static void MinimumAcceptableInputs()
{
byte[] output;
using (var deriveBytes = new Rfc2898DeriveBytes("", new byte[8], 1))
{
output = deriveBytes.GetBytes(1);
}
Assert.Equal(1, output.Length);
Assert.Equal(0xA6, output[0]);
}
[Fact]
public static void GetBytes_ZeroLength()
{
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(0));
}
}
[Fact]
public static void GetBytes_NegativeLength()
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt);
Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(int.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(int.MinValue / 2));
}
[Fact]
public static void GetBytes_NotIdempotent()
{
byte[] first;
byte[] second;
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(32);
second = deriveBytes.GetBytes(32);
}
Assert.NotEqual(first, second);
}
[Theory]
[InlineData(2)]
[InlineData(5)]
[InlineData(10)]
[InlineData(16)]
[InlineData(20)]
[InlineData(25)]
[InlineData(32)]
[InlineData(40)]
[InlineData(192)]
public static void GetBytes_StreamLike(int size)
{
byte[] first;
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(size);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt))
{
byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2);
byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length);
Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length);
Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length);
}
Assert.Equal(first, second);
}
[Theory]
[InlineData(2)]
[InlineData(5)]
[InlineData(10)]
[InlineData(16)]
[InlineData(20)]
[InlineData(25)]
[InlineData(32)]
[InlineData(40)]
[InlineData(192)]
public static void GetBytes_StreamLike_OneAtATime(int size)
{
byte[] first;
using (var deriveBytes = new Rfc2898DeriveBytes(TestPasswordB, s_testSaltB))
{
first = deriveBytes.GetBytes(size);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new Rfc2898DeriveBytes(TestPasswordB, s_testSaltB))
{
for (int i = 0; i < second.Length; i++)
{
second[i] = deriveBytes.GetBytes(1)[0];
}
}
Assert.Equal(first, second);
}
[Fact]
public static void GetBytes_KnownValues_1()
{
TestKnownValue(
TestPassword,
s_testSalt,
DefaultIterationCount,
new byte[]
{
0x6C, 0x3C, 0x55, 0xA4, 0x2E, 0xE9, 0xD6, 0xAE,
0x7D, 0x28, 0x6C, 0x83, 0xE4, 0xD7, 0xA3, 0xC8,
0xB5, 0x93, 0x9F, 0x45, 0x2F, 0x2B, 0xF3, 0x68,
0xFA, 0xE8, 0xB2, 0x74, 0x55, 0x3A, 0x36, 0x8A,
});
}
[Fact]
public static void GetBytes_KnownValues_2()
{
TestKnownValue(
TestPassword,
s_testSalt,
DefaultIterationCount + 1,
new byte[]
{
0x8E, 0x9B, 0xF7, 0xC1, 0x83, 0xD4, 0xD1, 0x20,
0x87, 0xA8, 0x2C, 0xD7, 0xCD, 0x84, 0xBC, 0x1A,
0xC6, 0x7A, 0x7A, 0xDD, 0x46, 0xFA, 0x40, 0xAA,
0x60, 0x3A, 0x2B, 0x8B, 0x79, 0x2C, 0x8A, 0x6D,
});
}
[Fact]
public static void GetBytes_KnownValues_3()
{
TestKnownValue(
TestPassword,
s_testSaltB,
DefaultIterationCount,
new byte[]
{
0x4E, 0xF5, 0xA5, 0x85, 0x92, 0x9D, 0x8B, 0xC5,
0x57, 0x0C, 0x83, 0xB5, 0x19, 0x69, 0x4B, 0xC2,
0x4B, 0xAA, 0x09, 0xE9, 0xE7, 0x9C, 0x29, 0x94,
0x14, 0x19, 0xE3, 0x61, 0xDA, 0x36, 0x5B, 0xB3,
});
}
[Fact]
public static void GetBytes_KnownValues_4()
{
TestKnownValue(
TestPasswordB,
s_testSalt,
DefaultIterationCount,
new byte[]
{
0x86, 0xBB, 0xB3, 0xD7, 0x99, 0x0C, 0xAC, 0x4D,
0x1D, 0xB2, 0x78, 0x9D, 0x57, 0x5C, 0x06, 0x93,
0x97, 0x50, 0x72, 0xFF, 0x56, 0x57, 0xAC, 0x7F,
0x9B, 0xD2, 0x14, 0x9D, 0xE9, 0x95, 0xA2, 0x6D,
});
}
#if netcoreapp
[Theory]
[MemberData(nameof(KnownValuesTestCases))]
public static void GetBytes_KnownValues_WithAlgorithm(KnownValuesTestCase testCase)
{
byte[] output;
var pbkdf2 = new Rfc2898DeriveBytes(
testCase.Password,
testCase.Salt,
testCase.IterationCount,
new HashAlgorithmName(testCase.HashAlgorithmName));
using (pbkdf2)
{
output = pbkdf2.GetBytes(testCase.AnswerHex.Length / 2);
}
Assert.Equal(testCase.AnswerHex, output.ByteArrayToHex());
}
[Theory]
[InlineData("SHA1")]
[InlineData("SHA256")]
[InlineData("SHA384")]
[InlineData("SHA512")]
public static void CheckHashAlgorithmValue(string hashAlgorithmName)
{
HashAlgorithmName hashAlgorithm = new HashAlgorithmName(hashAlgorithmName);
using (var pbkdf2 = new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, hashAlgorithm))
{
Assert.Equal(hashAlgorithm, pbkdf2.HashAlgorithm);
}
}
#endif
[Fact]
public static void CryptDeriveKey_NotSupported()
{
using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<PlatformNotSupportedException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, new byte[8]));
}
}
private static void TestKnownValue(string password, byte[] salt, int iterationCount, byte[] expected)
{
byte[] output;
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, iterationCount))
{
output = deriveBytes.GetBytes(expected.Length);
}
Assert.Equal(expected, output);
}
public static IEnumerable<object[]> KnownValuesTestCases()
{
HashSet<string> testCaseNames = new HashSet<string>();
// Wrap the class in the MemberData-required-object[].
foreach (KnownValuesTestCase testCase in GetKnownValuesTestCases())
{
if (!testCaseNames.Add(testCase.CaseName))
{
throw new InvalidOperationException($"Duplicate test case name: {testCase.CaseName}");
}
yield return new object[] { testCase };
}
}
private static IEnumerable<KnownValuesTestCase> GetKnownValuesTestCases()
{
Encoding ascii = Encoding.ASCII;
yield return new KnownValuesTestCase
{
CaseName = "RFC 3211 Section 3 #1",
HashAlgorithmName = "SHA1",
Password = "password",
Salt = "1234567878563412".HexToByteArray(),
IterationCount = 5,
AnswerHex = "D1DAA78615F287E6",
};
yield return new KnownValuesTestCase
{
CaseName = "RFC 3211 Section 3 #2",
HashAlgorithmName = "SHA1",
Password = "All n-entities must communicate with other n-entities via n-1 entiteeheehees",
Salt = "1234567878563412".HexToByteArray(),
IterationCount = 500,
AnswerHex = "6A8970BF68C92CAEA84A8DF28510858607126380CC47AB2D",
};
yield return new KnownValuesTestCase
{
CaseName = "RFC 6070 Case 5",
HashAlgorithmName = "SHA1",
Password = "passwordPASSWORDpassword",
Salt = ascii.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"),
IterationCount = 4096,
AnswerHex = "3D2EEC4FE41C849B80C8D83662C0E44A8B291A964CF2F07038",
};
// From OpenSSL.
// https://github.com/openssl/openssl/blob/6f0ac0e2f27d9240516edb9a23b7863e7ad02898/test/evptests.txt
// Corroborated on http://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors,
// though the SO answer stopped at 25 bytes.
yield return new KnownValuesTestCase
{
CaseName = "RFC 6070#5 SHA256",
HashAlgorithmName = "SHA256",
Password = "passwordPASSWORDpassword",
Salt = ascii.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"),
IterationCount = 4096,
AnswerHex =
"348C89DBCBD32B2F32D814B8116E84CF2B17347EBC1800181C4E2A1FB8DD53E1C635518C7DAC47E9",
};
// From OpenSSL.
yield return new KnownValuesTestCase
{
CaseName = "RFC 6070#5 SHA512",
HashAlgorithmName = "SHA512",
Password = "passwordPASSWORDpassword",
Salt = ascii.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"),
IterationCount = 4096,
AnswerHex = (
"8C0511F4C6E597C6AC6315D8F0362E225F3C501495BA23B868C005174DC4EE71" +
"115B59F9E60CD9532FA33E0F75AEFE30225C583A186CD82BD4DAEA9724A3D3B8"),
};
// Verified against BCryptDeriveKeyPBKDF2, as an independent implementation.
yield return new KnownValuesTestCase
{
CaseName = "RFC 3962 Appendix B#1 SHA384-24000",
HashAlgorithmName = "SHA384",
Password = "password",
Salt = ascii.GetBytes("ATHENA.MIT.EDUraeburn"),
IterationCount = 24000,
AnswerHex = (
"4B138897F289129C6E80965F96B940F76BBC0363CD22190E0BD94ADBA79BE33E" +
"02C9D8E0AF0D19B295B02828770587F672E0ED182A9A59BA5E07120CA936E6BF" +
"F5D425688253C2A8336ED30DA898C67FD9DDFD8EF3F8C708392E2E2458716DF8" +
"6799372DEF27AB36AF239D7D654A56A51395086A322B9322977F62A98662B57E"),
};
// These "alternate" tests are made up, due to a lack of test corpus diversity
yield return new KnownValuesTestCase
{
CaseName = "SHA256 alternate",
HashAlgorithmName = "SHA256",
Password = "PLACEHOLDER",
Salt = ascii.GetBytes("abcdefghij"),
IterationCount = 1,
AnswerHex = (
// T-Block 1
"9352784113E5E6DC21FC82ADA3A321D64962F760DF6EAA8E46CEEF4FAF6C6E" +
// T-Block 2
"EE6DB97E5852FC4C15FA7C52FACDEDE89B916BCC864028084A2CF0889F7F76"),
};
yield return new KnownValuesTestCase
{
CaseName = "SHA384 alternate",
HashAlgorithmName = "SHA384",
Password = "PLACEHOLDER",
Salt = ascii.GetBytes("abcdefghij"),
IterationCount = 1,
AnswerHex = (
// T-Block 1
"B9A10C6C82F36482D76C0C38C982C05F8BB21211ACBE1D1104B4F647DDEAEE179B92ACB0E00A304B791FD0" +
// T-Block 2
"3C6A08364D0A47CD1F15E0E314800FF3AC9CF2E93B3F81A5EB67FE9F2FE6E86B0430B59902CCB5FD190E67"),
};
yield return new KnownValuesTestCase
{
CaseName = "SHA512 alternate",
HashAlgorithmName = "SHA512",
Password = "PLACEHOLDER",
Salt = ascii.GetBytes("abcdefghij"),
IterationCount = 1,
AnswerHex = (
// T-Block 1
"AD8CE08CFA8F932CF9FEDDCDB6E4BC6417D61F0465D408C0BFE9656E2C1C47" +
"1424537ADB2D9EBE4E4232F474EFEE2AF347F21A804F64CBC05474A6DCE0A5" +
// T-Block 2
"078100F813C1F8388EC233C1397D5E18C6509B5483141EF836C15A34D6DC67" +
"A3C46A45798A2839CFD239749219E9F2EDAD3249EC8221AFB17C0028A4A0A5"),
};
}
public class KnownValuesTestCase
{
public string CaseName { get; set; }
public string HashAlgorithmName { get; set; }
public string Password { get; set; }
public byte[] Salt { get; set; }
public int IterationCount { get; set; }
public string AnswerHex { get; set; }
public override string ToString()
{
return CaseName;
}
}
}
}
| |
// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Calendars
{
/// <summary>
/// Implementation of the algorithms described in
/// http://www.cs.tau.ac.il/~nachum/calendar-book/papers/calendar.ps, using scriptural
/// month numbering.
/// </summary>
internal static class HebrewScripturalCalculator
{
internal const int MaxYear = 9999;
internal const int MinYear = 1;
// Use the bottom two bits of the day value to indicate Heshvan/Kislev.
// Using the top bits causes issues for negative day values (only relevant for
// invalid years, but still problematic in general).
private const int IsHeshvanLongCacheBit = 1 << 0;
private const int IsKislevShortCacheBit = 1 << 1;
// Number of bits to shift the elapsed days in order to get the cache value.
private const int ElapsedDaysCacheShift = 2;
// Cache of when each year starts (in terms of absolute days). This is the heart of
// the algorithm, so just caching this is highly effective.
// Each entry additionally encodes the length of Heshvan and Kislev. We could encode
// more information too, but those are the tricky bits.
private static readonly YearStartCacheEntry[] YearCache = YearStartCacheEntry.CreateCache();
internal static bool IsLeapYear(int year) => ((year * 7) + 1) % 19 < 7;
internal static YearMonthDay GetYearMonthDay(int year, int dayOfYear)
{
unchecked
{
// Work out everything about the year in one go.
int cache = GetOrPopulateCache(year);
int heshvanLength = (cache & IsHeshvanLongCacheBit) != 0 ? 30 : 29;
int kislevLength = (cache & IsKislevShortCacheBit) != 0 ? 29 : 30;
bool isLeap = IsLeapYear(year);
int firstAdarLength = isLeap ? 30 : 29;
if (dayOfYear < 31)
{
// Tishri
return new YearMonthDay(year, 7, dayOfYear);
}
if (dayOfYear < 31 + heshvanLength)
{
// Heshvan
return new YearMonthDay(year, 8, dayOfYear - 30);
}
// Now "day of year without Heshvan"...
dayOfYear -= heshvanLength;
if (dayOfYear < 31 + kislevLength)
{
// Kislev
return new YearMonthDay(year, 9, dayOfYear - 30);
}
// Now "day of year without Heshvan or Kislev"...
dayOfYear -= kislevLength;
if (dayOfYear < 31 + 29)
{
// Tevet
return new YearMonthDay(year, 10, dayOfYear - 30);
}
if (dayOfYear < 31 + 29 + 30)
{
// Shevat
return new YearMonthDay(year, 11, dayOfYear - (30 + 29));
}
if (dayOfYear < 31 + 29 + 30 + firstAdarLength)
{
// Adar / Adar I
return new YearMonthDay(year, 12, dayOfYear - (30 + 29 + 30));
}
// Now "day of year without first month of Adar"
dayOfYear -= firstAdarLength;
if (isLeap)
{
if (dayOfYear < 31 + 29 + 30 + 29)
{
return new YearMonthDay(year, 13, dayOfYear - (30 + 29 + 30));
}
// Now "day of year without any Adar"
dayOfYear -= 29;
}
// We could definitely do a binary search from here, but it would only
// a few comparisons at most, and simplicity trumps optimization.
if (dayOfYear < 31 + 29 + 30 + 30)
{
// Nisan
return new YearMonthDay(year, 1, dayOfYear - (30 + 29 + 30));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29)
{
// Iyar
return new YearMonthDay(year, 2, dayOfYear - (30 + 29 + 30 + 30));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29 + 30)
{
// Sivan
return new YearMonthDay(year, 3, dayOfYear - (30 + 29 + 30 + 30 + 29));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29 + 30 + 29)
{
// Tamuz
return new YearMonthDay(year, 4, dayOfYear - (30 + 29 + 30 + 30 + 29 + 30));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29 + 30 + 29 + 30)
{
// Av
return new YearMonthDay(year, 5, dayOfYear - (30 + 29 + 30 + 30 + 29 + 30 + 29));
}
// Elul
return new YearMonthDay(year, 6, dayOfYear - (30 + 29 + 30 + 30 + 29 + 30 + 29 + 30));
}
}
internal static int GetDaysFromStartOfYearToStartOfMonth(int year, int month)
{
// Work out everything about the year in one go. (Admittedly we don't always need it all... but for
// anything other than Tishri and Heshvan, we at least need the length of Heshvan...)
unchecked
{
int cache = GetOrPopulateCache(year);
int heshvanLength = (cache & IsHeshvanLongCacheBit) != 0 ? 30 : 29;
int kislevLength = (cache & IsKislevShortCacheBit) != 0 ? 29 : 30;
bool isLeap = IsLeapYear(year);
int firstAdarLength = isLeap ? 30 : 29;
int secondAdarLength = isLeap ? 29 : 0;
return month switch
{
// Note: this could be made slightly faster (at least in terms of the apparent IL) by
// putting all the additions of compile-time constants in one place. Indeed, we could
// go further by only using isLeap at most once per case. However, this code is clearer
// and there's no evidence that this is a bottleneck.
// Nisan
1 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength,
// Iyar
2 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + 30,
// Sivan
3 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29),
// Tamuz
4 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29 + 30),
// Av
5 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29 + 30 + 29),
// Elul
6 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29 + 30 + 29 + 30),
// Tishri
7 => 0,
// Heshvan
8 => 30,
// Kislev
9 => 30 + heshvanLength,
// Tevet
10 => 30 + heshvanLength + kislevLength,
// Shevat
11 => 30 + heshvanLength + kislevLength + 29,
// Adar / Adar I
12 => 30 + heshvanLength + kislevLength + 29 + 30,
// Adar II
13 => 30 + heshvanLength + kislevLength + 29 + 30 + firstAdarLength,
// TODO: It would be nice for this to be simple via Preconditions
_ => throw new ArgumentOutOfRangeException(nameof(month), month, $"Value should be in range [1-13]")
};
}
}
internal static int DaysInMonth(int year, int month) => month switch
{
// FIXME: How do we express multiple cases in a switch expression?
// We want: (2, 4, 6, 10, 13) => 29,
2 => 29,
4 => 29,
6 => 29,
10 => 29,
13 => 29,
8 => IsHeshvanLong(year) ? 30 : 29,
9 => IsKislevShort(year) ? 29 : 30,
12 => IsLeapYear(year) ? 30 : 29,
_ => 30 // 1, 3, 5, 7, 11, 13
};
private static bool IsHeshvanLong(int year)
{
int cache = GetOrPopulateCache(year);
return (cache & IsHeshvanLongCacheBit) != 0;
}
private static bool IsKislevShort(int year)
{
int cache = GetOrPopulateCache(year);
return (cache & IsKislevShortCacheBit) != 0;
}
/// <summary>
/// Elapsed days since the Hebrew epoch at the start of the given Hebrew year.
/// This is *inclusive* of the first day of the year, so ElapsedDays(1) returns 1.
/// </summary>
internal static int ElapsedDays(int year)
{
int cache = GetOrPopulateCache(year);
return cache >> ElapsedDaysCacheShift;
}
private static int ElapsedDaysNoCache(int year)
{
int monthsElapsed = (235 * ((year - 1) / 19)) // Months in complete cycles so far
+ (12 * ((year - 1) % 19)) // Regular months in this cycle
+ ((((year - 1) % 19) * 7 + 1) / 19); // Leap months this cycle
// Second option in the paper, which keeps values smaller
int partsElapsed = 204 + (793 * (monthsElapsed % 1080));
int hoursElapsed = 5 + (12 * monthsElapsed) + (793 * (monthsElapsed / 1080)) + (partsElapsed / 1080);
int day = 1 + (29 * monthsElapsed) + (hoursElapsed / 24);
int parts = ((hoursElapsed % 24) * 1080) + (partsElapsed % 1080);
bool postponeRoshHaShanah = (parts >= 19440) ||
(day % 7 == 2 && parts >= 9924 && !IsLeapYear(year)) ||
(day % 7 == 1 && parts >= 16789 && IsLeapYear(year - 1));
int alternativeDay = postponeRoshHaShanah ? 1 + day : day;
int alternativeDayMod7 = alternativeDay % 7;
return (alternativeDayMod7 == 0 || alternativeDayMod7 == 3 || alternativeDayMod7 == 5)
? alternativeDay + 1 : alternativeDay;
}
/// <summary>
/// Returns the cached "elapsed day at start of year / IsHeshvanLong / IsKislevShort" combination,
/// populating the cache if necessary. Bits 2-24 are the "elapsed days start of year"; bit 0 is
/// "is Heshvan long"; bit 1 is "is Kislev short". If the year is out of the range for the cache,
/// the value is populated but not cached.
/// </summary>
/// <param name="year"></param>
private static int GetOrPopulateCache(int year)
{
if (year < MinYear || year > MaxYear)
{
return ComputeCacheEntry(year);
}
int cacheIndex = YearStartCacheEntry.GetCacheIndex(year);
YearStartCacheEntry cacheEntry = YearCache[cacheIndex];
if (!cacheEntry.IsValidForYear(year))
{
int days = ComputeCacheEntry(year);
cacheEntry = new YearStartCacheEntry(year, days);
YearCache[cacheIndex] = cacheEntry;
}
return cacheEntry.StartOfYearDays;
}
/// <summary>
/// Computes the cache entry value for the given year, but without populating the cache.
/// </summary>
private static int ComputeCacheEntry(int year)
{
int days = ElapsedDaysNoCache(year);
// We want the elapsed days for the next year as well. Check the cache if possible.
int nextYear = year + 1;
int nextYearDays;
if (nextYear <= MaxYear)
{
int cacheIndex = YearStartCacheEntry.GetCacheIndex(nextYear);
YearStartCacheEntry cacheEntry = YearCache[cacheIndex];
nextYearDays = cacheEntry.IsValidForYear(nextYear)
? cacheEntry.StartOfYearDays >> ElapsedDaysCacheShift
: ElapsedDaysNoCache(nextYear);
}
else
{
nextYearDays = ElapsedDaysNoCache(year + 1);
}
int daysInYear = nextYearDays - days;
bool isHeshvanLong = daysInYear % 10 == 5;
bool isKislevShort = daysInYear % 10 == 3;
return (days << ElapsedDaysCacheShift)
| (isHeshvanLong ? IsHeshvanLongCacheBit : 0)
| (isKislevShort ? IsKislevShortCacheBit : 0);
}
internal static int DaysInYear(int year) => ElapsedDays(year + 1) - ElapsedDays(year);
}
}
| |
#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.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using Microsoft.Identity.Json.Utilities;
using System.Collections;
#if !HAVE_LINQ
using Microsoft.Identity.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Microsoft.Identity.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
internal class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="System.Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="System.Type"/> of the collection items.</value>
public Type CollectionItemType { get; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; }
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; }
internal bool ShouldCreateWrapper { get; }
internal bool CanDeserialize { get; private set; }
private readonly ConstructorInfo _parameterizedConstructor;
private ObjectConstructor<object> _parameterizedCreator;
private ObjectConstructor<object> _overrideCreator;
internal ObjectConstructor<object> ParameterizedCreator
{
get
{
if (_parameterizedCreator == null)
{
_parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor);
}
return _parameterizedCreator;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object> OverrideCreator
{
get => _overrideCreator;
set
{
_overrideCreator = value;
// hacky
CanDeserialize = true;
}
}
/// <summary>
/// Gets a value indicating whether the creator has a parameter with the collection values.
/// </summary>
/// <value><c>true</c> if the creator has a parameter with the collection values; otherwise, <c>false</c>.</value>
public bool HasParameterizedCreator { get; set; }
internal bool HasParameterizedCreatorInternal => HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null;
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
IsArray = CreatedType.IsArray;
bool canDeserialize;
Type tempCollectionType;
if (IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = IsArray && UnderlyingType.GetArrayRank() > 1;
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
}
else
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
}
if (underlyingType == typeof(IList))
{
CreatedType = typeof(List<object>);
}
if (CollectionItemType != null)
{
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
}
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
{
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
}
#if HAVE_ISET
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
{
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
}
#endif
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
#if HAVE_READ_ONLY_COLLECTIONS
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>)))
{
CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType);
}
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType);
#if HAVE_FSHARP_TYPES
StoreFSharpListCreatorIfNecessary(underlyingType);
#endif
IsReadOnlyOrFixedSize = true;
canDeserialize = HasParameterizedCreatorInternal;
}
#endif
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
{
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
}
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
#if HAVE_FSHARP_TYPES
StoreFSharpListCreatorIfNecessary(underlyingType);
#endif
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = HasParameterizedCreatorInternal;
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
#if NET20 || NET35
if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType))
{
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray))
{
ShouldCreateWrapper = true;
}
}
#endif
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(
underlyingType,
CollectionItemType,
out Type immutableCreatedType,
out ObjectConstructor<object> immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
CanDeserialize = true;
}
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
}
else
{
constructorArgument = _genericCollectionDefinitionType;
}
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null)
? typeof(object)
: CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
#if HAVE_FSHARP_TYPES
private void StoreFSharpListCreatorIfNecessary(Type underlyingType)
{
if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName)
{
FSharpUtils.EnsureInitialized(underlyingType.Assembly());
_parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType);
}
}
#endif
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("_weakref", typeof(IronPython.Modules.PythonWeakRef))]
namespace IronPython.Modules {
public static partial class PythonWeakRef {
public const string __doc__ = "Provides support for creating weak references and proxies to objects";
/// <summary>
/// Wrapper provided for backwards compatibility.
/// </summary>
internal static IWeakReferenceable ConvertToWeakReferenceable(PythonContext context, object obj) {
return context.ConvertToWeakReferenceable(obj);
}
public static int getweakrefcount(CodeContext context, object @object) {
return @ref.GetWeakRefCount(PythonContext.GetContext(context), @object);
}
public static List getweakrefs(CodeContext context, object @object) {
return @ref.GetWeakRefs(PythonContext.GetContext(context), @object);
}
public static object proxy(CodeContext context, object @object) {
return proxy(context, @object, null);
}
public static object proxy(CodeContext context, object @object, object callback) {
if (PythonOps.IsCallable(context, @object)) {
return weakcallableproxy.MakeNew(context, @object, callback);
} else {
return weakproxy.MakeNew(context, @object, callback);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType CallableProxyType = DynamicHelpers.GetPythonTypeFromType(typeof(weakcallableproxy));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType ProxyType = DynamicHelpers.GetPythonTypeFromType(typeof(weakproxy));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType ReferenceType = DynamicHelpers.GetPythonTypeFromType(typeof(@ref));
[PythonType]
public class @ref : IStructuralEquatable
#if CLR2
, IValueEquality
#endif
{
private WeakHandle _target;
private int _hashVal;
private bool _fHasHash;
private CodeContext _context;
#region Python Constructors
public static object __new__(CodeContext context, PythonType cls, object @object) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(PythonContext.GetContext(context), @object);
if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(@ref))) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
if (wrt.GetHandlerCallback(i) == null && wrt.GetWeakRef(i) is @ref) {
return wrt.GetWeakRef(i);
}
}
}
return new @ref(context, @object);
} else {
return cls.CreateInstance(context, @object);
}
}
public static object __new__(CodeContext context, PythonType cls, object @object, object callback) {
if (callback == null) return __new__(context, cls, @object);
if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(@ref))) {
return new @ref(context, @object, callback);
} else {
return cls.CreateInstance(context, @object, callback);
}
}
#endregion
#region Constructors
public @ref(CodeContext context, object @object)
: this(context, @object, null) {
}
public @ref(CodeContext context, object @object, object callback) {
this._context = context;
WeakRefHelpers.InitializeWeakRef(this._context.GetPythonContext(), this, @object, callback);
this._target = new WeakHandle(@object, false);
}
#endregion
#region Finalizer
~@ref() {
// remove our self from the chain...
try {
if (_target.IsAlive) {
IWeakReferenceable iwr;
if (this._context.GetPythonContext().TryConvertToWeakReferenceable(_target.Target, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
// weak reference being finalized before target object,
// we don't want to run the callback when the object is
// finalized.
wrt.RemoveHandler(this);
}
}
_target.Free();
}
} catch (InvalidOperationException) {
// target was freed
}
}
#endregion
#region Static helpers
internal static int GetWeakRefCount(PythonContext context, object o) {
IWeakReferenceable iwr;
if (context.TryConvertToWeakReferenceable(o, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) return wrt.HandlerCount;
}
return 0;
}
internal static List GetWeakRefs(PythonContext context, object o) {
List l = new List();
IWeakReferenceable iwr;
if (context.TryConvertToWeakReferenceable(o, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
l.AddNoLock(wrt.GetWeakRef(i));
}
}
}
return l;
}
#endregion
[SpecialName]
public object Call(CodeContext context) {
if (!_target.IsAlive) {
return null;
}
try {
object res = _target.Target;
GC.KeepAlive(this);
return res;
} catch (InvalidOperationException) {
return null;
}
}
[return: MaybeNotImplemented]
public static NotImplementedType operator >(@ref self, object other) {
return PythonOps.NotImplemented;
}
[return: MaybeNotImplemented]
public static NotImplementedType operator <(@ref self, object other) {
return PythonOps.NotImplemented;
}
[return: MaybeNotImplemented]
public static NotImplementedType operator <=(@ref self, object other) {
return PythonOps.NotImplemented;
}
[return: MaybeNotImplemented]
public static NotImplementedType operator >=(@ref self, object other) {
return PythonOps.NotImplemented;
}
#region IValueEquality Members
#if CLR2
int IValueEquality.GetValueHashCode() {
return __hash__(DefaultContext.Default);
}
bool IValueEquality.ValueEquals(object other) {
return EqualsWorker(other, null);
}
#endif
#endregion
#region IStructuralEquatable Members
/// <summary>
/// Special hash function because IStructuralEquatable.GetHashCode is not allowed to throw.
/// </summary>
public int __hash__(CodeContext/*!*/ context) {
if (!_fHasHash) {
object refObj = _target.Target;
if (refObj == null) throw PythonOps.TypeError("weak object has gone away");
GC.KeepAlive(this);
_hashVal = PythonContext.GetContext(context).EqualityComparerNonGeneric.GetHashCode(refObj);
_fHasHash = true;
}
return _hashVal;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
if (!_fHasHash) {
object refObj = _target.Target;
GC.KeepAlive(this);
_hashVal = comparer.GetHashCode(refObj);
_fHasHash = true;
}
return _hashVal;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
return EqualsWorker(other, comparer);
}
private bool EqualsWorker(object other, IEqualityComparer comparer) {
if (object.ReferenceEquals(this, other)) {
return true;
}
bool fResult = false;
@ref wr = other as @ref;
if (wr != null) {
object ourTarget = _target.Target;
object itsTarget = wr._target.Target;
GC.KeepAlive(this);
GC.KeepAlive(wr);
if (ourTarget != null && itsTarget != null) {
fResult = RefEquals(ourTarget, itsTarget, comparer);
}
}
GC.KeepAlive(this);
return fResult;
}
/// <summary>
/// Special equals because none of the special cases in Ops.Equals
/// are applicable here, and the reference equality check breaks some tests.
/// </summary>
private static bool RefEquals(object x, object y, IEqualityComparer comparer) {
CodeContext context;
if (comparer != null && comparer is PythonContext.PythonEqualityComparer) {
context = ((PythonContext.PythonEqualityComparer)comparer).Context.SharedContext;
} else {
context = DefaultContext.Default;
}
object ret;
if (PythonTypeOps.TryInvokeBinaryOperator(context, x, y, "__eq__", out ret) &&
ret != NotImplementedType.Value) {
return (bool)ret;
}
if (PythonTypeOps.TryInvokeBinaryOperator(context, y, x, "__eq__", out ret) &&
ret != NotImplementedType.Value) {
return (bool)ret;
}
if (comparer != null) {
return comparer.Equals(x, y);
}
return x.Equals(y);
}
#endregion
}
[PythonType, DynamicBaseTypeAttribute, PythonHidden]
public sealed partial class weakproxy : IPythonObject, ICodeFormattable, IProxyObject, IPythonMembersList, IStructuralEquatable
#if CLR2
, IValueEquality
#endif
{
private readonly WeakHandle _target;
private readonly CodeContext/*!*/ _context;
#region Python Constructors
internal static object MakeNew(CodeContext/*!*/ context, object @object, object callback) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(PythonContext.GetContext(context), @object);
if (callback == null) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
if (wrt.GetHandlerCallback(i) == null && wrt.GetWeakRef(i) is weakproxy) {
return wrt.GetWeakRef(i);
}
}
}
}
return new weakproxy(context, @object, callback);
}
#endregion
#region Constructors
private weakproxy(CodeContext/*!*/ context, object target, object callback) {
WeakRefHelpers.InitializeWeakRef(PythonContext.GetContext(context), this, target, callback);
_target = new WeakHandle(target, false);
_context = context;
}
#endregion
#region Finalizer
~weakproxy() {
// remove our self from the chain...
try {
IWeakReferenceable iwr;
if (this._context.GetPythonContext().TryConvertToWeakReferenceable(_target.Target, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
wrt.RemoveHandler(this);
}
_target.Free();
} catch (InvalidOperationException) {
// target was freed
}
}
#endregion
#region private members
/// <summary>
/// gets the object or throws a reference exception
/// </summary>
object GetObject() {
object res;
if (!TryGetObject(out res)) {
throw PythonOps.ReferenceError("weakly referenced object no longer exists");
}
return res;
}
bool TryGetObject(out object result) {
try {
result = _target.Target;
if (result == null) return false;
GC.KeepAlive(this);
return true;
} catch (InvalidOperationException) {
result = null;
return false;
}
}
#endregion
#region IPythonObject Members
PythonDictionary IPythonObject.Dict {
get {
IPythonObject sdo = GetObject() as IPythonObject;
if (sdo != null) {
return sdo.Dict;
}
return null;
}
}
PythonDictionary IPythonObject.SetDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).SetDict(dict);
}
bool IPythonObject.ReplaceDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).ReplaceDict(dict);
}
void IPythonObject.SetPythonType(PythonType newType) {
(GetObject() as IPythonObject).SetPythonType(newType);
}
PythonType IPythonObject.PythonType {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(weakproxy));
}
}
object[] IPythonObject.GetSlots() { return null; }
object[] IPythonObject.GetSlotsCreate() { return null; }
#endregion
#region object overloads
public override string ToString() {
return PythonOps.ToString(GetObject());
}
#endregion
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
object obj = _target.Target;
GC.KeepAlive(this);
return String.Format("<weakproxy at {0} to {1} at {2}>",
IdDispenser.GetId(this),
PythonOps.GetPythonTypeName(obj),
IdDispenser.GetId(obj));
}
#endregion
#region Custom member access
[SpecialName]
public object GetCustomMember(CodeContext/*!*/ context, string name) {
object value, o = GetObject();
if (PythonOps.TryGetBoundAttr(context, o, name, out value)) {
return value;
}
return OperationFailed.Value;
}
[SpecialName]
public void SetMember(CodeContext/*!*/ context, string name, object value) {
object o = GetObject();
PythonOps.SetAttr(context, o, name, value);
}
[SpecialName]
public void DeleteMember(CodeContext/*!*/ context, string name) {
object o = GetObject();
PythonOps.DeleteAttr(context, o, name);
}
IList<string> IMembersList.GetMemberNames() {
return PythonOps.GetStringMemberList(this);
}
IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) {
object o;
if (!TryGetObject(out o)) {
// if we've been disconnected return an empty list
return new List();
}
return PythonOps.GetAttrNames(context, o);
}
#endregion
#region IProxyObject Members
object IProxyObject.Target {
get { return GetObject(); }
}
#endregion
#region IValueEquality Members
#if CLR2
int IValueEquality.GetValueHashCode() {
throw PythonOps.TypeErrorForUnhashableType("weakproxy");
}
bool IValueEquality.ValueEquals(object other) {
weakproxy wrp = other as weakproxy;
if (wrp != null) return EqualsWorker(wrp);
return PythonOps.EqualRetBool(_context, GetObject(), other);
}
#endif
#endregion
#region IStructuralEquatable Members
public const object __hash__ = null;
private bool EqualsWorker(weakproxy other) {
return PythonOps.EqualRetBool(_context, GetObject(), other.GetObject());
}
/// <summary>
/// Special equality function because IStructuralEquatable.Equals is not allowed to throw.
/// </summary>
[return: MaybeNotImplemented]
public object __eq__(object other) {
if (!(other is weakproxy)) return NotImplementedType.Value;
return ScriptingRuntimeHelpers.BooleanToObject(EqualsWorker((weakproxy)other));
}
[return: MaybeNotImplemented]
public object __ne__(object other) {
if (!(other is weakproxy)) return NotImplementedType.Value;
return ScriptingRuntimeHelpers.BooleanToObject(!EqualsWorker((weakproxy)other));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
object obj;
if (TryGetObject(out obj)) {
return comparer.GetHashCode(obj);
}
return comparer.GetHashCode(null);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
object obj;
if (!TryGetObject(out obj)) {
obj = null;
}
weakproxy wrp = other as weakproxy;
if (wrp != null) {
object otherObj;
if (!TryGetObject(out otherObj)) {
otherObj = null;
}
return comparer.Equals(obj, otherObj);
}
return comparer.Equals(obj, other);
}
#endregion
public object __nonzero__() {
return Converter.ConvertToBoolean(GetObject());
}
public static explicit operator bool(weakproxy self) {
return Converter.ConvertToBoolean(self.GetObject());
}
}
[PythonType, DynamicBaseTypeAttribute, PythonHidden]
public sealed partial class weakcallableproxy :
IPythonObject,
ICodeFormattable,
IProxyObject,
IStructuralEquatable,
#if CLR2
IValueEquality,
#endif
IPythonMembersList {
private WeakHandle _target;
private readonly CodeContext/*!*/ _context;
#region Python Constructors
internal static object MakeNew(CodeContext/*!*/ context, object @object, object callback) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(PythonContext.GetContext(context), @object);
if (callback == null) {
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt != null) {
for (int i = 0; i < wrt.HandlerCount; i++) {
if (wrt.GetHandlerCallback(i) == null &&
wrt.GetWeakRef(i) is weakcallableproxy) {
return wrt.GetWeakRef(i);
}
}
}
}
return new weakcallableproxy(context, @object, callback);
}
#endregion
#region Constructors
private weakcallableproxy(CodeContext context, object target, object callback) {
WeakRefHelpers.InitializeWeakRef(PythonContext.GetContext(context), this, target, callback);
_target = new WeakHandle(target, false);
_context = context;
}
#endregion
#region Finalizer
~weakcallableproxy() {
// remove our self from the chain...
try {
IWeakReferenceable iwr;
if (this._context.GetPythonContext().TryConvertToWeakReferenceable(_target.Target, out iwr)) {
WeakRefTracker wrt = iwr.GetWeakRef();
wrt.RemoveHandler(this);
}
_target.Free();
} catch (InvalidOperationException) {
// target was freed
}
}
#endregion
#region private members
/// <summary>
/// gets the object or throws a reference exception
/// </summary>
private object GetObject() {
object res;
if (!TryGetObject(out res)) {
throw PythonOps.ReferenceError("weakly referenced object no longer exists");
}
return res;
}
private bool TryGetObject(out object result) {
try {
result = _target.Target;
if (result == null) return false;
GC.KeepAlive(this);
return true;
} catch (InvalidOperationException) {
result = null;
return false;
}
}
#endregion
#region IPythonObject Members
PythonDictionary IPythonObject.Dict {
get {
return (GetObject() as IPythonObject).Dict;
}
}
PythonDictionary IPythonObject.SetDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).SetDict(dict);
}
bool IPythonObject.ReplaceDict(PythonDictionary dict) {
return (GetObject() as IPythonObject).ReplaceDict(dict);
}
void IPythonObject.SetPythonType(PythonType newType) {
(GetObject() as IPythonObject).SetPythonType(newType);
}
PythonType IPythonObject.PythonType {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(weakcallableproxy));
}
}
object[] IPythonObject.GetSlots() { return null; }
object[] IPythonObject.GetSlotsCreate() { return null; }
#endregion
#region object overloads
public override string ToString() {
return PythonOps.ToString(GetObject());
}
#endregion
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
object obj = _target.Target;
GC.KeepAlive(this);
return String.Format("<weakproxy at {0} to {1} at {2}>",
IdDispenser.GetId(this),
PythonOps.GetPythonTypeName(obj),
IdDispenser.GetId(obj));
}
#endregion
[SpecialName]
public object Call(CodeContext/*!*/ context, params object[] args) {
return PythonContext.GetContext(context).CallSplat(GetObject(), args);
}
[SpecialName]
public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
return PythonCalls.CallWithKeywordArgs(context, GetObject(), args, dict);
}
#region Custom members access
[SpecialName]
public object GetCustomMember(CodeContext/*!*/ context, string name) {
object o = GetObject();
object value;
if (PythonOps.TryGetBoundAttr(context, o, name, out value)) {
return value;
}
return OperationFailed.Value;
}
[SpecialName]
public void SetMember(CodeContext/*!*/ context, string name, object value) {
object o = GetObject();
PythonOps.SetAttr(context, o, name, value);
}
[SpecialName]
public void DeleteMember(CodeContext/*!*/ context, string name) {
object o = GetObject();
PythonOps.DeleteAttr(context, o, name);
}
IList<string> IMembersList.GetMemberNames() {
return PythonOps.GetStringMemberList(this);
}
IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) {
object o;
if (!TryGetObject(out o)) {
// if we've been disconnected return an empty list
return new List();
}
return PythonOps.GetAttrNames(context, o);
}
#endregion
#region IProxyObject Members
object IProxyObject.Target {
get { return GetObject(); }
}
#endregion
#region IValueEquality Members
#if CLR2
int IValueEquality.GetValueHashCode() {
throw PythonOps.TypeErrorForUnhashableType("weakcallableproxy");
}
bool IValueEquality.ValueEquals(object other) {
return __eq__(other);
}
#endif
#endregion
#region IStructuralEquatable Members
public const object __hash__ = null;
/// <summary>
/// Special equality function because IStructuralEquatable.Equals is not allowed to throw.
/// </summary>
public bool __eq__(object other) {
weakcallableproxy wrp = other as weakcallableproxy;
if (wrp != null) return GetObject().Equals(wrp.GetObject());
return PythonOps.EqualRetBool(_context, GetObject(), other);
}
public bool __ne__(object other) {
return !__eq__(other);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
object obj;
if (TryGetObject(out obj)) {
return comparer.GetHashCode(obj);
}
return comparer.GetHashCode(null);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
object obj;
if (!TryGetObject(out obj)) {
obj = null;
}
weakcallableproxy wrp = other as weakcallableproxy;
if (wrp != null) {
object otherObj;
if (!TryGetObject(out otherObj)) {
otherObj = null;
}
return comparer.Equals(obj, otherObj);
}
return comparer.Equals(obj, other);
}
#endregion
public object __nonzero__() {
return Converter.ConvertToBoolean(GetObject());
}
}
static class WeakRefHelpers {
public static void InitializeWeakRef(PythonContext context, object self, object target, object callback) {
IWeakReferenceable iwr = ConvertToWeakReferenceable(context, target);
WeakRefTracker wrt = iwr.GetWeakRef();
if (wrt == null) {
if (!iwr.SetWeakRef(new WeakRefTracker(callback, self))) {
throw PythonOps.TypeError("cannot create weak reference to '{0}' object", PythonOps.GetPythonTypeName(target));
}
} else {
wrt.ChainCallback(callback, self);
}
}
}
}
[PythonType("wrapper_descriptor")]
class SlotWrapper : PythonTypeSlot, ICodeFormattable {
private readonly string _name;
private readonly PythonType _type;
public SlotWrapper(string slotName, PythonType targetType) {
_name = slotName;
_type = targetType;
}
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
return String.Format("<slot wrapper {0} of {1} objects>",
PythonOps.Repr(context, _name),
PythonOps.Repr(context, _type.Name));
}
#endregion
#region PythonTypeSlot Overrides
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
if (instance == null) {
value = this;
return true;
}
IProxyObject proxy = instance as IProxyObject;
if (proxy == null)
throw PythonOps.TypeError("descriptor for {0} object doesn't apply to {1} object",
PythonOps.Repr(context, _type.Name),
PythonOps.Repr(context, PythonTypeOps.GetName(instance)));
if (!DynamicHelpers.GetPythonType(proxy.Target).TryGetBoundMember(context, proxy.Target, _name, out value))
return false;
value = new GenericMethodWrapper(_name, proxy);
return true;
}
#endregion
}
[PythonType("method-wrapper")]
public class GenericMethodWrapper {
string name;
IProxyObject target;
public GenericMethodWrapper(string methodName, IProxyObject proxyTarget) {
name = methodName;
target = proxyTarget;
}
[SpecialName]
public object Call(CodeContext context, params object[] args) {
return PythonOps.Invoke(context, target.Target, name, args);
}
[SpecialName]
public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
object targetMethod;
if (!DynamicHelpers.GetPythonType(target.Target).TryGetBoundMember(context, target.Target, name, out targetMethod))
throw PythonOps.AttributeError("type {0} has no attribute {1}",
DynamicHelpers.GetPythonType(target.Target),
name);
return PythonCalls.CallWithKeywordArgs(context, targetMethod, args, dict);
}
}
}
| |
//
// PlayerInterface.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright 2007-2010 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.Linq;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
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.Gui;
using Banshee.Gui.Widgets;
using Banshee.Gui.Dialogs;
using Banshee.Widgets;
using Banshee.Collection.Gui;
using Banshee.Sources.Gui;
namespace Nereid
{
public class PlayerInterface : BaseClientWindow, IClientWindow, IDBusObjectName, IService, IDisposable, IHasSourceView
{
const string CONFIG_NAMESPACE = "player_window";
static readonly SchemaEntry<int> WidthSchema = WindowConfiguration.NewWidthSchema (CONFIG_NAMESPACE, 1024);
static readonly SchemaEntry<int> HeightSchema = WindowConfiguration.NewHeightSchema (CONFIG_NAMESPACE, 700);
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 primary_vbox;
private Table header_table;
private MainMenu main_menu;
private Toolbar header_toolbar;
private HBox footer_toolbar;
private HPaned views_pane;
private ViewContainer view_container;
private VBox source_box;
private Widget track_info_container;
private CoverArtDisplay cover_art_display;
private Widget cover_art_container;
private ConnectedSeekSlider seek_slider;
private TaskStatusIcon task_status;
private Alignment search_entry_align;
// Major Interaction Components
private SourceView source_view;
private CompositeTrackSourceContents composite_view;
private ObjectListSourceContents object_view;
private Label status_label;
public MainMenu MainMenu {
get { return main_menu; }
}
public Toolbar HeaderToolbar {
get { return header_toolbar; }
}
public Table HeaderTable {
get { return header_table; }
}
protected PlayerInterface (IntPtr ptr) : base (ptr)
{
}
private void SetSimple (bool simple)
{
var widgets = new Widget [] { main_menu, source_box, footer_toolbar, track_info_container };
foreach (var w in widgets.Where (w => w != null)) {
w.Visible = !simple;
}
}
public PlayerInterface () :
base (Catalog.GetString ("Banshee Media Player"),
new WindowConfiguration (WidthSchema, HeightSchema, XPosSchema, YPosSchema, MaximizedSchema))
{
}
protected override void Initialize ()
{
InitialShowPresent ();
}
private bool interface_constructed;
protected override void OnShown ()
{
if (interface_constructed) {
base.OnShown ();
return;
}
interface_constructed = true;
uint timer = Log.DebugTimerStart ();
BuildPrimaryLayout ();
ConnectEvents ();
ActionService.SourceActions.SourceView = this;
composite_view.TrackView.HasFocus = true;
Log.DebugTimerPrint (timer, "Constructed Nereid interface: {0}");
base.OnShown ();
}
#region System Overrides
protected override void Dispose (bool disposing)
{
lock (this) {
ServiceManager.SourceManager.ActiveSourceChanged -= OnActiveSourceChanged;
ServiceManager.SourceManager.SourceUpdated -= OnSourceUpdated;
if (disposing) {
Hide ();
}
base.Dispose (disposing);
}
}
#endregion
#region Interface Construction
private void BuildPrimaryLayout ()
{
primary_vbox = new VBox ();
BuildHeader ();
BuildViews ();
BuildFooter ();
search_entry_align = new Alignment (1.0f, 0.5f, 0f, 0f);
var box = new HBox () { Spacing = 2 };
var grabber = new GrabHandle ();
var search_entry = view_container.SearchEntry;
grabber.ControlWidthOf (search_entry, 150, 350, false);
int search_entry_width = SearchEntryWidth.Get ();
// -1 indicates that height should be preserved
search_entry.SetSizeRequest (search_entry_width, -1);
search_entry.SizeAllocated += (o, a) => {
SearchEntryWidth.Set (search_entry.Allocation.Width);
};
box.PackStart (grabber, false, false, 0);
box.PackStart (view_container.SearchEntry, false, false, 0);
search_entry_align.Child = box;
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/SearchEntry", search_entry_align);
search_entry_align.Visible = view_container.SearchSensitive = true;
search_entry_align.ShowAll ();
primary_vbox.Show ();
Add (primary_vbox);
}
private void BuildHeader ()
{
header_table = new Table (2, 2, false);
header_table.Show ();
header_table.Vexpand = false;
primary_vbox.PackStart (header_table, false, false, 0);
main_menu = new MainMenu ();
if (!PlatformDetection.IsMac) {
main_menu.Show ();
header_table.Attach (main_menu, 0, 1, 0, 1,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Shrink, 0, 0);
}
Alignment toolbar_alignment = new Alignment (0.0f, 0.0f, 1.0f, 1.0f);
toolbar_alignment.TopPadding = 3u;
toolbar_alignment.BottomPadding = 3u;
header_toolbar = (Toolbar)ActionService.UIManager.GetWidget ("/HeaderToolbar");
header_toolbar.ShowArrow = false;
header_toolbar.ToolbarStyle = ToolbarStyle.BothHoriz;
header_toolbar.Show ();
toolbar_alignment.Add (header_toolbar);
toolbar_alignment.Show ();
header_table.Attach (toolbar_alignment, 0, 2, 1, 2,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Shrink, 0, 0);
var next_button = new NextButton (ActionService);
next_button.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/NextArrowButton", next_button);
seek_slider = new ConnectedSeekSlider () { Resizable = ShowSeekSliderResizer.Get () };
seek_slider.SeekSlider.WidthRequest = SeekSliderWidth.Get ();
seek_slider.SeekSlider.SizeAllocated += (o, a) => {
SeekSliderWidth.Set (seek_slider.SeekSlider.Allocation.Width);
};
seek_slider.ShowAll ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/SeekSlider", seek_slider);
var track_info_display = new ClassicTrackInfoDisplay ();
track_info_display.Show ();
track_info_container = TrackInfoDisplay.GetEditable (track_info_display);
track_info_container.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/TrackInfoDisplay", track_info_container, true);
var volume_button = new ConnectedVolumeButton ();
volume_button.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/VolumeButton", volume_button);
}
private void BuildViews ()
{
source_box = new VBox ();
views_pane = new HPaned ();
PersistentPaneController.Control (views_pane, SourceViewWidth);
view_container = new ViewContainer ();
source_view = new SourceView ();
composite_view = new CompositeTrackSourceContents ();
Container source_scroll;
Hyena.Widgets.ScrolledWindow window;
if (ApplicationContext.CommandLine.Contains ("smooth-scroll")) {
window = new Hyena.Widgets.SmoothScrolledWindow ();
} else {
window = new Hyena.Widgets.ScrolledWindow ();
}
window.Add (source_view);
source_scroll = window;
composite_view.TrackView.HeaderVisible = false;
view_container.Content = composite_view;
source_box.PackStart (source_scroll, true, true, 0);
source_box.PackStart (new UserJobTileHost (), false, false, 0);
UpdateCoverArtDisplay ();
source_view.SetSizeRequest (125, -1);
view_container.SetSizeRequest (425, -1);
views_pane.Pack1 (source_box, false, false);
views_pane.Pack2 (view_container, true, false);
source_box.ShowAll ();
view_container.Show ();
views_pane.Show ();
primary_vbox.PackStart (views_pane, true, true, 0);
}
private void UpdateCoverArtDisplay ()
{
if (ShowCoverArt.Get ()) {
if (cover_art_display == null && source_box != null) {
cover_art_display = new CoverArtDisplay () { Visible = true };
source_box.SizeAllocated += OnSourceBoxSizeAllocated;
cover_art_display.HeightRequest = SourceViewWidth.Get ();
source_box.PackStart (cover_art_container = TrackInfoDisplay.GetEditable (cover_art_display), false, false, 4);
source_box.ShowAll ();
}
} else if (cover_art_display != null) {
cover_art_display.Hide ();
source_box.Remove (cover_art_container);
source_box.SizeAllocated -= OnSourceBoxSizeAllocated;
cover_art_display.Dispose ();
cover_art_display = null;
}
}
private void OnSourceBoxSizeAllocated (object o, EventArgs args)
{
cover_art_display.HeightRequest = source_box.Allocation.Width;
}
private void BuildFooter ()
{
footer_toolbar = new HBox () { BorderWidth = 2 };
task_status = new Banshee.Gui.Widgets.TaskStatusIcon ();
EventBox status_event_box = new EventBox ();
status_event_box.ButtonPressEvent += OnStatusBoxButtonPress;
status_label = new Label ();
status_event_box.Add (status_label);
HBox status_hbox = new HBox (true, 0);
status_hbox.PackStart (status_event_box, false, false, 0);
Alignment status_align = new Alignment (0.5f, 0.5f, 1.0f, 1.0f);
status_align.Add (status_hbox);
RepeatActionButton repeat_button = new RepeatActionButton ();
repeat_button.SizeAllocated += delegate (object o, Gtk.SizeAllocatedArgs args) {
status_align.LeftPadding = (uint)args.Allocation.Width;
};
footer_toolbar.PackStart (task_status, false, false, 0);
footer_toolbar.PackStart (status_align, true, true, 0);
footer_toolbar.PackStart (repeat_button, false, false, 0);
footer_toolbar.ShowAll ();
primary_vbox.PackStart (footer_toolbar, false, true, 0);
}
private void OnStatusBoxButtonPress (object o, ButtonPressEventArgs args)
{
Source source = ServiceManager.SourceManager.ActiveSource;
if (source != null) {
source.CycleStatusFormat ();
UpdateSourceInformation ();
}
}
#endregion
#region Events and Logic Setup
protected override void ConnectEvents ()
{
base.ConnectEvents ();
// Service events
ServiceManager.SourceManager.ActiveSourceChanged += OnActiveSourceChanged;
ServiceManager.SourceManager.SourceUpdated += OnSourceUpdated;
ActionService.TrackActions ["SearchForSameArtistAction"].Activated += OnProgrammaticSearch;
ActionService.TrackActions ["SearchForSameAlbumAction"].Activated += OnProgrammaticSearch;
(ActionService.ViewActions ["ShowCoverArtAction"] as Gtk.ToggleAction).Active = ShowCoverArt.Get ();
ActionService.ViewActions ["ShowCoverArtAction"].Activated += (o, a) => {
ShowCoverArt.Set ((o as Gtk.ToggleAction).Active);
UpdateCoverArtDisplay ();
};
// UI events
view_container.SearchEntry.Changed += OnSearchEntryChanged;
// TODO: Check that this still works, it was using SizeRequested
views_pane.SizeAllocated += delegate {
SourceViewWidth.Set (views_pane.Position);
};
source_view.RowActivated += delegate {
Source source = ServiceManager.SourceManager.ActiveSource;
var handler = source.Properties.Get<System.Action> ("ActivationAction");
if (handler != null) {
handler ();
} else if (source is ITrackModelSource) {
ServiceManager.PlaybackController.NextSource = (ITrackModelSource)source;
// Allow changing the play source without stopping the current song by
// holding ctrl when activating a source. After the song is done, playback will
// continue from the new source.
if (GtkUtilities.NoImportantModifiersAreSet (Gdk.ModifierType.ControlMask)) {
ServiceManager.PlaybackController.Next ();
}
}
};
}
#endregion
#region Service Event Handlers
private void OnProgrammaticSearch (object o, EventArgs args)
{
Source source = ServiceManager.SourceManager.ActiveSource;
view_container.SearchEntry.Ready = false;
view_container.SearchEntry.Query = source.FilterQuery;
view_container.SearchEntry.Ready = true;
}
private Source previous_source = null;
private TrackListModel previous_track_model = null;
private void OnActiveSourceChanged (SourceEventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
Source source = ServiceManager.SourceManager.ActiveSource;
search_entry_align.Visible = view_container.SearchSensitive = source != null && source.CanSearch;
if (source == null) {
return;
}
view_container.SearchEntry.Ready = false;
view_container.SearchEntry.CancelSearch ();
/* Translators: this is a verb (command), not a noun (things) */
var msg = source.Properties.Get<string> ("SearchEntryDescription") ?? Catalog.GetString ("Search");
view_container.SearchEntry.EmptyMessage = msg;
view_container.SearchEntry.TooltipText = msg;
if (source.FilterQuery != null) {
view_container.SearchEntry.Query = source.FilterQuery;
view_container.SearchEntry.ActivateFilter ((int)source.FilterType);
}
if (view_container.Content != null) {
view_container.Content.ResetSource ();
}
if (previous_track_model != null) {
previous_track_model.Reloaded -= HandleTrackModelReloaded;
previous_track_model = null;
}
if (source is ITrackModelSource) {
previous_track_model = (source as ITrackModelSource).TrackModel;
previous_track_model.Reloaded += HandleTrackModelReloaded;
}
if (previous_source != null) {
previous_source.Properties.PropertyChanged -= OnSourcePropertyChanged;
}
previous_source = source;
previous_source.Properties.PropertyChanged += OnSourcePropertyChanged;
UpdateSourceContents (source);
UpdateSourceInformation ();
view_container.SearchEntry.Ready = true;
SetSimple (source.Properties.Get<bool> ("Nereid.SimpleUI"));
});
}
private void OnSourcePropertyChanged (object o, PropertyChangeEventArgs args)
{
switch (args.PropertyName) {
case "Nereid.SourceContents":
ThreadAssist.ProxyToMain (delegate {
UpdateSourceContents (previous_source);
});
break;
case "FilterQuery":
var source = ServiceManager.SourceManager.ActiveSource;
var search_entry = source.Properties.Get<SearchEntry> ("Nereid.SearchEntry") ?? view_container.SearchEntry;
if (!search_entry.HasFocus) {
ThreadAssist.ProxyToMain (delegate {
view_container.SearchEntry.Ready = false;
view_container.SearchEntry.Query = source.FilterQuery;
view_container.SearchEntry.Ready = true;
});
}
break;
case "Nereid.SimpleUI":
SetSimple (ServiceManager.SourceManager.ActiveSource.Properties.Get<bool> ("Nereid.SimpleUI"));
break;
}
}
private void UpdateSourceContents (Source source)
{
if (source == null) {
return;
}
// Connect the source models to the views if possible
ISourceContents contents = source.GetProperty<ISourceContents> ("Nereid.SourceContents",
source.GetInheritedProperty<bool> ("Nereid.SourceContentsPropagate"));
view_container.ClearHeaderWidget ();
view_container.ClearFooter ();
if (contents != null) {
if (view_container.Content != contents) {
view_container.Content = contents;
}
view_container.Content.SetSource (source);
view_container.Show ();
} else if (source is ITrackModelSource) {
view_container.Content = composite_view;
view_container.Content.SetSource (source);
view_container.Show ();
} else if (source is Hyena.Data.IObjectListModel) {
if (object_view == null) {
object_view = new ObjectListSourceContents ();
}
view_container.Content = object_view;
view_container.Content.SetSource (source);
view_container.Show ();
} else {
view_container.Hide ();
}
// Associate the view with the model
if (view_container.Visible && view_container.Content is ITrackModelSourceContents) {
ITrackModelSourceContents track_content = view_container.Content as ITrackModelSourceContents;
source.Properties.Set<IListView<TrackInfo>> ("Track.IListView", track_content.TrackView);
}
var title_widget = source.Properties.Get<Widget> ("Nereid.SourceContents.TitleWidget");
if (title_widget != null) {
Hyena.Log.WarningFormat ("Nereid.SourceContents.TitleWidget is no longer used (from {0})", source.Name);
}
Widget header_widget = null;
if (source.Properties.Contains ("Nereid.SourceContents.HeaderWidget")) {
header_widget = source.Properties.Get<Widget> ("Nereid.SourceContents.HeaderWidget");
}
if (header_widget != null) {
view_container.SetHeaderWidget (header_widget);
}
Widget footer_widget = null;
if (source.Properties.Contains ("Nereid.SourceContents.FooterWidget")) {
footer_widget = source.Properties.Get<Widget> ("Nereid.SourceContents.FooterWidget");
}
if (footer_widget != null) {
view_container.SetFooter (footer_widget);
}
}
private void OnSourceUpdated (SourceEventArgs args)
{
if (args.Source == ServiceManager.SourceManager.ActiveSource) {
ThreadAssist.ProxyToMain (delegate {
UpdateSourceInformation ();
});
}
}
#endregion
#region UI Event Handlers
private void OnSearchEntryChanged (object o, EventArgs args)
{
Source source = ServiceManager.SourceManager.ActiveSource;
if (source == null)
return;
source.FilterType = (TrackFilterType)view_container.SearchEntry.ActiveFilterID;
source.FilterQuery = view_container.SearchEntry.Query;
}
#endregion
#region Implement Interfaces
// IHasSourceView
public Source HighlightedSource {
get { return source_view.HighlightedSource; }
}
public void BeginRenameSource (Source source)
{
source_view.BeginRenameSource (source);
}
public void ResetHighlight ()
{
source_view.ResetHighlight ();
}
public override Box ViewContainer {
get { return view_container; }
}
#endregion
#region Gtk.Window Overrides
private bool accel_group_active = true;
private void OnEntryFocusOutEvent (object o, FocusOutEventArgs args)
{
if (!accel_group_active) {
AddAccelGroup (ActionService.UIManager.AccelGroup);
accel_group_active = true;
}
(o as Widget).FocusOutEvent -= OnEntryFocusOutEvent;
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
bool focus_search = false;
bool disable_keybindings = Focus is Gtk.Entry;
if (!disable_keybindings) {
var widget = Focus;
while (widget != null) {
if (widget is IDisableKeybindings) {
disable_keybindings = true;
break;
}
widget = widget.Parent;
}
}
// Don't disable them if ctrl is pressed, unless ctrl-a is pressed
if (evnt.Key != Gdk.Key.a) {
disable_keybindings &= (evnt.State & Gdk.ModifierType.ControlMask) == 0 &&
evnt.Key != Gdk.Key.Control_L && evnt.Key != Gdk.Key.Control_R;
}
if (disable_keybindings) {
if (accel_group_active) {
RemoveAccelGroup (ActionService.UIManager.AccelGroup);
accel_group_active = false;
// Reinstate the AccelGroup as soon as the focus leaves the entry
Focus.FocusOutEvent += OnEntryFocusOutEvent;
}
} else {
if (!accel_group_active) {
AddAccelGroup (ActionService.UIManager.AccelGroup);
accel_group_active = true;
}
}
switch (evnt.Key) {
case Gdk.Key.f:
if (Gdk.ModifierType.ControlMask == (evnt.State & Gdk.ModifierType.ControlMask)) {
focus_search = true;
}
break;
case Gdk.Key.S:
case Gdk.Key.s:
case Gdk.Key.slash:
if (!disable_keybindings) {
focus_search = true;
}
break;
case Gdk.Key.F3:
focus_search = true;
break;
case Gdk.Key.F11:
ActionService.ViewActions["FullScreenAction"].Activate ();
break;
}
// The source might have its own custom search entry - use it if so
var src = ServiceManager.SourceManager.ActiveSource;
var search_entry = src.Properties.Get<SearchEntry> ("Nereid.SearchEntry") ?? view_container.SearchEntry;
if (focus_search && search_entry.Visible && !source_view.EditingRow) {
search_entry.GrabFocus ();
search_entry.HasFocus = true;
return true;
}
return base.OnKeyPressEvent (evnt);
}
#endregion
#region Popup Status Bar
#if false
private Gdk.FilterReturn OnGdkEventFilter (IntPtr xevent, Gdk.Event gdkevent)
{
if (!IsRealized || !IsMapped) {
return Gdk.FilterReturn.Continue;
}
Gdk.ModifierType mask;
int x, y;
GdkWindow.GetPointer (out x, out y, out mask);
return Gdk.FilterReturn.Continue;
}
#endif
#endregion
#region Helper Functions
private void HandleTrackModelReloaded (object sender, EventArgs args)
{
ThreadAssist.ProxyToMain (UpdateSourceInformation);
}
private void UpdateSourceInformation ()
{
if (status_label == null) {
return;
}
Source source = ServiceManager.SourceManager.ActiveSource;
if (source == null) {
status_label.Text = String.Empty;
return;
}
status_label.Text = source.GetStatusText ();
// We need a bit longer delay between query character typed to search initiated
// when the library is sufficiently big; see bgo #540835
bool long_delay = source.FilteredCount > 6000 || (source.Parent ?? source).Count > 12000;
view_container.SearchEntry.ChangeTimeoutMs = long_delay ? (uint)250 : (uint)25;
}
#endregion
#region Configuration Schemas
public static readonly SchemaEntry<int> SourceViewWidth = new SchemaEntry<int> (
"player_window", "source_view_width",
175,
"Source View Width",
"Width of Source View Column."
);
public static readonly SchemaEntry<bool> ShowCoverArt = new SchemaEntry<bool> (
"player_window", "show_cover_art",
false,
"Show cover art",
"Show cover art below source view if available"
);
private static readonly SchemaEntry<bool> ShowSeekSliderResizer = new SchemaEntry<bool> (
"player_window", "show_seek_slider_resizer",
true, "Show seek slider resize grip", ""
);
private static readonly SchemaEntry<int> SeekSliderWidth = new SchemaEntry<int> (
"player_window", "seek_slider_width",
175, "Width of seek slider in px", ""
);
private static readonly SchemaEntry<int> SearchEntryWidth = new SchemaEntry<int> (
"player_window", "search_entry_width",
200, "Width of search entry element in px", ""
);
#endregion
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
string IDBusObjectName.ExportObjectName {
get { return "ClientWindow"; }
}
string IService.ServiceName {
get { return "NereidPlayerInterface"; }
}
}
}
| |
using System.IO;
using System.Linq;
using VersionOne.Profile;
// TODO at least move classes to separate files
namespace VersionOne.ServiceHost.Core {
public delegate void ProcessFileDelegate(string file);
public delegate void ProcessFileBatchDelegate(string[] files);
public delegate void ProcessFolderDelegate(string folder);
public delegate void ProcessFolderBatchDelegate(string[] folders);
public abstract class FileSystemMonitor {
private readonly IProfile profile;
private IProfile processedPathsProfile;
private IProfile ProcessedPaths {
get {
return processedPathsProfile ?? (processedPathsProfile = profile["ProcessedFiles"]);
// Retaining name "ProcessedFiles" for backward-compatibility
}
}
protected string FilterPattern { get; set; }
protected string WatchFolder { get; set; }
/// <summary>
/// Get the processed state of the given file from the profile.
/// </summary>
/// <param name="file">File to look up.</param>
/// <returns>True if processed. False if not processed. Null if not in profile.</returns>
protected bool? GetState(string file) {
var value = ProcessedPaths[file].Value;
if(value == null) {
return null;
}
return bool.Parse(value);
}
/// <summary>
/// Save the processing state for the given file to the profile.
/// </summary>
/// <param name="file">File in question.</param>
/// <param name="done">True if processed.</param>
protected void SaveState(string file, bool? done) {
ProcessedPaths[file].Value = done == null ? null : done.ToString();
}
public FileSystemMonitor(IProfile profile, string watchFolder, string filterPattern) {
this.profile = profile;
WatchFolder = watchFolder;
FilterPattern = filterPattern;
if(string.IsNullOrEmpty(FilterPattern)) {
FilterPattern = "*.*";
}
var path = Path.GetFullPath(WatchFolder);
if(!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
}
/// <summary>
/// Perform the basic processing pattern.
/// </summary>
/// <param name="path">A file or directory name, depending on the subclass implementation.</param>
protected void ProcessPath(string path) {
if (GetState(path) == null) {
SaveState(path, false);
InvokeProcessor(path);
SaveState(path, true);
}
}
protected abstract void InvokeProcessor(string path);
}
public class FileMonitor : FileSystemMonitor {
private readonly ProcessFileDelegate processor;
public FileMonitor(IProfile profile, string watchfolder, string filterpattern, ProcessFileDelegate processor) : base(profile, watchfolder, filterpattern) {
this.processor = processor;
}
public void ProcessFolder(object pubobj) {
var path = Path.GetFullPath(WatchFolder);
var files = Directory.GetFiles(path, FilterPattern);
foreach(var file in files) {
ProcessPath(file);
}
}
protected override void InvokeProcessor(string path) {
processor(path);
}
}
public class FolderMonitor : FileSystemMonitor {
private readonly ProcessFolderDelegate processor;
public FolderMonitor(IProfile profile, string watchFolder, string filterPattern, ProcessFolderDelegate processor) : base(profile, watchFolder, filterPattern) {
this.processor = processor;
}
public void ProcessFolder(object pubobj) {
var path = Path.GetFullPath(WatchFolder);
var subFolders = Directory.GetDirectories(path, FilterPattern);
foreach(var subFolder in subFolders) {
ProcessPath(subFolder);
}
}
protected override void InvokeProcessor(string path) {
processor(path);
}
}
public class BatchFolderMonitor : FileSystemMonitor {
private readonly ProcessFolderBatchDelegate processor;
public BatchFolderMonitor(IProfile profile, string watchFolder, string filterPattern, ProcessFolderBatchDelegate processor) : base(profile, watchFolder, filterPattern) {
this.processor = processor;
}
public void ProcessFolder(object pubobj) {
var path = Path.GetFullPath(WatchFolder);
var subFolders = Directory.GetDirectories(path, FilterPattern, SearchOption.AllDirectories);
var notProcessed = subFolders.Where(subFolder => GetState(subFolder) == null).ToList();
if(notProcessed.Count == 0) {
return;
}
foreach(var subFolder in notProcessed) {
SaveState(subFolder, false);
}
processor(notProcessed.ToArray());
foreach(var subFolder in notProcessed) {
SaveState(subFolder, true);
}
}
protected override void InvokeProcessor(string path) {
// TODO: Fix this smell
}
}
/// <summary>
/// More thoroughly determines if a file has been processed.
/// Compares file modified stamps for paths that have been logged.
/// </summary>
public class RecyclingFileMonitor {
private readonly IProfile profile;
private IProfile processedPathsProfile;
private readonly ProcessFileBatchDelegate processor;
private IProfile ProcessedPaths {
get {
return processedPathsProfile ?? (processedPathsProfile = profile["ProcessedFiles"]);
// Retaining name "ProcessedFiles" for backward-compatibility
}
}
protected string FilterPattern { get; set; }
protected string WatchFolder { get; set; }
/// <summary>
/// Get the processed state of the given file from the profile.
/// </summary>
/// <param name="file">File to look up.</param>
/// <returns>True if processed. False if not processed. Null if not in profile.</returns>
protected bool? GetState(string file) {
var value = ProcessedPaths[file].Value;
if(value == null) {
return null;
}
var haveProcessed = bool.Parse(value);
if (haveProcessed) {
// we've seen this path before, so look at the last write timestamp
var stampValue = ProcessedPaths[file]["LastWrite"].Value;
long storedLastWrite;
if (long.TryParse(stampValue, out storedLastWrite)) {
var actualLastWrite = File.GetLastWriteTimeUtc(file).ToBinary();
if(actualLastWrite > storedLastWrite) {
return null;
}
}
return true;
}
return false;
}
/// <summary>
/// Save the processing state for the given file to the profile.
/// </summary>
/// <param name="file">File in question.</param>
/// <param name="done">True if processed.</param>
protected void SaveState(string file, bool? done) {
ProcessedPaths[file].Value = done == null ? null : done.ToString();
if (done.HasValue && done.Value) {
var lastWrite = File.GetLastWriteTimeUtc(file).ToBinary();
ProcessedPaths[file]["LastWrite"].Value = lastWrite.ToString();
}
}
public RecyclingFileMonitor(IProfile profile, string watchFolder, string filterPattern, ProcessFileBatchDelegate processor) {
this.processor = processor;
this.profile = profile;
WatchFolder = watchFolder;
FilterPattern = filterPattern;
if(string.IsNullOrEmpty(FilterPattern)) {
FilterPattern = "*.*";
}
var path = Path.GetFullPath(WatchFolder);
if(!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
}
protected void InvokeProcessor(string[] files) {
processor(files);
}
public void ProcessFolder(object pubobj) {
var path = Path.GetFullPath(WatchFolder);
var files = Directory.GetFiles(path, FilterPattern, SearchOption.AllDirectories);
var toProcess = files.Where(file => GetState(file) == null).ToList();
foreach(var file in toProcess) {
SaveState(file, false);
}
InvokeProcessor(toProcess.ToArray());
foreach(var file in toProcess) {
SaveState(file, true);
}
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocType
// ObjectType: DocType
// CSLAType: EditableRoot
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using Csla.Rules;
using Csla.Rules.CommonRules;
using DocStore.Business.Security;
namespace DocStore.Business
{
/// <summary>
/// Document type (editable root object).<br/>
/// This is a generated <see cref="DocType"/> business object.
/// </summary>
[Serializable]
public partial class DocType : BusinessBase<DocType>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="DocTypeID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> DocTypeIDProperty = RegisterProperty<int>(p => p.DocTypeID, "Doc Type ID");
/// <summary>
/// Gets the Doc Type ID.
/// </summary>
/// <value>The Doc Type ID.</value>
public int DocTypeID
{
get { return GetProperty(DocTypeIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocTypeName"/> property.
/// </summary>
public static readonly PropertyInfo<string> DocTypeNameProperty = RegisterProperty<string>(p => p.DocTypeName, "Doc Type Name");
/// <summary>
/// Gets or sets the Doc Type Name.
/// </summary>
/// <value>The Doc Type Name.</value>
public string DocTypeName
{
get { return GetProperty(DocTypeNameProperty); }
set { SetProperty(DocTypeNameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// Gets the Create User ID.
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// Gets the Change User ID.
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Gets the Create User Name.
/// </summary>
/// <value>The Create User Name.</value>
public string CreateUserName
{
get
{
var result = string.Empty;
if (Admin.UserNVL.GetUserNVL().ContainsKey(CreateUserID))
result = Admin.UserNVL.GetUserNVL().GetItemByKey(CreateUserID).Value;
return result;
}
}
/// <summary>
/// Gets the Change User Name.
/// </summary>
/// <value>The Change User Name.</value>
public string ChangeUserName
{
get
{
var result = string.Empty;
if (Admin.UserNVL.GetUserNVL().ContainsKey(ChangeUserID))
result = Admin.UserNVL.GetUserNVL().GetItemByKey(ChangeUserID).Value;
return result;
}
}
#endregion
#region BusinessBase<T> overrides
/// <summary>
/// Returns a string that represents the current <see cref="DocType"/>
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
// Return the Primary Key as a string
return DocTypeName.ToString();
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocType"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="DocType"/> object.</returns>
public static DocType NewDocType()
{
return DataPortal.Create<DocType>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocType"/> object, based on given parameters.
/// </summary>
/// <param name="docTypeID">The DocTypeID parameter of the DocType to fetch.</param>
/// <returns>A reference to the fetched <see cref="DocType"/> object.</returns>
public static DocType GetDocType(int docTypeID)
{
return DataPortal.Fetch<DocType>(docTypeID);
}
/// <summary>
/// Factory method. Deletes a <see cref="DocType"/> object, based on given parameters.
/// </summary>
/// <param name="docTypeID">The DocTypeID of the DocType to delete.</param>
public static void DeleteDocType(int docTypeID)
{
DataPortal.Delete<DocType>(docTypeID);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocType"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewDocType(EventHandler<DataPortalResult<DocType>> callback)
{
DataPortal.BeginCreate<DocType>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="DocType"/> object, based on given parameters.
/// </summary>
/// <param name="docTypeID">The DocTypeID parameter of the DocType to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetDocType(int docTypeID, EventHandler<DataPortalResult<DocType>> callback)
{
DataPortal.BeginFetch<DocType>(docTypeID, callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="DocType"/> object, based on given parameters.
/// </summary>
/// <param name="docTypeID">The DocTypeID of the DocType to delete.</param>
/// <param name="callback">The completion callback method.</param>
public static void DeleteDocType(int docTypeID, EventHandler<DataPortalResult<DocType>> callback)
{
DataPortal.BeginDelete<DocType>(docTypeID, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocType"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocType()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Object Authorization
/// <summary>
/// Adds the object authorization rules.
/// </summary>
protected static void AddObjectAuthorizationRules()
{
BusinessRules.AddRule(typeof (DocType), new IsInRole(AuthorizationActions.CreateObject, "Manager"));
BusinessRules.AddRule(typeof (DocType), new IsInRole(AuthorizationActions.GetObject, "User"));
BusinessRules.AddRule(typeof (DocType), new IsInRole(AuthorizationActions.EditObject, "Manager"));
BusinessRules.AddRule(typeof (DocType), new IsInRole(AuthorizationActions.DeleteObject, "Admin"));
AddObjectAuthorizationRulesExtend();
}
/// <summary>
/// Allows the set up of custom object authorization rules.
/// </summary>
static partial void AddObjectAuthorizationRulesExtend();
/// <summary>
/// Checks if the current user can create a new DocType object.
/// </summary>
/// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns>
public static bool CanAddObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(DocType));
}
/// <summary>
/// Checks if the current user can retrieve DocType's properties.
/// </summary>
/// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns>
public static bool CanGetObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(DocType));
}
/// <summary>
/// Checks if the current user can change DocType's properties.
/// </summary>
/// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns>
public static bool CanEditObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(DocType));
}
/// <summary>
/// Checks if the current user can delete a DocType object.
/// </summary>
/// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns>
public static bool CanDeleteObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(DocType));
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="DocType"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(DocTypeIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="DocType"/> object from the database, based on given criteria.
/// </summary>
/// <param name="docTypeID">The Doc Type ID.</param>
protected void DataPortal_Fetch(int docTypeID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetDocType", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocTypeID", docTypeID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, docTypeID);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="DocType"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(DocTypeIDProperty, dr.GetInt32("DocTypeID"));
LoadProperty(DocTypeNameProperty, dr.GetString("DocTypeName"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="DocType"/> object in the database.
/// </summary>
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddDocType", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(DocTypeIDProperty, (int) cmd.Parameters["@DocTypeID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="DocType"/> object.
/// </summary>
protected override void DataPortal_Update()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateDocType", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
OnPropertyChanged("ChangeUserName");
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
OnPropertyChanged("CreateUserName");
}
}
/// <summary>
/// Self deletes the <see cref="DocType"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(DocTypeID);
}
/// <summary>
/// Deletes the <see cref="DocType"/> object from database.
/// </summary>
/// <param name="docTypeID">The delete criteria.</param>
protected void DataPortal_Delete(int docTypeID)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteDocType", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocTypeID", docTypeID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, docTypeID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
ctx.Commit();
}
}
#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
}
}
| |
namespace Newtonsoft.Json
{
using System;
using System.IO;
using System.Globalization;
using Utilities;
using System.Xml;
using Converters;
/// <summary>
/// Provides methods for converting between common language runtime types and JavaScript types.
/// </summary>
public static class JavaScriptConvert
{
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True;
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False;
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null;
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined;
internal static long InitialJavaScriptDateTicks;
internal static DateTime MinimumJavaScriptDate;
static JavaScriptConvert()
{
True = "true";
False = "false";
Null = "null";
Undefined = "undefined";
InitialJavaScriptDateTicks = (new DateTime(1970, 1, 1)).Ticks;
MinimumJavaScriptDate = new DateTime(100, 1, 1);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value);
return "new Date(" + javaScriptTicks + ")";
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
{
if (dateTime < MinimumJavaScriptDate)
dateTime = MinimumJavaScriptDate;
long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks)/(long)10000;
return javaScriptTicks;
}
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
{
DateTime dateTime = new DateTime((javaScriptTicks*10000) + InitialJavaScriptDateTicks);
return dateTime;
}
/// <summary>
/// Converts the <see cref="Boolean"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString();
}
/// <summary>
/// Converts the <see cref="Int32"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="UInt16"/>.</returns>
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="UInt32"/>.</returns>
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="UInt64"/>.</returns>
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Double"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Byte"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="SByte"/>.</returns>
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Guid"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return '"' + value.ToString("D", CultureInfo.InvariantCulture) + '"';
}
/// <summary>
/// Converts the <see cref="String"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimter">The string delimiter character.</param>
/// <returns>A Json string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimter = '"')
{
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
{
return Null;
}
else if (value is IConvertible)
{
var convertible = value as IConvertible;
switch (convertible.GetTypeCode())
{
case TypeCode.String:
return ToString((string)convertible);
case TypeCode.Char:
return ToString((char)convertible);
case TypeCode.Boolean:
return ToString((bool)convertible);
case TypeCode.SByte:
return ToString((sbyte)convertible);
case TypeCode.Int16:
return ToString((short)convertible);
case TypeCode.UInt16:
return ToString((ushort)convertible);
case TypeCode.Int32:
return ToString((int)convertible);
case TypeCode.Byte:
return ToString((byte)convertible);
case TypeCode.UInt32:
return ToString((uint)convertible);
case TypeCode.Int64:
return ToString((long)convertible);
case TypeCode.UInt64:
return ToString((ulong)convertible);
case TypeCode.Single:
return ToString((float)convertible);
case TypeCode.Double:
return ToString((double)convertible);
case TypeCode.DateTime:
return ToString((DateTime)convertible);
case TypeCode.Decimal:
return ToString((decimal)convertible);
}
}
throw new ArgumentException(
string.Format(
"Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.",
value.GetType()));
}
/// <summary>
/// Serializes the specified object to a Json object.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A Json string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, null);
}
public static string SerializeObject(object value, params JsonConverter[] converters)
{
var sw = new StringWriter(CultureInfo.InvariantCulture);
var jsonSerializer = new JsonSerializer();
if (!CollectionUtils.IsNullOrEmpty<JsonConverter>(converters))
{
for (int i = 0; i < converters.Length; i++)
{
jsonSerializer.Converters.Add(converters[i]);
}
}
using (JsonWriter jsonWriter = new JsonWriter(sw))
{
//jsonWriter.Formatting = Formatting.Indented;
jsonSerializer.Serialize(jsonWriter, value);
}
return sw.ToString();
}
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <param name="value">The object to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, null);
}
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <param name="value">The object to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, null);
}
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, null);
}
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
var sr = new StringReader(value);
var jsonSerializer = new JsonSerializer();
if (!CollectionUtils.IsNullOrEmpty<JsonConverter>(converters))
{
for (int i = 0; i < converters.Length; i++)
{
jsonSerializer.Converters.Add(converters[i]);
}
}
object deserializedValue;
using (var jsonReader = new JsonReader(sr))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, type);
}
return deserializedValue;
}
public static string SerializeXmlNode(XmlNode node)
{
var converter = new XmlNodeConverter();
return SerializeObject(node, converter);
}
public static XmlNode DeerializeXmlNode(string value)
{
var converter = new XmlNodeConverter();
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <author name="Daniel Grunwald"/>
// <version>$Revision: 5948 $</version>
// </file>
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using System.Windows.Threading;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;
namespace ICSharpCode.AvalonEdit.Editing
{
/// <summary>
/// Helper class with caret-related methods.
/// </summary>
public sealed class Caret
{
readonly TextArea textArea;
readonly TextView textView;
readonly CaretLayer caretAdorner;
bool visible;
internal Caret(TextArea textArea)
{
this.textArea = textArea;
this.textView = textArea.TextView;
position = new TextViewPosition(1, 1, 0);
caretAdorner = new CaretLayer(textView);
textView.InsertLayer(caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace);
textView.VisualLinesChanged += TextView_VisualLinesChanged;
textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
void TextView_VisualLinesChanged(object sender, EventArgs e)
{
if (visible) {
Show();
}
// required because the visual columns might have changed if the
// element generators did something differently than on the last run
// (e.g. a FoldingSection was collapsed)
InvalidateVisualColumn();
}
void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
if (caretAdorner != null) {
caretAdorner.InvalidateVisual();
}
}
double desiredXPos = double.NaN;
TextViewPosition position;
/// <summary>
/// Gets/Sets the position of the caret.
/// Retrieving this property will validate the visual column (which can be expensive).
/// Use the <see cref="Location"/> property instead if you don't need the visual column.
/// </summary>
public TextViewPosition Position {
get {
ValidateVisualColumn();
return position;
}
set {
if (position != value) {
position = value;
storedCaretOffset = -1;
//Debug.WriteLine("Caret position changing to " + value);
ValidatePosition();
InvalidateVisualColumn();
RaisePositionChanged();
Log("Caret position changed to " + value);
if (visible)
Show();
}
}
}
/// <summary>
/// Gets/Sets the location of the caret.
/// The getter of this property is faster than <see cref="Position"/> because it doesn't have
/// to validate the visual column.
/// </summary>
public TextLocation Location {
get {
return position;
}
set {
this.Position = new TextViewPosition(value);
}
}
/// <summary>
/// Gets/Sets the caret line.
/// </summary>
public int Line {
get { return position.Line; }
set {
this.Position = new TextViewPosition(value, position.Column);
}
}
/// <summary>
/// Gets/Sets the caret column.
/// </summary>
public int Column {
get { return position.Column; }
set {
this.Position = new TextViewPosition(position.Line, value);
}
}
/// <summary>
/// Gets/Sets the caret visual column.
/// </summary>
public int VisualColumn {
get {
ValidateVisualColumn();
return position.VisualColumn;
}
set {
this.Position = new TextViewPosition(position.Line, position.Column, value);
}
}
int storedCaretOffset;
internal void OnDocumentChanging()
{
storedCaretOffset = this.Offset;
InvalidateVisualColumn();
}
internal void OnDocumentChanged(DocumentChangeEventArgs e)
{
InvalidateVisualColumn();
if (storedCaretOffset >= 0) {
int newCaretOffset = e.GetNewOffset(storedCaretOffset, AnchorMovementType.AfterInsertion);
TextDocument document = textArea.Document;
if (document != null) {
// keep visual column
this.Position = new TextViewPosition(document.GetLocation(newCaretOffset), position.VisualColumn);
}
}
storedCaretOffset = -1;
}
/// <summary>
/// Gets/Sets the caret offset.
/// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN.
/// </summary>
public int Offset {
get {
TextDocument document = textArea.Document;
if (document == null) {
return 0;
} else {
return document.GetOffset(position);
}
}
set {
TextDocument document = textArea.Document;
if (document != null) {
this.Position = new TextViewPosition(document.GetLocation(value));
this.DesiredXPos = double.NaN;
}
}
}
/// <summary>
/// Gets/Sets the desired x-position of the caret, in device-independent pixels.
/// This property is NaN if the caret has no desired position.
/// </summary>
public double DesiredXPos {
get { return desiredXPos; }
set { desiredXPos = value; }
}
void ValidatePosition()
{
if (position.Line < 1)
position.Line = 1;
if (position.Column < 1)
position.Column = 1;
if (position.VisualColumn < -1)
position.VisualColumn = -1;
TextDocument document = textArea.Document;
if (document != null) {
if (position.Line > document.LineCount) {
position.Line = document.LineCount;
position.Column = document.GetLineByNumber(position.Line).Length + 1;
position.VisualColumn = -1;
} else {
DocumentLine line = document.GetLineByNumber(position.Line);
if (position.Column > line.Length + 1) {
position.Column = line.Length + 1;
position.VisualColumn = -1;
}
}
}
}
/// <summary>
/// Event raised when the caret position has changed.
/// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls),
/// the PositionChanged event is raised only once at the end of the document update.
/// </summary>
public event EventHandler PositionChanged;
bool raisePositionChangedOnUpdateFinished;
void RaisePositionChanged()
{
if (textArea.Document != null && textArea.Document.IsInUpdate) {
raisePositionChangedOnUpdateFinished = true;
} else {
if (PositionChanged != null) {
PositionChanged(this, EventArgs.Empty);
}
}
}
internal void OnDocumentUpdateFinished()
{
if (raisePositionChangedOnUpdateFinished) {
if (PositionChanged != null) {
PositionChanged(this, EventArgs.Empty);
}
}
}
bool visualColumnValid;
void ValidateVisualColumn()
{
if (!visualColumnValid) {
TextDocument document = textArea.Document;
if (document != null) {
Debug.WriteLine("Explicit validation of caret column");
var documentLine = document.GetLineByNumber(position.Line);
RevalidateVisualColumn(textView.GetOrConstructVisualLine(documentLine));
}
}
}
void InvalidateVisualColumn()
{
visualColumnValid = false;
}
/// <summary>
/// Validates the visual column of the caret using the specified visual line.
/// The visual line must contain the caret offset.
/// </summary>
void RevalidateVisualColumn(VisualLine visualLine)
{
if (visualLine == null)
throw new ArgumentNullException("visualLine");
// mark column as validated
visualColumnValid = true;
int caretOffset = textView.Document.GetOffset(position);
int firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset;
if (position.VisualColumn < 0) {
position.VisualColumn = visualLine.GetVisualColumn(caretOffset - firstDocumentLineOffset);
} else {
int offsetFromVisualColumn = visualLine.GetRelativeOffset(position.VisualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != caretOffset) {
position.VisualColumn = visualLine.GetVisualColumn(caretOffset - firstDocumentLineOffset);
} else {
if (position.VisualColumn > visualLine.VisualLength) {
position.VisualColumn = visualLine.VisualLength;
}
}
}
// search possible caret positions
int newVisualColumnForwards = visualLine.GetNextCaretPosition(position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal);
// If position.VisualColumn was valid, we're done with validation.
if (newVisualColumnForwards != position.VisualColumn) {
// also search backwards so that we can pick the better match
int newVisualColumnBackwards = visualLine.GetNextCaretPosition(position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal);
if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0)
throw ThrowUtil.NoValidCaretPosition();
// determine offsets for new visual column positions
int newOffsetForwards;
if (newVisualColumnForwards >= 0)
newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset;
else
newOffsetForwards = -1;
int newOffsetBackwards;
if (newVisualColumnBackwards >= 0)
newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset;
else
newOffsetBackwards = -1;
int newVisualColumn, newOffset;
// if there's only one valid position, use it
if (newVisualColumnForwards < 0) {
newVisualColumn = newVisualColumnBackwards;
newOffset = newOffsetBackwards;
} else if (newVisualColumnBackwards < 0) {
newVisualColumn = newVisualColumnForwards;
newOffset = newOffsetForwards;
} else {
// two valid positions: find the better match
if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) {
// backwards is better
newVisualColumn = newVisualColumnBackwards;
newOffset = newOffsetBackwards;
} else {
// forwards is better
newVisualColumn = newVisualColumnForwards;
newOffset = newOffsetForwards;
}
}
this.Position = new TextViewPosition(textView.Document.GetLocation(newOffset), newVisualColumn);
}
}
Rect CalcCaretRectangle(VisualLine visualLine)
{
if (!visualColumnValid) {
RevalidateVisualColumn(visualLine);
}
TextLine textLine = visualLine.GetTextLine(position.VisualColumn);
double xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(position.VisualColumn, 0));
double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop);
double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineBottom);
return new Rect(xPos,
lineTop,
SystemParameters.CaretWidth,
lineBottom - lineTop);
}
/// <summary>
/// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document.
/// </summary>
public Rect CalculateCaretRectangle()
{
if (textView != null && textView.Document != null) {
VisualLine visualLine = textView.GetOrConstructVisualLine(textView.Document.GetLineByNumber(position.Line));
return CalcCaretRectangle(visualLine);
} else {
return Rect.Empty;
}
}
/// <summary>
/// Minimum distance of the caret to the view border.
/// </summary>
internal const double MinimumDistanceToViewBorder = 30;
/// <summary>
/// Scrolls the text view so that the caret is visible.
/// </summary>
public void BringCaretToView()
{
BringCaretToView(MinimumDistanceToViewBorder);
}
internal void BringCaretToView(double border)
{
Rect caretRectangle = CalculateCaretRectangle();
if (!caretRectangle.IsEmpty) {
caretRectangle.Inflate(border, border);
textView.MakeVisible(caretRectangle);
}
}
/// <summary>
/// Makes the caret visible and updates its on-screen position.
/// </summary>
public void Show()
{
Log("Caret.Show()");
visible = true;
if (!showScheduled) {
showScheduled = true;
textArea.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(ShowInternal));
}
}
bool showScheduled;
bool hasWin32Caret;
void ShowInternal()
{
showScheduled = false;
// if show was scheduled but caret hidden in the meantime
if (!visible)
return;
if (caretAdorner != null && textView != null) {
VisualLine visualLine = textView.GetVisualLine(position.Line);
if (visualLine != null) {
Rect caretRect = CalcCaretRectangle(visualLine);
// Create Win32 caret so that Windows knows where our managed caret is. This is necessary for
// features like 'Follow text editing' in the Windows Magnifier.
if (!hasWin32Caret) {
hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size);
}
if (hasWin32Caret) {
Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset);
}
caretAdorner.Show(caretRect);
} else {
caretAdorner.Hide();
}
}
}
/// <summary>
/// Makes the caret invisible.
/// </summary>
public void Hide()
{
Log("Caret.Hide()");
visible = false;
if (hasWin32Caret) {
Win32.DestroyCaret();
hasWin32Caret = false;
}
if (caretAdorner != null) {
caretAdorner.Hide();
}
}
[Conditional("DEBUG")]
static void Log(string text)
{
// commented out to make debug output less noisy - add back if there are any problems with the caret
//Debug.WriteLine(text);
}
/// <summary>
/// Gets/Sets the color of the caret.
/// </summary>
public Brush CaretBrush {
get { return caretAdorner.CaretBrush; }
set { caretAdorner.CaretBrush = value; }
}
}
}
| |
// 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.
/*=============================================================================
**
**
**
** Purpose: The base class for all exceptional conditions.
**
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Security.Permissions;
using System.Security;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Exception))]
[Serializable]
[ComVisible(true)]
public class Exception : ISerializable, _Exception
{
private void Init()
{
_message = null;
_stackTrace = null;
_dynamicMethods = null;
HResult = __HResults.COR_E_EXCEPTION;
_xcode = _COMPlusExceptionCode;
_xptrs = (IntPtr) 0;
// Initialize the WatsonBuckets to be null
_watsonBuckets = null;
// Initialize the watson bucketing IP
_ipForWatsonBuckets = UIntPtr.Zero;
#if FEATURE_SERIALIZATION
_safeSerializationManager = new SafeSerializationManager();
#endif // FEATURE_SERIALIZATION
}
public Exception() {
Init();
}
public Exception(String message) {
Init();
_message = message;
}
// Creates a new Exception. All derived classes should
// provide this constructor.
// Note: the stack trace is not started until the exception
// is thrown
//
public Exception (String message, Exception innerException) {
Init();
_message = message;
_innerException = innerException;
}
[System.Security.SecuritySafeCritical] // auto-generated
protected Exception(SerializationInfo info, StreamingContext context)
{
if (info==null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
_className = info.GetString("ClassName");
_message = info.GetString("Message");
_data = (IDictionary)(info.GetValueNoThrow("Data",typeof(IDictionary)));
_innerException = (Exception)(info.GetValue("InnerException",typeof(Exception)));
_helpURL = info.GetString("HelpURL");
_stackTraceString = info.GetString("StackTraceString");
_remoteStackTraceString = info.GetString("RemoteStackTraceString");
_remoteStackIndex = info.GetInt32("RemoteStackIndex");
_exceptionMethodString = (String)(info.GetValue("ExceptionMethod",typeof(String)));
HResult = info.GetInt32("HResult");
_source = info.GetString("Source");
// Get the WatsonBuckets that were serialized - this is particularly
// done to support exceptions going across AD transitions.
//
// We use the no throw version since we could be deserializing a pre-V4
// exception object that may not have this entry. In such a case, we would
// get null.
_watsonBuckets = (Object)info.GetValueNoThrow("WatsonBuckets", typeof(byte[]));
#if FEATURE_SERIALIZATION
_safeSerializationManager = info.GetValueNoThrow("SafeSerializationManager", typeof(SafeSerializationManager)) as SafeSerializationManager;
#endif // FEATURE_SERIALIZATION
if (_className == null || HResult==0)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
// If we are constructing a new exception after a cross-appdomain call...
if (context.State == StreamingContextStates.CrossAppDomain)
{
// ...this new exception may get thrown. It is logically a re-throw, but
// physically a brand-new exception. Since the stack trace is cleared
// on a new exception, the "_remoteStackTraceString" is provided to
// effectively import a stack trace from a "remote" exception. So,
// move the _stackTraceString into the _remoteStackTraceString. Note
// that if there is an existing _remoteStackTraceString, it will be
// preserved at the head of the new string, so everything works as
// expected.
// Even if this exception is NOT thrown, things will still work as expected
// because the StackTrace property returns the concatenation of the
// _remoteStackTraceString and the _stackTraceString.
_remoteStackTraceString = _remoteStackTraceString + _stackTraceString;
_stackTraceString = null;
}
}
public virtual String Message {
get {
if (_message == null) {
if (_className==null) {
_className = GetClassName();
}
return Environment.GetResourceString("Exception_WasThrown", _className);
} else {
return _message;
}
}
}
public virtual IDictionary Data {
[System.Security.SecuritySafeCritical] // auto-generated
get {
if (_data == null)
if (IsImmutableAgileException(this))
_data = new EmptyReadOnlyDictionaryInternal();
else
_data = new ListDictionaryInternal();
return _data;
}
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsImmutableAgileException(Exception e);
#if FEATURE_COMINTEROP
//
// Exception requires anything to be added into Data dictionary is serializable
// This wrapper is made serializable to satisfy this requirement but does NOT serialize
// the object and simply ignores it during serialization, because we only need
// the exception instance in the app to hold the error object alive.
// Once the exception is serialized to debugger, debugger only needs the error reference string
//
[Serializable]
internal class __RestrictedErrorObject
{
// Hold the error object instance but don't serialize/deserialize it
[NonSerialized]
private object _realErrorObject;
internal __RestrictedErrorObject(object errorObject)
{
_realErrorObject = errorObject;
}
public object RealErrorObject
{
get
{
return _realErrorObject;
}
}
}
[FriendAccessAllowed]
internal void AddExceptionDataForRestrictedErrorInfo(
string restrictedError,
string restrictedErrorReference,
string restrictedCapabilitySid,
object restrictedErrorObject,
bool hasrestrictedLanguageErrorObject = false)
{
IDictionary dict = Data;
if (dict != null)
{
dict.Add("RestrictedDescription", restrictedError);
dict.Add("RestrictedErrorReference", restrictedErrorReference);
dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid);
// Keep the error object alive so that user could retrieve error information
// using Data["RestrictedErrorReference"]
dict.Add("__RestrictedErrorObject", (restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject)));
dict.Add("__HasRestrictedLanguageErrorObject", hasrestrictedLanguageErrorObject);
}
}
internal bool TryGetRestrictedLanguageErrorObject(out object restrictedErrorObject)
{
restrictedErrorObject = null;
if (Data != null && Data.Contains("__HasRestrictedLanguageErrorObject"))
{
if (Data.Contains("__RestrictedErrorObject"))
{
__RestrictedErrorObject restrictedObject = Data["__RestrictedErrorObject"] as __RestrictedErrorObject;
if (restrictedObject != null)
restrictedErrorObject = restrictedObject.RealErrorObject;
}
return (bool)Data["__HasRestrictedLanguageErrorObject"];
}
return false;
}
#endif // FEATURE_COMINTEROP
private string GetClassName()
{
// Will include namespace but not full instantiation and assembly name.
if (_className == null)
_className = GetType().ToString();
return _className;
}
// Retrieves the lowest exception (inner most) for the given Exception.
// This will traverse exceptions using the innerException property.
//
public virtual Exception GetBaseException()
{
Exception inner = InnerException;
Exception back = this;
while (inner != null) {
back = inner;
inner = inner.InnerException;
}
return back;
}
// Returns the inner exception contained in this exception
//
public Exception InnerException {
get { return _innerException; }
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern private IRuntimeMethodInfo GetMethodFromStackTrace(Object stackTrace);
[System.Security.SecuritySafeCritical] // auto-generated
private MethodBase GetExceptionMethodFromStackTrace()
{
IRuntimeMethodInfo method = GetMethodFromStackTrace(_stackTrace);
// Under certain race conditions when exceptions are re-used, this can be null
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
public MethodBase TargetSite {
[System.Security.SecuritySafeCritical] // auto-generated
get {
return GetTargetSiteInternal();
}
}
// this function is provided as a private helper to avoid the security demand
[System.Security.SecurityCritical] // auto-generated
private MethodBase GetTargetSiteInternal() {
if (_exceptionMethod!=null) {
return _exceptionMethod;
}
if (_stackTrace==null) {
return null;
}
if (_exceptionMethodString!=null) {
_exceptionMethod = GetExceptionMethodFromString();
} else {
_exceptionMethod = GetExceptionMethodFromStackTrace();
}
return _exceptionMethod;
}
// Returns the stack trace as a string. If no stack trace is
// available, null is returned.
public virtual String StackTrace
{
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
get
{
// By default attempt to include file and line number info
return GetStackTrace(true);
}
}
// Computes and returns the stack trace as a string
// Attempts to get source file and line number information if needFileInfo
// is true. Note that this requires FileIOPermission(PathDiscovery), and so
// will usually fail in CoreCLR. To avoid the demand and resulting
// SecurityException we can explicitly not even try to get fileinfo.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private string GetStackTrace(bool needFileInfo)
{
string stackTraceString = _stackTraceString;
string remoteStackTraceString = _remoteStackTraceString;
#if !FEATURE_CORECLR
if (!needFileInfo)
{
// Filter out file names/paths and line numbers from _stackTraceString and _remoteStackTraceString.
// This is used only when generating stack trace for Watson where the strings must be PII-free.
stackTraceString = StripFileInfo(stackTraceString, false);
remoteStackTraceString = StripFileInfo(remoteStackTraceString, true);
}
#endif // !FEATURE_CORECLR
// if no stack trace, try to get one
if (stackTraceString != null)
{
return remoteStackTraceString + stackTraceString;
}
if (_stackTrace == null)
{
return remoteStackTraceString;
}
// Obtain the stack trace string. Note that since Environment.GetStackTrace
// will add the path to the source file if the PDB is present and a demand
// for FileIOPermission(PathDiscovery) succeeds, we need to make sure we
// don't store the stack trace string in the _stackTraceString member variable.
String tempStackTraceString = Environment.GetStackTrace(this, needFileInfo);
return remoteStackTraceString + tempStackTraceString;
}
[FriendAccessAllowed]
internal void SetErrorCode(int hr)
{
HResult = hr;
}
// Sets the help link for this exception.
// This should be in a URL/URN form, such as:
// "file:///C:/Applications/Bazzal/help.html#ErrorNum42"
// Changed to be a read-write String and not return an exception
public virtual String HelpLink
{
get
{
return _helpURL;
}
set
{
_helpURL = value;
}
}
public virtual String Source {
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
get {
if (_source == null)
{
StackTrace st = new StackTrace(this,true);
if (st.FrameCount>0)
{
StackFrame sf = st.GetFrame(0);
MethodBase method = sf.GetMethod();
Module module = method.Module;
RuntimeModule rtModule = module as RuntimeModule;
if (rtModule == null)
{
System.Reflection.Emit.ModuleBuilder moduleBuilder = module as System.Reflection.Emit.ModuleBuilder;
if (moduleBuilder != null)
rtModule = moduleBuilder.InternalModule;
else
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeReflectionObject"));
}
_source = rtModule.GetRuntimeAssembly().GetSimpleName();
}
}
return _source;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
set { _source = value; }
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public override String ToString()
{
return ToString(true, true);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private String ToString(bool needFileLineInfo, bool needMessage) {
String message = (needMessage ? Message : null);
String s;
if (message == null || message.Length <= 0) {
s = GetClassName();
}
else {
s = GetClassName() + ": " + message;
}
if (_innerException!=null) {
s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine +
" " + Environment.GetResourceString("Exception_EndOfInnerExceptionStack");
}
string stackTrace = GetStackTrace(needFileLineInfo);
if (stackTrace != null)
{
s += Environment.NewLine + stackTrace;
}
return s;
}
[System.Security.SecurityCritical] // auto-generated
private String GetExceptionMethodString() {
MethodBase methBase = GetTargetSiteInternal();
if (methBase==null) {
return null;
}
if (methBase is System.Reflection.Emit.DynamicMethod.RTDynamicMethod)
{
// DynamicMethods cannot be serialized
return null;
}
// Note that the newline separator is only a separator, chosen such that
// it won't (generally) occur in a method name. This string is used
// only for serialization of the Exception Method.
char separator = '\n';
StringBuilder result = new StringBuilder();
if (methBase is ConstructorInfo) {
RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase;
Type t = rci.ReflectedType;
result.Append((int)MemberTypes.Constructor);
result.Append(separator);
result.Append(rci.Name);
if (t!=null)
{
result.Append(separator);
result.Append(t.Assembly.FullName);
result.Append(separator);
result.Append(t.FullName);
}
result.Append(separator);
result.Append(rci.ToString());
} else {
Contract.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
Type t = rmi.DeclaringType;
result.Append((int)MemberTypes.Method);
result.Append(separator);
result.Append(rmi.Name);
result.Append(separator);
result.Append(rmi.Module.Assembly.FullName);
result.Append(separator);
if (t != null)
{
result.Append(t.FullName);
result.Append(separator);
}
result.Append(rmi.ToString());
}
return result.ToString();
}
[System.Security.SecurityCritical] // auto-generated
private MethodBase GetExceptionMethodFromString() {
Contract.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
String[] args = _exceptionMethodString.Split(new char[]{'\0', '\n'});
if (args.Length!=5) {
throw new SerializationException();
}
SerializationInfo si = new SerializationInfo(typeof(MemberInfoSerializationHolder), new FormatterConverter());
si.AddValue("MemberType", (int)Int32.Parse(args[0], CultureInfo.InvariantCulture), typeof(Int32));
si.AddValue("Name", args[1], typeof(String));
si.AddValue("AssemblyName", args[2], typeof(String));
si.AddValue("ClassName", args[3]);
si.AddValue("Signature", args[4]);
MethodBase result;
StreamingContext sc = new StreamingContext(StreamingContextStates.All);
try {
result = (MethodBase)new MemberInfoSerializationHolder(si, sc).GetRealObject(sc);
} catch (SerializationException) {
result = null;
}
return result;
}
#if FEATURE_SERIALIZATION
protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
{
add { _safeSerializationManager.SerializeObjectState += value; }
remove { _safeSerializationManager.SerializeObjectState -= value; }
}
#endif // FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
String tempStackTraceString = _stackTraceString;
if (_stackTrace!=null)
{
if (tempStackTraceString==null)
{
tempStackTraceString = Environment.GetStackTrace(this, true);
}
if (_exceptionMethod==null)
{
_exceptionMethod = GetExceptionMethodFromStackTrace();
}
}
if (_source == null)
{
_source = Source; // Set the Source information correctly before serialization
}
info.AddValue("ClassName", GetClassName(), typeof(String));
info.AddValue("Message", _message, typeof(String));
info.AddValue("Data", _data, typeof(IDictionary));
info.AddValue("InnerException", _innerException, typeof(Exception));
info.AddValue("HelpURL", _helpURL, typeof(String));
info.AddValue("StackTraceString", tempStackTraceString, typeof(String));
info.AddValue("RemoteStackTraceString", _remoteStackTraceString, typeof(String));
info.AddValue("RemoteStackIndex", _remoteStackIndex, typeof(Int32));
info.AddValue("ExceptionMethod", GetExceptionMethodString(), typeof(String));
info.AddValue("HResult", HResult);
info.AddValue("Source", _source, typeof(String));
// Serialize the Watson bucket details as well
info.AddValue("WatsonBuckets", _watsonBuckets, typeof(byte[]));
#if FEATURE_SERIALIZATION
if (_safeSerializationManager != null && _safeSerializationManager.IsActive)
{
info.AddValue("SafeSerializationManager", _safeSerializationManager, typeof(SafeSerializationManager));
// User classes derived from Exception must have a valid _safeSerializationManager.
// Exceptions defined in mscorlib don't use this field might not have it initalized (since they are
// often created in the VM with AllocateObject instead if the managed construtor)
// If you are adding code to use a SafeSerializationManager from an mscorlib exception, update
// this assert to ensure that it fails when that exception's _safeSerializationManager is NULL
Contract.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)),
"User defined exceptions must have a valid _safeSerializationManager");
// Handle serializing any transparent or partial trust subclass data
_safeSerializationManager.CompleteSerialization(this, info, context);
}
#endif // FEATURE_SERIALIZATION
}
// This is used by remoting to preserve the server side stack trace
// by appending it to the message ... before the exception is rethrown
// at the client call site.
internal Exception PrepForRemoting()
{
String tmp = null;
if (_remoteStackIndex == 0)
{
tmp = Environment.NewLine+ "Server stack trace: " + Environment.NewLine
+ StackTrace
+ Environment.NewLine + Environment.NewLine
+ "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine;
}
else
{
tmp = StackTrace
+ Environment.NewLine + Environment.NewLine
+ "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine;
}
_remoteStackTraceString = tmp;
_remoteStackIndex++;
return this;
}
// This method will clear the _stackTrace of the exception object upon deserialization
// to ensure that references from another AD/Process dont get accidently used.
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
_stackTrace = null;
// We wont serialize or deserialize the IP for Watson bucketing since
// we dont know where the deserialized object will be used in.
// Using it across process or an AppDomain could be invalid and result
// in AV in the runtime.
//
// Hence, we set it to zero when deserialization takes place.
_ipForWatsonBuckets = UIntPtr.Zero;
#if FEATURE_SERIALIZATION
if (_safeSerializationManager == null)
{
_safeSerializationManager = new SafeSerializationManager();
}
else
{
_safeSerializationManager.CompleteDeserialization(this);
}
#endif // FEATURE_SERIALIZATION
}
// This is used by the runtime when re-throwing a managed exception. It will
// copy the stack trace to _remoteStackTraceString.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
internal void InternalPreserveStackTrace()
{
string tmpStackTraceString;
#if FEATURE_APPX
if (AppDomain.IsAppXModel())
{
// Call our internal GetStackTrace in AppX so we can parse the result should
// we need to strip file/line info from it to make it PII-free. Calling the
// public and overridable StackTrace getter here was probably not intended.
tmpStackTraceString = GetStackTrace(true);
// Make sure that the _source field is initialized if Source is not overriden.
// We want it to contain the original faulting point.
string source = Source;
}
else
#else // FEATURE_APPX
#if FEATURE_CORESYSTEM
// Preinitialize _source on CoreSystem as well. The legacy behavior is not ideal and
// we keep it for back compat but we can afford to make the change on the Phone.
string source = Source;
#endif // FEATURE_CORESYSTEM
#endif // FEATURE_APPX
{
// Call the StackTrace getter in classic for compat.
tmpStackTraceString = StackTrace;
}
if (tmpStackTraceString != null && tmpStackTraceString.Length > 0)
{
_remoteStackTraceString = tmpStackTraceString + Environment.NewLine;
}
_stackTrace = null;
_stackTraceString = null;
}
#if FEATURE_EXCEPTIONDISPATCHINFO
// This is the object against which a lock will be taken
// when attempt to restore the EDI. Since its static, its possible
// that unrelated exception object restorations could get blocked
// for a small duration but that sounds reasonable considering
// such scenarios are going to be extremely rare, where timing
// matches precisely.
[OptionalField]
private static object s_EDILock = new object();
internal UIntPtr IPForWatsonBuckets
{
get {
return _ipForWatsonBuckets;
}
}
internal object WatsonBuckets
{
get
{
return _watsonBuckets;
}
}
internal string RemoteStackTrace
{
get
{
return _remoteStackTraceString;
}
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void PrepareForForeignExceptionRaise();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetStackTracesDeepCopy(Exception exception, out object currentStackTrace, out object dynamicMethodArray);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SaveStackTracesFromDeepCopy(Exception exception, object currentStackTrace, object dynamicMethodArray);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyStackTrace(object currentStackTrace);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyDynamicMethods(object currentDynamicMethods);
#if !FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern string StripFileInfo(string stackTrace, bool isRemoteStackTrace);
#endif // !FEATURE_CORECLR
[SecuritySafeCritical]
internal object DeepCopyStackTrace(object currentStackTrace)
{
if (currentStackTrace != null)
{
return CopyStackTrace(currentStackTrace);
}
else
{
return null;
}
}
[SecuritySafeCritical]
internal object DeepCopyDynamicMethods(object currentDynamicMethods)
{
if (currentDynamicMethods != null)
{
return CopyDynamicMethods(currentDynamicMethods);
}
else
{
return null;
}
}
[SecuritySafeCritical]
internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray)
{
GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray);
}
// This is invoked by ExceptionDispatchInfo.Throw to restore the exception stack trace, corresponding to the original throw of the
// exception, just before the exception is "rethrown".
[SecuritySafeCritical]
internal void RestoreExceptionDispatchInfo(System.Runtime.ExceptionServices.ExceptionDispatchInfo exceptionDispatchInfo)
{
bool fCanProcessException = !(IsImmutableAgileException(this));
// Restore only for non-preallocated exceptions
if (fCanProcessException)
{
// Take a lock to ensure only one thread can restore the details
// at a time against this exception object that could have
// multiple ExceptionDispatchInfo instances associated with it.
//
// We do this inside a finally clause to ensure ThreadAbort cannot
// be injected while we have taken the lock. This is to prevent
// unrelated exception restorations from getting blocked due to TAE.
try{}
finally
{
// When restoring back the fields, we again create a copy and set reference to them
// in the exception object. This will ensure that when this exception is thrown and these
// fields are modified, then EDI's references remain intact.
//
// Since deep copying can throw on OOM, try to get the copies
// outside the lock.
object _stackTraceCopy = (exceptionDispatchInfo.BinaryStackTraceArray == null)?null:DeepCopyStackTrace(exceptionDispatchInfo.BinaryStackTraceArray);
object _dynamicMethodsCopy = (exceptionDispatchInfo.DynamicMethodArray == null)?null:DeepCopyDynamicMethods(exceptionDispatchInfo.DynamicMethodArray);
// Finally, restore the information.
//
// Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance,
// they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock.
lock(Exception.s_EDILock)
{
_watsonBuckets = exceptionDispatchInfo.WatsonBuckets;
_ipForWatsonBuckets = exceptionDispatchInfo.IPForWatsonBuckets;
_remoteStackTraceString = exceptionDispatchInfo.RemoteStackTrace;
SaveStackTracesFromDeepCopy(this, _stackTraceCopy, _dynamicMethodsCopy);
}
_stackTraceString = null;
// Marks the TES state to indicate we have restored foreign exception
// dispatch information.
Exception.PrepareForForeignExceptionRaise();
}
}
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
private String _className; //Needed for serialization.
private MethodBase _exceptionMethod; //Needed for serialization.
private String _exceptionMethodString; //Needed for serialization.
internal String _message;
private IDictionary _data;
private Exception _innerException;
private String _helpURL;
private Object _stackTrace;
[OptionalField] // This isnt present in pre-V4 exception objects that would be serialized.
private Object _watsonBuckets;
private String _stackTraceString; //Needed for serialization.
private String _remoteStackTraceString;
private int _remoteStackIndex;
#pragma warning disable 414 // Field is not used from managed.
// _dynamicMethods is an array of System.Resolver objects, used to keep
// DynamicMethodDescs alive for the lifetime of the exception. We do this because
// the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed
// unless a System.Resolver object roots it.
private Object _dynamicMethods;
#pragma warning restore 414
// @MANAGED: HResult is used from within the EE! Rename with care - check VM directory
internal int _HResult; // HResult
public int HResult
{
get
{
return _HResult;
}
protected set
{
_HResult = value;
}
}
private String _source; // Mainly used by VB.
// WARNING: Don't delete/rename _xptrs and _xcode - used by functions
// on Marshal class. Native functions are in COMUtilNative.cpp & AppDomain
private IntPtr _xptrs; // Internal EE stuff
#pragma warning disable 414 // Field is not used from managed.
private int _xcode; // Internal EE stuff
#pragma warning restore 414
[OptionalField]
private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing
#if FEATURE_SERIALIZATION
[OptionalField(VersionAdded = 4)]
private SafeSerializationManager _safeSerializationManager;
#endif // FEATURE_SERIALIZATION
// See clr\src\vm\excep.h's EXCEPTION_COMPLUS definition:
private const int _COMPlusExceptionCode = unchecked((int)0xe0434352); // Win32 exception code for COM+ exceptions
// InternalToString is called by the runtime to get the exception text
// and create a corresponding CrossAppDomainMarshaledException
[System.Security.SecurityCritical] // auto-generated
internal virtual String InternalToString()
{
try
{
#pragma warning disable 618
SecurityPermission sp= new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
#pragma warning restore 618
sp.Assert();
}
catch
{
//under normal conditions there should be no exceptions
//however if something wrong happens we still can call the usual ToString
}
// Get the current stack trace string.
return ToString(true, true);
}
#if !FEATURE_CORECLR
// this method is required so Object.GetType is not made virtual by the compiler
// _Exception.GetType()
public new Type GetType()
{
return base.GetType();
}
#endif
internal bool IsTransient
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
return nIsTransient(_HResult);
}
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool nIsTransient(int hr);
// This piece of infrastructure exists to help avoid deadlocks
// between parts of mscorlib that might throw an exception while
// holding a lock that are also used by mscorlib's ResourceManager
// instance. As a special case of code that may throw while holding
// a lock, we also need to fix our asynchronous exceptions to use
// Win32 resources as well (assuming we ever call a managed
// constructor on instances of them). We should grow this set of
// exception messages as we discover problems, then move the resources
// involved to native code.
internal enum ExceptionMessageKind
{
ThreadAbort = 1,
ThreadInterrupted = 2,
OutOfMemory = 3
}
// See comment on ExceptionMessageKind
[System.Security.SecuritySafeCritical] // auto-generated
internal static String GetMessageFromNativeResources(ExceptionMessageKind kind)
{
string retMesg = null;
GetMessageFromNativeResources(kind, JitHelpers.GetStringHandleOnStack(ref retMesg));
return retMesg;
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg);
}
#if FEATURE_CORECLR
//--------------------------------------------------------------------------
// Telesto: Telesto doesn't support appdomain marshaling of objects so
// managed exceptions that leak across appdomain boundaries are flatted to
// its ToString() output and rethrown as an CrossAppDomainMarshaledException.
// The Message field is set to the ToString() output of the original exception.
//--------------------------------------------------------------------------
[Serializable]
internal sealed class CrossAppDomainMarshaledException : SystemException
{
public CrossAppDomainMarshaledException(String message, int errorCode)
: base(message)
{
SetErrorCode(errorCode);
}
// Normally, only Telesto's UEF will see these exceptions.
// This override prints out the original Exception's ToString()
// output and hides the fact that it is wrapped inside another excepton.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal override String InternalToString()
{
return Message;
}
}
#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 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyInteger
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// IntModel operations.
/// </summary>
public partial class IntModel : IServiceOperations<AutoRestIntegerTestService>, IIntModel
{
/// <summary>
/// Initializes a new instance of the IntModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public IntModel(AutoRestIntegerTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestIntegerTestService
/// </summary>
public AutoRestIntegerTestService Client { get; private set; }
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<int?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/null").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<int?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<int?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<int?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<int?>> GetOverflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetOverflowInt32", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint32").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<int?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<int?>> GetUnderflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetUnderflowInt32", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint32").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<int?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<long?>> GetOverflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetOverflowInt64", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint64").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<long?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<long?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<long?>> GetUnderflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetUnderflowInt64", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint64").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<long?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<long?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMax32WithHttpMessagesAsync(int? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (intBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "intBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutMax32", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/max/32").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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 = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMax64WithHttpMessagesAsync(long? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (intBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "intBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutMax64", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/max/64").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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 = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMin32WithHttpMessagesAsync(int? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (intBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "intBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutMin32", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/min/32").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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 = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMin64WithHttpMessagesAsync(long? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (intBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "intBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("intBody", intBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutMin64", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "int/min/64").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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 = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
#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 System.Web.Mail
// SSCLI 1.0 has no support for System.Web.Mail
#if !NETCF && !SSCLI
using System;
using System.IO;
using System.Text;
#if NET_2_0 || MONO_2_0
using System.Net.Mail;
#else
using System.Web.Mail;
#endif
using log4net.Layout;
using log4net.Core;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Send an e-mail when a specific logging event occurs, typically on errors
/// or fatal errors.
/// </summary>
/// <remarks>
/// <para>
/// The number of logging events delivered in this e-mail depend on
/// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The
/// <see cref="SmtpAppender"/> keeps only the last
/// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its
/// cyclic buffer. This keeps memory requirements at a reasonable level while
/// still delivering useful application context.
/// </para>
/// <note type="caution">
/// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime.
/// For these features to be enabled you need to ensure that you are using a version of
/// the log4net assembly that is built against the MS .NET 1.1 framework and that you are
/// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending
/// unauthenticated messages to a server listening on port 25 (the default) is supported.
/// </note>
/// <para>
/// Authentication is supported by setting the <see cref="Authentication"/> property to
/// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>.
/// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/>
/// and <see cref="Password"/> properties must also be set.
/// </para>
/// <para>
/// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class SmtpAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public SmtpAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string To
{
get { return m_to; }
set { m_to = MaybeTrimSeparators(value); }
}
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses
/// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string Cc
{
get { return m_cc; }
set { m_cc = MaybeTrimSeparators(value); }
}
/// <summary>
/// Gets or sets a semicolon-delimited list of recipient e-mail addresses
/// that will be blind carbon copied.
/// </summary>
/// <value>
/// A semicolon-delimited list of e-mail addresses.
/// </value>
/// <remarks>
/// <para>
/// A semicolon-delimited list of recipient e-mail addresses.
/// </para>
/// </remarks>
public string Bcc
{
get { return m_bcc; }
set { m_bcc = MaybeTrimSeparators(value); }
}
/// <summary>
/// Gets or sets the e-mail address of the sender.
/// </summary>
/// <value>
/// The e-mail address of the sender.
/// </value>
/// <remarks>
/// <para>
/// The e-mail address of the sender.
/// </para>
/// </remarks>
public string From
{
get { return m_from; }
set { m_from = value; }
}
/// <summary>
/// Gets or sets the subject line of the e-mail message.
/// </summary>
/// <value>
/// The subject line of the e-mail message.
/// </value>
/// <remarks>
/// <para>
/// The subject line of the e-mail message.
/// </para>
/// </remarks>
public string Subject
{
get { return m_subject; }
set { m_subject = value; }
}
/// <summary>
/// Gets or sets the name of the SMTP relay mail server to use to send
/// the e-mail messages.
/// </summary>
/// <value>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </value>
/// <remarks>
/// <para>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </para>
/// </remarks>
public string SmtpHost
{
get { return m_smtpHost; }
set { m_smtpHost = value; }
}
/// <summary>
/// The mode to use to authentication with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>,
/// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>.
/// The default value is <see cref="SmtpAuthentication.None"/>. When using
/// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/>
/// and <see cref="Password"/> to use to authenticate.
/// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current
/// thread, if impersonating, or the process will be used to authenticate.
/// </para>
/// </remarks>
public SmtpAuthentication Authentication
{
get { return m_authentication; }
set { m_authentication = value; }
}
/// <summary>
/// The username to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the username will be ignored.
/// </para>
/// </remarks>
public string Username
{
get { return m_username; }
set { m_username = value; }
}
/// <summary>
/// The password to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the password will be ignored.
/// </para>
/// </remarks>
public string Password
{
get { return m_password; }
set { m_password = value; }
}
/// <summary>
/// The port on which the SMTP server is listening
/// </summary>
/// <remarks>
/// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// The port on which the SMTP server is listening. The default
/// port is <c>25</c>. The Port can only be changed when running on
/// the MS .NET 1.1 runtime.
/// </para>
/// </remarks>
public int Port
{
get { return m_port; }
set { m_port = value; }
}
/// <summary>
/// Gets or sets the priority of the e-mail message
/// </summary>
/// <value>
/// One of the <see cref="MailPriority"/> values.
/// </value>
/// <remarks>
/// <para>
/// Sets the priority of the e-mails generated by this
/// appender. The default priority is <see cref="MailPriority.Normal"/>.
/// </para>
/// <para>
/// If you are using this appender to report errors then
/// you may want to set the priority to <see cref="MailPriority.High"/>.
/// </para>
/// </remarks>
public MailPriority Priority
{
get { return m_mailPriority; }
set { m_mailPriority = value; }
}
#if NET_2_0 || MONO_2_0
/// <summary>
/// Enable or disable use of SSL when sending e-mail message
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public bool EnableSsl
{
get { return m_enableSsl; }
set { m_enableSsl = value; }
}
/// <summary>
/// Gets or sets the reply-to e-mail address.
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public string ReplyTo
{
get { return m_replyTo; }
set { m_replyTo = value; }
}
#endif
/// <summary>
/// Gets or sets the subject encoding to be used.
/// </summary>
/// <remarks>
/// The default encoding is the operating system's current ANSI codepage.
/// </remarks>
public Encoding SubjectEncoding
{
get { return m_subjectEncoding; }
set { m_subjectEncoding = value; }
}
/// <summary>
/// Gets or sets the body encoding to be used.
/// </summary>
/// <remarks>
/// The default encoding is the operating system's current ANSI codepage.
/// </remarks>
public Encoding BodyEncoding
{
get { return m_bodyEncoding; }
set { m_bodyEncoding = value; }
}
#endregion // Public Instance Properties
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Sends the contents of the cyclic buffer as an e-mail message.
/// </summary>
/// <param name="events">The logging events to send.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize again.
try
{
StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
string t = Layout.Header;
if (t != null)
{
writer.Write(t);
}
for(int i = 0; i < events.Length; i++)
{
// Render the event and append the text to the buffer
RenderLoggingEvent(writer, events[i]);
}
t = Layout.Footer;
if (t != null)
{
writer.Write(t);
}
SendEmail(writer.ToString());
}
catch(Exception e)
{
ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
}
}
#endregion // Override implementation of BufferingAppenderSkeleton
#region Override implementation of AppenderSkeleton
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // Override implementation of AppenderSkeleton
#region Protected Methods
/// <summary>
/// Send the email message
/// </summary>
/// <param name="messageBody">the body text to include in the mail</param>
virtual protected void SendEmail(string messageBody)
{
#if NET_2_0 || MONO_2_0
// .NET 2.0 has a new API for SMTP email System.Net.Mail
// This API supports credentials and multiple hosts correctly.
// The old API is deprecated.
// Create and configure the smtp client
SmtpClient smtpClient = new SmtpClient();
if (!String.IsNullOrEmpty(m_smtpHost))
{
smtpClient.Host = m_smtpHost;
}
smtpClient.Port = m_port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = m_enableSsl;
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.Body = messageBody;
mailMessage.BodyEncoding = m_bodyEncoding;
mailMessage.From = new MailAddress(m_from);
mailMessage.To.Add(m_to);
if (!String.IsNullOrEmpty(m_cc))
{
mailMessage.CC.Add(m_cc);
}
if (!String.IsNullOrEmpty(m_bcc))
{
mailMessage.Bcc.Add(m_bcc);
}
if (!String.IsNullOrEmpty(m_replyTo))
{
// .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete:
// 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202'
#if !NET_4_0 && !MONO_4_0
mailMessage.ReplyTo = new MailAddress(m_replyTo);
#else
mailMessage.ReplyToList.Add(new MailAddress(m_replyTo));
#endif
}
mailMessage.Subject = m_subject;
mailMessage.SubjectEncoding = m_subjectEncoding;
mailMessage.Priority = m_mailPriority;
// TODO: Consider using SendAsync to send the message without blocking. This would be a change in
// behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors.
smtpClient.Send(mailMessage);
}
#else
// .NET 1.x uses the System.Web.Mail API for sending Mail
MailMessage mailMessage = new MailMessage();
mailMessage.Body = messageBody;
mailMessage.BodyEncoding = m_bodyEncoding;
mailMessage.From = m_from;
mailMessage.To = m_to;
if (m_cc != null && m_cc.Length > 0)
{
mailMessage.Cc = m_cc;
}
if (m_bcc != null && m_bcc.Length > 0)
{
mailMessage.Bcc = m_bcc;
}
mailMessage.Subject = m_subject;
#if !MONO && !NET_1_0 && !NET_1_1 && !CLI_1_0
mailMessage.SubjectEncoding = m_subjectEncoding;
#endif
mailMessage.Priority = m_mailPriority;
#if NET_1_1
// The Fields property on the MailMessage allows the CDO properties to be set directly.
// This property is only available on .NET Framework 1.1 and the implementation must understand
// the CDO properties. For details of the fields available in CDO see:
//
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp
//
try
{
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2);
}
// Set the port if not the default value
if (m_port != 25)
{
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port);
}
}
catch(MissingMethodException missingMethodException)
{
// If we were compiled against .NET 1.1 but are running against .NET 1.0 then
// we will get a MissingMethodException when accessing the MailMessage.Fields property.
ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException);
}
#else
if (m_authentication != SmtpAuthentication.None)
{
ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
}
if (m_port != 25)
{
ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
}
#endif // if NET_1_1
if (m_smtpHost != null && m_smtpHost.Length > 0)
{
SmtpMail.SmtpServer = m_smtpHost;
}
SmtpMail.Send(mailMessage);
#endif // if NET_2_0
}
#endregion // Protected Methods
#region Private Instance Fields
private string m_to;
private string m_cc;
private string m_bcc;
private string m_from;
private string m_subject;
private string m_smtpHost;
private Encoding m_subjectEncoding = Encoding.UTF8;
private Encoding m_bodyEncoding = Encoding.UTF8;
// authentication fields
private SmtpAuthentication m_authentication = SmtpAuthentication.None;
private string m_username;
private string m_password;
// server port, default port 25
private int m_port = 25;
private MailPriority m_mailPriority = MailPriority.Normal;
#if NET_2_0 || MONO_2_0
private bool m_enableSsl = false;
private string m_replyTo;
#endif
#endregion // Private Instance Fields
#region SmtpAuthentication Enum
/// <summary>
/// Values for the <see cref="SmtpAppender.Authentication"/> property.
/// </summary>
/// <remarks>
/// <para>
/// SMTP authentication modes.
/// </para>
/// </remarks>
public enum SmtpAuthentication
{
/// <summary>
/// No authentication
/// </summary>
None,
/// <summary>
/// Basic authentication.
/// </summary>
/// <remarks>
/// Requires a username and password to be supplied
/// </remarks>
Basic,
/// <summary>
/// Integrated authentication
/// </summary>
/// <remarks>
/// Uses the Windows credentials from the current thread or process to authenticate.
/// </remarks>
Ntlm
}
#endregion // SmtpAuthentication Enum
private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' };
/// <summary>
/// trims leading and trailing commas or semicolons
/// </summary>
private static string MaybeTrimSeparators(string s) {
#if NET_2_0 || MONO_2_0
return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS);
#else
return s != null && s.Length > 0 ? s : s.Trim(ADDRESS_DELIMITERS);
#endif
}
}
}
#endif // !NETCF && !SSCLI
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JoinRpg.Data.Write.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using JoinRpg.Domain.Schedules;
using JoinRpg.Interfaces;
using JoinRpg.Services.Interfaces;
#nullable enable
namespace JoinRpg.Services.Impl
{
[UsedImplicitly]
public class FieldSetupServiceImpl : DbServiceImplBase, IFieldSetupService
{
public async Task AddField(CreateFieldRequest request)
{
var project = await ProjectRepository.GetProjectAsync(request.ProjectId);
_ = project.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
if (project.GetTimeSlotFieldOrDefault() != null && request.FieldType == ProjectFieldType.ScheduleTimeSlotField)
{
throw new JoinFieldScheduleShouldBeUniqueException(project);
}
if (project.GetRoomFieldOrDefault() != null && request.FieldType == ProjectFieldType.ScheduleRoomField)
{
throw new JoinFieldScheduleShouldBeUniqueException(project);
}
var field = new ProjectField
{
ProjectId = request.ProjectId,
Project = project,
FieldType = request.FieldType,
FieldBoundTo = request.FieldBoundTo,
};
await SetFieldPropertiesFromRequest(request, field);
project.ProjectFields.Add(field);
SetScheduleStatusBasedOnFields(project);
_ = UnitOfWork.GetDbSet<ProjectField>().Add(field);
await UnitOfWork.SaveChangesAsync();
}
public async Task UpdateFieldParams(UpdateFieldRequest request)
{
var field = await ProjectRepository.GetProjectField(request.ProjectId, request.ProjectFieldId);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
// If we are changing field.CanPlayerEdit, we should update variants to match
if (field.CanPlayerEdit != request.CanPlayerEdit)
{
foreach (var variant in field.DropdownValues)
{
variant.PlayerSelectable = request.CanPlayerEdit;
}
}
await SetFieldPropertiesFromRequest(request, field);
await UnitOfWork.SaveChangesAsync();
}
private async Task SetFieldPropertiesFromRequest(FieldRequestBase request, ProjectField field)
{
field.IsActive = true;
field.FieldName = Required(request.Name);
field.Description = new MarkdownString(request.FieldHint);
field.MasterDescription = new MarkdownString(request.MasterFieldHint);
field.CanPlayerEdit = request.CanPlayerEdit;
field.CanPlayerView = request.CanPlayerView;
field.ValidForNpc = request.ValidForNpc;
field.IsPublic = request.IsPublic;
field.MandatoryStatus = request.MandatoryStatus;
field.AvailableForCharacterGroupIds =
await ValidateCharacterGroupList(request.ProjectId, request.ShowForGroups);
field.IncludeInPrint = request.IncludeInPrint;
field.ShowOnUnApprovedClaims = request.ShowForUnapprovedClaims;
field.Price = request.Price;
field.ProgrammaticValue = request.ProgrammaticValue;
CreateOrUpdateSpecialGroup(field);
}
public async Task DeleteField(int projectId, int projectFieldId)
{
ProjectField field = await ProjectRepository.GetProjectField(projectId, projectFieldId);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
var project = field.Project;
if (field.IsName())
{
throw new JoinRpgNameFieldDeleteException(field);
}
if (field.IsDescription())
{
project.Details.CharacterDescription = null;
}
foreach (var fieldValueVariant in field.DropdownValues.ToArray()) //Required, cause we modify fields inside.
{
DeleteFieldVariantValueImpl(fieldValueVariant);
}
var characterGroup = field.CharacterGroup; // SmartDelete will nullify all depend properties
if (SmartDelete(field))
{
_ = SmartDelete(characterGroup);
}
else if (characterGroup != null)
{
characterGroup.IsActive = false;
}
SetScheduleStatusBasedOnFields(project);
await UnitOfWork.SaveChangesAsync();
}
public FieldSetupServiceImpl(IUnitOfWork unitOfWork, ICurrentUserAccessor currentUserAccessor) : base(unitOfWork, currentUserAccessor)
{
}
public async Task CreateFieldValueVariant(CreateFieldValueVariantRequest request)
{
var field = await ProjectRepository.GetProjectField(request.ProjectId, request.ProjectFieldId);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
CreateFieldValueVariantImpl(request, field);
await UnitOfWork.SaveChangesAsync();
}
public async Task UpdateFieldValueVariant(UpdateFieldValueVariantRequest request)
{
var field = await ProjectRepository.GetFieldValue(request.ProjectId,
request.ProjectFieldId,
request.ProjectFieldDropdownValueId);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
SetFieldVariantPropsFromRequest(request, field);
await UnitOfWork.SaveChangesAsync();
}
private void SetFieldVariantPropsFromRequest(FieldValueVariantRequestBase request,
ProjectFieldDropdownValue variant)
{
variant.Description = new MarkdownString(request.Description);
variant.Label = request.Label;
variant.IsActive = true;
variant.MasterDescription = new MarkdownString(request.MasterDescription);
variant.Price = request.Price;
variant.PlayerSelectable = request.PlayerSelectable;
if (variant.ProjectField.IsTimeSlot())
{
variant.SetTimeSlotOptions(request.TimeSlotOptions);
}
else
{
variant.ProgrammaticValue = request.ProgrammaticValue;
}
CreateOrUpdateSpecialGroup(variant);
}
private void CreateFieldValueVariantImpl(CreateFieldValueVariantRequest request, ProjectField field)
{
var fieldVariant = new ProjectFieldDropdownValue()
{
WasEverUsed = false,
ProjectId = field.ProjectId,
ProjectFieldId = field.ProjectFieldId,
Project = field.Project,
ProjectField = field,
};
SetFieldVariantPropsFromRequest(request, fieldVariant);
field.DropdownValues.Add(fieldVariant);
}
private void CreateOrUpdateSpecialGroup(ProjectFieldDropdownValue fieldValue)
{
var field = fieldValue.ProjectField;
if (!field.HasSpecialGroup())
{
return;
}
CreateOrUpdateSpecialGroup(field);
if (fieldValue.CharacterGroup == null)
{
fieldValue.CharacterGroup = new CharacterGroup()
{
AvaiableDirectSlots = 0,
HaveDirectSlots = false,
ParentCharacterGroupIds = new[] { field.CharacterGroup.CharacterGroupId },
ProjectId = fieldValue.ProjectId,
IsRoot = false,
IsSpecial = true,
ResponsibleMasterUserId = null,
};
MarkCreatedNow(fieldValue.CharacterGroup);
}
UpdateSpecialGroupProperties(fieldValue);
}
private void UpdateSpecialGroupProperties(ProjectFieldDropdownValue fieldValue)
{
var field = fieldValue.ProjectField;
var characterGroup = fieldValue.CharacterGroup;
var specialGroupName = fieldValue.GetSpecialGroupName();
Debug.Assert(characterGroup != null, "characterGroup != null");
if (characterGroup.IsPublic != field.IsPublic ||
characterGroup.IsActive != fieldValue.IsActive ||
characterGroup.Description != fieldValue.Description ||
characterGroup.CharacterGroupName != specialGroupName)
{
characterGroup.IsPublic = field.IsPublic;
characterGroup.IsActive = fieldValue.IsActive;
characterGroup.Description = fieldValue.Description;
characterGroup.CharacterGroupName = specialGroupName;
MarkChanged(characterGroup);
}
}
private void CreateOrUpdateSpecialGroup(ProjectField field)
{
if (!field.HasSpecialGroup())
{
return;
}
if (field.CharacterGroup == null)
{
field.CharacterGroup = new CharacterGroup()
{
AvaiableDirectSlots = 0,
HaveDirectSlots = false,
ParentCharacterGroupIds = new[] { field.Project.RootGroup.CharacterGroupId },
ProjectId = field.ProjectId,
IsRoot = false,
IsSpecial = true,
ResponsibleMasterUserId = null,
};
MarkCreatedNow(field.CharacterGroup);
}
foreach (var fieldValue in field.DropdownValues)
{
if (fieldValue.CharacterGroup == null)
{
continue; //We can't convert to LINQ because of RSRP-457084
}
UpdateSpecialGroupProperties(fieldValue);
}
UpdateSpecialGroupProperties(field);
}
private void UpdateSpecialGroupProperties(ProjectField field)
{
var characterGroup = field.CharacterGroup;
var specialGroupName = field.GetSpecialGroupName();
if (characterGroup.IsPublic != field.IsPublic || characterGroup.IsActive != field.IsActive ||
characterGroup.Description != field.Description ||
characterGroup.CharacterGroupName != specialGroupName)
{
characterGroup.IsPublic = field.IsPublic;
characterGroup.IsActive = field.IsActive;
characterGroup.Description = field.Description;
characterGroup.CharacterGroupName = specialGroupName;
MarkChanged(characterGroup);
}
}
public async Task<ProjectFieldDropdownValue> DeleteFieldValueVariant(int projectId, int projectFieldId, int valueId)
{
var value = await ProjectRepository.GetFieldValue(projectId, projectFieldId, valueId);
_ = value.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
DeleteFieldVariantValueImpl(value);
await UnitOfWork.SaveChangesAsync();
return value;
}
private void DeleteFieldVariantValueImpl(ProjectFieldDropdownValue value)
{
var characterGroup = value.CharacterGroup; // SmartDelete will nullify all depend properties
if (SmartDelete(value))
{
_ = SmartDelete(characterGroup);
}
else
{
if (characterGroup != null)
{
characterGroup.IsActive = false;
}
}
}
public async Task MoveField(int projectId, int projectcharacterfieldid, short direction)
{
var field = await ProjectRepository.GetProjectField(projectId, projectcharacterfieldid);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
field.Project.Details.FieldsOrdering
= field.Project.GetFieldsContainer().Move(field, direction).GetStoredOrder();
await UnitOfWork.SaveChangesAsync();
}
public async Task MoveFieldVariant(int projectid, int projectFieldId, int projectFieldVariantId, short direction)
{
var field = await ProjectRepository.GetProjectField(projectid, projectFieldId);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
field.ValuesOrdering =
field.GetFieldValuesContainer()
.Move(field.DropdownValues.Single(v => v.ProjectFieldDropdownValueId == projectFieldVariantId), direction)
.GetStoredOrder();
await UnitOfWork.SaveChangesAsync();
}
public async Task CreateFieldValueVariants(int projectId, int projectFieldId, string valuesToAdd)
{
var field = await ProjectRepository.GetProjectField(projectId, projectFieldId);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
foreach (var label in valuesToAdd.Split('\n').Select(v => v.Trim()).Where(v => !string.IsNullOrEmpty(v)))
{
CreateFieldValueVariantImpl(new CreateFieldValueVariantRequest(field.ProjectId,
label,
null,
field.ProjectFieldId,
null,
null,
0,
field.CanPlayerEdit,
timeSlotOptions: null),
field);
}
await UnitOfWork.SaveChangesAsync();
}
public async Task MoveFieldAfter(int projectId, int projectFieldId, int? afterFieldId)
{
var field = await ProjectRepository.GetProjectField(projectId, projectFieldId);
var afterField = afterFieldId == null
? null
: await ProjectRepository.GetProjectField(projectId, (int)afterFieldId);
_ = field.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
field.Project.Details.FieldsOrdering
= field.Project.GetFieldsContainer().MoveAfter(field, afterField).GetStoredOrder();
await UnitOfWork.SaveChangesAsync();
}
public async Task SetFieldSettingsAsync(FieldSettingsRequest request)
{
var project = await ProjectRepository.GetProjectAsync(request.ProjectId);
_ = project.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeFields);
project.Details.CharacterNameLegacyMode = request.LegacyModelEnabled;
project.Details.CharacterNameField = project.ProjectFields.SingleOrDefault(e => e.ProjectFieldId == request.NameField);
project.Details.CharacterDescription = project.ProjectFields.SingleOrDefault(e => e.ProjectFieldId == request.DescriptionField);
await UnitOfWork.SaveChangesAsync();
}
private static void SetScheduleStatusBasedOnFields(Project project)
{
project.Details.ScheduleEnabled =
project.GetTimeSlotFieldOrDefault() is not null && project.GetRoomFieldOrDefault() is not null;
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
public class Field
{
#region Fields
private string name;
private byte num;
private byte type;
private float scale;
private float offset;
private string units;
internal List<object> values = new List<object>();
internal List<Subfield> subfields = new List<Subfield>();
internal List<FieldComponent> components = new List<FieldComponent>();
#endregion
#region Properties
public string Name
{
get
{
return name;
}
}
public byte Num
{
get
{
return num;
}
set
{
num = value;
}
}
public byte Type
{
get
{
return type;
}
set
{
type = value;
}
}
public float Scale
{
get
{
return scale;
}
}
public float Offset
{
get
{
return offset;
}
}
public string Units
{
get
{
return units;
}
}
#endregion
#region Constructors
public Field(Field field)
{
if (field == null)
{
this.name = "unknown";
this.num = Fit.FieldNumInvalid;
this.type = 0;
this.scale = 1f;
this.offset = 0f;
this.units = "";
return;
}
this.name = field.Name;
this.num = field.Num;
this.type = field.Type;
this.scale = field.Scale;
this.offset = field.Offset;
this.units = field.units;
foreach (object obj in field.values)
{
this.values.Add(obj);
}
foreach (Subfield subfield in field.subfields)
{
this.subfields.Add(new Subfield(subfield));
}
foreach (FieldComponent component in field.components)
{
this.components.Add(new FieldComponent(component));
}
}
internal Field(string name, byte num, byte type, float scale, float offset, string units)
{
this.name = name;
this.num = num;
this.type = type;
this.scale = scale;
this.offset = offset;
this.units = units;
}
#endregion
#region Methods
public string GetName()
{
return GetName((Subfield)null);
}
public string GetName(byte subfieldIndex)
{
return GetName(GetSubfield(subfieldIndex));
}
public string GetName(string subFieldName)
{
return GetName(GetSubfield(subFieldName));
}
private string GetName(Subfield subfield)
{
if (subfield == null)
{
return name;
}
else
{
return subfield.Name;
}
}
public byte GetNum()
{
return num;
}
new public byte GetType()
{
return GetType((Subfield)null);
}
public byte GetType(byte subfieldIndex)
{
return GetType(GetSubfield(subfieldIndex));
}
public byte GetType(string subFieldName)
{
return GetType(GetSubfield(subFieldName));
}
private byte GetType(Subfield subfield)
{
if (subfield == null)
{
return type;
}
else
{
return subfield.Type;
}
}
public string GetUnits()
{
return GetUnits((Subfield)null);
}
public string GetUnits(byte subfieldIndex)
{
return GetUnits(GetSubfield(subfieldIndex));
}
public string GetUnits(string subFieldName)
{
return GetUnits(GetSubfield(subFieldName));
}
private string GetUnits(Subfield subfield)
{
if (subfield == null)
{
return units;
}
else
{
return subfield.Units;
}
}
public byte GetSize()
{
byte size = 0;
switch (Type & Fit.BaseTypeNumMask)
{
case Fit.Enum:
case Fit.SInt8:
case Fit.UInt8:
case Fit.SInt16:
case Fit.UInt16:
case Fit.SInt32:
case Fit.UInt32:
case Fit.Float32:
case Fit.Float64:
case Fit.UInt8z:
case Fit.UInt16z:
case Fit.UInt32z:
case Fit.Byte:
size = (byte)(GetNumValues() * Fit.BaseType[Type & Fit.BaseTypeNumMask].size);
break;
case Fit.String:
// Each string may be of differing length
// The fit binary must also include a null terminator
foreach (byte[] element in values)
{
size += (byte)(element.Length + 1);
}
break;
default:
break;
}
return size;
}
internal Subfield GetSubfield(string subfieldName)
{
foreach (Subfield subfield in subfields)
{
if (subfield.Name == subfieldName)
{
return subfield;
}
}
return null;
}
internal Subfield GetSubfield(int subfieldIndex)
{
// SubfieldIndexActiveSubfield and SubfieldIndexMainField
// will be out of this range
if (subfieldIndex >=0 && subfieldIndex < subfields.Count)
{
return subfields[subfieldIndex];
}
return null;
}
internal bool IsSigned()
{
return IsSigned((Subfield)null);
}
internal bool IsSigned(int subfieldIndex)
{
return IsSigned(GetSubfield(subfieldIndex));
}
internal bool IsSigned(string subfieldName)
{
return IsSigned(GetSubfield(subfieldName));
}
internal bool IsSigned(Subfield subfield)
{
if (subfield == null)
{
return Fit.BaseType[Type & Fit.BaseTypeNumMask].isSigned;
}
else
{
return Fit.BaseType[subfield.Type & Fit.BaseTypeNumMask].isSigned;
}
}
public void AddValue(Object value)
{
values.Add(value);
}
public int GetNumValues()
{
return this.values.Count;
}
public long? GetBitsValue(int offset, int bits, byte componentType)
{
long? value = 0;
long data = 0;
long mask;
int index = 0;
int bitsInValue = 0;
int bitsInData;
// Ensure the destination type can hold the desired number of bits.
// We don't support arrays in the destination at this time.
if ((Fit.BaseType[componentType & Fit.BaseTypeNumMask].size * 8) < bits)
{
bits = Fit.BaseType[componentType & Fit.BaseTypeNumMask].size * 8;
}
while (bitsInValue < bits)
{
try
{
data = Convert.ToInt64(this.values[index++]);
}
catch (ArgumentOutOfRangeException)
{
// If we run out of bits it likely is because our profile is newer and defines
// additional components not present in the field
return null;
}
// Shift data to reach desired bits starting at 'offset'
// If offset is larger than the containing types size,
// we must grab additional elements
data >>= offset;
bitsInData = Fit.BaseType[Type & Fit.BaseTypeNumMask].size * 8 - offset;
offset -= Fit.BaseType[Type & Fit.BaseTypeNumMask].size * 8;
if (bitsInData > 0)
{
// We have reached desired data, pull off bits until we
// get enough
offset = 0;
// If there are more bits available in data than we need
// just capture those we need
if (bitsInData > (bits - bitsInValue))
{
bitsInData = bits - bitsInValue;
}
mask = (1L << bitsInData) - 1;
value |= ((data & mask) << bitsInValue);
bitsInValue += bitsInData;
}
}
// Sign extend if needed
if (Fit.BaseType[componentType & Fit.BaseTypeNumMask].isSigned == true &&
Fit.BaseType[componentType & Fit.BaseTypeNumMask].isInteger == true)
{
long signBit = (1L << (bits - 1));
if ((value & signBit) != 0)
{
value = -signBit + (value & (signBit - 1));
}
}
return value;
}
public object GetValue()
{
return GetValue(0, (Subfield)null);
}
public object GetValue(int index)
{
return GetValue(index, (Subfield)null);
}
public object GetValue(int index, int subfieldIndex)
{
return GetValue(index, GetSubfield(subfieldIndex));
}
public object GetValue(int index, string subfieldName)
{
return GetValue(index, GetSubfield(subfieldName));
}
public object GetValue(int index, Subfield subfield)
{
float scale, offset;
if (index >= values.Count || index < 0)
{
return null;
}
if (subfield == null)
{
scale = this.Scale;
offset = this.Offset;
}
else
{
scale = subfield.Scale;
offset = subfield.Offset;
}
object value = values[index];
if (IsNumeric())
{
if (scale != 1.0 || Offset != 0.0)
{
value = Convert.ToSingle(value);
value = (float)value / scale - offset;
}
}
return value;
}
public void SetValue(object value)
{
SetValue(0, value, (Subfield)null);
}
public void SetValue(object value, int subfieldIndex)
{
SetValue(0, value, GetSubfield(subfieldIndex));
}
public void SetValue(object value, string subfieldName)
{
SetValue(0, value, GetSubfield(subfieldName));
}
public void SetValue(int index, object value)
{
SetValue(index, value, (Subfield)null);
}
public void SetValue(int index, object value, int subfieldIndex)
{
SetValue(index, value, GetSubfield(subfieldIndex));
}
public void SetValue(int index, object value, string subfieldName)
{
SetValue(index, value, GetSubfield(subfieldName));
}
public void SetValue(int index, object value, Subfield subfield)
{
float scale, offset;
while (index >= GetNumValues())
{
// Add placeholders of the correct type so GetSize() will
// still compute correctly
switch (Type & Fit.BaseTypeNumMask)
{
case Fit.Enum:
case Fit.Byte:
case Fit.UInt8:
case Fit.UInt8z:
values.Add(new byte());
break;
case Fit.SInt8:
values.Add(new sbyte());
break;
case Fit.SInt16:
values.Add(new short());
break;
case Fit.UInt16:
case Fit.UInt16z:
values.Add(new ushort());
break;
case Fit.SInt32:
values.Add(new int());
break;
case Fit.UInt32:
case Fit.UInt32z:
values.Add(new uint());
break;
case Fit.Float32:
values.Add(new float());
break;
case Fit.Float64:
values.Add(new double());
break;
case Fit.String:
values.Add(new byte[0]);
break;
default:
break;
}
}
if (subfield == null)
{
scale = this.Scale;
offset = this.Offset;
}
else
{
scale = subfield.Scale;
offset = this.Offset;
}
if (IsNumeric())
{
if (scale != 1.0 || Offset != 0.0)
{
value = Convert.ToSingle(value);
value = ((float)value + offset) * scale;
}
}
// Must convert value back to the base type, if there was a scale or offset it will
// have been converted to float. Caller also may have passed in an unexpected type.
try
{
switch (Type & Fit.BaseTypeNumMask)
{
case Fit.Enum:
case Fit.Byte:
case Fit.UInt8:
case Fit.UInt8z:
value = Convert.ToByte(value);
break;
case Fit.SInt8:
value = Convert.ToSByte(value);
break;
case Fit.SInt16:
value = Convert.ToInt16(value);
break;
case Fit.UInt16:
case Fit.UInt16z:
value = Convert.ToUInt16(value);
break;
case Fit.SInt32:
value = Convert.ToInt32(value);
break;
case Fit.UInt32:
case Fit.UInt32z:
value = Convert.ToUInt32(value);
break;
case Fit.Float32:
value = Convert.ToSingle(value);
break;
case Fit.Float64:
value = Convert.ToDouble(value);
break;
default:
break;
}
}
// If an exception happens while converting, set the value to invalid
catch (Exception)
{
value = Fit.BaseType[Type & Fit.BaseTypeNumMask].invalidValue;
}
values[index] = value;
}
public void SetRawValue(int index, object value)
{
while (index >= GetNumValues())
{
// Add placeholders of the correct type so GetSize() will
// still compute correctly
switch (Type & Fit.BaseTypeNumMask)
{
case Fit.Enum:
case Fit.Byte:
case Fit.UInt8:
case Fit.UInt8z:
values.Add(new byte());
break;
case Fit.SInt8:
values.Add(new sbyte());
break;
case Fit.SInt16:
values.Add(new short());
break;
case Fit.UInt16:
case Fit.UInt16z:
values.Add(new ushort());
break;
case Fit.SInt32:
values.Add(new int());
break;
case Fit.UInt32:
case Fit.UInt32z:
values.Add(new uint());
break;
case Fit.Float32:
values.Add(new float());
break;
case Fit.Float64:
values.Add(new double());
break;
case Fit.String:
values.Add(new byte[0]);
break;
default:
break;
}
}
// Must convert value back to the base type, caller may have passed in an unexpected type.
switch (Type & Fit.BaseTypeNumMask)
{
case Fit.Enum:
case Fit.Byte:
case Fit.UInt8:
case Fit.UInt8z:
value = Convert.ToByte(value);
break;
case Fit.SInt8:
value = Convert.ToSByte(value);
break;
case Fit.SInt16:
value = Convert.ToInt16(value);
break;
case Fit.UInt16:
case Fit.UInt16z:
value = Convert.ToUInt16(value);
break;
case Fit.SInt32:
value = Convert.ToInt32(value);
break;
case Fit.UInt32:
case Fit.UInt32z:
value = Convert.ToUInt32(value);
break;
case Fit.Float32:
value = Convert.ToSingle(value);
break;
case Fit.Float64:
value = Convert.ToDouble(value);
break;
default:
break;
}
values[index] = value;
}
public object GetRawValue(int index)
{
if (index >= values.Count || index < 0)
{
return null;
}
object value = values[index];
return value;
}
public bool IsNumeric()
{
bool isNumeric;
switch (this.Type & Fit.BaseTypeNumMask)
{
case Fit.Enum:
case Fit.String:
isNumeric = false;
break;
case Fit.SInt8:
case Fit.UInt8:
case Fit.SInt16:
case Fit.UInt16:
case Fit.SInt32:
case Fit.UInt32:
case Fit.Float32:
case Fit.Float64:
case Fit.UInt8z:
case Fit.UInt16z:
case Fit.UInt32z:
case Fit.Byte:
isNumeric = true;
break;
default:
throw new FitException("Field:IsNumeric - Unexpected Fit Type" + this.Type);
}
return isNumeric;
}
#endregion
}
} // namespace
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Threading;
using MindTouch.Collections;
using MindTouch.Deki.Data;
using MindTouch.Deki.Logic;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Threading;
using MindTouch.Xml;
namespace MindTouch.Deki {
public class DekiChangeSink {
//--- Types ---
private class ChangeData {
public XUri Channel;
public XUri Resource;
public string[] Origin;
public XDoc Doc;
}
//--- Constants ---
private const string PAGES = "pages";
private const string FILES = "files";
private const string COMMENTS = "comments";
private const string USERS = "users";
private const string BAN = "ban";
private const string SITE = "site";
private const string PROPERTY = "properties";
private const string TAGS = "tags";
private const string START = "start";
private const string STARTED = "started";
private const string STOP = "stop";
private const string NO_OP = "noop";
private const string CREATE = "create";
private const string MOVE = "move";
private const string UPDATE = "update";
private const string DELETE = "delete";
private const string CREATE_ALIAS = "createalias";
private const string DEPENDENTS_CHANGED = "dependentschanged";
private const string MESSAGE = "message";
private const string RESTORE = "restore";
private const string REVERT = "revert";
private const string PASSWORD = "password";
private const string LOGIN = "login";
private const string TALK = "talk";
private const string RE_INDEX = "reindex";
private const string SECURITY = "security";
private const string VIEW = "view";
private const string RATED = "rated";
private const string SETTINGS = "settings";
//--- Class Fields
private static readonly log4net.ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly string _wikiid;
private readonly XUri _apiUri;
private readonly Plug _publishPlug;
private readonly XUri _channel;
private readonly ProcessingQueue<ChangeData> _changeQueue;
//--- Constructors ---
public DekiChangeSink(string wikiid, XUri apiUri, Plug publishPlug) {
_wikiid = wikiid;
_apiUri = apiUri;
_publishPlug = publishPlug;
_channel = new XUri(string.Format("event://{0}/deki/", _wikiid));
_changeQueue = new ProcessingQueue<ChangeData>(Publish, 10);
}
//--- Methods ---
public void InstanceStarted(DateTime eventTime) {
try {
XUri channel = _channel.At(SITE, STARTED);
XUri resource = _apiUri.AsServerUri();
Queue(eventTime, channel, resource, new[] { _apiUri.AsServerUri().ToString() }, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("uri", _apiUri.AsServerUri().ToString()));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "InstanceStarted", "event couldn't be created");
}
}
public void InstanceStarting(DateTime eventTime) {
try {
XUri channel = _channel.At(SITE, START);
XUri resource = _apiUri.AsServerUri();
Queue(eventTime, channel, resource, new[] { _apiUri.AsServerUri().ToString() }, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("uri", _apiUri.AsServerUri().ToString()));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "InstanceStarting", "event couldn't be created");
}
}
public void InstanceShutdown(DateTime eventTime) {
try {
XUri channel = _channel.At(SITE, STOP);
XUri resource = _apiUri.AsServerUri();
Queue(eventTime, channel, resource, new[] { _apiUri.AsServerUri().ToString() }, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("uri", _apiUri.AsServerUri().ToString()));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "InstanceShutdown", "event couldn't be created");
}
}
public void InstanceSettingsChanged(DateTime eventTime) {
try {
XUri channel = _channel.At(SITE, SETTINGS,UPDATE);
XUri resource = _apiUri.AsServerUri();
Queue(eventTime, channel, resource, new[] { _apiUri.AsServerUri().ToString() }, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("uri", _apiUri.AsServerUri().ToString()));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "InstanceSettingsChanged", "event couldn't be created");
}
}
public void UserCreate(DateTime eventTime, UserBE user) {
UserChanged(eventTime, user, CREATE);
}
public void UserUpdate(DateTime eventTime, UserBE user) {
UserChanged(eventTime, user, UPDATE);
}
private void UserDependentChanged(DateTime eventTime, UserBE user, params string[] path) {
UserChanged(eventTime, user, ArrayUtil.Concat(new string[] { DEPENDENTS_CHANGED }, path));
}
public void UserChangePassword(DateTime eventTime, UserBE user) {
UserChanged(eventTime, user, UPDATE, PASSWORD);
}
public void UserLogin(DateTime eventTime, UserBE user) {
UserChanged(eventTime, user, LOGIN);
}
private void UserChanged(DateTime eventTime, UserBE user, params string[] path) {
try {
XUri channel = _channel.At(USERS).At(path);
XUri resource = UserBL.GetUri(user).WithHost(_wikiid);
Queue(eventTime, channel, resource, new string[] { resource.AsServerUri().ToString() }, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("userid", user.ID)
.Elem("uri", UserBL.GetUri(user).AsServerUri().ToString())
.Elem("path", UserBL.GetUriUiHomePage(user).Path.TrimStart('/')));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "UserChanged", "event couldn't be created");
}
}
public void BanCreated(DateTime eventTime, BanBE ban) {
BanEvent(eventTime, ban, CREATE);
}
public void BanRemoved(DateTime eventTime, BanBE ban) {
BanEvent(eventTime, ban, DELETE);
}
private void BanEvent(DateTime eventTime, BanBE ban, params string[] channelPath) {
try {
XUri channel = _channel.At(BAN).At(channelPath);
XDoc doc = new XDoc("deki-event")
.Elem("channel", channel)
.Elem("banid", ban.Id)
.Elem("reason", ban.Reason)
.Elem("by", ban.ByUserId);
if(ban.BanAddresses.Count > 0) {
doc.Start("addresses");
foreach(string address in ban.BanAddresses) {
doc.Elem("address", address);
}
doc.End();
}
if(ban.BanUserIds.Count > 0) {
doc.Start("users");
foreach(uint userId in ban.BanUserIds) {
doc.Start("user").Attr("id", userId).End();
}
doc.End();
}
Queue(eventTime, channel, null, new string[] { string.Format("http://{0}/deki", _wikiid) }, doc);
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "BanEvent", "event couldn't be created");
}
}
public void IndexRebuildStart(DateTime eventTime) {
try {
XUri channel = _channel.At(SITE).At(RE_INDEX);
Queue(eventTime, channel, null, new string[] { string.Format("http://{0}/deki", _wikiid) }, new XDoc("deki-event")
.Elem("channel", channel));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "IndexRebuildStart", "event couldn't be created");
}
}
public void CommentCreate(DateTime eventTime, CommentBE comment, PageBE parent, UserBE user) {
PageDependentChanged(eventTime, parent, user, COMMENTS, CREATE);
CommentChanged(eventTime, comment, parent, user, CREATE);
}
public void CommentUpdate(DateTime eventTime, CommentBE comment, PageBE parent, UserBE user) {
PageDependentChanged(eventTime, parent, user, COMMENTS, UPDATE);
CommentChanged(eventTime, comment, parent, user, UPDATE);
}
public void CommentPoke(DateTime eventTime, CommentBE comment, PageBE parent, UserBE user) {
CommentChanged(eventTime, comment, parent, user, NO_OP);
}
public void CommentDelete(DateTime eventTime, CommentBE comment, PageBE parent, UserBE user) {
PageDependentChanged(eventTime, parent, user, COMMENTS, DELETE);
CommentChanged(eventTime, comment, parent, user, DELETE);
}
private void CommentChanged(DateTime eventTime, CommentBE comment, PageBE parent, UserBE user, params string[] channelPath) {
try {
XUri channel = _channel.At(COMMENTS).At(channelPath);
XUri resource = CommentBL.GetUri(comment).WithHost(_wikiid);
string[] origin = new string[] { CommentBL.GetUri(comment).AsServerUri().ToString() };
string path = parent.Title.AsUiUriPath() + "#comment" + comment.Number;
XDoc doc = new XDoc("deki-event")
//userid is deprecated and user/id should be used instead
.Elem("userid", comment.PosterUserId)
.Elem("pageid", comment.PageId)
.Elem("uri.page", PageBL.GetUriCanonical(parent).AsServerUri().ToString())
.Start("user")
.Attr("id", user.ID)
.Attr("anonymous", UserBL.IsAnonymous(user))
.Elem("uri", UserBL.GetUri(user))
.End()
.Elem("channel", channel)
.Elem("uri", CommentBL.GetUri(comment).AsServerUri().ToString())
.Elem("path", path)
.Start("content").Attr("uri", CommentBL.GetUri(comment).AsServerUri().At("content").ToString()).End();
if(comment.Content.Length < 255) {
doc["content"].Attr("type", comment.ContentMimeType).Value(comment.Content);
}
Queue(eventTime, channel, resource, origin, doc);
} catch(Exception e) {
_log.WarnMethodCall("CommentChanged", "event couldn't be created");
}
}
public void PageMove(DateTime eventTime, PageBE oldPage, PageBE newPage, UserBE user) {
try {
XUri channel = _channel.At(PAGES, MOVE);
XUri resource = PageBL.GetUriCanonical(newPage).WithHost(_wikiid);
var origin = new[] {
PageBL.GetUriCanonical(newPage).AsServerUri().ToString(),
XUri.Localhost + "/" + oldPage.Title.AsUiUriPath(),
XUri.Localhost + "/" + newPage.Title.AsUiUriPath(),
};
Queue(eventTime, channel, resource, origin, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("uri", PageBL.GetUriCanonical(newPage).AsServerUri().ToString())
.Elem("pageid", newPage.ID)
.Start("user")
.Attr("id", user.ID)
.Attr("anonymous", UserBL.IsAnonymous(user))
.Elem("uri", UserBL.GetUri(user))
.End()
.Start("content.uri")
.Attr("type", "application/xml")
.Value(PageBL.GetUriContentsCanonical(newPage).AsServerUri().With("format", "xhtml").ToString())
.End()
.Elem("revision.uri", PageBL.GetUriRevisionCanonical(newPage).AsServerUri().ToString())
.Elem("tags.uri", PageBL.GetUriCanonical(newPage).At("tags").AsServerUri().ToString())
.Elem("comments.uri", PageBL.GetUriCanonical(newPage).At("comments").AsServerUri().ToString())
.Elem("path", newPage.Title.AsUiUriPath())
.Elem("previous-path", oldPage.Title.AsUiUriPath()));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "PageMove", "event couldn't be created");
}
}
public void PagePoke(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, NO_OP);
}
public void PageCreate(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, CREATE);
}
public void PageUpdate(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, UPDATE);
}
public void PageTagsUpdate(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, TAGS, UPDATE);
}
public void PageRated(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, RATED);
}
public void PageDelete(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, DELETE);
}
public void PageAliasCreate(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, CREATE_ALIAS);
}
public void PageRevert(DateTime eventTime, PageBE page, UserBE user, int rev) {
PageChanged(eventTime, page, user, new XDoc("reverted-to").Value(rev), REVERT);
}
public void PageViewed(DateTime eventTime, PageBE page, UserBE user) {
PageChanged(eventTime, page, user, null, VIEW);
}
private void PageDependentChanged(DateTime eventTime, PageBE page, UserBE user, params string[] path) {
PageChanged(eventTime, page, user, null, ArrayUtil.Concat(new string[] { DEPENDENTS_CHANGED }, path));
}
public void PageMessage(DateTime eventTime, PageBE page, UserBE user, XDoc body, string[] path) {
PageChanged(eventTime, page, user, body, ArrayUtil.Concat(new string[] { MESSAGE }, path));
}
private void PageChanged(DateTime eventTime, PageBE page, UserBE user, XDoc extra, params string[] path) {
try {
XUri channel = _channel.At(PAGES).At(path);
XUri resource = PageBL.GetUriCanonical(page).WithHost(_wikiid);
string[] origin = new string[] { PageBL.GetUriCanonical(page).AsServerUri().ToString(), XUri.Localhost + "/" + page.Title.AsUiUriPath() };
XDoc doc = new XDoc("deki-event")
.Elem("channel", channel)
// BUGBUGBUG: This will generally generate a Uri based on the request that caused the event,
// which may not really be canonical
.Elem("uri", PageBL.GetUriCanonical(page).AsPublicUri().ToString())
.Elem("pageid", page.ID)
.Start("user")
.Attr("id", user.ID)
.Attr("anonymous", UserBL.IsAnonymous(user))
.Elem("uri", UserBL.GetUri(user))
.End()
.Start("content.uri")
.Attr("type", "application/xml")
.Value(PageBL.GetUriContentsCanonical(page).With("format", "xhtml").AsServerUri().ToString())
.End()
.Elem("revision.uri", PageBL.GetUriRevisionCanonical(page).AsServerUri().ToString())
.Elem("tags.uri", PageBL.GetUriCanonical(page).At("tags").AsServerUri().ToString())
.Elem("comments.uri", PageBL.GetUriCanonical(page).At("comments").AsServerUri().ToString())
.Elem("path", page.Title.AsUiUriPath());
if(extra != null) {
doc.Add(extra);
}
Queue(eventTime, channel, resource, origin, doc);
if(page.Title.IsTalk) {
PageBE front = PageBL.GetPageByTitle(page.Title.AsFront());
if((front != null) && (front.ID > 0)) {
PageChanged(eventTime, front, user, extra, ArrayUtil.Concat(new string[] { DEPENDENTS_CHANGED, TALK }, path));
}
}
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "PageChanged", "event couldn't be created");
}
}
public void PageSecuritySet(DateTime eventTime, PageBE page, CascadeType cascade) {
PageSecurityChanged(eventTime, page, cascade, SECURITY, CREATE);
}
public void PageSecurityUpdated(DateTime eventTime, PageBE page, CascadeType cascade) {
PageSecurityChanged(eventTime, page, cascade, SECURITY, UPDATE);
}
public void PageSecurityDelete(DateTime eventTime, PageBE page) {
PageSecurityChanged(eventTime, page, CascadeType.NONE, SECURITY, DELETE);
}
private void PageSecurityChanged(DateTime eventTime, PageBE page, CascadeType cascade, params string[] path) {
try {
XUri channel = _channel.At(PAGES).At(path);
XUri resource = PageBL.GetUriCanonical(page).WithHost(_wikiid);
string[] origin = new string[] { PageBL.GetUriCanonical(page).AsServerUri().ToString(), XUri.Localhost + "/" + page.Title.AsUiUriPath() };
Queue(eventTime, channel, resource, origin, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("uri", PageBL.GetUriCanonical(page).AsServerUri().ToString())
.Elem("pageid", page.ID)
.Start("security")
.Attr("cascade", cascade.ToString().ToLower())
.End());
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "PageSecurityChanged", "event couldn't be created");
}
}
public void AttachmentCreate(DateTime eventTime, AttachmentBE attachment, UserBE user) {
PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, FILES, CREATE);
AttachmentChanged(eventTime, attachment, CREATE);
}
public void AttachmentUpdate(DateTime eventTime, AttachmentBE attachment, UserBE user) {
PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, FILES, UPDATE);
AttachmentChanged(eventTime, attachment, UPDATE);
}
public void AttachmentDelete(DateTime eventTime, AttachmentBE attachment, UserBE user) {
PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, FILES, DELETE);
AttachmentChanged(eventTime, attachment, DELETE);
}
public void AttachmentMove(DateTime eventTime, AttachmentBE attachment, PageBE sourcePage, UserBE user) {
PageDependentChanged(eventTime, sourcePage, user, FILES, DELETE);
PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, FILES, CREATE);
AttachmentChanged(eventTime, attachment, MOVE);
}
public void AttachmentRestore(DateTime eventTime, AttachmentBE attachment, UserBE user) {
PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, FILES, RESTORE);
AttachmentChanged(eventTime, attachment, RESTORE);
}
public void AttachmentPoke(DateTime eventTime, AttachmentBE attachment) {
AttachmentChanged(eventTime, attachment, NO_OP);
}
private void AttachmentChanged(DateTime eventTime, AttachmentBE attachment, params string[] path) {
try {
XUri channel = _channel.At(FILES).At(path);
XUri attachmentUri = AttachmentBL.Instance.GetUri(attachment);
XUri resource = attachmentUri.WithHost(_wikiid);
string[] origin = new string[] { attachmentUri.AsServerUri().ToString() };
Queue(eventTime, channel, resource, origin, new XDoc("deki-event")
.Elem("channel", channel)
.Elem("fileid", attachment.FileId ?? 0)
.Elem("uri", attachmentUri.AsServerUri().ToString())
.Elem("content.uri", attachmentUri.AsServerUri().ToString())
.Elem("revision.uri", attachmentUri.At("info").With("revision", attachment.Revision.ToString()).AsServerUri().ToString())
.Elem("path", attachmentUri.Path));
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "AttachmentChanged", "event couldn't be created");
}
}
public void PropertyCreate(DateTime eventTime, PropertyBE prop, UserBE user, ResourceBE.Type parentType, XUri parentUri) {
NotifyPropertyParent(eventTime, prop, user, parentType, CREATE);
PropertyChanged(eventTime, prop, user, parentType, parentUri, CREATE);
}
public void PropertyUpdate(DateTime eventTime, PropertyBE prop, UserBE user, ResourceBE.Type parentType, XUri parentUri) {
NotifyPropertyParent(eventTime, prop, user, parentType, UPDATE);
PropertyChanged(eventTime, prop, user, parentType, parentUri, UPDATE);
}
public void PropertyDelete(DateTime eventTime, PropertyBE prop, UserBE user, ResourceBE.Type parentType, XUri parentUri) {
NotifyPropertyParent(eventTime, prop, user, parentType, DELETE);
PropertyChanged(eventTime, prop, user, parentType, parentUri, DELETE);
}
private void NotifyPropertyParent(DateTime eventTime, PropertyBE prop, UserBE user, ResourceBE.Type parentType, string action) {
if(parentType == ResourceBE.Type.PAGE && prop.ParentPageId != null) {
PageBE parentPage = PageBL.GetPageById(prop.ParentPageId.Value);
if(parentPage != null) {
PageDependentChanged(eventTime, parentPage, user, PROPERTY, action);
}
} else if(parentType == ResourceBE.Type.USER) {
// Owner of property may not be same as requesting user.
// The dependentschanged event is triggered on the property owner.
if(prop.ParentUserId != null) {
// Optimization to avoid a db call when operating on your own user property.
if(user.ID != prop.ParentUserId.Value) {
user = UserBL.GetUserById(prop.ParentUserId.Value);
if(user == null) {
_log.WarnFormat("Could not find owner user (id: {0}) of user property (key: {1})", prop.ParentUserId.Value, prop.Name);
return;
}
}
}
UserDependentChanged(eventTime, user, PROPERTY, action);
}
//TODO (maxm): trigger file property changes
}
private void PropertyChanged(DateTime eventTime, PropertyBE prop, UserBE user, ResourceBE.Type parentType, XUri parentUri, params string[] path) {
try {
string parent = string.Empty;
switch(parentType) {
case ResourceBE.Type.PAGE:
parent = PAGES;
break;
case ResourceBE.Type.FILE:
parent = FILES;
break;
case ResourceBE.Type.USER:
parent = USERS;
break;
case ResourceBE.Type.SITE:
parent = SITE;
break;
}
XUri channel = _channel.At(parent).At(PROPERTY).At(path);
XUri resource = prop.UriInfo(parentUri);
string[] origin = new string[] { resource.ToString() };
XDoc doc = new XDoc("deki-event")
.Elem("channel", channel)
.Elem("name", prop.Name)
.Elem("uri", resource)
.Start("content")
.Attr("mime-type", prop.MimeType.FullType)
.Attr("size", prop.Size)
.Attr("href", prop.UriContent(parentUri));
if(prop.MimeType.MainType == MimeType.TEXT.MainType && prop.Size < 256) {
doc.Value(prop.Content.ToText());
}
doc.End();
if(parentType == ResourceBE.Type.PAGE) {
doc.Elem("pageid", prop.ParentPageId ?? 0);
} else if(parentType == ResourceBE.Type.USER) {
doc.Elem("userid", prop.ParentUserId ?? 0);
} else if(parentType == ResourceBE.Type.FILE) {
AttachmentBE attachment = (AttachmentBE)prop.ParentResource;
doc.Elem("fileid", attachment.FileId ?? 0);
PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, ArrayUtil.Concat(new string[] { FILES, PROPERTY }, path));
}
Queue(eventTime, channel, resource, origin, doc);
} catch(Exception e) {
_log.WarnExceptionMethodCall(e, "PropertyChanged", "event couldn't be created");
}
}
private void Queue(DateTime eventTime, XUri channel, XUri resource, string[] origin, XDoc doc) {
doc.Attr("wikiid", _wikiid).Attr("event-time", eventTime);
var data = new ChangeData();
data.Channel = channel;
data.Resource = resource == null ? null : resource.WithoutQuery().WithoutFragment();
data.Origin = origin;
data.Doc = doc;
if(!_changeQueue.TryEnqueue(data)) {
_log.WarnFormat("unable to enqueue change data into processing queue");
}
}
private void Publish(ChangeData data) {
_log.DebugFormat("publishing {0} on channel {1}", data.Resource, data.Channel);
DreamMessage message = DreamMessage.Ok(data.Doc);
message.Headers.DreamEventChannel = data.Channel.ToString();
if(data.Resource != null) {
message.Headers.DreamEventResource = data.Resource.ToString();
}
message.Headers.DreamEventOrigin = data.Origin;
_publishPlug.Post(message, new Result<DreamMessage>()).WhenDone(
r => {
if(r.HasException) {
_log.Warn("unable to publish deki change", r.Exception);
} else if(!r.Value.IsSuccessful) {
_log.WarnFormat("unable to publish deki change: {0}", r.Value.Status);
}
});
}
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Universal charset detector code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shy Shalom <shooshX@gmail.com>
* Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port)
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
using System;
namespace Ude.Core
{
public abstract class HungarianModel : SequenceModel
{
//Model Table:
//total sequences: 100%
//first 512 sequences: 94.7368%
//first 1024 sequences:5.2623%
//rest sequences: 0.8894%
//negative sequences: 0.0009%
private readonly static byte[] HUNGARIAN_LANG_MODEL = {
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,2,3,3,1,1,2,2,2,2,2,1,2,
3,2,2,3,3,3,3,3,2,3,3,3,3,3,3,1,2,3,3,3,3,2,3,3,1,1,3,3,0,1,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,
3,2,1,3,3,3,3,3,2,3,3,3,3,3,1,1,2,3,3,3,3,3,3,3,1,1,3,2,0,1,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,1,1,2,3,3,3,1,3,3,3,3,3,1,3,3,2,2,0,3,2,3,
0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,3,3,2,3,3,2,2,3,2,3,2,0,3,2,2,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,
3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,3,1,2,3,2,2,3,1,2,3,3,2,2,0,3,3,3,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,3,2,3,3,3,3,2,3,3,3,3,0,2,3,2,
0,0,0,1,1,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,2,1,3,2,2,3,2,1,3,2,2,1,0,3,3,1,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,2,2,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,3,2,2,3,1,1,3,2,0,1,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,1,3,3,3,3,3,2,2,1,3,3,3,0,1,1,2,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,2,0,3,2,3,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0,
3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,1,3,2,2,2,3,1,1,3,3,1,1,0,3,3,2,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,2,3,3,3,3,3,1,2,3,2,2,0,2,2,2,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,2,2,2,3,1,3,3,2,2,1,3,3,3,1,1,3,1,2,3,2,3,2,2,2,1,0,2,2,2,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,
3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,2,2,3,2,1,0,3,2,0,1,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,1,0,3,3,3,3,0,2,3,0,0,2,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,2,3,3,2,2,2,2,3,3,0,1,2,3,2,3,2,2,3,2,1,2,0,2,2,2,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,
3,3,3,3,3,3,1,2,3,3,3,2,1,2,3,3,2,2,2,3,2,3,3,1,3,3,1,1,0,2,3,2,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,1,2,2,2,2,3,3,3,1,1,1,3,3,1,1,3,1,1,3,2,1,2,3,1,1,0,2,2,2,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,2,1,2,1,1,3,3,1,1,1,1,3,3,1,1,2,2,1,2,1,1,2,2,1,1,0,2,2,1,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,1,1,2,1,1,3,3,1,0,1,1,3,3,2,0,1,1,2,3,1,0,2,2,1,0,0,1,3,2,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,2,1,3,3,3,3,3,1,2,3,2,3,3,2,1,1,3,2,3,2,1,2,2,0,1,2,1,0,0,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,3,3,3,2,2,2,2,3,1,2,2,1,1,3,3,0,3,2,1,2,3,2,1,3,3,1,1,0,2,1,3,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,3,3,2,2,2,3,2,3,3,3,2,1,1,3,3,1,1,1,2,2,3,2,3,2,2,2,1,0,2,2,1,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
1,0,0,3,3,3,3,3,0,0,3,3,2,3,0,0,0,2,3,3,1,0,1,2,0,0,1,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,2,3,3,3,3,3,1,2,3,3,2,2,1,1,0,3,3,2,2,1,2,2,1,0,2,2,0,1,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,2,2,1,3,1,2,3,3,2,2,1,1,2,2,1,1,1,1,3,2,1,1,1,1,2,1,0,1,2,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
2,3,3,1,1,1,1,1,3,3,3,0,1,1,3,3,1,1,1,1,1,2,2,0,3,1,1,2,0,2,1,1,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
3,1,0,1,2,1,2,2,0,1,2,3,1,2,0,0,0,2,1,1,1,1,1,2,0,0,1,1,0,0,0,0,
1,2,1,2,2,2,1,2,1,2,0,2,0,2,2,1,1,2,1,1,2,1,1,1,0,1,0,0,0,1,1,0,
1,1,1,2,3,2,3,3,0,1,2,2,3,1,0,1,0,2,1,2,2,0,1,1,0,0,1,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,3,3,2,2,1,0,0,3,2,3,2,0,0,0,1,1,3,0,0,1,1,0,0,2,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,1,2,2,3,3,1,0,1,3,2,3,1,1,1,0,1,1,1,1,1,3,1,0,0,2,2,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,1,1,2,2,2,1,0,1,2,3,3,2,0,0,0,2,1,1,1,2,1,1,1,0,1,1,1,0,0,0,
1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,2,1,1,1,1,1,1,0,1,1,1,0,0,1,1,
3,2,2,1,0,0,1,1,2,2,0,3,0,1,2,1,1,0,0,1,1,1,0,1,1,1,1,0,2,1,1,1,
2,2,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,1,1,2,3,1,1,1,1,1,1,1,1,1,0,1,
2,3,3,0,1,0,0,0,3,3,1,0,0,1,2,2,1,0,0,0,0,2,0,0,1,1,1,0,2,1,1,1,
2,1,1,1,1,1,1,2,1,1,0,1,1,0,1,1,1,0,1,2,1,1,0,1,1,1,1,1,1,1,0,1,
2,3,3,0,1,0,0,0,2,2,0,0,0,0,1,2,2,0,0,0,0,1,0,0,1,1,0,0,2,0,1,0,
2,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1,
3,2,2,0,1,0,1,0,2,3,2,0,0,1,2,2,1,0,0,1,1,1,0,0,2,1,0,1,2,2,1,1,
2,1,1,1,1,1,1,2,1,1,1,1,1,1,0,2,1,0,1,1,0,1,1,1,0,1,1,2,1,1,0,1,
2,2,2,0,0,1,0,0,2,2,1,1,0,0,2,1,1,0,0,0,1,2,0,0,2,1,0,0,2,1,1,1,
2,1,1,1,1,2,1,2,1,1,1,2,2,1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,
1,2,3,0,0,0,1,0,3,2,1,0,0,1,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,2,1,
1,1,0,0,0,1,0,1,1,1,1,1,2,0,0,1,0,0,0,2,0,0,1,1,1,1,1,1,1,1,0,1,
3,0,0,2,1,2,2,1,0,0,2,1,2,2,0,0,0,2,1,1,1,0,1,1,0,0,1,1,2,0,0,0,
1,2,1,2,2,1,1,2,1,2,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,0,0,1,
1,3,2,0,0,0,1,0,2,2,2,0,0,0,2,2,1,0,0,0,0,3,1,1,1,1,0,0,2,1,1,1,
2,1,0,1,1,1,0,1,1,1,1,1,1,1,0,2,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,1,
2,3,2,0,0,0,1,0,2,2,0,0,0,0,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,1,0,
2,1,1,1,1,2,1,2,1,2,0,1,1,1,0,2,1,1,1,2,1,1,1,1,0,1,1,1,1,1,0,1,
3,1,1,2,2,2,3,2,1,1,2,2,1,1,0,1,0,2,2,1,1,1,1,1,0,0,1,1,0,1,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,0,0,0,0,0,2,2,0,0,0,0,2,2,1,0,0,0,1,1,0,0,1,2,0,0,2,1,1,1,
2,2,1,1,1,2,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,1,1,0,1,2,1,1,1,0,1,
1,0,0,1,2,3,2,1,0,0,2,0,1,1,0,0,0,1,1,1,1,0,1,1,0,0,1,0,0,0,0,0,
1,2,1,2,1,2,1,1,1,2,0,2,1,1,1,0,1,2,0,0,1,1,1,0,0,0,0,0,0,0,0,0,
2,3,2,0,0,0,0,0,1,1,2,1,0,0,1,1,1,0,0,0,0,2,0,0,1,1,0,0,2,1,1,1,
2,1,1,1,1,1,1,2,1,0,1,1,1,1,0,2,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,
1,2,2,0,1,1,1,0,2,2,2,0,0,0,3,2,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,0,
1,1,0,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,0,0,1,1,1,0,1,0,1,
2,1,0,2,1,1,2,2,1,1,2,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1,1,0,0,0,
1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,1,0,
1,2,3,0,0,0,1,0,2,2,0,0,0,0,2,2,0,0,0,0,0,1,0,0,1,0,0,0,2,0,1,0,
2,1,1,1,1,1,0,2,0,0,0,1,2,1,1,1,1,0,1,2,0,1,0,1,0,1,1,1,0,1,0,1,
2,2,2,0,0,0,1,0,2,1,2,0,0,0,1,1,2,0,0,0,0,1,0,0,1,1,0,0,2,1,0,1,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1,
1,2,2,0,0,0,1,0,2,2,2,0,0,0,1,1,0,0,0,0,0,1,1,0,2,0,0,1,1,1,0,1,
1,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,0,0,1,
1,0,0,1,0,1,2,1,0,0,1,1,1,2,0,0,0,1,1,0,1,0,1,1,0,0,1,0,0,0,0,0,
0,2,1,2,1,1,1,1,1,2,0,2,0,1,1,0,1,2,1,0,1,1,1,0,0,0,0,0,0,1,0,0,
2,1,1,0,1,2,0,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,2,1,0,1,
2,2,1,1,1,1,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,0,1,0,1,1,1,1,1,0,1,
1,2,2,0,0,0,0,0,1,1,0,0,0,0,2,1,0,0,0,0,0,2,0,0,2,2,0,0,2,0,0,1,
2,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1,
1,1,2,0,0,3,1,0,2,1,1,1,0,0,1,1,1,0,0,0,1,1,0,0,0,1,0,0,1,0,1,0,
1,2,1,0,1,1,1,2,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0,1,0,0,
2,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,2,0,0,0,
2,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,1,0,1,
2,1,1,1,2,1,1,1,0,1,1,2,1,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,0,1,1,1,1,1,0,0,1,1,2,1,0,0,0,1,1,0,0,0,1,1,0,0,1,0,1,0,0,0,
1,2,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,
2,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,2,0,0,1,0,0,1,0,1,0,0,0,
0,1,1,1,1,1,1,1,1,2,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,
1,0,0,1,1,1,1,1,0,0,2,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,
0,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,
1,0,0,1,1,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,1,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,1,1,0,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,
2,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,0,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,1,0,1,1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,
};
public HungarianModel(byte[] charToOrderMap, string name)
: base(charToOrderMap, HUNGARIAN_LANG_MODEL, 0.947368f,
false, name)
{
}
}
public class Latin2HungarianModel : HungarianModel
{
private readonly static byte[] LATIN2_CHAR_TO_ORDER_MAP = {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
+253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47,
46, 71, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253,
253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8,
23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253,
159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,
175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,
191,192,193,194,195,196,197, 75,198,199,200,201,202,203,204,205,
79,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,
221, 51, 81,222, 78,223,224,225,226, 44,227,228,229, 61,230,231,
232,233,234, 58,235, 66, 59,236,237,238, 60, 69, 63,239,240,241,
82, 14, 74,242, 70, 80,243, 72,244, 15, 83, 77, 84, 30, 76, 85,
245,246,247, 25, 73, 42, 24,248,249,250, 31, 56, 29,251,252,253,
};
public Latin2HungarianModel() : base(LATIN2_CHAR_TO_ORDER_MAP, "ISO-8859-2")
{
}
}
public class Win1250HungarianModel : HungarianModel
{
private readonly static byte[] WIN1250_CHAR_TO_ORDER_MAP = {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
+253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47,
46, 72, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253,
253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8,
23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253,
161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,
177,178,179,180, 78,181, 69,182,183,184,185,186,187,188,189,190,
191,192,193,194,195,196,197, 76,198,199,200,201,202,203,204,205,
81,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,
221, 51, 83,222, 80,223,224,225,226, 44,227,228,229, 61,230,231,
232,233,234, 58,235, 66, 59,236,237,238, 60, 70, 63,239,240,241,
84, 14, 75,242, 71, 82,243, 73,244, 15, 85, 79, 86, 30, 77, 87,
245,246,247, 25, 74, 42, 24,248,249,250, 31, 56, 29,251,252,253,
};
public Win1250HungarianModel() : base(WIN1250_CHAR_TO_ORDER_MAP, "windows-1250")
{
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Environment.ObjectState
{
/// <summary>
/// Enumeration values for Crater (env.obj.appear.point.crater, Crater,
/// section 12.1.2.2.4)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public struct Crater
{
private byte size;
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(Crater left, Crater right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Crater left, Crater right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
// If parameters are null return false (cast to object to prevent recursive loop!)
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
/// <summary>
/// Performs an explicit conversion from <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> to <see cref="System.UInt32"/>.
/// </summary>
/// <param name="obj">The <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> scheme instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator uint(Crater obj)
{
return obj.ToUInt32();
}
/// <summary>
/// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/>.
/// </summary>
/// <param name="value">The uint value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Crater(uint value)
{
return Crater.FromUInt32(value);
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance from the byte array.
/// </summary>
/// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/>.</param>
/// <param name="index">The starting position within value.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance, represented by a byte array.</returns>
/// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception>
/// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception>
public static Crater FromByteArray(byte[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (index < 0 ||
index > array.Length - 1 ||
index + 4 > array.Length - 1)
{
throw new IndexOutOfRangeException();
}
return FromUInt32(BitConverter.ToUInt32(array, index));
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance from the uint value.
/// </summary>
/// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance, represented by the uint value.</returns>
public static Crater FromUInt32(uint value)
{
Crater ps = new Crater();
uint mask0 = 0xff0000;
byte shift0 = 16;
uint newValue0 = value & mask0 >> shift0;
ps.Size = (byte)newValue0;
return ps;
}
/// <summary>
/// Gets or sets the size.
/// </summary>
/// <value>The size.</value>
public byte Size
{
get { return this.size; }
set { this.size = value; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is Crater))
{
return false;
}
return this.Equals((Crater)obj);
}
/// <summary>
/// Determines whether the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Crater other)
{
// If parameter is null return false (cast to object to prevent recursive loop!)
if ((object)other == null)
{
return false;
}
return
this.Size == other.Size;
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> to the byte array.
/// </summary>
/// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance.</returns>
public byte[] ToByteArray()
{
return BitConverter.GetBytes(this.ToUInt32());
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> to the uint value.
/// </summary>
/// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.Crater"/> instance.</returns>
public uint ToUInt32()
{
uint val = 0;
val |= (uint)((uint)this.Size << 16);
return val;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int hash = 17;
// Overflow is fine, just wrap
unchecked
{
hash = (hash * 29) + this.Size.GetHashCode();
}
return hash;
}
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
$VisibilityOptionsLoaded = false;
$VisibilityClassLoaded = false;
$EVisibilityLayers_Initialized = false;
$EVisibilityArrayMode = true;
function toggleWireframe( %val ) {
if (!%val)
return;
$gfx::wireframe = !$gfx::wireframe;
}
GlobalActionMap.bind(keyboard, "alt numpad1", toggleWireframe);
//==============================================================================
function EVisibilityLayers::toggleVisibility(%this) {
ETools.toggleTool("VisibilityLayers");
visibilityToggleBtn.setStateOn(%this.visible);
if ( %this.visible ) {
%this.onShow();
}
}
//------------------------------------------------------------------------------
//==============================================================================
function EVisibilityLayers::onShow( %this ) {
%this.init();
%this.updateOptions();
}
//==============================================================================
function EVisibilityLayers::init( %this ) {
%this.updatePresetMenu();
if(!$EVisibilityLayers_Initialized) {
// Create the array if it doesn't already exist.
if ( !isObject( ar_EVisibilityLayers ) )
%array = newArrayObject("ar_EVisibilityLayers");
// Create the array if it doesn't already exist.
if ( !isObject( ar_EVisibilityLayersClass ) )
%classArray = newArrayObject("ar_EVisibilityLayersClass");
%this.array = ar_EVisibilityLayers;
%this.classArray = ar_EVisibilityLayersClass;
//EVisibilityLayers.position = visibilityToggleBtn.position;
%this.initOptions();
%this.addClassOptions();
$EVisibilityLayers_Initialized = true;
}
}
//------------------------------------------------------------------------------
function EVisibilityLayers::updateOptions( %this ) {
// First clear the stack control.
EVisibilityLayers-->theVisOptionsList.clear();
// Go through all the
// parameters in our array and
// create a check box for each.
for ( %i = 0; %i < %this.array.count(); %i++ ) {
%text = " " @ %this.array.getValue( %i );
%val = %this.array.getKey( %i );
%var = getWord( %val, 0 );
%toggleFunction = getWord( %val, 1 );
%textLength = strlen( %text );
%cmd = "";
if ( %toggleFunction !$= "" )
%cmd = %toggleFunction @ "( $thisControl.getValue() );";
%checkBox = new GuiCheckBoxCtrl() {
canSaveDynamicFields = "0";
isContainer = "0";
Profile = "ToolsCheckBoxProfile";
HorizSizing = "right";
VertSizing = "bottom";
Position = "0 0";
Extent = (%textLength * 4) @ " 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
Variable = %var;
tooltipprofile = "ToolsToolTipProfile";
hovertime = "1000";
text = %text;
groupNum = "-1";
buttonType = "ToggleButton";
useMouseEvents = "0";
useInactiveState = "0";
Command = %cmd;
};
%this-->theVisOptionsList.addGuiControl( %checkBox );
}
}
function EVisibilityLayers::initOptions( %this ) {
ar_EVisibilityLayers.empty();
// Expose stock visibility/debug options.
%this.addOption( "Render: Zones", "$Zone::isRenderable", "" );
%this.addOption( "Render: Portals", "$Portal::isRenderable", "" );
%this.addOption( "Render: Occlusion Volumes", "$OcclusionVolume::isRenderable", "" );
%this.addOption( "Render: Triggers", "$Trigger::renderTriggers", "" );
%this.addOption( "Render: PhysicalZones", "$PhysicalZone::renderZones", "" );
%this.addOption( "Render: Sound Emitters", "$SFXEmitter::renderEmitters", "" );
%this.addOption( "Render: Mission Area", "EWorldEditor.renderMissionArea", "" );
%this.addOption( "Render: Sound Spaces", "$SFXSpace::isRenderable", "" );
%this.addOption( "Wireframe Mode", "$gfx::wireframe", "" );
%this.addOption( "Debug Render: Player Collision", "$Player::renderCollision", "" );
%this.addOption( "Debug Render: Terrain", "$TerrainBlock::debugRender", "" );
%this.addOption( "Debug Render: Decals", "$Decals::debugRender", "" );
%this.addOption( "Debug Render: Light Frustums", "$Light::renderLightFrustums", "" );
%this.addOption( "Debug Render: Bounding Boxes", "$Scene::renderBoundingBoxes", "" );
%this.addOption( "AL: Disable Shadows", "$Shadows::disable", "" );
%this.addOption( "AL: Light Color Viz", "$AL_LightColorVisualizeVar", "toggleLightColorViz" );
%this.addOption( "AL: Light Specular Viz", "$AL_LightSpecularVisualizeVar", "toggleLightSpecularViz" );
%this.addOption( "AL: Normals Viz", "$AL_NormalsVisualizeVar", "toggleNormalsViz" );
%this.addOption( "AL: Depth Viz", "$AL_DepthVisualizeVar", "toggleDepthViz" );
%this.addOption( "Frustum Lock", "$Scene::lockCull", "" );
%this.addOption( "Disable Zone Culling", "$Scene::disableZoneCulling", "" );
%this.addOption( "Disable Terrain Occlusion", "$Scene::disableTerrainOcclusion", "" );
//PBR Script
%this.addOption( "Debug Render: Physics World", "$PhysicsWorld::render", "togglePhysicsDebugViz" );
%this.addOption( "AL: Environment Light", "$AL_LightMapShaderVar", "toggleLightMapViz" );
%this.addOption( "AL: Color Buffer", "$AL_ColorBufferShaderVar", "toggleColorBufferViz" );
%this.addOption( "AL: Spec Map(Rough)", "$AL_RoughMapShaderVar", "toggleRoughMapViz");
%this.addOption( "AL: Spec Map(Metal)", "$AL_MetalMapShaderVar", "toggleMetalMapViz");
%this.addOption( "AL: Backbuffer", "$AL_BackbufferVisualizeVar", "toggleBackbufferViz" );
//PBR Script End
$VisibilityOptionsLoaded = true;
}
function EVisibilityLayers::addOption( %this, %text, %varName, %toggleFunction ) {
// Create the array if it
// doesn't already exist.
if ( !isObject( %this.array ) )
%this.array = new ArrayObject();
%this.array.push_back( %varName @ " " @ %toggleFunction, %text );
%this.array.uniqueKey();
%this.array.sortd();
//%this.updateOptions();
}
//EVisibilityLayers.addClassOptions
function EVisibilityLayers::addClassOptions( %this ) {
%visList = %this-->theClassVisList;
%visArray = %this-->theClassVisArray;
%selList = %this-->theClassSelList;
%selArray = %this-->theClassSelArray;
%srcPill = %this-->theClassSelPill;
%visList.clear();
%selList.clear();
%visArray.clear();
%selArray.clear();
%visList.visible = !$EVisibilityArrayMode;
%visArray.visible = $EVisibilityArrayMode;
%selList.visible = !$EVisibilityArrayMode;
%selArray.visible = $EVisibilityArrayMode;
if ($EVisibilityArrayMode){
%visContainer = %visArray;
%selContainer = %selArray;
}else {
%visContainer = %visList;
%selContainer = %selList;
}
%selArray.visible = $EVisibilityArrayMode;
// First clear the stack control.
%classList = enumerateConsoleClasses( "SceneObject" );
%classCount = getFieldCount( %classList );
for ( %i = 0; %i < %classCount; %i++ ) {
%className = getField( %classList, %i );
%this.classArray.push_back( %className );
}
// Remove duplicates and sort by key.
%this.classArray.uniqueKey();
%this.classArray.sortka();
// Go through all the
// parameters in our array and
// create a check box for each.
for ( %i = 0; %i < %this.classArray.count(); %i++ ) {
%class = %this.classArray.getKey( %i );
%visVar = "$" @ %class @ "::isRenderable";
%selVar = "$" @ %class @ "::isSelectable";
%textLength = strlen( %class );
%text = " " @ %class;
%visPill = cloneObject(EVisibilityCheckBoxSrc);
%visCheck = %visPill.getObject(0);
%visPill.setName("EVis_Visible_"@%class);
%visCheck.variable = %visVar;
%visCheck.command = "EVisibilityLayers.toggleRenderable(\""@%class@"\");";
%visCheck.text = %text;
%visCheck.tooltip = "Show/hide all " @ %class @ " objects.";
%visContainer.addGuiControl(%visPill);
%selPill = cloneObject(EVisibilityCheckBoxSrc);
%visPill.setName("EVis_Select_"@%class);
%selCheck = %selPill.getObject(0);
%selCheck.variable = %selVar;
%selCheck.command = "EVisibilityLayers.toggleSelectable(\""@%class@"\");";
%selCheck.text = %text;
%selCheck.tooltip = "Show/hide all " @ %class @ " objects.";
%selContainer.addGuiControl(%selPill);
continue;
// Add visibility toggle.
%visCheckBox = new GuiCheckBoxCtrl() {
canSaveDynamicFields = "0";
isContainer = "0";
Profile = "ToolsCheckBoxProfile";
HorizSizing = "right";
VertSizing = "bottom";
Position = "0 0";
Extent = (%textLength * 4) @ " 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
Variable = %visVar;
command = "EVisibilityLayers.toggleRenderable(\""@%class@"\");";
tooltipprofile = "ToolsToolTipProfile";
hovertime = "1000";
tooltip = "Show/hide all " @ %class @ " objects.";
text = %text;
groupNum = "-1";
buttonType = "ToggleButton";
useMouseEvents = "0";
useInactiveState = "0";
};
//Variable = %visVar;
%visList.addGuiControl( %visCheckBox );
// Add selectability toggle.
%selCheckBox = new GuiCheckBoxCtrl() {
canSaveDynamicFields = "0";
isContainer = "0";
Profile = "ToolsCheckBoxProfile";
HorizSizing = "right";
VertSizing = "bottom";
Position = "0 0";
Extent = (%textLength * 4) @ " 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
command = "EVisibilityLayers.toggleSelectable(\""@%class@"\");";
Variable = %selVar;
tooltipprofile = "ToolsToolTipProfile";
hovertime = "1000";
tooltip = "Enable/disable selection of all " @ %class @ " objects.";
text = %text;
groupNum = "-1";
buttonType = "ToggleButton";
useMouseEvents = "0";
useInactiveState = "0";
};
//Variable = %selVar;
%selList.addGuiControl( %selCheckBox );
//eval("%visON = $" @ %class @ "::isRenderable;");
//eval("%selON = $" @ %class @ "::isSelectable;");
//%visCheckBox.setStateOn(%visON);
//%selCheckBox.setStateOn(%selON);
}
if ($EVisibilityArrayMode){
%visContainer.refresh();
%selContainer.refresh();
}
$VisibilityClassLoaded = true;
}
//==============================================================================
function EVisibilityLayers::toggleRenderable( %this,%class ) {
//eval("$" @ %class @ "::isRenderable = !$"@ %class @ "::isRenderable;");
%visVar = "$" @ %class @ "::isRenderable";
//%selVar = "$" @ %class @ "::isSelectable";
if (!%visVar)
eval("$" @ %class @ "::isSelectable = \"0\";");
else
eval("$" @ %class @ "::isSelectable = \"1\";");
}
function EVisibilityLayers::toggleSelectable( %this,%class ) {
//eval("$" @ %class @ "::isRenderable = !$"@ %class @ "::isRenderable;");
%selVar = "$" @ %class @ "::isSelectable";
if (%selVar)
eval("$" @ %class @ "::isRenderable = \"1\";");
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using Bam.Core;
namespace flex
{
class FlexGeneratedSource :
C.SourceFile,
Bam.Core.ICloneModule
{
private FlexSourceFile SourceModule;
protected override void
Init()
{
base.Init();
var graph = Bam.Core.Graph.Instance;
this.Compiler = graph.FindReferencedModule<FlexTool>();
this.Requires(this.Compiler);
var parentModule = graph.ModuleStack.Peek();
this.InputPath = this.CreateTokenizedString(
"$(0)/$(1)/$(config)/@isrelative(@dir(@trimstart(@relativeto($(FlexSource),$(packagedir)),../)),.)/lex.@changeextension(#valid($(FlexModuleName),@basename($(FlexSource))),.cpp)",
parentModule.Macros[Bam.Core.ModuleMacroNames.PackageBuildDirectory],
parentModule.Macros[Bam.Core.ModuleMacroNames.ModuleName]
);
}
public Bam.Core.TokenizedString ModuleName
{
get
{
return this.Macros["FlexModuleName"];
}
set
{
this.Macros.Add("FlexModuleName", value);
}
}
public FlexSourceFile Source
{
get
{
return this.SourceModule;
}
set
{
this.SourceModule = value;
this.DependsOn(value);
this.Macros.Add("FlexSource", value.InputPath);
}
}
protected override void
EvaluateInternal()
{
this.ReasonToExecute = null;
var generatedPath = this.GeneratedPaths[SourceFileKey].ToString();
if (!System.IO.File.Exists(generatedPath))
{
this.ReasonToExecute = Bam.Core.ExecuteReasoning.FileDoesNotExist(
this.GeneratedPaths[SourceFileKey]
);
return;
}
var generatedFileWriteTime = System.IO.File.GetLastWriteTime(generatedPath);
var sourceFileWriteTime = System.IO.File.GetLastWriteTime(this.SourceModule.InputPath.ToString());
if (sourceFileWriteTime > generatedFileWriteTime)
{
this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer(
this.GeneratedPaths[SourceFileKey],
this.SourceModule.InputPath
);
return;
}
}
protected override void
ExecuteInternal(
Bam.Core.ExecutionContext context)
{
switch (Bam.Core.Graph.Instance.Mode)
{
#if D_PACKAGE_MAKEFILEBUILDER
case "MakeFile":
MakeFileBuilder.Support.Add(this);
break;
#endif
#if D_PACKAGE_NATIVEBUILDER
case "Native":
NativeBuilder.Support.RunCommandLineTool(this, context);
break;
#endif
#if D_PACKAGE_VSSOLUTIONBUILDER
case "VSSolution":
VSSolutionBuilder.Support.AddCustomBuildStepForCommandLineTool(
this,
this.GeneratedPaths[SourceFileKey],
"Flex'ing",
true
);
break;
#endif
#if D_PACKAGE_XCODEBUILDER
case "Xcode":
{
XcodeBuilder.Support.AddPreBuildStepForCommandLineTool(
this,
out XcodeBuilder.Target target,
out XcodeBuilder.Configuration configuration,
XcodeBuilder.FileReference.EFileType.LexFile,
true,
false,
outputPaths: new Bam.Core.TokenizedStringArray(this.GeneratedPaths[SourceFileKey])
);
}
break;
#endif
default:
throw new System.NotImplementedException();
}
}
private Bam.Core.PreBuiltTool Compiler
{
get
{
return this.Tool as Bam.Core.PreBuiltTool;
}
set
{
this.Tool = value;
}
}
public Bam.Core.TokenizedString LibrarySearchPath
{
get
{
if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows))
{
return this.Compiler.Macros["LibraryPath"];
}
return null; // indicates system library
}
}
public string StandardLibrary(
C.LinkerTool linker)
{
if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows))
{
if (linker is VisualCCommon.LinkerBase)
{
return string.Empty; // the library provided does not link with VisualC, use %option noyywrap
}
else
{
return "-lfl";
}
}
else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX))
{
return "-ll"; // note libl.a not libfl.a
}
return "-lfl";
}
Bam.Core.Module
ICloneModule.Clone(
Bam.Core.Module parent,
Bam.Core.Module.PostInitDelegate postInitCB)
{
var clone = Bam.Core.Module.CloneWithPrivatePatches<FlexGeneratedSource>(
this,
parent,
postInitCallback: postInitCB
);
clone.ModuleName = this.ModuleName;
clone.Source = this.Source;
return clone;
}
public override System.Collections.Generic.IEnumerable<(Bam.Core.Module module, string pathKey)> InputModulePaths
{
get
{
yield return (this.SourceModule, FlexSourceFile.FlexSourceKey);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using Eto.Drawing;
using Eto.Forms;
#if IOS
using NSView = UIKit.UIView;
using ObjCRuntime;
using Foundation;
#elif XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
#elif OSX
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#endif
namespace Eto.Mac.Forms
{
public interface IMacControlHandler
{
NSView ContainerControl { get; }
Size PositionOffset { get; }
Size MinimumSize { get; set; }
bool IsEventHandled(string eventName);
NSView ContentControl { get; }
NSView EventControl { get; }
bool AutoSize { get; }
SizeF GetPreferredSize(SizeF availableSize);
}
[Register("ObserverHelper")]
public class ObserverHelper : NSObject
{
bool isNotification;
bool isControl;
public Action<ObserverActionEventArgs> Action { get; set; }
public NSString KeyPath { get; set; }
WeakReference control;
public NSObject Control { get { return (NSObject)(control != null ? control.Target : null); } set { control = new WeakReference(value); } }
WeakReference widget;
public Widget Widget { get { return (Widget)(widget != null ? widget.Target : null); } set { widget = new WeakReference(value); } }
WeakReference handler;
public object Handler { get { return handler != null ? handler.Target : null; } set { handler = new WeakReference(value); } }
static readonly Selector selPerformAction = new Selector("performAction:");
[Export("performAction:")]
public void PerformAction(NSNotification notification)
{
Action(new ObserverActionEventArgs(this, notification));
}
public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
Action(new ObserverActionEventArgs(this, null));
}
public void AddToNotificationCenter()
{
var c = Control;
if (!isNotification && c != null)
{
NSNotificationCenter.DefaultCenter.AddObserver(this, selPerformAction, KeyPath, c);
c.DangerousRetain();
isNotification = true;
}
}
public void AddToControl()
{
var c = Control;
if (!isControl && c != null)
{
//Console.WriteLine ("{0}: 3. Adding observer! {1}, {2}", ((IRef)this.Handler).WidgetID, this.GetType (), Control.GetHashCode ());
c.AddObserver(this, KeyPath, NSKeyValueObservingOptions.New, IntPtr.Zero);
c.DangerousRetain();
isControl = true;
}
}
public void Remove()
{
var c = Control;
if (isNotification)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(this);
if (c != null)
c.DangerousRelease();
isNotification = false;
}
if (isControl && c != null && KeyPath != null)
{
//Console.WriteLine ("{0}: 4. Removing observer! {1}, {2}", ((IRef)this.Handler).WidgetID, Handler.GetType (), Control.GetHashCode ());
c.RemoveObserver(this, KeyPath);
c.DangerousRelease();
isControl = false;
}
}
protected override void Dispose(bool disposing)
{
Remove();
base.Dispose(disposing);
}
}
public class ObserverActionEventArgs : EventArgs
{
readonly ObserverHelper observer;
public ObserverActionEventArgs(ObserverHelper observer, NSNotification notification)
{
this.observer = observer;
this.Notification = notification;
}
public Widget Widget { get { return observer.Widget; } }
public object Handler { get { return observer.Handler; } }
public object Control { get { return observer.Control; } }
public NSString KeyPath { get { return observer.KeyPath; } }
public NSNotification Notification { get; private set; }
}
public interface IMacControl
{
WeakReference WeakHandler { get; }
}
public class MacBase<TControl, TWidget, TCallback> : WidgetHandler<TControl, TWidget, TCallback>
where TControl: class
where TWidget: Widget
{
List<ObserverHelper> observers;
public static object GetHandler(object control)
{
var notification = control as NSNotification;
if (notification != null)
control = notification.Object;
var macControl = control as IMacControl;
if (macControl == null || macControl.WeakHandler == null)
return null;
return macControl.WeakHandler.Target;
}
public void AddMethod(IntPtr selector, Delegate action, string arguments, object control)
{
var type = control.GetType();
#if OSX
if (!typeof(IMacControl).IsAssignableFrom(type))
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Control '{0}' does not inherit from IMacControl", type));
#endif
var classHandle = Class.GetHandle(type);
ObjCExtensions.AddMethod(classHandle, selector, action, arguments);
}
public NSObject AddObserver(NSString key, Action<ObserverActionEventArgs> action, NSObject control)
{
if (observers == null)
observers = new List<ObserverHelper>();
var observer = new ObserverHelper
{
Action = action,
KeyPath = key,
Control = control,
Widget = Widget,
Handler = this
};
observer.AddToNotificationCenter();
observers.Add(observer);
return observer;
}
public void AddControlObserver(NSString key, Action<ObserverActionEventArgs> action, NSObject control)
{
if (observers == null)
observers = new List<ObserverHelper>();
var observer = new ObserverHelper
{
Action = action,
KeyPath = key,
Control = control,
Widget = Widget,
Handler = this
};
observer.AddToControl();
observers.Add(observer);
}
protected override void Dispose(bool disposing)
{
if (observers != null)
{
foreach (var observer in observers)
{
observer.Remove();
}
observers = null;
}
#if OSX
// HACK: Remove when Dispose() actually works!
if (disposing && DisposeControl)
{
var obj = Control as NSObject;
if (obj != null)
{
obj.SafeDispose();
Control = null;
}
}
#endif
base.Dispose(disposing);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework;
namespace OpenSim.Server.Handlers
{
public class UserProfilesHandlers
{
public UserProfilesHandlers ()
{
}
}
public class JsonRpcProfileHandlers
{
static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
public IUserProfilesService Service
{
get; private set;
}
public JsonRpcProfileHandlers(IUserProfilesService service)
{
Service = service;
}
#region Classifieds
/// <summary>
/// Request avatar's classified ads.
/// </summary>
/// <returns>
/// An array containing all the calassified uuid and it's name created by the creator id
/// </returns>
/// <param name='json'>
/// Our parameters are in the OSDMap json["params"]
/// </param>
/// <param name='response'>
/// If set to <c>true</c> response.
/// </param>
public bool AvatarClassifiedsRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
m_log.DebugFormat ("Classified Request");
return false;
}
OSDMap request = (OSDMap)json["params"];
UUID creatorId = new UUID(request["creatorId"].AsString());
OSDArray data = (OSDArray) Service.AvatarClassifiedsRequest(creatorId);
response.Result = data;
return true;
}
public bool ClassifiedUpdate(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "Error parsing classified update request";
m_log.DebugFormat ("Classified Update Request");
return false;
}
string result = string.Empty;
UserClassifiedAdd ad = new UserClassifiedAdd();
object Ad = (object)ad;
OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]);
if(Service.ClassifiedUpdate(ad, ref result))
{
response.Result = OSD.SerializeMembers(ad);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
public bool ClassifiedDelete(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
m_log.DebugFormat ("Classified Delete Request");
return false;
}
OSDMap request = (OSDMap)json["params"];
UUID classifiedId = new UUID(request["classifiedId"].AsString());
if (Service.ClassifiedDelete(classifiedId))
return true;
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = "data error removing record";
return false;
}
public bool ClassifiedInfoRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("Classified Info Request");
return false;
}
string result = string.Empty;
UserClassifiedAdd ad = new UserClassifiedAdd();
object Ad = (object)ad;
OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]);
if(Service.ClassifiedInfoRequest(ref ad, ref result))
{
response.Result = OSD.SerializeMembers(ad);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
#endregion Classifieds
#region Picks
public bool AvatarPicksRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
m_log.DebugFormat ("Avatar Picks Request");
return false;
}
OSDMap request = (OSDMap)json["params"];
UUID creatorId = new UUID(request["creatorId"].AsString());
OSDArray data = (OSDArray) Service.AvatarPicksRequest(creatorId);
response.Result = data;
return true;
}
public bool PickInfoRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("Avatar Picks Info Request");
return false;
}
string result = string.Empty;
UserProfilePick pick = new UserProfilePick();
object Pick = (object)pick;
OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]);
if(Service.PickInfoRequest(ref pick, ref result))
{
response.Result = OSD.SerializeMembers(pick);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
public bool PicksUpdate(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("Avatar Picks Update Request");
return false;
}
string result = string.Empty;
UserProfilePick pick = new UserProfilePick();
object Pick = (object)pick;
OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]);
if(Service.PicksUpdate(ref pick, ref result))
{
response.Result = OSD.SerializeMembers(pick);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = "unable to update pick";
return false;
}
public bool PicksDelete(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
m_log.DebugFormat ("Avatar Picks Delete Request");
return false;
}
OSDMap request = (OSDMap)json["params"];
UUID pickId = new UUID(request["pickId"].AsString());
if(Service.PicksDelete(pickId))
return true;
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = "data error removing record";
return false;
}
#endregion Picks
#region Notes
public bool AvatarNotesRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "Params missing";
m_log.DebugFormat ("Avatar Notes Request");
return false;
}
string result = string.Empty;
UserProfileNotes note = new UserProfileNotes();
object Note = (object)note;
OSD.DeserializeMembers(ref Note, (OSDMap)json["params"]);
if(Service.AvatarNotesRequest(ref note))
{
response.Result = OSD.SerializeMembers(note);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = "Error reading notes";
return false;
}
public bool NotesUpdate(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "No parameters";
m_log.DebugFormat ("Avatar Notes Update Request");
return false;
}
string result = string.Empty;
UserProfileNotes note = new UserProfileNotes();
object Notes = (object) note;
OSD.DeserializeMembers(ref Notes, (OSDMap)json["params"]);
if(Service.NotesUpdate(ref note, ref result))
{
response.Result = OSD.SerializeMembers(note);
return true;
}
return true;
}
#endregion Notes
#region Profile Properties
public bool AvatarPropertiesRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("Avatar Properties Request");
return false;
}
string result = string.Empty;
UserProfileProperties props = new UserProfileProperties();
object Props = (object)props;
OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]);
if(Service.AvatarPropertiesRequest(ref props, ref result))
{
response.Result = OSD.SerializeMembers(props);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
public bool AvatarPropertiesUpdate(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("Avatar Properties Update Request");
return false;
}
string result = string.Empty;
UserProfileProperties props = new UserProfileProperties();
object Props = (object)props;
OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]);
if(Service.AvatarPropertiesUpdate(ref props, ref result))
{
response.Result = OSD.SerializeMembers(props);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
#endregion Profile Properties
#region Interests
public bool AvatarInterestsUpdate(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("Avatar Interests Update Request");
return false;
}
string result = string.Empty;
UserProfileProperties props = new UserProfileProperties();
object Props = (object)props;
OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]);
if(Service.AvatarInterestsUpdate(props, ref result))
{
response.Result = OSD.SerializeMembers(props);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
#endregion Interests
#region User Preferences
public bool UserPreferencesRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
m_log.DebugFormat ("User Preferences Request");
return false;
}
string result = string.Empty;
UserPreferences prefs = new UserPreferences();
object Prefs = (object)prefs;
OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]);
if(Service.UserPreferencesRequest(ref prefs, ref result))
{
response.Result = OSD.SerializeMembers(prefs);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
m_log.InfoFormat("[PROFILES]: User preferences request error - {0}", response.Error.Message);
return false;
}
public bool UserPreferenecesUpdate(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("User Preferences Update Request");
return false;
}
string result = string.Empty;
UserPreferences prefs = new UserPreferences();
object Prefs = (object)prefs;
OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]);
if(Service.UserPreferencesUpdate(ref prefs, ref result))
{
response.Result = OSD.SerializeMembers(prefs);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
m_log.InfoFormat("[PROFILES]: User preferences update error - {0}", response.Error.Message);
return false;
}
#endregion User Preferences
#region Utility
public bool AvatarImageAssetsRequest(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
m_log.DebugFormat ("Avatar Image Assets Request");
return false;
}
OSDMap request = (OSDMap)json["params"];
UUID avatarId = new UUID(request["avatarId"].AsString());
OSDArray data = (OSDArray) Service.AvatarImageAssetsRequest(avatarId);
response.Result = data;
return true;
}
#endregion Utiltiy
#region UserData
public bool RequestUserAppData(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("User Application Service URL Request: No Parameters!");
return false;
}
string result = string.Empty;
UserAppData props = new UserAppData();
object Props = (object)props;
OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]);
if(Service.RequestUserAppData(ref props, ref result))
{
OSDMap res = new OSDMap();
res["result"] = OSD.FromString("success");
res["token"] = OSD.FromString (result);
response.Result = res;
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
public bool UpdateUserAppData(OSDMap json, ref JsonRpcResponse response)
{
if(!json.ContainsKey("params"))
{
response.Error.Code = ErrorCode.ParseError;
response.Error.Message = "no parameters supplied";
m_log.DebugFormat ("User App Data Update Request");
return false;
}
string result = string.Empty;
UserAppData props = new UserAppData();
object Props = (object)props;
OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]);
if(Service.SetUserAppData(props, ref result))
{
response.Result = OSD.SerializeMembers(props);
return true;
}
response.Error.Code = ErrorCode.InternalError;
response.Error.Message = string.Format("{0}", result);
return false;
}
#endregion UserData
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// VM Snapshot Schedule
/// First published in .
/// </summary>
public partial class VMSS : XenObject<VMSS>
{
public VMSS()
{
}
public VMSS(string uuid,
string name_label,
string name_description,
bool enabled,
vmss_type type,
long retained_snapshots,
vmss_frequency frequency,
Dictionary<string, string> schedule,
DateTime last_run_time,
List<XenRef<VM>> VMs)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.enabled = enabled;
this.type = type;
this.retained_snapshots = retained_snapshots;
this.frequency = frequency;
this.schedule = schedule;
this.last_run_time = last_run_time;
this.VMs = VMs;
}
/// <summary>
/// Creates a new VMSS from a Proxy_VMSS.
/// </summary>
/// <param name="proxy"></param>
public VMSS(Proxy_VMSS proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VMSS update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
enabled = update.enabled;
type = update.type;
retained_snapshots = update.retained_snapshots;
frequency = update.frequency;
schedule = update.schedule;
last_run_time = update.last_run_time;
VMs = update.VMs;
}
internal void UpdateFromProxy(Proxy_VMSS proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
enabled = (bool)proxy.enabled;
type = proxy.type == null ? (vmss_type) 0 : (vmss_type)Helper.EnumParseDefault(typeof(vmss_type), (string)proxy.type);
retained_snapshots = proxy.retained_snapshots == null ? 0 : long.Parse((string)proxy.retained_snapshots);
frequency = proxy.frequency == null ? (vmss_frequency) 0 : (vmss_frequency)Helper.EnumParseDefault(typeof(vmss_frequency), (string)proxy.frequency);
schedule = proxy.schedule == null ? null : Maps.convert_from_proxy_string_string(proxy.schedule);
last_run_time = proxy.last_run_time;
VMs = proxy.VMs == null ? null : XenRef<VM>.Create(proxy.VMs);
}
public Proxy_VMSS ToProxy()
{
Proxy_VMSS result_ = new Proxy_VMSS();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.enabled = enabled;
result_.type = vmss_type_helper.ToString(type);
result_.retained_snapshots = retained_snapshots.ToString();
result_.frequency = vmss_frequency_helper.ToString(frequency);
result_.schedule = Maps.convert_to_proxy_string_string(schedule);
result_.last_run_time = last_run_time;
result_.VMs = (VMs != null) ? Helper.RefListToStringArray(VMs) : new string[] {};
return result_;
}
/// <summary>
/// Creates a new VMSS from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VMSS(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
enabled = Marshalling.ParseBool(table, "enabled");
type = (vmss_type)Helper.EnumParseDefault(typeof(vmss_type), Marshalling.ParseString(table, "type"));
retained_snapshots = Marshalling.ParseLong(table, "retained_snapshots");
frequency = (vmss_frequency)Helper.EnumParseDefault(typeof(vmss_frequency), Marshalling.ParseString(table, "frequency"));
schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "schedule"));
last_run_time = Marshalling.ParseDateTime(table, "last_run_time");
VMs = Marshalling.ParseSetRef<VM>(table, "VMs");
}
public bool DeepEquals(VMSS other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._enabled, other._enabled) &&
Helper.AreEqual2(this._type, other._type) &&
Helper.AreEqual2(this._retained_snapshots, other._retained_snapshots) &&
Helper.AreEqual2(this._frequency, other._frequency) &&
Helper.AreEqual2(this._schedule, other._schedule) &&
Helper.AreEqual2(this._last_run_time, other._last_run_time) &&
Helper.AreEqual2(this._VMs, other._VMs);
}
public override string SaveChanges(Session session, string opaqueRef, VMSS server)
{
if (opaqueRef == null)
{
Proxy_VMSS p = this.ToProxy();
return session.proxy.vmss_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
VMSS.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
VMSS.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_enabled, server._enabled))
{
VMSS.set_enabled(session, opaqueRef, _enabled);
}
if (!Helper.AreEqual2(_type, server._type))
{
VMSS.set_type(session, opaqueRef, _type);
}
if (!Helper.AreEqual2(_retained_snapshots, server._retained_snapshots))
{
VMSS.set_retained_snapshots(session, opaqueRef, _retained_snapshots);
}
if (!Helper.AreEqual2(_frequency, server._frequency))
{
VMSS.set_frequency(session, opaqueRef, _frequency);
}
if (!Helper.AreEqual2(_schedule, server._schedule))
{
VMSS.set_schedule(session, opaqueRef, _schedule);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static VMSS get_record(Session session, string _vmss)
{
return new VMSS((Proxy_VMSS)session.proxy.vmss_get_record(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get a reference to the VMSS instance with the specified UUID.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VMSS> get_by_uuid(Session session, string _uuid)
{
return XenRef<VMSS>.Create(session.proxy.vmss_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new VMSS instance, and return its handle.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VMSS> create(Session session, VMSS _record)
{
return XenRef<VMSS>.Create(session.proxy.vmss_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VMSS instance, and return its handle.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VMSS _record)
{
return XenRef<Task>.Create(session.proxy.async_vmss_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VMSS instance.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static void destroy(Session session, string _vmss)
{
session.proxy.vmss_destroy(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Destroy the specified VMSS instance.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static XenRef<Task> async_destroy(Session session, string _vmss)
{
return XenRef<Task>.Create(session.proxy.async_vmss_destroy(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get all the VMSS instances with the given label.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<VMSS>> get_by_name_label(Session session, string _label)
{
return XenRef<VMSS>.Create(session.proxy.vmss_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string get_uuid(Session session, string _vmss)
{
return (string)session.proxy.vmss_get_uuid(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the name/label field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string get_name_label(Session session, string _vmss)
{
return (string)session.proxy.vmss_get_name_label(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the name/description field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string get_name_description(Session session, string _vmss)
{
return (string)session.proxy.vmss_get_name_description(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the enabled field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static bool get_enabled(Session session, string _vmss)
{
return (bool)session.proxy.vmss_get_enabled(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the type field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static vmss_type get_type(Session session, string _vmss)
{
return (vmss_type)Helper.EnumParseDefault(typeof(vmss_type), (string)session.proxy.vmss_get_type(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the retained_snapshots field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static long get_retained_snapshots(Session session, string _vmss)
{
return long.Parse((string)session.proxy.vmss_get_retained_snapshots(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the frequency field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static vmss_frequency get_frequency(Session session, string _vmss)
{
return (vmss_frequency)Helper.EnumParseDefault(typeof(vmss_frequency), (string)session.proxy.vmss_get_frequency(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the schedule field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static Dictionary<string, string> get_schedule(Session session, string _vmss)
{
return Maps.convert_from_proxy_string_string(session.proxy.vmss_get_schedule(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the last_run_time field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static DateTime get_last_run_time(Session session, string _vmss)
{
return session.proxy.vmss_get_last_run_time(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the VMs field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static List<XenRef<VM>> get_VMs(Session session, string _vmss)
{
return XenRef<VM>.Create(session.proxy.vmss_get_vms(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Set the name/label field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _vmss, string _label)
{
session.proxy.vmss_set_name_label(session.uuid, (_vmss != null) ? _vmss : "", (_label != null) ? _label : "").parse();
}
/// <summary>
/// Set the name/description field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _vmss, string _description)
{
session.proxy.vmss_set_name_description(session.uuid, (_vmss != null) ? _vmss : "", (_description != null) ? _description : "").parse();
}
/// <summary>
/// Set the enabled field of the given VMSS.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_enabled">New value to set</param>
public static void set_enabled(Session session, string _vmss, bool _enabled)
{
session.proxy.vmss_set_enabled(session.uuid, (_vmss != null) ? _vmss : "", _enabled).parse();
}
/// <summary>
/// This call executes the snapshot schedule immediately
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string snapshot_now(Session session, string _vmss)
{
return (string)session.proxy.vmss_snapshot_now(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
///
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the value to set</param>
public static void set_retained_snapshots(Session session, string _vmss, long _value)
{
session.proxy.vmss_set_retained_snapshots(session.uuid, (_vmss != null) ? _vmss : "", _value.ToString()).parse();
}
/// <summary>
/// Set the value of the frequency field
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the snapshot schedule frequency</param>
public static void set_frequency(Session session, string _vmss, vmss_frequency _value)
{
session.proxy.vmss_set_frequency(session.uuid, (_vmss != null) ? _vmss : "", vmss_frequency_helper.ToString(_value)).parse();
}
/// <summary>
///
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the value to set</param>
public static void set_schedule(Session session, string _vmss, Dictionary<string, string> _value)
{
session.proxy.vmss_set_schedule(session.uuid, (_vmss != null) ? _vmss : "", Maps.convert_to_proxy_string_string(_value)).parse();
}
/// <summary>
///
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_key">the key to add</param>
/// <param name="_value">the value to add</param>
public static void add_to_schedule(Session session, string _vmss, string _key, string _value)
{
session.proxy.vmss_add_to_schedule(session.uuid, (_vmss != null) ? _vmss : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_key">the key to remove</param>
public static void remove_from_schedule(Session session, string _vmss, string _key)
{
session.proxy.vmss_remove_from_schedule(session.uuid, (_vmss != null) ? _vmss : "", (_key != null) ? _key : "").parse();
}
/// <summary>
///
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the value to set</param>
public static void set_last_run_time(Session session, string _vmss, DateTime _value)
{
session.proxy.vmss_set_last_run_time(session.uuid, (_vmss != null) ? _vmss : "", _value).parse();
}
/// <summary>
///
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the snapshot schedule type</param>
public static void set_type(Session session, string _vmss, vmss_type _value)
{
session.proxy.vmss_set_type(session.uuid, (_vmss != null) ? _vmss : "", vmss_type_helper.ToString(_value)).parse();
}
/// <summary>
/// Return a list of all the VMSSs known to the system.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VMSS>> get_all(Session session)
{
return XenRef<VMSS>.Create(session.proxy.vmss_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VMSS Records at once, in a single XML RPC call
/// First published in .
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VMSS>, VMSS> get_all_records(Session session)
{
return XenRef<VMSS>.Create<Proxy_VMSS>(session.proxy.vmss_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// enable or disable this snapshot schedule
/// </summary>
public virtual bool enabled
{
get { return _enabled; }
set
{
if (!Helper.AreEqual(value, _enabled))
{
_enabled = value;
Changed = true;
NotifyPropertyChanged("enabled");
}
}
}
private bool _enabled;
/// <summary>
/// type of the snapshot schedule
/// </summary>
public virtual vmss_type type
{
get { return _type; }
set
{
if (!Helper.AreEqual(value, _type))
{
_type = value;
Changed = true;
NotifyPropertyChanged("type");
}
}
}
private vmss_type _type;
/// <summary>
/// maximum number of snapshots that should be stored at any time
/// </summary>
public virtual long retained_snapshots
{
get { return _retained_snapshots; }
set
{
if (!Helper.AreEqual(value, _retained_snapshots))
{
_retained_snapshots = value;
Changed = true;
NotifyPropertyChanged("retained_snapshots");
}
}
}
private long _retained_snapshots;
/// <summary>
/// frequency of taking snapshot from snapshot schedule
/// </summary>
public virtual vmss_frequency frequency
{
get { return _frequency; }
set
{
if (!Helper.AreEqual(value, _frequency))
{
_frequency = value;
Changed = true;
NotifyPropertyChanged("frequency");
}
}
}
private vmss_frequency _frequency;
/// <summary>
/// schedule of the snapshot containing 'hour', 'min', 'days'. Date/time-related information is in Local Timezone
/// </summary>
public virtual Dictionary<string, string> schedule
{
get { return _schedule; }
set
{
if (!Helper.AreEqual(value, _schedule))
{
_schedule = value;
Changed = true;
NotifyPropertyChanged("schedule");
}
}
}
private Dictionary<string, string> _schedule;
/// <summary>
/// time of the last snapshot
/// </summary>
public virtual DateTime last_run_time
{
get { return _last_run_time; }
set
{
if (!Helper.AreEqual(value, _last_run_time))
{
_last_run_time = value;
Changed = true;
NotifyPropertyChanged("last_run_time");
}
}
}
private DateTime _last_run_time;
/// <summary>
/// all VMs attached to this snapshot schedule
/// </summary>
public virtual List<XenRef<VM>> VMs
{
get { return _VMs; }
set
{
if (!Helper.AreEqual(value, _VMs))
{
_VMs = value;
Changed = true;
NotifyPropertyChanged("VMs");
}
}
}
private List<XenRef<VM>> _VMs;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace InControl.iOS.Xcode
{
class PropertyCommentChecker
{
private int m_Level;
private bool m_All;
private List<List<string>> m_Props;
/* The argument is an array of matcher strings each of which determine
whether a property with a certain path needs to be decorated with a
comment.
A path is a number of path elements concatenated by '/'. The last path
element is either:
the key if we're referring to a dict key
the value if we're referring to a value in an array
the value if we're referring to a value in a dict
All other path elements are either:
the key if the container is dict
'*' if the container is array
Path matcher has the same structure as a path, except that any of the
elements may be '*'. Matcher matches a path if both have the same number
of elements and for each pair matcher element is the same as path element
or is '*'.
a/b/c matches a/b/c but not a/b nor a/b/c/d
a/* /c matches a/d/c but not a/b nor a/b/c/d
* /* /* matches any path from three elements
*/
protected PropertyCommentChecker( int level, List<List<string>> props )
{
m_Level = level;
m_All = false;
m_Props = props;
}
public PropertyCommentChecker()
{
m_Level = 0;
m_All = false;
m_Props = new List<List<string>>();
}
public PropertyCommentChecker( IEnumerable<string> props )
{
m_Level = 0;
m_All = false;
m_Props = new List<List<string>>();
foreach (var prop in props)
{
m_Props.Add( new List<string>( prop.Split( '/' ) ) );
}
}
bool CheckContained( string prop )
{
if (m_All)
return true;
foreach (var list in m_Props)
{
if (list.Count == m_Level + 1)
{
if (list[m_Level] == prop)
return true;
if (list[m_Level] == "*")
{
m_All = true; // short-circuit all at this level
return true;
}
}
}
return false;
}
public bool CheckStringValueInArray( string value )
{
return CheckContained( value );
}
public bool CheckKeyInDict( string key )
{
return CheckContained( key );
}
public bool CheckStringValueInDict( string key, string value )
{
foreach (var list in m_Props)
{
if (list.Count == m_Level + 2)
{
if ((list[m_Level] == "*" || list[m_Level] == key) &&
list[m_Level + 1] == "*" || list[m_Level + 1] == value)
return true;
}
}
return false;
}
public PropertyCommentChecker NextLevel( string prop )
{
var newList = new List<List<string>>();
foreach (var list in m_Props)
{
if (list.Count <= m_Level + 1)
continue;
if (list[m_Level] == "*" || list[m_Level] == prop)
newList.Add( list );
}
return new PropertyCommentChecker( m_Level + 1, newList );
}
}
class Serializer
{
public static PBXElementDict ParseTreeAST( TreeAST ast, TokenList tokens, string text )
{
var el = new PBXElementDict();
foreach (var kv in ast.values)
{
PBXElementString key = ParseIdentifierAST( kv.key, tokens, text );
PBXElement value = ParseValueAST( kv.value, tokens, text );
el[key.value] = value;
}
return el;
}
public static PBXElementArray ParseArrayAST( ArrayAST ast, TokenList tokens, string text )
{
var el = new PBXElementArray();
foreach (var v in ast.values)
{
el.values.Add( ParseValueAST( v, tokens, text ) );
}
return el;
}
public static PBXElement ParseValueAST( ValueAST ast, TokenList tokens, string text )
{
if (ast is TreeAST)
return ParseTreeAST( (TreeAST) ast, tokens, text );
if (ast is ArrayAST)
return ParseArrayAST( (ArrayAST) ast, tokens, text );
if (ast is IdentifierAST)
return ParseIdentifierAST( (IdentifierAST) ast, tokens, text );
return null;
}
public static PBXElementString ParseIdentifierAST( IdentifierAST ast, TokenList tokens, string text )
{
Token tok = tokens[ast.value];
string value;
switch (tok.type)
{
case TokenType.String:
value = text.Substring( tok.begin, tok.end - tok.begin );
return new PBXElementString( value );
case TokenType.QuotedString:
value = text.Substring( tok.begin, tok.end - tok.begin );
value = PBXStream.UnquoteString( value );
return new PBXElementString( value );
default:
throw new Exception( "Internal parser error" );
}
}
static string k_Indent = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
static string GetIndent( int indent )
{
return k_Indent.Substring( 0, indent );
}
static void WriteStringImpl( StringBuilder sb, string s, bool comment, GUIDToCommentMap comments )
{
if (comment)
comments.WriteStringBuilder( sb, s );
else
sb.Append( PBXStream.QuoteStringIfNeeded( s ) );
}
public static void WriteDictKeyValue( StringBuilder sb, string key, PBXElement value, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments )
{
if (!compact)
{
sb.Append( "\n" );
sb.Append( GetIndent( indent ) );
}
WriteStringImpl( sb, key, checker.CheckKeyInDict( key ), comments );
sb.Append( " = " );
if (value is PBXElementString)
WriteStringImpl( sb, value.AsString(), checker.CheckStringValueInDict( key, value.AsString() ), comments );
else
if (value is PBXElementDict)
WriteDict( sb, value.AsDict(), indent, compact, checker.NextLevel( key ), comments );
else
if (value is PBXElementArray)
WriteArray( sb, value.AsArray(), indent, compact, checker.NextLevel( key ), comments );
sb.Append( ";" );
if (compact)
sb.Append( " " );
}
public static void WriteDict( StringBuilder sb, PBXElementDict el, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments )
{
sb.Append( "{" );
if (el.Contains( "isa" ))
WriteDictKeyValue( sb, "isa", el["isa"], indent + 1, compact, checker, comments );
var keys = new List<string>( el.values.Keys );
keys.Sort( StringComparer.Ordinal );
foreach (var key in keys)
{
if (key != "isa")
WriteDictKeyValue( sb, key, el[key], indent + 1, compact, checker, comments );
}
if (!compact)
{
sb.Append( "\n" );
sb.Append( GetIndent( indent ) );
}
sb.Append( "}" );
}
public static void WriteArray( StringBuilder sb, PBXElementArray el, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments )
{
sb.Append( "(" );
foreach (var value in el.values)
{
if (!compact)
{
sb.Append( "\n" );
sb.Append( GetIndent( indent + 1 ) );
}
if (value is PBXElementString)
WriteStringImpl( sb, value.AsString(), checker.CheckStringValueInArray( value.AsString() ), comments );
else
if (value is PBXElementDict)
WriteDict( sb, value.AsDict(), indent + 1, compact, checker.NextLevel( "*" ), comments );
else
if (value is PBXElementArray)
WriteArray( sb, value.AsArray(), indent + 1, compact, checker.NextLevel( "*" ), comments );
sb.Append( "," );
if (compact)
sb.Append( " " );
}
if (!compact)
{
sb.Append( "\n" );
sb.Append( GetIndent( indent ) );
}
sb.Append( ")" );
}
}
}
// namespace UnityEditor.iOS.Xcode
| |
// 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.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.SqlServer.Server
{
// SmiMetaDataProperty defines an extended, optional property to be used on the SmiMetaData class
// This approach to adding properties is added combat the growing number of sparsely-used properties
// that are specially handled on the base classes
internal enum SmiPropertySelector
{
DefaultFields = 0x0,
SortOrder = 0x1,
UniqueKey = 0x2,
}
// Simple collection for properties. Could extend to IDictionary support if needed in future.
internal class SmiMetaDataPropertyCollection
{
private const int SelectorCount = 3; // number of elements in SmiPropertySelector
private SmiMetaDataProperty[] _properties;
private bool _isReadOnly;
internal static readonly SmiMetaDataPropertyCollection EmptyInstance;
// Singleton empty instances to ensure each property is always non-null
private static readonly SmiDefaultFieldsProperty s_emptyDefaultFields = new SmiDefaultFieldsProperty(new List<bool>());
private static readonly SmiOrderProperty s_emptySortOrder = new SmiOrderProperty(new List<SmiOrderProperty.SmiColumnOrder>());
private static readonly SmiUniqueKeyProperty s_emptyUniqueKey = new SmiUniqueKeyProperty(new List<bool>());
static SmiMetaDataPropertyCollection()
{
EmptyInstance = new SmiMetaDataPropertyCollection();
EmptyInstance.SetReadOnly();
}
internal SmiMetaDataPropertyCollection()
{
_properties = new SmiMetaDataProperty[SelectorCount];
_isReadOnly = false;
_properties[(int)SmiPropertySelector.DefaultFields] = s_emptyDefaultFields;
_properties[(int)SmiPropertySelector.SortOrder] = s_emptySortOrder;
_properties[(int)SmiPropertySelector.UniqueKey] = s_emptyUniqueKey;
}
internal SmiMetaDataProperty this[SmiPropertySelector key]
{
get
{
return _properties[(int)key];
}
set
{
if (null == value)
{
throw ADP.InternalError(ADP.InternalErrorCode.InvalidSmiCall);
}
EnsureWritable();
_properties[(int)key] = value;
}
}
internal bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
// Allow switching to read only, but not back.
internal void SetReadOnly()
{
_isReadOnly = true;
}
private void EnsureWritable()
{
if (IsReadOnly)
{
throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
}
}
}
// Base class for properties
internal abstract class SmiMetaDataProperty
{
}
// Property defining a list of column ordinals that define a unique key
internal class SmiUniqueKeyProperty : SmiMetaDataProperty
{
private IList<bool> _columns;
internal SmiUniqueKeyProperty(IList<bool> columnIsKey)
{
_columns = new System.Collections.ObjectModel.ReadOnlyCollection<bool>(columnIsKey);
}
// indexed by column ordinal indicating for each column whether it is key or not
internal bool this[int ordinal]
{
get
{
if (_columns.Count <= ordinal)
{
return false;
}
else
{
return _columns[ordinal];
}
}
}
[Conditional("DEBUG")]
internal void CheckCount(int countToMatch)
{
Debug.Assert(0 == _columns.Count || countToMatch == _columns.Count,
"SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _columns.Count +
") not equal to checked size (" + countToMatch + ")");
}
}
// Property defining a sort order for a set of columns (by ordinal and ASC/DESC).
internal class SmiOrderProperty : SmiMetaDataProperty
{
internal struct SmiColumnOrder
{
internal int SortOrdinal;
internal SortOrder Order;
}
private IList<SmiColumnOrder> _columns;
internal SmiOrderProperty(IList<SmiColumnOrder> columnOrders)
{
_columns = new System.Collections.ObjectModel.ReadOnlyCollection<SmiColumnOrder>(columnOrders);
}
// Readonly list of the columnorder instances making up the sort order
// order in list indicates precedence
internal SmiColumnOrder this[int ordinal]
{
get
{
if (_columns.Count <= ordinal)
{
SmiColumnOrder order = new SmiColumnOrder();
order.Order = SortOrder.Unspecified;
order.SortOrdinal = -1;
return order;
}
else
{
return _columns[ordinal];
}
}
}
[Conditional("DEBUG")]
internal void CheckCount(int countToMatch)
{
Debug.Assert(0 == _columns.Count || countToMatch == _columns.Count,
"SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _columns.Count +
") not equal to checked size (" + countToMatch + ")");
}
}
// property defining inheritance relationship(s)
internal class SmiDefaultFieldsProperty : SmiMetaDataProperty
{
#region private fields
private IList<bool> _defaults;
#endregion
#region internal interface
internal SmiDefaultFieldsProperty(IList<bool> defaultFields)
{
_defaults = new System.Collections.ObjectModel.ReadOnlyCollection<bool>(defaultFields);
}
internal bool this[int ordinal]
{
get
{
if (_defaults.Count <= ordinal)
{
return false;
}
else
{
return _defaults[ordinal];
}
}
}
[Conditional("DEBUG")]
internal void CheckCount(int countToMatch)
{
Debug.Assert(0 == _defaults.Count || countToMatch == _defaults.Count,
"SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _defaults.Count +
") not equal to checked size (" + countToMatch + ")");
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators.Postgres;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit.Generators.Postgres
{
[TestFixture]
public class PostgresGeneratorTests
{
protected PostgresGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new PostgresGenerator();
}
[Test]
public void CanCreateTableWithDateTimeOffsetColumn()
{
var tableName = "TestTable1";
var expression = new CreateTableExpression { TableName = tableName };
expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn1", Type = DbType.DateTimeOffset });
expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn2", Type = DbType.DateTime2 });
expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn3", Type = DbType.Date });
expression.Columns.Add(new ColumnDefinition { TableName = tableName, Name = "TestColumn4", Type = DbType.Time });
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("CREATE TABLE \"public\".\"{0}\" (\"TestColumn1\" timestamptz NOT NULL, \"TestColumn2\" timestamp NOT NULL, \"TestColumn3\" date NOT NULL, \"TestColumn4\" time NOT NULL)", tableName));
}
[Test]
public void CanCreateAutoIncrementColumnForInt64()
{
var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression();
expression.Columns[0].Type = DbType.Int64;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" bigserial NOT NULL, \"TestColumn2\" integer NOT NULL)");
}
[Test]
public void CanCreateTableWithBinaryColumnWithSize()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].Type = DbType.Binary;
expression.Columns[0].Size = 10000;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" bytea NOT NULL, \"TestColumn2\" integer NOT NULL)"); // PostgreSQL does not actually use the configured size
}
[Test]
public void CanCreateTableWithBoolDefaultValue()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].DefaultValue = true;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" text NOT NULL DEFAULT true, \"TestColumn2\" integer NOT NULL)");
}
[Test]
public void CanUseSystemMethodCurrentUserAsADefaultValueForAColumn()
{
const string tableName = "NewTable";
var columnDefinition = new ColumnDefinition { Name = "NewColumn", Size = 15, Type = DbType.String, DefaultValue = SystemMethods.CurrentUser };
var expression = new CreateColumnExpression { Column = columnDefinition, TableName = tableName };
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" varchar(15) NOT NULL DEFAULT current_user");
}
[Test]
public void CanUseSystemMethodCurrentUTCDateTimeAsADefaultValueForAColumn()
{
const string tableName = "NewTable";
var columnDefinition = new ColumnDefinition { Name = "NewColumn", Size = 5, Type = DbType.String, DefaultValue = SystemMethods.CurrentUTCDateTime };
var expression = new CreateColumnExpression { Column = columnDefinition, TableName = tableName };
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" varchar(5) NOT NULL DEFAULT (now() at time zone 'UTC')");
}
[Test]
public void ExplicitUnicodeStringIgnoredForNonSqlServer()
{
var expression = new InsertDataExpression {TableName = "TestTable"};
expression.Rows.Add(new InsertionDataDefinition
{
new KeyValuePair<string, object>("NormalString", "Just'in"),
new KeyValuePair<string, object>("UnicodeString", new ExplicitUnicodeString("codethinked'.com"))
});
var result = Generator.Generate(expression);
result.ShouldBe("INSERT INTO \"public\".\"TestTable\" (\"NormalString\",\"UnicodeString\") VALUES ('Just''in','codethinked''.com');");
}
[Test]
public void CanAlterColumnAndSetAsNullable()
{
var expression = new AlterColumnExpression
{
Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = true },
SchemaName = "TestSchema",
TableName = "TestTable1"
};
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text, ALTER \"TestColumn1\" DROP NOT NULL");
}
[Test]
public void CanAlterColumnAndSetAsNotNullable()
{
var expression = new AlterColumnExpression
{
Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = false },
SchemaName = "TestSchema",
TableName = "TestTable1"
};
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text, ALTER \"TestColumn1\" SET NOT NULL");
}
[Test]
public void CanAlterDefaultConstraintToNewGuid()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.NewGuid;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT uuid_generate_v4()");
}
[Test]
public void CanDeleteDefaultConstraint()
{
var expression = new DeleteDefaultConstraintExpression
{
ColumnName = "TestColumn1",
SchemaName = "TestSchema",
TableName = "TestTable1"
};
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT");
}
[Test]
public void CanAlterDefaultConstraintToCurrentUser()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.CurrentUser;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT current_user");
}
[Test]
public void CanAlterDefaultConstraintToCurrentDate()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.CurrentDateTime;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT now()");
}
[Test]
public void CanAlterDefaultConstraintToCurrentUtcDateTime()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.CurrentUTCDateTime;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT (now() at time zone 'UTC')");
}
[Test]
public void CanAlterColumnAndOnlySetTypeIfIsNullableNotSet()
{
var expression = new AlterColumnExpression
{
Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = null },
SchemaName = "TestSchema",
TableName = "TestTable1"
};
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text");
}
}
}
| |
/*
Copyright (c) 2010 by Genstein
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
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.Text;
using System.IO;
using System.Diagnostics;
namespace Trizbort.Export
{
class Inform6Exporter : CodeExporter
{
const char SingleQuote = '\'';
const char DoubleQuote = '"';
public override string FileDialogTitle
{
get { return "Export Inform 6 Source Code"; }
}
public override List<KeyValuePair<string, string>> FileDialogFilters
{
get
{
return new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Inform 6 Source Files", ".inf"),
new KeyValuePair<string, string>("Text Files", ".txt"),
};
}
}
protected override IEnumerable<string> ReservedWords
{
get { return new string[] { "Constant", "Story", "Headline", "Include", "Object", "with", "has", "hasnt", "not", "and", "or", "n_to", "s_to", "e_to", "w_to", "nw_to", "ne_to", "sw_to", "se_to", "u_to", "d_to", "in_to", "out_to", "before", "after", "if", "else", "print", "player", "location", "description" }; }
}
protected override Encoding Encoding
{
get { return Encoding.ASCII; }
}
protected override void ExportHeader(StreamWriter writer, string title, string author, string description)
{
writer.WriteLine("Constant Story {0};", ToI6String(title, DoubleQuote));
writer.WriteLine("Constant Headline {0};", ToI6String(string.Format("^By {0}^{1}^^", author, description), DoubleQuote));
writer.WriteLine();
writer.WriteLine("Include \"Parser\";");
writer.WriteLine("Include \"VerbLib\";");
writer.WriteLine();
}
protected override void ExportContent(StreamWriter writer)
{
foreach (var location in LocationsInExportOrder)
{
writer.WriteLine("Object {0} {1}", location.ExportName, ToI6String(location.Room.Name, DoubleQuote));
writer.WriteLine(" with description");
writer.WriteLine(" {0},", ToI6String(location.Room.PrimaryDescription, DoubleQuote));
foreach (var direction in AllDirections)
{
var exit = location.GetBestExit(direction);
if (exit != null)
{
writer.WriteLine(" {0} {1},", ToI6PropertyName(direction), exit.Target.ExportName);
}
}
writer.WriteLine(" has {0}light;", location.Room.IsDark ? "~" : string.Empty);
writer.WriteLine();
ExportThings(writer, location.Things, null, 1);
}
writer.WriteLine("[ Initialise;");
if (LocationsInExportOrder.Count > 0)
{
writer.WriteLine(" location = {0};", LocationsInExportOrder[0].ExportName);
}
else
{
writer.WriteLine(" ! location = ...;");
}
writer.WriteLine(" ! \"^^Your opening paragraph here...^^\";");
writer.WriteLine("];");
writer.WriteLine();
writer.WriteLine("Include \"Grammar\";");
writer.WriteLine();
}
private void ExportThings(StreamWriter writer, List<Thing> things, Thing container, int indent)
{
foreach (var thing in things)
{
if (thing.Container != container)
{
// match only the container we're given, or lack thereof
continue;
}
writer.WriteLine("Object {0} {1} {2}", Repeat("-> ", indent), thing.ExportName, ToI6String(StripOddCharacters(thing.DisplayName, ' ', '-').Trim(), DoubleQuote));
writer.Write(" with name {0}", ToI6Words(StripOddCharacters(thing.DisplayName, ' ', '-')));
if (thing.Contents.Count > 0)
{
writer.WriteLine(",");
writer.WriteLine(" has open container;");
}
else
{
writer.WriteLine(";");
}
writer.WriteLine();
ExportThings(writer, thing.Contents, thing, indent + 1);
}
}
private static string ToI6Words(string text)
{
var words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0)
{
return ToI6String("thing", SingleQuote);
}
string output = string.Empty;
foreach (var word in words)
{
if (output.Length > 0)
{
output += ' ';
}
output += ToI6String(word, SingleQuote);
}
return output;
}
private static string Repeat(string s, int times)
{
var text = string.Empty;
for (var index = 0; index < times; ++index)
{
text += s;
}
return text;
}
private static string ToI6String(string text, char quote)
{
if (text == null)
{
text = string.Empty;
}
return string.Format("{1}{0}{1}", text.Replace('\"', '~').Replace("\r", string.Empty).Replace('\n', '^'), quote);
}
private static string ToI6PropertyName(AutomapDirection direction)
{
switch (direction)
{
case AutomapDirection.North:
return "n_to";
case AutomapDirection.South:
return "s_to";
case AutomapDirection.East:
return "e_to";
case AutomapDirection.West:
return "w_to";
case AutomapDirection.NorthEast:
return "ne_to";
case AutomapDirection.NorthWest:
return "nw_to";
case AutomapDirection.SouthEast:
return "se_to";
case AutomapDirection.SouthWest:
return "sw_to";
case AutomapDirection.Up:
return "u_to";
case AutomapDirection.Down:
return "d_to";
case AutomapDirection.In:
return "in_to";
case AutomapDirection.Out:
return "out_to";
default:
Debug.Assert(false, "Unrecognised automap direction.");
return "north";
}
}
protected override string GetExportName(Room room, int? suffix)
{
var name = StripOddCharacters(room.Name);
if (string.IsNullOrEmpty(name))
{
name = "room";
}
if (suffix != null)
{
name = string.Format("{0}{1}", name, suffix);
}
return name;
}
protected override string GetExportNameForObject(string displayName, int? suffix)
{
var name = StripOddCharacters(displayName);
if (string.IsNullOrEmpty(name))
{
name = "item";
}
if (suffix != null)
{
name = string.Format("{0}{1}", name, suffix);
}
return name;
}
private static string StripOddCharacters(string text, params char[] exclude)
{
var exclusions = new List<char>(exclude);
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
var result = string.Empty;
foreach (var c in text)
{
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || exclusions.Contains(c))
{
result += c;
}
}
return result;
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
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 Kodestruct.Common.Mathematics;
using Kodestruct.Common.Section.Interfaces;
namespace Kodestruct.Common.Section.SectionTypes
{
/// <summary>
/// Generic channel shape with geometric parameters provided in a constructor.
/// The corners are assumed to be sharp 90-degree corners, as would be typical
/// for a shape built-up from plates.
/// </summary>
public class SectionChannel : CompoundShape, ISectionChannel
{
public SectionChannel(string Name, double d, double b_f,
double t_f, double t_w)
: base(Name)
{
this._d = d;
this._b_f = b_f;
this._t_f = t_f;
this._t_w = t_w;
IsWeakAxis = false;
AreFlangeTipsDown = false;
}
public SectionChannel(string Name, double d, double b_f,
double t_f, double t_w, bool IsWeakAxis, bool AreFlangeTipsDown)
: base(Name)
{
this._d = d;
this._b_f = b_f;
this._t_f = t_f;
this._t_w = t_w;
this.IsWeakAxis = IsWeakAxis;
this.AreFlangeTipsDown = AreFlangeTipsDown;
}
public bool IsWeakAxis { get; set; }
public bool AreFlangeTipsDown { get; set; }
#region Section properties specific to channel
private double _d;
public double d
{
get { return _d; }
}
private double _h_o;
public double h_o
{
get
{
_h_o = d - t_f / 2.0 - t_f / 2.0;
return _h_o;
}
}
private double _b_f;
public double b_f
{
get { return _b_f; }
}
private double _t_f;
public double t_f
{
get { return _t_f; }
}
private double _t_w;
public double t_w
{
get { return _t_w; }
}
private double flangeClearDistance;
public double FlangeClearDistance
{
get
{
flangeClearDistance = d - 2*t_f;
return flangeClearDistance;
}
}
private double _k;
public double k
{
get { return _k; }
set { _k = value; }
}
#endregion
/// <summary>
/// Defines a set of rectangles for analysis with respect to
/// x-axis, each occupying full width of section.
/// </summary>
/// <returns>List of analysis rectangles</returns>
public override List<CompoundShapePart> GetCompoundRectangleXAxisList()
{
if (IsWeakAxis == false)
{
return getXList();
}
else
{
return getYList();
}
}
private List<CompoundShapePart> getXList()
{
List<CompoundShapePart> rectX = new List<CompoundShapePart>()
{
new CompoundShapePart(b_f,t_f, new Point2D(0,d/2.0-t_f/2.0)),
new CompoundShapePart(t_w,d-2*t_f, new Point2D(0,0)),
new CompoundShapePart(b_f,t_f, new Point2D(0,-(d/2.0-t_f/2.0)))
};
return rectX;
}
/// <summary>
/// Defines a set of rectangles for analysis with respect to
/// y-axis, each occupying full height of section. The rectangles are rotated 90 deg.,
/// because internally the properties are calculated with respect to x-axis.
/// </summary>
/// <returns>List of analysis rectangles</returns>
public override List<CompoundShapePart> GetCompoundRectangleYAxisList()
{
List<CompoundShapePart> Ylist;
if (IsWeakAxis == false)
{
Ylist= getYList();
}
else
{
Ylist = getXList();
}
return Ylist;
}
private List<CompoundShapePart> getYList()
{
//Converted to TEE
//Insertion point measured from top
List<CompoundShapePart> rectY;
if (AreFlangeTipsDown == true)
{
rectY = new List<CompoundShapePart>()
{
new CompoundShapePart(d, t_w, new Point2D(0, -t_w/2.0)),
new CompoundShapePart(2*t_f,b_f-t_w, new Point2D(0, -(t_w+(b_f -t_w)/2.0))),
};
}
else
{
rectY = new List<CompoundShapePart>()
{
new CompoundShapePart(2*t_f,b_f-t_w, new Point2D(0, (t_w+(b_f -t_w)/2.0))),
new CompoundShapePart(d, t_w, new Point2D(0,(b_f -t_w)+t_w/2.0)),
};
}
return rectY;
}
protected override void CalculateWarpingConstant()
{
////AISC Design Guide 09 3.20
double h = d - t_f;
////AISC Design Guide 09 3.21
double b_prime = b_f - ((t_w) / (2.0));
////AISC Design Guide 09 3.19
double E_o = ((t_f * Math.Pow(b_prime, 2)) / (2.0 * b_prime * t_f + ((h * t_w) / (3.0))));
////AISC Design Guide 09 3.18
_C_w = ((Math.Pow(h, 2) * Math.Pow(b_prime, 2) * t_f * (b_prime - 3.0 * E_o)) / (6.0)) + Math.Pow(E_o, 2) * I_x;
}
}
}
| |
//from http://www.codeproject.com/cs/internet/SendFileToNET.asp
using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections.Generic;
namespace SIL.Email
{
class MAPI
{
public bool AddRecipientTo(string email)
{
return AddRecipient(email, HowTo.MAPI_TO);
}
public bool AddRecipientCc(string email)
{
return AddRecipient(email, HowTo.MAPI_CC);
}
public bool AddRecipientBcc(string email)
{
return AddRecipient(email, HowTo.MAPI_BCC);
}
public void AddAttachment(string strAttachmentFileName)
{
m_attachments.Add(strAttachmentFileName);
}
public bool SendMailPopup(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI | MAPI_DIALOG);
}
public bool SendMailDirect(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI);
}
[DllImport("MAPI32.DLL")]
static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
/// <summary>
///
/// </summary>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="how"></param>
/// <returns>true if successful</returns>
bool SendMail(string strSubject, string strBody, int how)
{
MapiMessage msg = new MapiMessage();
msg.subject = strSubject;
msg.noteText = strBody;
msg.recips = GetRecipients(out msg.recipCount);
msg.files = GetAttachments(out msg.fileCount);
m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how, 0);
// if (m_lastError > 1)
// MessageBox.Show("MAPISendMail failed! " + GetLastError(), "MAPISendMail");
//todo if(m_lastError==25)
//bad recipient
var success = m_lastError == 0; // m_lastError gets reset by Cleanup()
Cleanup(ref msg);
return success;//NB: doesn't seem to cach user "denial" using outlook's warning dialog
}
bool AddRecipient(string email, HowTo howTo)
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.recipClass = (int)howTo;
recipient.name = email;
// Note: For Outlook Express it would be better to also set recipient.address so that it
// shows the email address in the confirmation dialog, but this messes up things in
// Outlook and Windows Mail.
m_recipients.Add(recipient);
return true;
}
IntPtr GetRecipients(out int recipCount)
{
recipCount = 0;
if (m_recipients.Count == 0)
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count * size);
IntPtr ptr = intPtr;
foreach (MapiRecipDesc mapiDesc in m_recipients)
{
Marshal.StructureToPtr(mapiDesc, (IntPtr)ptr, false);
ptr += size;
}
recipCount = m_recipients.Count;
return intPtr;
}
IntPtr GetAttachments(out int fileCount)
{
fileCount = 0;
if (m_attachments == null)
return IntPtr.Zero;
if ((m_attachments.Count <= 0) || (m_attachments.Count > maxAttachments))
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiFileDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_attachments.Count * size);
MapiFileDesc mapiFileDesc = new MapiFileDesc();
mapiFileDesc.position = -1;
int ptr = (int)intPtr;
foreach (string strAttachment in m_attachments)
{
mapiFileDesc.name = Path.GetFileName(strAttachment);
mapiFileDesc.path = strAttachment;
Marshal.StructureToPtr(mapiFileDesc, (IntPtr)ptr, false);
ptr += size;
}
fileCount = m_attachments.Count;
return intPtr;
}
void Cleanup(ref MapiMessage msg)
{
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
IntPtr ptr;
if (msg.recips != IntPtr.Zero)
{
ptr = msg.recips;
for (int i = 0; i < msg.recipCount; i++)
{
Marshal.DestroyStructure(ptr, typeof(MapiRecipDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.recips);
}
if (msg.files != IntPtr.Zero)
{
size = Marshal.SizeOf(typeof(MapiFileDesc));
ptr = msg.files;
for (int i = 0; i < msg.fileCount; i++)
{
Marshal.DestroyStructure(ptr, typeof(MapiFileDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.files);
}
m_recipients.Clear();
m_attachments.Clear();
m_lastError = 0;
}
public string GetLastError()
{
if (m_lastError >= 0 && m_lastError <= 26)
return Errors[m_lastError];
return "MAPI error [" + m_lastError + "]";
}
readonly string[] Errors = new[]
{
"OK [0]", "User abort [1]", "General MAPI failure [2]", "MAPI login failure [3]",
"Disk full [4]", "Insufficient memory [5]", "Access denied [6]", "-unknown- [7]",
"Too many sessions [8]", "Too many files were specified [9]", "Too many recipients were specified [10]", "A specified attachment was not found [11]",
"Attachment open failure [12]", "Attachment write failure [13]", "Unknown recipient [14]", "Bad recipient type [15]",
"No messages [16]", "Invalid message [17]", "Text too large [18]", "Invalid session [19]",
"Type not supported [20]", "A recipient was specified ambiguously [21]", "Message in use [22]", "Network failure [23]",
"Invalid edit fields [24]", "Invalid recipients [25]", "Not supported [26]"
};
readonly List<MapiRecipDesc> m_recipients = new List<MapiRecipDesc>();
readonly List<string> m_attachments = new List<string>();
int m_lastError;
const int MAPI_LOGON_UI = 0x00000001;
const int MAPI_DIALOG = 0x00000008;
const int maxAttachments = 20;
enum HowTo
{
MAPI_ORIG,
MAPI_TO,
MAPI_CC,
MAPI_BCC
};
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiMessage
{
public int reserved;
public string subject;
public string noteText;
public string messageType;
public string dateReceived;
public string conversationID;
public int flags;
public IntPtr originator;
public int recipCount;
public IntPtr recips;
public int fileCount;
public IntPtr files;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileDesc
{
public int reserved;
public int flags;
public int position;
public string path;
public string name;
public IntPtr type;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiRecipDesc
{
public int reserved;
public int recipClass;
public string name;
public string address;
public int eIDSize;
public IntPtr entryID;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.TypeNamesShouldNotMatchNamespacesAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpTypeNamesShouldNotMatchNamespacesFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.TypeNamesShouldNotMatchNamespacesAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicTypeNamesShouldNotMatchNamespacesFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class TypeNamesShouldNotMatchNamespacesTests
{
private static DiagnosticResult CSharpDefaultResultAt(int line, int column, string typeName, string namespaceName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.DefaultRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName, namespaceName);
private static DiagnosticResult CSharpSystemResultAt(int line, int column, string typeName, string namespaceName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.SystemRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName, namespaceName);
private static DiagnosticResult BasicDefaultResultAt(int line, int column, string typeName, string namespaceName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.DefaultRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName, namespaceName);
private static DiagnosticResult BasicSystemResultAt(int line, int column, string typeName, string namespaceName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(TypeNamesShouldNotMatchNamespacesAnalyzer.SystemRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName, namespaceName);
[Fact]
public async Task CA1724CSharpValidNameAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C
{
}");
}
[Fact]
public async Task CA1724CSharpInvalidNameMatchingFormsNamespaceInSystemRuleAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Forms
{
}",
CSharpSystemResultAt(2, 14, "Forms", "System.Windows.Forms"));
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CA1724CSharpInvalidNameMatchingFormsNamespaceInSystemRule_Internal_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal class Forms
{
}
public class Outer
{
private class Forms
{
}
}
internal class Outer2
{
public class Forms
{
}
}
");
}
[Fact]
public async Task CA1724CSharpInvalidNameMatchingSdkNamespaceInDefaultRuleAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{ @"
public class Sdk
{
}
",
},
AdditionalReferences = { MetadataReference.CreateFromFile(typeof(Xunit.Sdk.AllException).Assembly.Location) }
},
ExpectedDiagnostics =
{
CSharpDefaultResultAt(2, 14, "Sdk", "Xunit.Sdk"),
}
}.RunAsync();
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_NoDiagnostic_NamespaceWithNoTypesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace A.B
{
}
namespace D
{
public class A {}
}");
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_NoDiagnostic_NamespaceWithNoExternallyVisibleTypesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace A
{
internal class C { }
}
namespace D
{
public class A {}
}");
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_NoDiagnostic_NamespaceWithNoExternallyVisibleTypes_02Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace A
{
namespace B
{
internal class C { }
}
}
namespace D
{
public class A {}
}");
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_NoDiagnostic_ClashingTypeIsNotExternallyVisibleAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace A
{
namespace B
{
public class C { }
}
}
namespace D
{
internal class A {}
}");
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMemberAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace A
{
public class C { }
}
namespace D
{
public class A {}
}",
// Test0.cs(9,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'A'. Change either name to eliminate the conflict.
CSharpDefaultResultAt(9, 18, "A", "A"));
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMember_02Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace B
{
namespace A
{
public class C { }
}
}
namespace D
{
public class A {}
}",
// Test0.cs(12,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'B.A'. Change either name to eliminate the conflict.
CSharpDefaultResultAt(12, 18, "A", "B.A"));
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMember_InChildNamespaceAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace A
{
namespace B
{
public class C { }
}
}
namespace D
{
public class A {}
}",
// Test0.cs(12,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'A'. Change either name to eliminate the conflict.
CSharpDefaultResultAt(12, 18, "A", "A"));
}
[Fact, WorkItem(1673, "https://github.com/dotnet/roslyn-analyzers/issues/1673")]
public async Task CA1724CSharp_Diagnostic_NamespaceWithExternallyVisibleTypeMember_InChildNamespace_02Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace A.B
{
public class C { }
}
namespace D
{
public class A {}
}",
// Test0.cs(9,18): warning CA1724: The type name A conflicts in whole or in part with the namespace name 'A'. Change either name to eliminate the conflict.
CSharpDefaultResultAt(9, 18, "A", "A"));
}
[Fact]
public async Task CA1724VisualBasicValidNameAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class C
End Class");
}
[Fact]
public async Task CA1724VisualBasicInvalidNameMatchingFormsNamespaceInSystemRuleAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Forms
End Class",
BasicSystemResultAt(2, 14, "Forms", "System.Windows.Forms"));
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CA1724VisualBasicInvalidNameMatchingFormsNamespaceInSystemRule_Internal_NoDiagnosticAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Class Forms
End Class
Public Class Outer
Private Class Forms
End Class
End Class
Friend Class Outer2
Public Class Forms
End Class
End Class
");
}
[Fact]
public async Task CA1724VisualBasicInvalidNameMatchingSdkNamespaceInDefaultRuleAsync()
{
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class Sdk
End Class"
},
AdditionalReferences = { MetadataReference.CreateFromFile(typeof(Xunit.Sdk.AllException).Assembly.Location) }
},
ExpectedDiagnostics =
{
BasicDefaultResultAt(2, 14, "Sdk", "Xunit.Sdk"),
}
}.RunAsync();
}
}
}
| |
#if UNITY_5 && (!UNITY_5_0 && !UNITY_5_1)
#define UNITY_5_2_AND_GREATER
#endif
#if UNITY_5 && (!UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2)
#define UNITY_5_3_AND_GREATER
#endif
using System.Collections.Generic;
using System.Linq;
using DldUtil;
using UnityEditor;
using UnityEngine;
namespace BuildReportTool
{
public static class UnityBuildSettingsUtility
{
// ================================================================================================
public static GUIContent[] GetBuildSettingsCategoryListForDropdownBox()
{
// WARNING! changing contents here will require changing code in:
//
// SetSelectedSettingsIdxFromBuildReportValues
// SetSettingsShownFromIdx
//
// as they rely on the array indices
//
return new GUIContent[]
{
/* 0 */ new GUIContent("Windows"),
/* 1 */ new GUIContent("Mac"),
/* 2 */ new GUIContent("Linux"),
/* 3 */ new GUIContent("Web"),
/* 4 */ new GUIContent("Web GL"),
/* 5 */ new GUIContent("iOS"),
/* 6 */ new GUIContent("Android"),
/* 7 */ new GUIContent("Blackberry"),
/* 8 */ new GUIContent("Xbox 360"),
/* 9 */ new GUIContent("Xbox One"),
/* 10 */ new GUIContent("Playstation 3"),
/* 11 */ new GUIContent("Playstation 4"),
/* 12 */ new GUIContent("Playstation Vita (Native)"),
/* 13 */ new GUIContent("Samsung TV"),
};
}
public static int GetIdxFromBuildReportValues(BuildInfo buildReportToDisplay)
{
BuildSettingCategory b = ReportGenerator.GetBuildSettingCategoryFromBuildValues(buildReportToDisplay);
switch (b)
{
case BuildSettingCategory.WindowsDesktopStandalone:
return 0;
case BuildSettingCategory.MacStandalone:
return 1;
case BuildSettingCategory.LinuxStandalone:
return 2;
case BuildSettingCategory.WebPlayer:
return 3;
case BuildSettingCategory.WebGL:
return 4;
case BuildSettingCategory.iOS:
return 5;
case BuildSettingCategory.Android:
return 6;
case BuildSettingCategory.Blackberry:
return 7;
case BuildSettingCategory.Xbox360:
return 8;
case BuildSettingCategory.XboxOne:
return 9;
case BuildSettingCategory.PS3:
return 10;
case BuildSettingCategory.PS4:
return 11;
case BuildSettingCategory.PSVita:
return 12;
case BuildSettingCategory.SamsungTV:
return 13;
}
return -1;
}
public static BuildSettingCategory GetSettingsCategoryFromIdx(int idx)
{
switch (idx)
{
case 0:
return BuildSettingCategory.WindowsDesktopStandalone;
case 1:
return BuildSettingCategory.MacStandalone;
case 2:
return BuildSettingCategory.LinuxStandalone;
case 3:
return BuildSettingCategory.WebPlayer;
case 4:
return BuildSettingCategory.WebGL;
case 5:
return BuildSettingCategory.iOS;
case 6:
return BuildSettingCategory.Android;
case 7:
return BuildSettingCategory.Blackberry;
case 8:
return BuildSettingCategory.Xbox360;
case 9:
return BuildSettingCategory.XboxOne;
case 10:
return BuildSettingCategory.PS3;
case 11:
return BuildSettingCategory.PS4;
case 12:
return BuildSettingCategory.PSVita;
case 13:
return BuildSettingCategory.SamsungTV;
}
return BuildSettingCategory.None;
}
public static string GetReadableBuildSettingCategory(BuildSettingCategory b)
{
switch (b)
{
case BuildSettingCategory.WindowsDesktopStandalone:
return "Windows";
case BuildSettingCategory.WindowsStoreApp:
return "Windows Store App";
case BuildSettingCategory.WindowsPhone8:
return "Windows Phone 8";
case BuildSettingCategory.MacStandalone:
return "Mac";
case BuildSettingCategory.LinuxStandalone:
return "Linux";
case BuildSettingCategory.WebPlayer:
return "Web Player";
case BuildSettingCategory.Xbox360:
return "Xbox 360";
case BuildSettingCategory.XboxOne:
return "Xbox One";
case BuildSettingCategory.PS3:
return "Playstation 3";
case BuildSettingCategory.PS4:
return "Playstation 4";
case BuildSettingCategory.PSVita:
return "Playstation Vita (Native)";
case BuildSettingCategory.PSM:
return "Playstation Mobile";
case BuildSettingCategory.WebGL:
return "Web GL";
}
return b.ToString();
}
// ================================================================================================
public static void Populate(UnityBuildSettings settings)
{
PopulateGeneralSettings(settings);
PopulateWebSettings(settings);
PopulateStandaloneSettings(settings);
PopulateMobileSettings(settings);
PopulateTvDeviceSettings(settings);
PopulateBigConsoleGen07Settings(settings);
PopulateBigConsoleGen08Settings(settings);
}
public static void PopulateGeneralSettings(UnityBuildSettings settings)
{
settings.CompanyName = PlayerSettings.companyName;
settings.ProductName = PlayerSettings.productName;
settings.UsingAdvancedLicense = PlayerSettings.advancedLicense;
// debug settings
// ---------------------------------------------------------------
settings.EnableDevelopmentBuild = EditorUserBuildSettings.development;
settings.EnableDebugLog = PlayerSettings.usePlayerLog;
settings.EnableSourceDebugging = EditorUserBuildSettings.allowDebugging;
settings.EnableExplicitNullChecks = EditorUserBuildSettings.explicitNullChecks;
#if UNITY_5
settings.EnableCrashReportApi = PlayerSettings.enableCrashReportAPI;
settings.EnableInternalProfiler = PlayerSettings.enableInternalProfiler;
settings.ActionOnDotNetUnhandledException = PlayerSettings.actionOnDotNetUnhandledException.ToString();
#endif
settings.ConnectProfiler = EditorUserBuildSettings.connectProfiler;
#if UNITY_5_3_AND_GREATER
// this setting actually started appearing in Unity 5.2.2 (it is not present in 5.2.1)
// but our script compilation defines can't detect the patch number in the version,
// so we have no choice but to restrict this to 5.3
settings.ForceOptimizeScriptCompilation = EditorUserBuildSettings.forceOptimizeScriptCompilation;
#endif
// build settings
// ---------------------------------------------------------------
settings.EnableHeadlessMode = EditorUserBuildSettings.enableHeadlessMode;
settings.InstallInBuildFolder = EditorUserBuildSettings.installInBuildFolder;
#if UNITY_5
settings.ForceInstallation = EditorUserBuildSettings.forceInstallation;
settings.BuildScriptsOnly = EditorUserBuildSettings.buildScriptsOnly;
settings.BakeCollisionMeshes = PlayerSettings.bakeCollisionMeshes;
#endif
#if !UNITY_5
settings.StripPhysicsCode = PlayerSettings.stripPhysics;
#endif
settings.StripUnusedMeshComponents = PlayerSettings.stripUnusedMeshComponents;
#if UNITY_5_2_AND_GREATER
settings.StripEngineCode = PlayerSettings.stripEngineCode;
#endif
// code settings
// ---------------------------------------------------------------
Dictionary<string, DldUtil.GetRspDefines.Entry> customDefines = DldUtil.GetRspDefines.GetDefines();
List<string> defines = new List<string>();
defines.AddRange(EditorUserBuildSettings.activeScriptCompilationDefines);
foreach(KeyValuePair<string, DldUtil.GetRspDefines.Entry> customDefine in customDefines)
{
if (customDefine.Value.TimesDefinedInBuiltIn == 0)
{
defines.Add(customDefine.Key);
}
}
settings.CompileDefines = defines.ToArray();
settings.StrippingLevelUsed = PlayerSettings.strippingLevel.ToString();
settings.NETApiCompatibilityLevel = PlayerSettings.apiCompatibilityLevel.ToString();
settings.AOTOptions = PlayerSettings.aotOptions;
settings.LocationUsageDescription = PlayerSettings.locationUsageDescription;
// rendering settings
// ---------------------------------------------------------------
settings.ColorSpaceUsed = PlayerSettings.colorSpace.ToString();
settings.UseMultithreadedRendering = PlayerSettings.MTRendering;
settings.UseGPUSkinning = PlayerSettings.gpuSkinning;
settings.RenderingPathUsed = PlayerSettings.renderingPath.ToString();
settings.VisibleInBackground = PlayerSettings.visibleInBackground;
#if UNITY_5_2_AND_GREATER
settings.EnableVirtualRealitySupport = PlayerSettings.virtualRealitySupported;
#endif
// collect all aspect ratios
UnityEditor.AspectRatio[] aspectRatios = {
UnityEditor.AspectRatio.Aspect4by3,
UnityEditor.AspectRatio.Aspect5by4,
UnityEditor.AspectRatio.Aspect16by9,
UnityEditor.AspectRatio.Aspect16by10,
UnityEditor.AspectRatio.AspectOthers
};
List<string> aspectRatiosList = new List<string>();
for (int n = 0, len = aspectRatios.Length; n < len; ++n )
{
if (PlayerSettings.HasAspectRatio(aspectRatios[n]))
{
aspectRatiosList.Add(aspectRatios[n].ToString());
}
}
if (aspectRatiosList.Count == 0)
{
aspectRatiosList.Add("none");
}
settings.AspectRatiosAllowed = aspectRatiosList.ToArray();
#if UNITY_5_3_AND_GREATER
settings.GraphicsAPIsUsed = PlayerSettings.GetGraphicsAPIs(EditorUserBuildSettings.activeBuildTarget).Select(type => type.ToString()).ToArray();
#endif
// shared settings
// ---------------------------------------------------------------
// shared between web and standalone
settings.RunInBackground = PlayerSettings.runInBackground;
}
public static void PopulateWebSettings(UnityBuildSettings settings)
{
// web player settings
// ---------------------------------------------------------------
settings.WebPlayerDefaultScreenWidth = PlayerSettings.defaultWebScreenWidth;
settings.WebPlayerDefaultScreenHeight = PlayerSettings.defaultWebScreenHeight;
settings.WebPlayerEnableStreaming = EditorUserBuildSettings.webPlayerStreamed;
settings.WebPlayerDeployOffline = EditorUserBuildSettings.webPlayerOfflineDeployment;
#if UNITY_5_3
settings.WebPlayerFirstStreamedLevelWithResources = 0;
#else
settings.WebPlayerFirstStreamedLevelWithResources = PlayerSettings.firstStreamedLevelWithResources;
#endif
#if UNITY_5
settings.WebGLOptimizationLevel = EditorUserBuildSettings.webGLOptimizationLevel.ToString();
#endif
}
public static string GetReadableWebGLOptimizationLevel(string optimizationLevelCode)
{
switch(optimizationLevelCode)
{
case "1":
return "1: Slow (fast builds)";
case "2":
return "2: Fast";
case "3":
return "3: Fastest (very slow builds)";
}
return optimizationLevelCode;
}
public static void PopulateStandaloneSettings(UnityBuildSettings settings)
{
// standalone (windows/mac/linux) build settings
// ---------------------------------------------------------------
settings.StandaloneResolutionDialogSettingUsed = PlayerSettings.displayResolutionDialog.ToString();
settings.StandaloneDefaultScreenWidth = PlayerSettings.defaultScreenWidth;
settings.StandaloneDefaultScreenHeight = PlayerSettings.defaultScreenHeight;
settings.StandaloneFullScreenByDefault = PlayerSettings.defaultIsFullScreen;
#if UNITY_5_3_AND_GREATER
settings.StandaloneAllowFullScreenSwitch = PlayerSettings.allowFullscreenSwitch;
#endif
settings.StandaloneCaptureSingleScreen = PlayerSettings.captureSingleScreen;
settings.StandaloneForceSingleInstance = PlayerSettings.forceSingleInstance;
settings.StandaloneEnableResizableWindow = PlayerSettings.resizableWindow;
// windows only build settings
// ---------------------------------------------------------------
#if !UNITY_5_3
settings.WinUseDirect3D11IfAvailable = PlayerSettings.useDirect3D11;
#endif
settings.WinDirect3D9FullscreenModeUsed = PlayerSettings.d3d9FullscreenMode.ToString();
#if UNITY_5
settings.WinDirect3D11FullscreenModeUsed = PlayerSettings.d3d11FullscreenMode.ToString();
#endif
settings.StandaloneUseStereoscopic3d = PlayerSettings.stereoscopic3D;
// Windows Store App only build settings
// ---------------------------------------------------------------
#if UNITY_5
settings.WSAGenerateReferenceProjects = EditorUserBuildSettings.wsaGenerateReferenceProjects;
#endif
#if UNITY_5_2_AND_GREATER
settings.WSASDK = EditorUserBuildSettings.wsaSDK.ToString();
#endif
// mac only build settings
// ---------------------------------------------------------------
settings.MacUseAppStoreValidation = PlayerSettings.useMacAppStoreValidation;
settings.MacFullscreenModeUsed = PlayerSettings.macFullscreenMode.ToString();
}
public static void PopulateMobileSettings(UnityBuildSettings settings)
{
// Mobile build settings
// ---------------------------------------------------------------
settings.MobileBundleIdentifier = PlayerSettings.bundleIdentifier; // ("Bundle Identifier" in iOS, "Package Identifier" in Android)
settings.MobileBundleVersion = PlayerSettings.bundleVersion; // ("Bundle Version" in iOS, "Version Name" in Android)
settings.MobileHideStatusBar = PlayerSettings.statusBarHidden;
settings.MobileAccelerometerFrequency = PlayerSettings.accelerometerFrequency;
settings.MobileDefaultOrientationUsed = PlayerSettings.defaultInterfaceOrientation.ToString();
settings.MobileEnableAutorotateToPortrait = PlayerSettings.allowedAutorotateToPortrait;
settings.MobileEnableAutorotateToReversePortrait = PlayerSettings.allowedAutorotateToPortraitUpsideDown;
settings.MobileEnableAutorotateToLandscapeLeft = PlayerSettings.allowedAutorotateToLandscapeLeft;
settings.MobileEnableAutorotateToLandscapeRight = PlayerSettings.allowedAutorotateToLandscapeRight;
settings.MobileEnableOSAutorotation = PlayerSettings.useAnimatedAutorotation;
settings.Use32BitDisplayBuffer = PlayerSettings.use32BitDisplayBuffer;
// iOS only build settings
// ---------------------------------------------------------------
// Unity 5: EditorUserBuildSettings.appendProject is removed
#if !UNITY_5
settings.iOSAppendedToProject = EditorUserBuildSettings.appendProject;
#endif
settings.iOSSymlinkLibraries = EditorUserBuildSettings.symlinkLibraries;
settings.iOSAppDisplayName = PlayerSettings.iOS.applicationDisplayName;
settings.iOSScriptCallOptimizationUsed = PlayerSettings.iOS.scriptCallOptimization.ToString();
settings.iOSSDKVersionUsed = PlayerSettings.iOS.sdkVersion.ToString();
settings.iOSTargetOSVersion = PlayerSettings.iOS.targetOSVersion.ToString();
settings.iOSTargetDevice = PlayerSettings.iOS.targetDevice.ToString();
#if UNITY_5_3
// not sure what the equivalent is for PlayerSettings.iOS.targetResolution in Unity 5.3
// Unity 5.3 has a Screen.resolutions but I don't know which of those in the array would be the iOS target resolution
#else
settings.iOSTargetResolution = PlayerSettings.iOS.targetResolution.ToString();
#endif
settings.iOSIsIconPrerendered = PlayerSettings.iOS.prerenderedIcon;
settings.iOSRequiresPersistentWiFi = PlayerSettings.iOS.requiresPersistentWiFi.ToString();
settings.iOSStatusBarStyle = PlayerSettings.iOS.statusBarStyle.ToString();
#if !UNITY_5
settings.iOSExitOnSuspend = PlayerSettings.iOS.exitOnSuspend;
#else
settings.iOSAppInBackgroundBehavior = PlayerSettings.iOS.appInBackgroundBehavior.ToString();
#endif
settings.iOSShowProgressBarInLoadingScreen = PlayerSettings.iOS.showActivityIndicatorOnLoading.ToString();
#if UNITY_5
settings.iOSLogObjCUncaughtExceptions = PlayerSettings.logObjCUncaughtExceptions;
#endif
#if UNITY_5_3
settings.iOSTargetGraphics = string.Join(",", PlayerSettings.GetGraphicsAPIs(BuildTarget.iOS).Select(type => type.ToString()).ToArray());
#else
settings.iOSTargetGraphics = PlayerSettings.targetIOSGraphics.ToString();
#endif
// Android only build settings
// ---------------------------------------------------------------
settings.AndroidBuildSubtarget = EditorUserBuildSettings.androidBuildSubtarget.ToString();
settings.AndroidUseAPKExpansionFiles = PlayerSettings.Android.useAPKExpansionFiles;
#if UNITY_5
settings.AndroidAsAndroidProject = EditorUserBuildSettings.exportAsGoogleAndroidProject;
settings.AndroidIsGame = PlayerSettings.Android.androidIsGame;
settings.AndroidTvCompatible = PlayerSettings.Android.androidTVCompatibility;
#endif
settings.AndroidUseLicenseVerification = PlayerSettings.Android.licenseVerification;
#if !UNITY_5
settings.AndroidUse24BitDepthBuffer = PlayerSettings.Android.use24BitDepthBuffer;
#else
settings.AndroidDisableDepthAndStencilBuffers = PlayerSettings.Android.disableDepthAndStencilBuffers;
#endif
settings.AndroidVersionCode = PlayerSettings.Android.bundleVersionCode;
settings.AndroidMinSDKVersion = PlayerSettings.Android.minSdkVersion.ToString();
settings.AndroidTargetDevice = PlayerSettings.Android.targetDevice.ToString();
settings.AndroidSplashScreenScaleMode = PlayerSettings.Android.splashScreenScale.ToString();
settings.AndroidPreferredInstallLocation = PlayerSettings.Android.preferredInstallLocation.ToString();
settings.AndroidForceInternetPermission = PlayerSettings.Android.forceInternetPermission;
settings.AndroidForceSDCardPermission = PlayerSettings.Android.forceSDCardPermission;
settings.AndroidShowProgressBarInLoadingScreen = PlayerSettings.Android.showActivityIndicatorOnLoading.ToString();
settings.AndroidKeyAliasName = PlayerSettings.Android.keyaliasName;
settings.AndroidKeystoreName = PlayerSettings.Android.keystoreName;
// BlackBerry only build settings
// ---------------------------------------------------------------
settings.BlackBerryBuildSubtarget = EditorUserBuildSettings.blackberryBuildSubtarget.ToString();
settings.BlackBerryBuildType = EditorUserBuildSettings.blackberryBuildType.ToString();
#if !UNITY_5
settings.BlackBerryAuthorID = PlayerSettings.BlackBerry.authorId;
#endif
settings.BlackBerryDeviceAddress = PlayerSettings.BlackBerry.deviceAddress;
settings.BlackBerrySaveLogPath = PlayerSettings.BlackBerry.saveLogPath;
settings.BlackBerryTokenPath = PlayerSettings.BlackBerry.tokenPath;
settings.BlackBerryTokenAuthor = PlayerSettings.BlackBerry.tokenAuthor;
settings.BlackBerryTokenExpiration = PlayerSettings.BlackBerry.tokenExpires;
settings.BlackBerryHasCamPermissions = PlayerSettings.BlackBerry.HasCameraPermissions();
settings.BlackBerryHasMicPermissions = PlayerSettings.BlackBerry.HasMicrophonePermissions();
settings.BlackBerryHasGpsPermissions = PlayerSettings.BlackBerry.HasGPSPermissions();
settings.BlackBerryHasIdPermissions = PlayerSettings.BlackBerry.HasIdentificationPermissions();
settings.BlackBerryHasSharedPermissions = PlayerSettings.BlackBerry.HasSharedPermissions();
}
public static void PopulateTvDeviceSettings(UnityBuildSettings settings)
{
settings.SamsungTVDeviceAddress = PlayerSettings.SamsungTV.deviceAddress;
#if UNITY_5
settings.SamsungTVAuthor = PlayerSettings.SamsungTV.productAuthor;
settings.SamsungTVAuthorEmail = PlayerSettings.SamsungTV.productAuthorEmail;
settings.SamsungTVAuthorWebsiteUrl = PlayerSettings.SamsungTV.productLink;
settings.SamsungTVCategory = PlayerSettings.SamsungTV.productCategory.ToString();
settings.SamsungTVDescription = PlayerSettings.SamsungTV.productDescription;
#endif
}
public static void PopulateBigConsoleGen07Settings(UnityBuildSettings settings)
{
// XBox 360 build settings
// ---------------------------------------------------------------
settings.Xbox360BuildSubtarget = EditorUserBuildSettings.xboxBuildSubtarget.ToString();
settings.Xbox360RunMethod = EditorUserBuildSettings.xboxRunMethod.ToString();
settings.Xbox360TitleId = PlayerSettings.xboxTitleId;
settings.Xbox360ImageXexFilePath = PlayerSettings.xboxImageXexFilePath;
settings.Xbox360SpaFilePath = PlayerSettings.xboxSpaFilePath;
settings.Xbox360AutoGenerateSpa = PlayerSettings.xboxGenerateSpa;
settings.Xbox360EnableKinect = PlayerSettings.xboxEnableKinect;
settings.Xbox360EnableKinectAutoTracking = PlayerSettings.xboxEnableKinectAutoTracking;
settings.Xbox360EnableSpeech = PlayerSettings.xboxEnableSpeech;
settings.Xbox360EnableAvatar = PlayerSettings.xboxEnableAvatar;
settings.Xbox360SpeechDB = PlayerSettings.xboxSpeechDB;
settings.Xbox360AdditionalTitleMemSize = PlayerSettings.xboxAdditionalTitleMemorySize;
settings.Xbox360DeployKinectResources = PlayerSettings.xboxDeployKinectResources;
settings.Xbox360DeployKinectHeadOrientation = PlayerSettings.xboxDeployKinectHeadOrientation;
settings.Xbox360DeployKinectHeadPosition = PlayerSettings.xboxDeployKinectHeadPosition;
// Playstation devices build settings
// ---------------------------------------------------------------
settings.SCEBuildSubtarget = EditorUserBuildSettings.sceBuildSubtarget.ToString();
#if UNITY_5
settings.CompressBuildWithPsArc = EditorUserBuildSettings.compressWithPsArc;
settings.NeedSubmissionMaterials = EditorUserBuildSettings.needSubmissionMaterials;
#endif
// PS3 build settings
// ---------------------------------------------------------------
// paths
#if !UNITY_5
settings.PS3TitleConfigFilePath = PlayerSettings.ps3TitleConfigPath;
settings.PS3DLCConfigFilePath = PlayerSettings.ps3DLCConfigPath;
settings.PS3ThumbnailFilePath = PlayerSettings.ps3ThumbnailPath;
settings.PS3BackgroundImageFilePath = PlayerSettings.ps3BackgroundPath;
settings.PS3BackgroundSoundFilePath = PlayerSettings.ps3SoundPath;
settings.PS3TrophyPackagePath = PlayerSettings.ps3TrophyPackagePath;
settings.PS3InTrialMode = PlayerSettings.ps3TrialMode;
settings.PS3BootCheckMaxSaveGameSizeKB = PlayerSettings.ps3BootCheckMaxSaveGameSizeKB;
settings.PS3SaveGameSlots = PlayerSettings.ps3SaveGameSlots;
settings.PS3NpCommsId = PlayerSettings.ps3TrophyCommId;
settings.PS3NpCommsSig = PlayerSettings.ps3TrophyCommSig;
#else
settings.PS3TitleConfigFilePath = PlayerSettings.PS3.titleConfigPath;
settings.PS3DLCConfigFilePath = PlayerSettings.PS3.dlcConfigPath;
settings.PS3ThumbnailFilePath = PlayerSettings.PS3.thumbnailPath;
settings.PS3BackgroundImageFilePath = PlayerSettings.PS3.backgroundPath;
settings.PS3BackgroundSoundFilePath = PlayerSettings.PS3.soundPath;
settings.PS3TrophyPackagePath = PlayerSettings.PS3.npTrophyPackagePath;
settings.PS3InTrialMode = PlayerSettings.PS3.trialMode;
settings.PS3NpCommsId = PlayerSettings.PS3.npTrophyCommId;
settings.PS3NpCommsSig = PlayerSettings.PS3.npTrophyCommSig;
settings.PS3DisableDolbyEncoding = PlayerSettings.PS3.DisableDolbyEncoding;
settings.PS3EnableMoveSupport = PlayerSettings.PS3.EnableMoveSupport;
settings.PS3UseSPUForUmbra = PlayerSettings.PS3.UseSPUForUmbra;
settings.PS3EnableVerboseMemoryStats = PlayerSettings.PS3.EnableVerboseMemoryStats;
settings.PS3VideoMemoryForAudio = PlayerSettings.PS3.videoMemoryForAudio;
settings.PS3BootCheckMaxSaveGameSizeKB = PlayerSettings.PS3.bootCheckMaxSaveGameSizeKB;
settings.PS3SaveGameSlots = PlayerSettings.PS3.saveGameSlots;
settings.PS3NpAgeRating = PlayerSettings.PS3.npAgeRating;
#endif
settings.PS3VideoMemoryForVertexBuffers = PlayerSettings.PS3.videoMemoryForVertexBuffers;
// PS Vita build settings
// ---------------------------------------------------------------
#if !UNITY_5
settings.PSVTrophyPackagePath = PlayerSettings.psp2NPTrophyPackPath;
settings.PSVParamSfxPath = PlayerSettings.psp2ParamSfxPath;
settings.PSVNpCommsId = PlayerSettings.psp2NPCommsID;
settings.PSVNpCommsSig = PlayerSettings.psp2NPCommsSig;
#else
settings.PSVTrophyPackagePath = PlayerSettings.PSVita.npTrophyPackPath;
settings.PSVParamSfxPath = PlayerSettings.PSVita.paramSfxPath;
settings.PSVNpCommsId = PlayerSettings.PSVita.npCommunicationsID;
settings.PSVNpCommsSig = PlayerSettings.PSVita.npCommsSig;
settings.PSVBuildSubtarget = EditorUserBuildSettings.psp2BuildSubtarget.ToString();
settings.PSVShortTitle = PlayerSettings.PSVita.shortTitle;
settings.PSVAppVersion = PlayerSettings.PSVita.appVersion;
settings.PSVMasterVersion = PlayerSettings.PSVita.masterVersion;
settings.PSVAppCategory = PlayerSettings.PSVita.category.ToString();
settings.PSVContentId = PlayerSettings.PSVita.contentID;
settings.PSVNpAgeRating = PlayerSettings.PSVita.npAgeRating.ToString();
settings.PSVParentalLevel = PlayerSettings.PSVita.parentalLevel.ToString();
settings.PSVDrmType = PlayerSettings.PSVita.drmType.ToString();
settings.PSVUpgradable = PlayerSettings.PSVita.upgradable;
settings.PSVTvBootMode = PlayerSettings.PSVita.tvBootMode.ToString();
settings.PSVAcquireBgm = PlayerSettings.PSVita.acquireBGM;
settings.PSVAllowTwitterDialog = PlayerSettings.PSVita.AllowTwitterDialog;
settings.PSVMediaCapacity = PlayerSettings.PSVita.mediaCapacity.ToString();
settings.PSVStorageType = PlayerSettings.PSVita.storageType.ToString();
settings.PSVTvDisableEmu = PlayerSettings.PSVita.tvDisableEmu;
settings.PSVNpSupportGbmOrGjp = PlayerSettings.PSVita.npSupportGBMorGJP;
settings.PSVPowerMode = PlayerSettings.PSVita.powerMode.ToString();
settings.PSVUseLibLocation = PlayerSettings.PSVita.useLibLocation;
settings.PSVHealthWarning = PlayerSettings.PSVita.healthWarning;
settings.PSVEnterButtonAssignment = PlayerSettings.PSVita.enterButtonAssignment.ToString();
settings.PSVInfoBarColor = PlayerSettings.PSVita.infoBarColor;
settings.PSVShowInfoBarOnStartup = PlayerSettings.PSVita.infoBarOnStartup;
settings.PSVSaveDataQuota = PlayerSettings.PSVita.saveDataQuota;
// paths
settings.PSVPatchChangeInfoPath = PlayerSettings.PSVita.patchChangeInfoPath;
settings.PSVPatchOriginalPackPath = PlayerSettings.PSVita.patchOriginalPackage;
settings.PSVKeystoneFilePath = PlayerSettings.PSVita.keystoneFile;
settings.PSVLiveAreaBgImagePath = PlayerSettings.PSVita.liveAreaBackroundPath;
settings.PSVLiveAreaGateImagePath = PlayerSettings.PSVita.liveAreaGatePath;
settings.PSVCustomLiveAreaPath = PlayerSettings.PSVita.liveAreaPath;
settings.PSVLiveAreaTrialPath = PlayerSettings.PSVita.liveAreaTrialPath;
settings.PSVManualPath = PlayerSettings.PSVita.manualPath;
#endif
}
public static void PopulateBigConsoleGen08Settings(UnityBuildSettings settings)
{
#if UNITY_5
// Xbox One build settings
// ---------------------------------------------------------------
settings.XboxOneDeployMethod = EditorUserBuildSettings.xboxOneDeployMethod.ToString();
settings.XboxOneTitleId = PlayerSettings.XboxOne.TitleId;
settings.XboxOneContentId = PlayerSettings.XboxOne.ContentId;
settings.XboxOneProductId = PlayerSettings.XboxOne.ProductId;
settings.XboxOneSandboxId = PlayerSettings.XboxOne.SandboxId;
settings.XboxOneServiceConfigId = PlayerSettings.XboxOne.SCID;
settings.XboxOneVersion = PlayerSettings.XboxOne.Version;
settings.XboxOneIsContentPackage = PlayerSettings.XboxOne.IsContentPackage;
settings.XboxOneDescription = PlayerSettings.XboxOne.Description;
settings.XboxOnePackagingEncryptionLevel = PlayerSettings.XboxOne.PackagingEncryption.ToString();
settings.XboxOneAllowedProductIds = PlayerSettings.XboxOne.AllowedProductIds;
settings.XboxOneDisableKinectGpuReservation = PlayerSettings.XboxOne.DisableKinectGpuReservation;
settings.XboxOneEnableVariableGPU = PlayerSettings.XboxOne.EnableVariableGPU;
settings.XboxOneStreamingInstallLaunchRange = EditorUserBuildSettings.streamingInstallLaunchRange;
settings.XboxOnePersistentLocalStorageSize = PlayerSettings.XboxOne.PersistentLocalStorageSize;
settings.XboxOneSocketNames = PlayerSettings.XboxOne.SocketNames;
settings.XboxOneGameOsOverridePath = PlayerSettings.XboxOne.GameOsOverridePath;
settings.XboxOneAppManifestOverridePath = PlayerSettings.XboxOne.AppManifestOverridePath;
settings.XboxOnePackagingOverridePath = PlayerSettings.XboxOne.PackagingOverridePath;
// PS4 build settings
// ---------------------------------------------------------------
settings.PS4BuildSubtarget = EditorUserBuildSettings.ps4BuildSubtarget.ToString();
settings.PS4AppParameter1 = PlayerSettings.PS4.applicationParameter1;
settings.PS4AppParameter2 = PlayerSettings.PS4.applicationParameter2;
settings.PS4AppParameter3 = PlayerSettings.PS4.applicationParameter3;
settings.PS4AppParameter4 = PlayerSettings.PS4.applicationParameter4;
settings.PS4AppType = PlayerSettings.PS4.appType;
settings.PS4AppVersion = PlayerSettings.PS4.appVersion;
settings.PS4Category = PlayerSettings.PS4.category.ToString();
settings.PS4ContentId = PlayerSettings.PS4.contentID;
settings.PS4MasterVersion = PlayerSettings.PS4.masterVersion;
settings.PS4EnterButtonAssignment = PlayerSettings.PS4.enterButtonAssignment.ToString();
settings.PS4RemotePlayKeyAssignment = PlayerSettings.PS4.remotePlayKeyAssignment.ToString();
settings.PS4VideoOutPixelFormat = PlayerSettings.PS4.videoOutPixelFormat.ToString();
settings.PS4VideoOutResolution = PlayerSettings.PS4.videoOutResolution.ToString();
settings.PS4MonoEnvVars = PlayerSettings.PS4.monoEnv;
settings.PS4NpAgeRating = PlayerSettings.PS4.npAgeRating.ToString();
settings.PS4ParentalLevel = PlayerSettings.PS4.parentalLevel.ToString();
settings.PS4EnablePlayerPrefsSupport = PlayerSettings.PS4.playerPrefsSupport;
settings.PS4EnableFriendPushNotifications = PlayerSettings.PS4.pnFriends;
settings.PS4EnablePresencePushNotifications = PlayerSettings.PS4.pnPresence;
settings.PS4EnableSessionPushNotifications = PlayerSettings.PS4.pnSessions;
settings.PS4EnableGameCustomDataPushNotifications = PlayerSettings.PS4.pnGameCustomData;
// paths
settings.PS4BgImagePath = PlayerSettings.PS4.BackgroundImagePath;
settings.PS4BgMusicPath = PlayerSettings.PS4.BGMPath;
settings.PS4StartupImagePath = PlayerSettings.PS4.StartupImagePath;
settings.PS4ParamSfxPath = PlayerSettings.PS4.paramSfxPath;
settings.PS4NpTitleDatPath = PlayerSettings.PS4.NPtitleDatPath;
settings.PS4NpTrophyPackagePath = PlayerSettings.PS4.npTrophyPackPath;
settings.PS4PronunciationSigPath = PlayerSettings.PS4.PronunciationSIGPath;
settings.PS4PronunciationXmlPath = PlayerSettings.PS4.PronunciationXMLPath;
settings.PS4SaveDataImagePath = PlayerSettings.PS4.SaveDataImagePath;
settings.PS4ShareFilePath = PlayerSettings.PS4.ShareFilePath;
#endif
}
}
}
| |
using System;
using System.Collections;
using Stetic.Wrapper;
using Mono.Unix;
namespace Stetic.Editor
{
public class ActionMenu: Gtk.EventBox, IMenuItemContainer
{
ActionTreeNode parentNode;
ActionTreeNodeCollection nodes;
ArrayList menuItems = new ArrayList ();
Gtk.Table table;
ActionMenu openSubmenu;
Widget wrapper;
int dropPosition = -1;
int dropIndex;
Gtk.EventBox emptyLabel;
IMenuItemContainer parentMenu;
public ActionMenu (IntPtr p): base (p)
{}
internal ActionMenu (Widget wrapper, IMenuItemContainer parentMenu, ActionTreeNode node)
{
DND.DestSet (this, true);
parentNode = node;
this.parentMenu = parentMenu;
this.wrapper = wrapper;
this.nodes = node.Children;
table = new Gtk.Table (0, 0, false);
table.ColumnSpacing = 5;
table.RowSpacing = 5;
table.BorderWidth = 5;
this.AppPaintable = true;
Add (table);
Fill ();
parentNode.ChildNodeAdded += OnChildAdded;
parentNode.ChildNodeRemoved += OnChildRemoved;
}
public override void Dispose ()
{
foreach (Gtk.Widget w in table.Children) {
table.Remove (w);
w.Destroy ();
}
parentNode.ChildNodeAdded -= OnChildAdded;
parentNode.ChildNodeRemoved -= OnChildRemoved;
parentNode = null;
base.Dispose ();
}
public void Select (ActionTreeNode node)
{
if (node != null) {
ActionMenuItem item = FindMenuItem (node);
if (item != null)
item.Select ();
} else {
if (menuItems.Count > 0)
((ActionMenuItem)menuItems [0]).Select ();
else
InsertAction (0);
}
}
public ActionTreeNode ParentNode {
get { return parentNode; }
}
bool IMenuItemContainer.IsTopMenu {
get { return false; }
}
Gtk.Widget IMenuItemContainer.Widget {
get { return this; }
}
public void TrackWidgetPosition (Gtk.Widget refWidget, bool topMenu)
{
IDesignArea area = wrapper.GetDesignArea ();
Gdk.Rectangle rect = area.GetCoordinates (refWidget);
if (topMenu)
area.MoveWidget (this, rect.X, rect.Bottom);
else
area.MoveWidget (this, rect.Right, rect.Top);
GLib.Timeout.Add (50, new GLib.TimeoutHandler (RepositionSubmenu));
}
public bool RepositionSubmenu ()
{
if (openSubmenu == null)
return false;
ActionMenuItem item = FindMenuItem (openSubmenu.parentNode);
if (item != null)
openSubmenu.TrackWidgetPosition (item, false);
return false;
}
void Fill ()
{
menuItems.Clear ();
uint n = 0;
ActionMenuItem editItem = null;
if (nodes.Count > 0) {
foreach (ActionTreeNode node in nodes) {
ActionMenuItem item = new ActionMenuItem (wrapper, this, node);
item.KeyPressEvent += OnItemKeyPress;
item.Attach (table, n++, 0);
menuItems.Add (item);
// If adding an action with an empty name, select and start editing it
// if (node.Action != null && node.Action.Name.Length == 0)
// editItem = item;
}
}
emptyLabel = new Gtk.EventBox ();
emptyLabel.VisibleWindow = false;
Gtk.Label label = new Gtk.Label ();
label.Xalign = 0;
label.Markup = "<i><span foreground='darkgrey'>" + Catalog.GetString ("Click to create action") + "</span></i>";
emptyLabel.Add (label);
emptyLabel.ButtonPressEvent += OnAddClicked;
table.Attach (emptyLabel, 1, 2, n, n + 1);
ShowAll ();
if (editItem != null) {
// If there is an item with an empty action, it means that it was an item that was
// being edited. Restart the editing now.
GLib.Timeout.Add (200, delegate {
editItem.Select ();
editItem.EditingDone += OnEditingDone;
editItem.StartEditing ();
return false;
});
}
}
void Refresh ()
{
IDesignArea area = wrapper.GetDesignArea ();
ActionTreeNode selNode = null;
foreach (Gtk.Widget w in table.Children) {
ActionMenuItem ami = w as ActionMenuItem;
if (area.IsSelected (w) && ami != null) {
selNode = ami.Node;
area.ResetSelection (w);
}
table.Remove (w);
}
Fill ();
ActionMenuItem mi = FindMenuItem (selNode);
if (mi != null)
mi.Select ();
GLib.Timeout.Add (50, new GLib.TimeoutHandler (RepositionSubmenu));
}
public ActionMenu OpenSubmenu {
get { return openSubmenu; }
set {
if (openSubmenu != null) {
openSubmenu.OpenSubmenu = null;
IDesignArea area = wrapper.GetDesignArea ();
area.RemoveWidget (openSubmenu);
openSubmenu.Dispose ();
}
openSubmenu = value;
}
}
internal void ResetSelection ()
{
if (OpenSubmenu != null)
OpenSubmenu.ResetSelection ();
IDesignArea area = wrapper.GetDesignArea ();
if (area != null) {
foreach (Gtk.Widget w in table.Children) {
ActionMenuItem ami = w as ActionMenuItem;
if (ami != null)
area.ResetSelection (w);
}
}
}
ActionTreeNode InsertAction (int pos)
{
using (wrapper.UndoManager.AtomicChange) {
Wrapper.Action ac = (Wrapper.Action) ObjectWrapper.Create (wrapper.Project, new Gtk.Action ("", "", null, null));
ActionTreeNode newNode = new ActionTreeNode (Gtk.UIManagerItemType.Menuitem, null, ac);
nodes.Insert (pos, newNode);
ActionMenuItem item = FindMenuItem (newNode);
item.EditingDone += OnEditingDone;
item.Select ();
item.StartEditing ();
emptyLabel.Hide ();
if (wrapper.LocalActionGroups.Count == 0)
wrapper.LocalActionGroups.Add (new ActionGroup ("Default"));
wrapper.LocalActionGroups [0].Actions.Add (ac);
return newNode;
}
}
void DeleteAction (ActionMenuItem item)
{
int pos = menuItems.IndexOf (item);
item.Delete ();
if (pos >= menuItems.Count)
SelectLastItem ();
else
((ActionMenuItem)menuItems [pos]).Select ();
}
void OnEditingDone (object ob, MenuItemEditEventArgs args)
{
ActionMenuItem item = (ActionMenuItem) ob;
item.EditingDone -= OnEditingDone;
if (item.Node.Action.GtkAction.Label.Length == 0 && item.Node.Action.GtkAction.StockId == null) {
IDesignArea area = wrapper.GetDesignArea ();
area.ResetSelection (item);
using (wrapper.UndoManager.AtomicChange) {
nodes.Remove (item.Node);
wrapper.LocalActionGroups [0].Actions.Remove (item.Node.Action);
}
SelectLastItem ();
}
else {
if (args.ExitKey == Gdk.Key.Up || args.ExitKey == Gdk.Key.Down)
ProcessKey (item, args.ExitKey, Gdk.ModifierType.None);
}
}
void SelectLastItem ()
{
if (menuItems.Count > 0)
((ActionMenuItem)menuItems [menuItems.Count - 1]).Select ();
else if (parentMenu.Widget is ActionMenuBar) {
ActionMenuBar bar = (ActionMenuBar) parentMenu.Widget;
bar.Select (parentNode);
}
else if (parentMenu.Widget is ActionMenu) {
ActionMenu parentAM = (ActionMenu) parentMenu.Widget;
parentAM.Select (parentNode);
}
}
void OnChildAdded (object ob, ActionTreeNodeArgs args)
{
Refresh ();
}
void OnChildRemoved (object ob, ActionTreeNodeArgs args)
{
IDesignArea area = wrapper.GetDesignArea ();
IObjectSelection asel = area.GetSelection ();
ActionMenuItem curSel = asel != null ? asel.DataObject as ActionMenuItem : null;
int pos = menuItems.IndexOf (curSel);
ActionMenuItem mi = FindMenuItem (args.Node);
if (mi != null) {
// Remove the table row that contains the menu item
Gtk.Table.TableChild tc = (Gtk.Table.TableChild) table [mi];
uint row = tc.TopAttach;
mi.Detach ();
menuItems.Remove (mi);
foreach (Gtk.Widget w in table.Children) {
tc = (Gtk.Table.TableChild) table [w];
if (tc.TopAttach >= row)
tc.TopAttach--;
if (tc.BottomAttach > row)
tc.BottomAttach--;
}
if (pos != -1 && pos < menuItems.Count)
((ActionMenuItem)menuItems[pos]).Select ();
else
SelectLastItem ();
GLib.Timeout.Add (50, new GLib.TimeoutHandler (RepositionSubmenu));
}
}
protected override bool OnExposeEvent (Gdk.EventExpose ev)
{
int w, h;
this.GdkWindow.GetSize (out w, out h);
Gdk.Rectangle clip = new Gdk.Rectangle (0,0,w,h);
Gtk.Style.PaintBox (this.Style, this.GdkWindow, Gtk.StateType.Normal, Gtk.ShadowType.Out, clip, this, "menu", 0, 0, w, h);
bool r = base.OnExposeEvent (ev);
if (dropPosition != -1) {
GdkWindow.DrawRectangle (this.Style.BlackGC, true, 0, dropPosition - 1, w - 2, 3);
}
return r;
}
protected override bool OnButtonPressEvent (Gdk.EventButton ev)
{
return true;
}
void OnAddClicked (object s, Gtk.ButtonPressEventArgs args)
{
InsertAction (menuItems.Count);
args.RetVal = true;
}
protected override bool OnDragMotion (Gdk.DragContext context, int x, int y, uint time)
{
ActionPaletteItem dragItem = DND.DragWidget as ActionPaletteItem;
if (dragItem == null)
return false;
if (nodes.Count > 0) {
ActionMenuItem item = LocateWidget (x, y);
if (item != null) {
// Show the submenu to allow droping to it, but avoid
// droping a submenu inside itself
if (item.HasSubmenu && item.Node != dragItem.Node)
item.ShowSubmenu (wrapper.GetDesignArea(), item);
// Look for the index where to insert the new item
dropIndex = nodes.IndexOf (item.Node);
int mpos = item.Allocation.Y + item.Allocation.Height / 2;
if (y > mpos)
dropIndex++;
// Calculate the drop position, used to show the drop bar
if (dropIndex == 0)
dropPosition = item.Allocation.Y;
else if (dropIndex == menuItems.Count)
dropPosition = item.Allocation.Bottom;
else {
item = (ActionMenuItem) menuItems [dropIndex];
ActionMenuItem prevItem = (ActionMenuItem) menuItems [dropIndex - 1];
dropPosition = prevItem.Allocation.Bottom + (item.Allocation.Y - prevItem.Allocation.Bottom)/2;
}
}
} else
dropIndex = 0;
QueueDraw ();
return base.OnDragMotion (context, x, y, time);
}
protected override void OnDragLeave (Gdk.DragContext context, uint time)
{
dropPosition = -1;
QueueDraw ();
base.OnDragLeave (context, time);
}
protected override void OnDragDataReceived (Gdk.DragContext context, int x, int y, Gtk.SelectionData data, uint info, uint time)
{
}
protected override bool OnDragDrop (Gdk.DragContext context, int x, int y, uint time)
{
ActionPaletteItem dropped = DND.Drop (context, null, time) as ActionPaletteItem;
if (dropped == null)
return false;
if (dropped.Node.Type != Gtk.UIManagerItemType.Menuitem &&
dropped.Node.Type != Gtk.UIManagerItemType.Menu &&
dropped.Node.Type != Gtk.UIManagerItemType.Toolitem &&
dropped.Node.Type != Gtk.UIManagerItemType.Separator)
return false;
ActionTreeNode newNode = null;
// Toolitems are copied, not moved
using (wrapper.UndoManager.AtomicChange) {
if (dropped.Node.ParentNode != null && dropped.Node.Type != Gtk.UIManagerItemType.Toolitem) {
if (dropIndex < nodes.Count) {
// Do nothing if trying to drop the node over the same node
ActionTreeNode dropNode = nodes [dropIndex];
if (dropNode == dropped.Node)
return false;
dropped.Node.ParentNode.Children.Remove (dropped.Node);
// The drop position may have changed after removing the dropped node,
// so get it again.
dropIndex = nodes.IndexOf (dropNode);
nodes.Insert (dropIndex, dropped.Node);
} else {
dropped.Node.ParentNode.Children.Remove (dropped.Node);
nodes.Add (dropped.Node);
dropIndex = nodes.Count - 1;
}
} else {
newNode = new ActionTreeNode (Gtk.UIManagerItemType.Menuitem, null, dropped.Node.Action);
nodes.Insert (dropIndex, newNode);
}
// Select the dropped node
ActionMenuItem mi = (ActionMenuItem) menuItems [dropIndex];
mi.Select ();
}
return base.OnDragDrop (context, x, y, time);
}
[GLib.ConnectBefore]
void OnItemKeyPress (object s, Gtk.KeyPressEventArgs args)
{
ActionMenuItem item = (ActionMenuItem) s;
ProcessKey (item, args.Event.Key, args.Event.State);
args.RetVal = true;
}
void ProcessKey (ActionMenuItem item, Gdk.Key key, Gdk.ModifierType modifier)
{
int pos = menuItems.IndexOf (item);
switch (key) {
case Gdk.Key.Up:
if (pos > 0)
((ActionMenuItem)menuItems[pos - 1]).Select ();
else if (parentMenu.Widget is ActionMenuBar) {
ActionMenuBar bar = (ActionMenuBar) parentMenu.Widget;
bar.Select (parentNode);
}
break;
case Gdk.Key.Down:
if (pos < menuItems.Count - 1)
((ActionMenuItem)menuItems[pos + 1]).Select ();
else if (pos == menuItems.Count - 1) {
InsertAction (menuItems.Count);
}
break;
case Gdk.Key.Right:
if ((modifier & Gdk.ModifierType.ControlMask) != 0 && item.Node.Type == Gtk.UIManagerItemType.Menuitem) {
// Create a submenu
using (item.Node.Action.UndoManager.AtomicChange) {
item.Node.Type = Gtk.UIManagerItemType.Menu;
}
item.Node.Action.NotifyChanged ();
}
if (item.HasSubmenu) {
item.ShowSubmenu ();
if (openSubmenu != null)
openSubmenu.Select (null);
} else if (parentNode != null) {
ActionMenuBar parentMB = parentMenu.Widget as ActionMenuBar;
if (parentMB != null) {
int i = parentNode.ParentNode.Children.IndexOf (parentNode);
if (i < parentNode.ParentNode.Children.Count - 1)
parentMB.DropMenu (parentNode.ParentNode.Children [i + 1]);
}
}
break;
case Gdk.Key.Left:
if ((modifier & Gdk.ModifierType.ControlMask) != 0 && item.Node.Type == Gtk.UIManagerItemType.Menu) {
// Remove the submenu
OpenSubmenu = null;
using (item.Node.Action.UndoManager.AtomicChange) {
item.Node.Type = Gtk.UIManagerItemType.Menuitem;
item.Node.Children.Clear ();
}
item.Node.Action.NotifyChanged ();
break;
}
if (parentNode != null) {
ActionMenu parentAM = parentMenu.Widget as ActionMenu;
if (parentAM != null) {
parentAM.Select (parentNode);
}
ActionMenuBar parentMB = parentMenu.Widget as ActionMenuBar;
if (parentMB != null) {
int i = parentNode.ParentNode.Children.IndexOf (parentNode);
if (i > 0)
parentMB.DropMenu (parentNode.ParentNode.Children [i - 1]);
}
}
break;
case Gdk.Key.Return:
item.EditingDone += OnEditingDone;
item.StartEditing ();
break;
case Gdk.Key.Insert:
if ((modifier & Gdk.ModifierType.ControlMask) != 0)
InsertActionAt (item, true, true);
else
InsertActionAt (item, false, false);
break;
case Gdk.Key.Delete:
DeleteAction (item);
break;
}
}
void InsertActionAt (ActionMenuItem item, bool after, bool separator)
{
int pos = menuItems.IndexOf (item);
if (pos == -1)
return;
if (after)
pos++;
if (separator) {
ActionTreeNode newNode = new ActionTreeNode (Gtk.UIManagerItemType.Separator, null, null);
nodes.Insert (pos, newNode);
Select (newNode);
} else
InsertAction (pos);
}
void Paste (ActionMenuItem item)
{
}
void IMenuItemContainer.ShowContextMenu (ActionItem aitem)
{
ActionMenuItem menuItem = aitem as ActionMenuItem;
Gtk.Menu m = new Gtk.Menu ();
Gtk.MenuItem item = new Gtk.MenuItem (Catalog.GetString ("Insert Before"));
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
InsertActionAt (menuItem, false, false);
};
item = new Gtk.MenuItem (Catalog.GetString ("Insert After"));
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
InsertActionAt (menuItem, true, false);
};
item = new Gtk.MenuItem (Catalog.GetString ("Insert Separator Before"));
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
InsertActionAt (menuItem, false, true);
};
item = new Gtk.MenuItem (Catalog.GetString ("Insert Separator After"));
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
InsertActionAt (menuItem, true, true);
};
m.Add (new Gtk.SeparatorMenuItem ());
item = new Gtk.ImageMenuItem (Gtk.Stock.Cut, null);
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
menuItem.Cut ();
};
item.Visible = false; // No copy & paste for now
item = new Gtk.ImageMenuItem (Gtk.Stock.Copy, null);
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
menuItem.Copy ();
};
item.Visible = false;
item = new Gtk.ImageMenuItem (Gtk.Stock.Paste, null);
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
Paste (menuItem);
};
item.Visible = false;
item = new Gtk.ImageMenuItem (Gtk.Stock.Delete, null);
m.Add (item);
item.Activated += delegate (object s, EventArgs a) {
DeleteAction (menuItem);
};
m.ShowAll ();
m.Popup ();
}
internal void SaveStatus (ArrayList status)
{
for (int n=0; n<menuItems.Count; n++) {
ActionMenuItem item = (ActionMenuItem) menuItems [n];
if (item.IsSelected) {
status.Add (n);
return;
}
if (item.IsSubmenuVisible) {
status.Add (n);
OpenSubmenu.SaveStatus (status);
return;
}
}
}
internal void RestoreStatus (ArrayList status, int index)
{
int pos = (int) status [index];
if (pos >= menuItems.Count)
return;
ActionMenuItem item = (ActionMenuItem)menuItems [pos];
if (index == status.Count - 1) {
// The last position in the status is the selected item
item.Select ();
if (item.Node.Action != null && item.Node.Action.Name.Length == 0) {
// Then only case when there can have an action when an empty name
// is when the user clicked on the "add action" link. In this case,
// start editing the item again
item.EditingDone += OnEditingDone;
item.StartEditing ();
}
}
else {
item.ShowSubmenu ();
if (OpenSubmenu != null)
OpenSubmenu.RestoreStatus (status, index + 1);
}
}
ActionMenuItem LocateWidget (int x, int y)
{
foreach (ActionMenuItem mi in menuItems) {
if (mi.Allocation.Contains (x, y))
return mi;
}
return null;
}
ActionMenuItem FindMenuItem (ActionTreeNode node)
{
foreach (ActionMenuItem mi in menuItems) {
if (mi.Node == node)
return mi;
}
return null;
}
}
interface IMenuItemContainer
{
ActionMenu OpenSubmenu { get; set; }
bool IsTopMenu { get; }
Gtk.Widget Widget { get; }
void ShowContextMenu (ActionItem item);
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes the launch specification for one or more Spot instances.
/// </summary>
public partial class SpotFleetLaunchSpecification
{
private string _addressingType;
private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>();
private bool? _ebsOptimized;
private IamInstanceProfileSpecification _iamInstanceProfile;
private string _imageId;
private InstanceType _instanceType;
private string _kernelId;
private string _keyName;
private SpotFleetMonitoring _monitoring;
private List<InstanceNetworkInterfaceSpecification> _networkInterfaces = new List<InstanceNetworkInterfaceSpecification>();
private SpotPlacement _placement;
private string _ramdiskId;
private List<GroupIdentifier> _securityGroups = new List<GroupIdentifier>();
private string _spotPrice;
private string _subnetId;
private string _userData;
private double? _weightedCapacity;
/// <summary>
/// Gets and sets the property AddressingType.
/// <para>
/// Deprecated.
/// </para>
/// </summary>
public string AddressingType
{
get { return this._addressingType; }
set { this._addressingType = value; }
}
// Check to see if AddressingType property is set
internal bool IsSetAddressingType()
{
return this._addressingType != null;
}
/// <summary>
/// Gets and sets the property BlockDeviceMappings.
/// <para>
/// One or more block device mapping entries.
/// </para>
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get { return this._blockDeviceMappings; }
set { this._blockDeviceMappings = value; }
}
// Check to see if BlockDeviceMappings property is set
internal bool IsSetBlockDeviceMappings()
{
return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property EbsOptimized.
/// <para>
/// Indicates whether the instances are optimized for EBS I/O. This optimization provides
/// dedicated throughput to Amazon EBS and an optimized configuration stack to provide
/// optimal EBS I/O performance. This optimization isn't available with all instance types.
/// Additional usage charges apply when using an EBS Optimized instance.
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool EbsOptimized
{
get { return this._ebsOptimized.GetValueOrDefault(); }
set { this._ebsOptimized = value; }
}
// Check to see if EbsOptimized property is set
internal bool IsSetEbsOptimized()
{
return this._ebsOptimized.HasValue;
}
/// <summary>
/// Gets and sets the property IamInstanceProfile.
/// <para>
/// The IAM instance profile.
/// </para>
/// </summary>
public IamInstanceProfileSpecification IamInstanceProfile
{
get { return this._iamInstanceProfile; }
set { this._iamInstanceProfile = value; }
}
// Check to see if IamInstanceProfile property is set
internal bool IsSetIamInstanceProfile()
{
return this._iamInstanceProfile != null;
}
/// <summary>
/// Gets and sets the property ImageId.
/// <para>
/// The ID of the AMI.
/// </para>
/// </summary>
public string ImageId
{
get { return this._imageId; }
set { this._imageId = value; }
}
// Check to see if ImageId property is set
internal bool IsSetImageId()
{
return this._imageId != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type.
/// </para>
/// </summary>
public InstanceType InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property KernelId.
/// <para>
/// The ID of the kernel.
/// </para>
/// </summary>
public string KernelId
{
get { return this._kernelId; }
set { this._kernelId = value; }
}
// Check to see if KernelId property is set
internal bool IsSetKernelId()
{
return this._kernelId != null;
}
/// <summary>
/// Gets and sets the property KeyName.
/// <para>
/// The name of the key pair.
/// </para>
/// </summary>
public string KeyName
{
get { return this._keyName; }
set { this._keyName = value; }
}
// Check to see if KeyName property is set
internal bool IsSetKeyName()
{
return this._keyName != null;
}
/// <summary>
/// Gets and sets the property Monitoring.
/// <para>
/// Enable or disable monitoring for the instances.
/// </para>
/// </summary>
public SpotFleetMonitoring Monitoring
{
get { return this._monitoring; }
set { this._monitoring = value; }
}
// Check to see if Monitoring property is set
internal bool IsSetMonitoring()
{
return this._monitoring != null;
}
/// <summary>
/// Gets and sets the property NetworkInterfaces.
/// <para>
/// One or more network interfaces.
/// </para>
/// </summary>
public List<InstanceNetworkInterfaceSpecification> NetworkInterfaces
{
get { return this._networkInterfaces; }
set { this._networkInterfaces = value; }
}
// Check to see if NetworkInterfaces property is set
internal bool IsSetNetworkInterfaces()
{
return this._networkInterfaces != null && this._networkInterfaces.Count > 0;
}
/// <summary>
/// Gets and sets the property Placement.
/// <para>
/// The placement information.
/// </para>
/// </summary>
public SpotPlacement Placement
{
get { return this._placement; }
set { this._placement = value; }
}
// Check to see if Placement property is set
internal bool IsSetPlacement()
{
return this._placement != null;
}
/// <summary>
/// Gets and sets the property RamdiskId.
/// <para>
/// The ID of the RAM disk.
/// </para>
/// </summary>
public string RamdiskId
{
get { return this._ramdiskId; }
set { this._ramdiskId = value; }
}
// Check to see if RamdiskId property is set
internal bool IsSetRamdiskId()
{
return this._ramdiskId != null;
}
/// <summary>
/// Gets and sets the property SecurityGroups.
/// <para>
/// One or more security groups. To request an instance in a nondefault VPC, you must
/// specify the ID of the security group. To request an instance in EC2-Classic or a default
/// VPC, you can specify the name or the ID of the security group.
/// </para>
/// </summary>
public List<GroupIdentifier> SecurityGroups
{
get { return this._securityGroups; }
set { this._securityGroups = value; }
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this._securityGroups != null && this._securityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The bid price per unit hour for the specified instance type. If this value is not
/// specified, the default is the Spot bid price specified for the fleet. To determine
/// the bid price per unit hour, divide the Spot bid price by the value of <code>WeightedCapacity</code>.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property SubnetId.
/// <para>
/// The ID of the subnet in which to launch the instances.
/// </para>
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
// Check to see if SubnetId property is set
internal bool IsSetSubnetId()
{
return this._subnetId != null;
}
/// <summary>
/// Gets and sets the property UserData.
/// <para>
/// The Base64-encoded MIME user data to make available to the instances.
/// </para>
/// </summary>
public string UserData
{
get { return this._userData; }
set { this._userData = value; }
}
// Check to see if UserData property is set
internal bool IsSetUserData()
{
return this._userData != null;
}
/// <summary>
/// Gets and sets the property WeightedCapacity.
/// <para>
/// The number of units provided by the specified instance type. These are the same units
/// that you chose to set the target capacity in terms (instances or a performance characteristic
/// such as vCPUs, memory, or I/O).
/// </para>
///
/// <para>
/// If the target capacity divided by this value is not a whole number, we round the number
/// of instances to the next whole number. If this value is not specified, the default
/// is 1.
/// </para>
/// </summary>
public double WeightedCapacity
{
get { return this._weightedCapacity.GetValueOrDefault(); }
set { this._weightedCapacity = value; }
}
// Check to see if WeightedCapacity property is set
internal bool IsSetWeightedCapacity()
{
return this._weightedCapacity.HasValue;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace BriLib
{
public class Octree<T> where T : class
{
public enum Octant
{
TopLeftBack = 0,
TopLeftFront = 1,
BottomLeftBack = 2,
BottomLeftFront = 3,
TopRightBack = 4,
TopRightFront = 5,
BottomRightBack = 6,
BottomRightFront = 7,
}
public Tuple<float, float, float> Center { get { return new Tuple<float, float, float>(_bounds.X, _bounds.Y, _bounds.Z); } }
private int _maxObjectsPerNode;
private ThreeDimensionalBoundingBox _bounds;
private List<ThreeDimensionalPoint<T>> _children;
private Octree<T>[] _subtrees;
private Dictionary<T, ThreeDimensionalPoint<T>> _childMap;
public Octree(ThreeDimensionalBoundingBox bounds, int maxObjsPerNode)
: this(bounds, maxObjsPerNode, new Dictionary<T, ThreeDimensionalPoint<T>>()) { }
public Octree(float centerX, float centerY, float centerZ, float radius, int maxObjs)
: this(new ThreeDimensionalBoundingBox(centerX, centerY, centerZ, radius), maxObjs) { }
private Octree(ThreeDimensionalBoundingBox bounds, int maxObjs, Dictionary<T, ThreeDimensionalPoint<T>> childMap)
{
if (maxObjs <= 0)
{
throw new System.ArgumentOutOfRangeException("Must allow at least 1 object per octree node");
}
_maxObjectsPerNode = maxObjs;
_bounds = bounds;
_children = new List<ThreeDimensionalPoint<T>>();
_subtrees = new Octree<T>[8];
_childMap = childMap;
}
public Octant GetOctant(float x, float y, float z)
{
var isUp = y >= _bounds.Y;
var isLeft = x < _bounds.X;
var isBack = z >= _bounds.Z;
if (isUp && isLeft && isBack) return Octant.TopLeftBack;
if (isUp && !isLeft && isBack) return Octant.TopRightBack;
if (isUp && isLeft && !isBack) return Octant.TopLeftFront;
if (isUp && !isLeft && !isBack) return Octant.TopRightFront;
if (!isUp && isLeft && isBack) return Octant.BottomLeftBack;
if (!isUp && !isLeft && isBack) return Octant.BottomRightBack;
if (!isUp && isLeft && !isBack) return Octant.BottomLeftFront;
return Octant.BottomRightFront;
}
public void Insert(float x, float y, float z, T obj)
{
if (_childMap.ContainsKey(obj))
{
throw new System.ArgumentOutOfRangeException("Cannot add object already in tree: " + obj);
}
if (!_bounds.Intersects(x, y, z))
{
var vectorString = string.Format("[x={0}, y={1}, z={2}]", x, y, z);
var str = string.Format("Attempted to add point {0} outside of range of bounding box {1}", vectorString, _bounds.ToString());
throw new System.ArgumentOutOfRangeException(str);
}
if (_children.Count >= _maxObjectsPerNode)
{
Subdivide();
}
var hasSubTrees = _subtrees[0] != null;
if (hasSubTrees)
{
_subtrees[(int)GetOctant(x, y, z)].Insert(x, y, z, obj);
}
else
{
var point = new ThreeDimensionalPoint<T>(x, y, z, obj);
_children.Add(point);
_childMap.Add(obj, point);
}
}
public IEnumerable<T> GetRange(float x, float y, float z, float radius)
{
return GetRange(new ThreeDimensionalBoundingBox(x, y, z, radius));
}
public IEnumerable<T> GetRange(ThreeDimensionalBoundingBox bounds)
{
for (int i = 0; i < _children.Count; i++)
{
if (bounds.Intersects(_children[i].X, _children[i].Y, _children[i].Z))
{
yield return _children[i].StoredObject;
}
}
for (int i = 0; i < _subtrees.Length; i++)
{
if (_subtrees[i] == null || !_subtrees[i]._bounds.Intersects(bounds)) continue;
for (var enumerator = _subtrees[i].GetRange(bounds).GetEnumerator(); enumerator.MoveNext();)
{
yield return enumerator.Current;
}
}
}
public bool Remove(T obj)
{
if (!_childMap.ContainsKey(obj))
{
throw new System.ArgumentOutOfRangeException("Cannot remove element that was not in tree: " + obj);
}
for (int i = 0; i < _children.Count; i++)
{
if (_children[i].StoredObject == obj)
{
_children.RemoveAt(i);
_childMap.Remove(obj);
return true;
}
}
var point = _childMap[obj];
if (_subtrees[(int)GetOctant(point.X, point.Y, point.Z)].Remove(obj))
{
EvaluateSubtrees();
}
return false;
}
public T GetNearestObject(float x, float y, float z)
{
//If we have leaf nodes, check for closest and return it
if (_children.Count > 0)
{
var nearestDistance = float.MaxValue;
T nearestChild = null;
for (int i = 0; i < _children.Count; i++)
{
var child = _children[i];
var distance = MathHelpers.Distance(x, y, z, child.X, child.Y, child.Z);
if (distance < nearestDistance)
{
nearestDistance = distance;
nearestChild = child.StoredObject;
}
}
return nearestChild;
}
//If we don't have children, return
var hasSubTrees = _subtrees[0] != null;
if (!hasSubTrees) return null;
//First check for neighbor in the octant point is currently at. If we find something, store distance.
var startOctant = (int)GetOctant(x, y, z);
var distanceToBest = float.MaxValue;
var best = _subtrees[startOctant].GetNearestObject(x, y, z);
if (best != null)
{
var loc = _childMap[best];
distanceToBest = MathHelpers.Distance(x, y, z, loc.X, loc.Y, loc.Z);
}
//Only search other octants that have distance at nearest edge less than distance to current best point.
//Start by sorting the list of octants by distance, excluding ones that are too far or already visited.
List<Tuple<int, float>> subtreeList = new List<Tuple<int, float>>();
for (var enumerator = System.Enum.GetValues(typeof(Octant)).GetEnumerator(); enumerator.MoveNext();)
{
//Skip octant if it is the start octant
var octantIndex = (int)enumerator.Current;
if (octantIndex == startOctant) continue;
//If distance to nearest point of octant is greater than current best, skip
var distanceToOctant = _subtrees[octantIndex]._bounds.BoundsDistance(x, y, z);
if (distanceToBest <= distanceToOctant) continue;
//Otherwise, add the octant to the list, sorted in order of ascending distance
var octantEntry = new Tuple<int, float>(octantIndex, distanceToOctant);
if (subtreeList.Count == 0)
{
subtreeList.Add(octantEntry);
}
else
{
for (int i = 0; i < subtreeList.Count; i++)
{
if (octantEntry.Item2 < subtreeList[i].Item2)
{
subtreeList.Insert(i, octantEntry);
break;
}
else if (i == subtreeList.Count - 1)
{
subtreeList.Add(octantEntry);
break;
}
}
}
}
//Go through sorted octant list and try to better our best
for (int i = 0; i < subtreeList.Count; i++)
{
//If we have already found something closer than current octant, exit early
if (distanceToBest < subtreeList[i].Item2) break;
//Check if octant has a candidate for neighbor
var candidate = _subtrees[subtreeList[i].Item1].GetNearestObject(x, y, z);
if (candidate == null) continue;
//If candidate distance is shorter than current best, replace current best
var candidateLoc = _childMap[candidate];
var candidateDistance = MathHelpers.Distance(x, y, z, candidateLoc.X, candidateLoc.Y, candidateLoc.Z);
if (candidateDistance < distanceToBest)
{
best = candidate;
distanceToBest = candidateDistance;
}
}
return best;
}
private void Subdivide()
{
var rad = _bounds.Radius / 2f;
var x = _bounds.X;
var y = _bounds.Y;
var z = _bounds.Z;
var tlbBox = new ThreeDimensionalBoundingBox(x - rad, y + rad, z + rad, rad);
var trbBox = new ThreeDimensionalBoundingBox(x + rad, y + rad, z + rad, rad);
var tlfBox = new ThreeDimensionalBoundingBox(x - rad, y + rad, z - rad, rad);
var trfBox = new ThreeDimensionalBoundingBox(x + rad, y + rad, z - rad, rad);
var blbBox = new ThreeDimensionalBoundingBox(x - rad, y - rad, z + rad, rad);
var brbBox = new ThreeDimensionalBoundingBox(x + rad, y - rad, z + rad, rad);
var blfBox = new ThreeDimensionalBoundingBox(x - rad, y - rad, z - rad, rad);
var brfBox = new ThreeDimensionalBoundingBox(x + rad, y - rad, z - rad, rad);
_subtrees[(int)Octant.TopLeftBack] = new Octree<T>(tlbBox, _maxObjectsPerNode, _childMap);
_subtrees[(int)Octant.TopRightBack] = new Octree<T>(trbBox, _maxObjectsPerNode, _childMap);
_subtrees[(int)Octant.TopLeftFront] = new Octree<T>(tlfBox, _maxObjectsPerNode, _childMap);
_subtrees[(int)Octant.TopRightFront] = new Octree<T>(trfBox, _maxObjectsPerNode, _childMap);
_subtrees[(int)Octant.BottomLeftBack] = new Octree<T>(blbBox, _maxObjectsPerNode, _childMap);
_subtrees[(int)Octant.BottomRightBack] = new Octree<T>(brbBox, _maxObjectsPerNode, _childMap);
_subtrees[(int)Octant.BottomLeftFront] = new Octree<T>(blfBox, _maxObjectsPerNode, _childMap);
_subtrees[(int)Octant.BottomRightFront] = new Octree<T>(brfBox, _maxObjectsPerNode, _childMap);
for (int i = 0; i < _children.Count; i++)
{
var childX = _children[i].X;
var childY = _children[i].Y;
var childZ = _children[i].Z;
var child = _children[i].StoredObject;
_childMap.Remove(_children[i].StoredObject);
_subtrees[(int)GetOctant(childX, childY, childZ)].Insert(childX, childY, childZ, child);
}
_children = new List<ThreeDimensionalPoint<T>>();
}
private void EvaluateSubtrees()
{
var clearChildren = true;
for (var i = 0; i < _subtrees.Length; i++)
{
clearChildren &= _subtrees[i]._children.Count == 0;
}
if (clearChildren)
{
_subtrees = new Octree<T>[8];
}
}
}
}
| |
namespace Appleseed.Framework.Content.Security
{
using System;
using System.Security.Cryptography;
/// <summary>
/// The random password ldap.
/// </summary>
public class RandomPasswordLdap
{
#region Constants and Fields
/// <summary>
/// The default max password length.
/// </summary>
private const int DefaultMaxPasswordLength = 10;
/// <summary>
/// The default min password length.
/// </summary>
private const int DefaultMinPasswordLength = 8;
/// <summary>
/// The password chars lcase.
/// </summary>
private const string PasswordCharsLcase = "abcdefgijkmnopqrstwxyz";
/// <summary>
/// The password chars numeric.
/// </summary>
private const string PasswordCharsNumeric = "23456789";
/// <summary>
/// The password chars special.
/// </summary>
private const string PasswordCharsSpecial = "*$-+?_&=!%{}/";
/// <summary>
/// The password chars ucase.
/// </summary>
private const string PasswordCharsUcase = "ABCDEFGHJKLMNPQRSTWXYZ";
#endregion
#region Public Methods
/// <summary>
/// Generates a random password.
/// </summary>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random. It will be no shorter than the minimum default and
/// no longer than maximum default.
/// </remarks>
public static string Generate()
{
return Generate(DefaultMinPasswordLength, DefaultMaxPasswordLength);
}
/// <summary>
/// Generates a random password of the exact length.
/// </summary>
/// <param name="length">
/// Exact password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
public static string Generate(int length)
{
return Generate(length, length);
}
/// <summary>
/// Generates a random password.
/// </summary>
/// <param name="minLength">
/// Minimum password length.
/// </param>
/// <param name="maxLength">
/// Maximum password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random and it will fall with the range determined by the
/// function parameters.
/// </remarks>
public static string Generate(int minLength, int maxLength)
{
// Make sure that input parameters are valid.
if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
{
return null;
}
// Create a local array containing supported password characters
// grouped by types. You can remove character groups from this
// array, but doing so will weaken the password strength.
var charGroups = new[]
{
PasswordCharsLcase.ToCharArray(),
PasswordCharsUcase.ToCharArray(),
PasswordCharsNumeric.ToCharArray(),
PasswordCharsSpecial.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
var charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for (var i = 0; i < charsLeftInGroup.Length; i++)
{
charsLeftInGroup[i] = charGroups[i].Length;
}
// Use this array to track (iterate through) unused character groups.
var leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for (var i = 0; i < leftGroupsOrder.Length; i++)
{
leftGroupsOrder[i] = i;
}
// Because we cannot use the default randomizer, which is based on the
// current time (it will produce the same "random" number within a
// second), we will use a random number generator to seed the
// randomizer.
// Use a 4-byte array to fill it with random bytes and convert it then
// to an integer value.
var randomBytes = new byte[4];
// Generate 4 random bytes.
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
var seed = (randomBytes[0] & 0x7f) << 24 | randomBytes[1] << 16 | randomBytes[2] << 8 | randomBytes[3];
// Now, this is real randomization.
var random = new Random(seed);
// This array will hold password characters.
// Allocate appropriate memory for the password.
var password = minLength < maxLength ? new char[random.Next(minLength, maxLength + 1)] : new char[minLength];
// Index of the last non-processed group.
var lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate password characters one at a time.
for (var i = 0; i < password.Length; i++)
{
// Index which will be used to track not processed character groups.
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list. To allow a special character to appear in the
// first position, increment the second parameter of the Next
// function call by one, i.e. lastLeftGroupsOrderIdx + 1.
var nextLeftGroupsOrderIdx = lastLeftGroupsOrderIdx == 0 ? 0 : random.Next(0, lastLeftGroupsOrderIdx);
// Index of the next character group to be processed.
// Get the actual index of the character group, from which we will
// pick the next character.
var nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Index of the last non-processed character in a group.
// Get the index of the last unprocessed characters in this group.
var lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// Index of the next character to be added to password.
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
var nextCharIdx = lastCharIdx == 0 ? 0 : random.Next(0, lastCharIdx + 1);
// Add this character to the password.
password[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if (lastCharIdx == 0)
{
charsLeftInGroup[nextGroupIdx] = charGroups[nextGroupIdx].Length;
}
else
{
// There are more unprocessed characters left.
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if (lastCharIdx != nextCharIdx)
{
var temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] = charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if (lastLeftGroupsOrderIdx == 0)
{
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
}
else
{
// There are more unprocessed groups left.
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
{
var temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] = leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(password);
}
#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.IO;
using Microsoft.Protocols.TestTools.StackSdk;
namespace Microsoft.Protocols.TestTools.StackSdk.Security.Pac
{
/// <summary>
/// The PACTYPE structure is the topmost structure of the
/// PAC and specifies the number of elements in the PAC_INFO_BUFFER
/// array. The PACTYPE structure serves as the header
/// for the complete PAC data.
/// </summary>
public class PacType : IHasInterrelatedFields
{
/// <summary>
/// TD section 2.3: "All PAC elements MUST be placed on an 8-byte boundary."
/// </summary>
private const int PacTypeAlignUnit = 8;
private PacInfoBuffer[] pacInfoBuffers;
/// <summary>
/// The native PACTYPE object.
/// </summary>
public PACTYPE NativePacType;
/// <summary>
/// The list of PacInfoBuffer objects contained in the PACTYPE structure.
/// </summary>
public PacInfoBuffer[] PacInfoBuffers
{
get
{
return pacInfoBuffers;
}
}
/// <summary>
/// Calculate Server checksum (TD section 2.8.1) of the PAC message,
/// place the checksum as a PacInfoBuffer whose ulType_Values is V3.
/// Then calculate KDC checksum (TD section 2.8.2) of the PAC message,
/// place the checksum as a PacInfoBuffer whose ulType_Values is V4.
/// </summary>
/// <param name="serverSignKey">The server signature key used to generate server signature.</param>
/// <param name="kdcSignKey">The KDC signature key used to generate KDC signature.</param>
/// <exception cref="ArgumentNullException">serverSignkey or kdcSignKey is null.</exception>
public void Sign(byte[] serverSignKey, byte[] kdcSignKey)
{
// locate server and KDC signatures.
PacSignatureData serverSign;
PacSignatureData kdcSign;
FindSignatures(out serverSign, out kdcSign);
// types
PAC_SIGNATURE_DATA_SignatureType_Values serversignType = serverSign.NativePacSignatureData.SignatureType;
PAC_SIGNATURE_DATA_SignatureType_Values kdcSignType = kdcSign.NativePacSignatureData.SignatureType;
// clear signatures.
int serverLength = PacSignatureData.CalculateSignatureLength(serversignType);
serverSign.NativePacSignatureData.Signature = new byte[serverLength];
int kdcLength = PacSignatureData.CalculateSignatureLength(kdcSignType);
kdcSign.NativePacSignatureData.Signature = new byte[kdcLength];
// sign server
byte[] serverSignResult = PacSignatureData.Sign(
ToBytes(), serversignType, serverSignKey);
serverSign.NativePacSignatureData.Signature = serverSignResult;
// sign KDC
kdcSign.NativePacSignatureData.Signature = PacSignatureData.Sign(
serverSignResult, kdcSignType, kdcSignKey);
}
/// <summary>
/// Verify Server checksum (TD section 2.8.1) and KDC checksum (TD section 2.8.2)
/// of the PAC message.
/// </summary>
/// <param name="serverSignKey">The server signature key used to generate server signature.</param>
/// <param name="kdcSignKey">The KDC signature key used to generate KDC signature.</param>
/// <param name="isServerSignValid">true if server signature is valid.</param>
/// <param name="isKdcSignValid">true if KDC signature is valid.</param>
/// <exception cref="ArgumentNullException">serverSignkey or kdcSignKey is null.</exception>
public void ValidateSign(byte[] serverSignKey, byte[] kdcSignKey,
out bool isServerSignValid, out bool isKdcSignValid)
{
if (serverSignKey == null)
{
throw new ArgumentNullException("serverSignKey");
}
if (kdcSignKey == null)
{
throw new ArgumentNullException("kdcSignKey");
}
// locate server and KDC signatures.
PacSignatureData serverSign;
PacSignatureData kdcSign;
FindSignatures(out serverSign, out kdcSign);
// these validate operation will change signature values, so must backup and restore.
byte[] oldServerSign = null;
byte[] oldKdcSign = null;
isServerSignValid = false;
isKdcSignValid = false;
try
{
// types
PAC_SIGNATURE_DATA_SignatureType_Values serverSignType = serverSign.NativePacSignatureData.SignatureType;
PAC_SIGNATURE_DATA_SignatureType_Values kdcSignType = kdcSign.NativePacSignatureData.SignatureType;
// backup and clear signatures.
int serverLength = PacSignatureData.CalculateSignatureLength(serverSignType);
oldServerSign = serverSign.NativePacSignatureData.Signature;
serverSign.NativePacSignatureData.Signature = new byte[serverLength];
int kdcLength = PacSignatureData.CalculateSignatureLength(kdcSignType);
oldKdcSign = kdcSign.NativePacSignatureData.Signature;
kdcSign.NativePacSignatureData.Signature = new byte[kdcLength];
// validate server sign
byte[] serverSignResult = PacSignatureData.Sign(
ToBytes(), serverSignType, serverSignKey);
isServerSignValid = ArrayUtility.CompareArrays<byte>(serverSignResult, oldServerSign);
// validate KDC sign
byte[] kdcSignResult = PacSignatureData.Sign(
serverSignResult, kdcSignType, kdcSignKey);
isKdcSignValid = ArrayUtility.CompareArrays<byte>(kdcSignResult, oldKdcSign);
}
finally
{
// restore server signature
if (oldServerSign != null)
{
serverSign.NativePacSignatureData.Signature = oldServerSign;
}
// restore KDC signature
if (oldKdcSign != null)
{
kdcSign.NativePacSignatureData.Signature = oldKdcSign;
}
}
}
/// <summary>
/// Encode the instance of current class into bytes.
/// </summary>
/// <returns>The encoded bytes.</returns>
public byte[] ToBytes()
{
UpdateInterrelatedFields();
byte[] header = PacUtility.ObjectToMemory(NativePacType);
byte[][] bodyReferences = new byte[NativePacType.cBuffers][];
for (int i = 0; i < NativePacType.cBuffers; i++)
{
if (pacInfoBuffers[i] == null) continue;
bodyReferences[i] = pacInfoBuffers[i].EncodeBuffer();
int length = bodyReferences[i].Length;
// double check the totalLength
// NativePacType.Buffers[index].cbBufferSize has been updated in previous
// UpdateInterrelatedFields() method, given by each pacInfoBuffer's
// CalculateSize() method.
// following evaluation double check whether CalculateSize() method's
// result conforms to EncodeBuffer() method's result.
// Note: some kind of pacInfoBuffers return EncodeBuffer().Length as the
// CalculateSize(), such as NDR encoded structures. But some other
// pacInfoBuffers can calculate totalLength without encoding the structure.
AssertBufferSize(NativePacType.Buffers, i, length);
}
return ConcatenateBuffers(header, bodyReferences);
}
#region IHasInterrelatedFields Members
/// <summary>
/// Update cbBufferSize and Offset of all PAC_INFO_BUFFERs
/// after the buffers' content updated.
/// </summary>
public void UpdateInterrelatedFields()
{
AssertBuffersCount(pacInfoBuffers.Length, NativePacType.Buffers.Length);
int offset = CalculateHeaderSize();
for (int i = 0; i < pacInfoBuffers.Length; i++)
{
NativePacType.Buffers[i].Offset = (ulong)offset;
if (pacInfoBuffers[i] == null) continue;
int size = pacInfoBuffers[i].CalculateSize();
NativePacType.Buffers[i].cbBufferSize = (uint)size;
offset += size;
//TD section 2.3: "All PAC elements MUST be placed on an 8-byte boundary."
offset = PacUtility.AlignTo(offset, PacTypeAlignUnit);
}
}
#endregion
#region Internal Methods
/// <summary>
/// Construct an instance of current class by decoding specified bytes.
/// </summary>
/// <param name="buffer">The specified bytes.</param>
internal PacType(byte[] buffer)
{
NativePacType = PacUtility.MemoryToObject<PACTYPE>(buffer);
pacInfoBuffers = new PacInfoBuffer[NativePacType.Buffers.Length];
for (int i = 0; i < NativePacType.Buffers.Length; ++i)
{
if (NativePacType.Buffers[i].cbBufferSize > 0)
{
PacInfoBuffers[i] = PacInfoBuffer.DecodeBuffer(
NativePacType.Buffers[i],
buffer);
}
else PacInfoBuffers[i] = null;
}
}
/// <summary>
/// Creates an PacType instance using the specified signature types and PacInfoBuffers
/// </summary>
/// <param name="serverSignatureType">Server signature signatureType.</param>
/// <param name="serverSignKey">The server signature key used to generate server signature.</param>
/// <param name="kdcSignatureType">KDC signature Type.</param>
/// <param name="kdcSignKey">The KDC signature key used to generate KDC signature.</param>
/// <param name="buffers">A list of PacInfoBuffer used to create the PacType.
/// Note: DO NOT include the signatures (server signature and KDC signature)!</param>
/// <returns>The created PacType instance.</returns>
internal PacType(
PAC_SIGNATURE_DATA_SignatureType_Values serverSignatureType,
byte[] serverSignKey,
PAC_SIGNATURE_DATA_SignatureType_Values kdcSignatureType,
byte[] kdcSignKey,
params PacInfoBuffer[] buffers)
{
if (buffers == null || buffers.Length == 0)
{
throw new ArgumentNullException("buffers");
}
InitializePacInfoBuffers(serverSignatureType, kdcSignatureType, buffers);
InitializeNativePacType();
Sign(serverSignKey, kdcSignKey);
// after Sign(), the contentd of signature buffers are filled,
// and the lengths of which are changed.
// Then update interrelated fields, mainly totalLength and offset.
UpdateInterrelatedFields();
}
#endregion
#region Private Methods
/// <summary>
/// In constructor, initialize the native PACTYPE structure.
/// </summary>
private void InitializeNativePacType()
{
NativePacType = new PACTYPE();
NativePacType.Version = PACTYPE_Version_Values.V1;
NativePacType.cBuffers = (uint)pacInfoBuffers.Length;
NativePacType.Buffers = new PAC_INFO_BUFFER[pacInfoBuffers.Length];
for (int i = 0; i < pacInfoBuffers.Length; i++)
{
NativePacType.Buffers[i] = pacInfoBuffers[i].CreateNativeInfoBuffer();
}
}
/// <summary>
/// In constructor, initialize the member PacInfoBuffer array.
/// </summary>
/// <param name="serverSignatureType">The specified
/// Server Signature Type.</param>
/// <param name="kdcSignatureType">The specified
/// KDC Signature Type.</param>
/// <param name="buffers">PacInfoBuffers not including signatures.</param>
private void InitializePacInfoBuffers(
PAC_SIGNATURE_DATA_SignatureType_Values serverSignatureType,
PAC_SIGNATURE_DATA_SignatureType_Values kdcSignatureType,
PacInfoBuffer[] buffers)
{
// allocate 2 more buffers for server signature and KDC signature.
pacInfoBuffers = new PacInfoBuffer[buffers.Length + 2];
for (int i = 0; i < buffers.Length; i++)
{
pacInfoBuffers[i] = buffers[i];
}
// construct a n empty server signature
PacServerSignature serverSign = new PacServerSignature();
serverSign.NativePacSignatureData.SignatureType = serverSignatureType;
serverSign.NativePacSignatureData.Signature = new byte[0];
pacInfoBuffers[pacInfoBuffers.Length - 2] = serverSign;
// construct a n empty KDC signature
PacKdcSignature kdcSign = new PacKdcSignature();
kdcSign.NativePacSignatureData.SignatureType = kdcSignatureType;
kdcSign.NativePacSignatureData.Signature = new byte[0];
pacInfoBuffers[pacInfoBuffers.Length - 1] = kdcSign;
}
/// <summary>
/// Concatenate specified header buffer and specified body buffers.
/// </summary>
/// <param name="header">The specified header buffer.</param>
/// <param name="bodyReferences">The specified body buffers.</param>
/// <returns>The integrated buffer.</returns>
private byte[] ConcatenateBuffers(byte[] header, byte[][] bodyReferences)
{
// calculate total totalLength
int totalLength = header.Length;
for (int i = 0; i < NativePacType.cBuffers; i++)
{
if (bodyReferences[i] == null) continue;
int length = bodyReferences[i].Length;
// double check the length
// NativePacType.Buffers[index].cbBufferSize has been updated in previous
// UpdateInterrelatedFields() method, given by each pacInfoBuffer's
// CalculateSize() method.
// following evaluation double check whether CalculateSize() method's
// result conforms to EncodeBuffer() method's result.
// Note: some kind of pacInfoBuffers return EncodeBuffer().Length as the
// CalculateSize(), such as NDR encoded structures. But some other
// pacInfoBuffers can calculate totalLength without encoding the structure.
AssertBufferSize(NativePacType.Buffers, i, length);
totalLength += PacUtility.AlignTo(length, PacTypeAlignUnit);
}
byte[] total = new byte[totalLength];
int offset = 0;
Buffer.BlockCopy(header, 0, total, offset, header.Length);
offset += header.Length;
for (int i = 0; i < bodyReferences.Length; ++i)
{
if (bodyReferences[i] == null) continue;
int length = bodyReferences[i].Length;
Buffer.BlockCopy(bodyReferences[i], 0, total, offset, length);
offset += PacUtility.AlignTo(length, PacTypeAlignUnit);
}
return total;
}
/// <summary>
/// Assert buffers[index].cbBufferSiz == length.
/// Else throw ArgumentException.
/// </summary>
/// <param name="buffers">The specified PAC_INFO_BUFFER[] array.</param>
/// <param name="index">The specified array index.</param>
/// <param name="length">The expected length of array element's cbBufferSize.</param>
private static void AssertBufferSize(PAC_INFO_BUFFER[] buffers, int index, int length)
{
if (buffers[index].cbBufferSize != length)
{
throw new ArgumentException(
string.Format("NativePacType.Buffers[{0}].cbBufferSize {1} != length {2}",
index,
buffers[index].cbBufferSize,
length));
}
}
/// <summary>
/// Assert buffers' count actual is expected.
/// </summary>
/// <param name="expected">The expected buffers' count.</param>
/// <param name="actual">The actual buffers' count.</param>
private static void AssertBuffersCount(int expected, int actual)
{
if (expected != actual)
{
throw new ArgumentException(
string.Format("pacInfoBuffers.Length {0} != NativePacType.Buffers.Length {1}",
expected,
actual));
}
}
/// <summary>
/// Calculate the header buffer's size, in bytes.
/// </summary>
/// <returns>The header buffer's size, in bytes.</returns>
private int CalculateHeaderSize()
{
// uint CBuffers and Versions
int pacTypeHeaderSize = sizeof(uint) + sizeof(PACTYPE_Version_Values);
// uint PacInfoType and CbBufferSize, ulong Offset
long infoBufferHeaderSize = sizeof(PAC_INFO_BUFFER_Type_Values) + sizeof(uint) + sizeof(ulong);
return (int)(pacTypeHeaderSize + infoBufferHeaderSize * NativePacType.cBuffers);
}
/// <summary>
/// Find Server Signature and KDC signature.
/// </summary>
/// <param name="serverSign">The found Server Signature.</param>
/// <param name="kdcSign">The found KDC Signature.</param>
private void FindSignatures(out PacSignatureData serverSign, out PacSignatureData kdcSign)
{
serverSign = null;
kdcSign = null;
foreach (PacInfoBuffer infoBuffer in pacInfoBuffers)
{
if (infoBuffer == null) continue;
PAC_INFO_BUFFER_Type_Values ulType = infoBuffer.GetBufferInfoType();
if (ulType == PAC_INFO_BUFFER_Type_Values.ServerChecksum || ulType == PAC_INFO_BUFFER_Type_Values.KdcChecksum)
{
PacSignatureData sign = (PacSignatureData)infoBuffer;
if (ulType == PAC_INFO_BUFFER_Type_Values.ServerChecksum)
{
serverSign = sign;
}
else
{
kdcSign = sign;
}
}
}
AssertSignsNotNull(serverSign, kdcSign);
}
/// <summary>
/// Assert signatures are not null.
/// </summary>
/// <param name="serverSign">Server signature to be asserted.</param>
/// <param name="kdcSign">KDC signature to be asserted.</param>
private static void AssertSignsNotNull(PacSignatureData serverSign, PacSignatureData kdcSign)
{
if (serverSign == null)
{
throw new ArgumentException("server signature is not found");
}
if (kdcSign == null)
{
throw new ArgumentException("KDC signature is not found");
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureReport
{
using System.Linq;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestReportServiceForAzure : Microsoft.Rest.ServiceClient<AutoRestReportServiceForAzure>, IAutoRestReportServiceForAzure, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestReportServiceForAzure(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestReportServiceForAzure(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestReportServiceForAzure(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestReportServiceForAzure(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("http://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
/// <summary>
/// Get test coverage report
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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 (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, int?>>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IDictionary<string, int?>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.CustomerInsights
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for InteractionsOperations.
/// </summary>
public static partial class InteractionsOperationsExtensions
{
/// <summary>
/// Creates an interaction or updates an existing interaction within a hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate Interaction operation.
/// </param>
public static InteractionResourceFormat CreateOrUpdate(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName, InteractionResourceFormat parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, hubName, interactionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates an interaction or updates an existing interaction within a hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate Interaction operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<InteractionResourceFormat> CreateOrUpdateAsync(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName, InteractionResourceFormat parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, interactionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the specified interaction.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
/// <param name='localeCode'>
/// Locale of interaction to retrieve, default is en-us.
/// </param>
public static InteractionResourceFormat Get(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName, string localeCode = "en-us")
{
return operations.GetAsync(resourceGroupName, hubName, interactionName, localeCode).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified interaction.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
/// <param name='localeCode'>
/// Locale of interaction to retrieve, default is en-us.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<InteractionResourceFormat> GetAsync(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName, string localeCode = "en-us", CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, hubName, interactionName, localeCode, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all interactions in the hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='localeCode'>
/// Locale of interaction to retrieve, default is en-us.
/// </param>
public static IPage<InteractionResourceFormat> ListByHub(this IInteractionsOperations operations, string resourceGroupName, string hubName, string localeCode = "en-us")
{
return operations.ListByHubAsync(resourceGroupName, hubName, localeCode).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all interactions in the hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='localeCode'>
/// Locale of interaction to retrieve, default is en-us.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<InteractionResourceFormat>> ListByHubAsync(this IInteractionsOperations operations, string resourceGroupName, string hubName, string localeCode = "en-us", CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByHubWithHttpMessagesAsync(resourceGroupName, hubName, localeCode, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Suggests relationships to create relationship links.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
public static SuggestRelationshipLinksResponse SuggestRelationshipLinks(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName)
{
return operations.SuggestRelationshipLinksAsync(resourceGroupName, hubName, interactionName).GetAwaiter().GetResult();
}
/// <summary>
/// Suggests relationships to create relationship links.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SuggestRelationshipLinksResponse> SuggestRelationshipLinksAsync(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.SuggestRelationshipLinksWithHttpMessagesAsync(resourceGroupName, hubName, interactionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an interaction or updates an existing interaction within a hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate Interaction operation.
/// </param>
public static InteractionResourceFormat BeginCreateOrUpdate(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName, InteractionResourceFormat parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, hubName, interactionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates an interaction or updates an existing interaction within a hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='interactionName'>
/// The name of the interaction.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate Interaction operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<InteractionResourceFormat> BeginCreateOrUpdateAsync(this IInteractionsOperations operations, string resourceGroupName, string hubName, string interactionName, InteractionResourceFormat parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, interactionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all interactions in the hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<InteractionResourceFormat> ListByHubNext(this IInteractionsOperations operations, string nextPageLink)
{
return operations.ListByHubNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all interactions in the hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<InteractionResourceFormat>> ListByHubNextAsync(this IInteractionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByHubNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.Text;
using System.Diagnostics;
namespace Internal.TypeSystem
{
public sealed partial class InstantiatedType : MetadataType
{
private MetadataType _typeDef;
private Instantiation _instantiation;
internal InstantiatedType(MetadataType typeDef, Instantiation instantiation)
{
Debug.Assert(!(typeDef is InstantiatedType));
_typeDef = typeDef;
Debug.Assert(instantiation.Length > 0);
_instantiation = instantiation;
_baseType = this; // Not yet initialized flag
}
private int _hashCode;
public override int GetHashCode()
{
if (_hashCode == 0)
_hashCode = _instantiation.ComputeGenericInstanceHashCode(_typeDef.GetHashCode());
return _hashCode;
}
public override TypeSystemContext Context
{
get
{
return _typeDef.Context;
}
}
public override Instantiation Instantiation
{
get
{
return _instantiation;
}
}
private MetadataType _baseType /* = this */;
private MetadataType InitializeBaseType()
{
var uninst = _typeDef.MetadataBaseType;
return (_baseType = (uninst != null) ? (MetadataType)uninst.InstantiateSignature(_instantiation, new Instantiation()) : null);
}
public override DefType BaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
public override MetadataType MetadataBaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.CategoryMask) != 0)
{
flags |= _typeDef.Category;
}
if ((mask & TypeFlags.HasGenericVarianceComputed) != 0)
{
flags |= TypeFlags.HasGenericVarianceComputed;
if (_typeDef.HasVariance)
flags |= TypeFlags.HasGenericVariance;
}
if ((mask & TypeFlags.HasFinalizerComputed) != 0)
{
flags |= TypeFlags.HasFinalizerComputed;
if (_typeDef.HasFinalizer)
flags |= TypeFlags.HasFinalizer;
}
if ((mask & TypeFlags.IsByRefLikeComputed) != 0)
{
flags |= TypeFlags.IsByRefLikeComputed;
if (_typeDef.IsByRefLike)
flags |= TypeFlags.IsByRefLike;
}
return flags;
}
public override string Name
{
get
{
return _typeDef.Name;
}
}
public override string Namespace
{
get
{
return _typeDef.Namespace;
}
}
public override IEnumerable<MethodDesc> GetMethods()
{
foreach (var typicalMethodDef in _typeDef.GetMethods())
{
yield return _typeDef.Context.GetMethodForInstantiatedType(typicalMethodDef, this);
}
}
// TODO: Substitutions, generics, modopts, ...
public override MethodDesc GetMethod(string name, MethodSignature signature)
{
MethodDesc typicalMethodDef = _typeDef.GetMethod(name, signature);
if (typicalMethodDef == null)
return null;
return _typeDef.Context.GetMethodForInstantiatedType(typicalMethodDef, this);
}
public override MethodDesc GetStaticConstructor()
{
MethodDesc typicalCctor = _typeDef.GetStaticConstructor();
if (typicalCctor == null)
return null;
return _typeDef.Context.GetMethodForInstantiatedType(typicalCctor, this);
}
public override MethodDesc GetDefaultConstructor()
{
MethodDesc typicalCtor = _typeDef.GetDefaultConstructor();
if (typicalCtor == null)
return null;
return _typeDef.Context.GetMethodForInstantiatedType(typicalCtor, this);
}
public override MethodDesc GetFinalizer()
{
MethodDesc typicalFinalizer = _typeDef.GetFinalizer();
if (typicalFinalizer == null)
return null;
MetadataType typeInHierarchy = this;
// Note, we go back to the type definition/typical method definition in this code.
// If the finalizer is implemented on a base type that is also a generic, then the
// typicalFinalizer in that case is a MethodForInstantiatedType for an instantiated type
// which is instantiated over the open type variables of the derived type.
while (typicalFinalizer.OwningType.GetTypeDefinition() != typeInHierarchy.GetTypeDefinition())
{
typeInHierarchy = typeInHierarchy.MetadataBaseType;
}
if (typeInHierarchy == typicalFinalizer.OwningType)
{
return typicalFinalizer;
}
else
{
Debug.Assert(typeInHierarchy is InstantiatedType);
return _typeDef.Context.GetMethodForInstantiatedType(typicalFinalizer.GetTypicalMethodDefinition(), (InstantiatedType)typeInHierarchy);
}
}
public override IEnumerable<FieldDesc> GetFields()
{
foreach (var fieldDef in _typeDef.GetFields())
{
yield return _typeDef.Context.GetFieldForInstantiatedType(fieldDef, this);
}
}
// TODO: Substitutions, generics, modopts, ...
public override FieldDesc GetField(string name)
{
FieldDesc fieldDef = _typeDef.GetField(name);
if (fieldDef == null)
return null;
return _typeDef.Context.GetFieldForInstantiatedType(fieldDef, this);
}
public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc[] clone = null;
for (int i = 0; i < _instantiation.Length; i++)
{
TypeDesc uninst = _instantiation[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new TypeDesc[_instantiation.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = _instantiation[j];
}
}
clone[i] = inst;
}
}
return (clone == null) ? this : _typeDef.Context.GetInstantiatedType(_typeDef, new Instantiation(clone));
}
/// <summary>
/// Instantiate an array of TypeDescs over typeInstantiation and methodInstantiation
/// </summary>
public static T[] InstantiateTypeArray<T>(T[] uninstantiatedTypes, Instantiation typeInstantiation, Instantiation methodInstantiation) where T : TypeDesc
{
T[] clone = null;
for (int i = 0; i < uninstantiatedTypes.Length; i++)
{
T uninst = uninstantiatedTypes[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new T[uninstantiatedTypes.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = uninstantiatedTypes[j];
}
}
clone[i] = (T)inst;
}
}
return clone != null ? clone : uninstantiatedTypes;
}
// Strips instantiation. E.g C<int> -> C<T>
public override TypeDesc GetTypeDefinition()
{
return _typeDef;
}
public override string ToString()
{
var sb = new StringBuilder(_typeDef.ToString());
sb.Append('<');
sb.Append(_instantiation.ToString());
sb.Append('>');
return sb.ToString();
}
// Properties that are passed through from the type definition
public override ClassLayoutMetadata GetClassLayout()
{
return _typeDef.GetClassLayout();
}
public override bool IsExplicitLayout
{
get
{
return _typeDef.IsExplicitLayout;
}
}
public override bool IsSequentialLayout
{
get
{
return _typeDef.IsSequentialLayout;
}
}
public override bool IsBeforeFieldInit
{
get
{
return _typeDef.IsBeforeFieldInit;
}
}
public override bool IsModuleType
{
get
{
// The global module type cannot be generic.
return false;
}
}
public override bool IsSealed
{
get
{
return _typeDef.IsSealed;
}
}
public override bool IsAbstract
{
get
{
return _typeDef.IsAbstract;
}
}
public override ModuleDesc Module
{
get
{
return _typeDef.Module;
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return _typeDef.HasCustomAttribute(attributeNamespace, attributeName);
}
public override DefType ContainingType
{
get
{
// Return the result from the typical type definition.
return _typeDef.ContainingType;
}
}
public override MetadataType GetNestedType(string name)
{
// Return the result from the typical type definition.
return _typeDef.GetNestedType(name);
}
public override IEnumerable<MetadataType> GetNestedTypes()
{
// Return the result from the typical type definition.
return _typeDef.GetNestedTypes();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedAdapter
{
using System.Collections.Generic;
/// <summary>
/// Storage Index data element
/// </summary>
public class StorageIndexDataElementData : DataElementData
{
/// <summary>
/// Initializes a new instance of the StorageIndexDataElementData class.
/// </summary>
public StorageIndexDataElementData()
{
this.StorageIndexManifestMapping = new StorageIndexManifestMapping();
this.StorageIndexCellMappingList = new List<StorageIndexCellMapping>();
this.StorageIndexRevisionMappingList = new List<StorageIndexRevisionMapping>();
}
/// <summary>
/// Gets or sets the storage index manifest mappings (with manifest mapping extended GUID and serial number).
/// </summary>
public StorageIndexManifestMapping StorageIndexManifestMapping { get; set; }
/// <summary>
/// Gets or sets storage index manifest mappings.
/// </summary>
public List<StorageIndexCellMapping> StorageIndexCellMappingList { get; set; }
/// <summary>
/// Gets or sets the list of storage index revision mappings (with revision and revision mapping extended GUIDs, and revision mapping serial number).
/// </summary>
public List<StorageIndexRevisionMapping> StorageIndexRevisionMappingList { get; set; }
/// <summary>
/// Used to convert the element into a byte List.
/// </summary>
/// <returns>A Byte list</returns>
public override List<byte> SerializeToByteList()
{
List<byte> byteList = new List<byte>();
if (this.StorageIndexManifestMapping != null)
{
byteList.AddRange(this.StorageIndexManifestMapping.SerializeToByteList());
}
if (this.StorageIndexCellMappingList != null)
{
foreach (StorageIndexCellMapping cellMapping in this.StorageIndexCellMappingList)
{
byteList.AddRange(cellMapping.SerializeToByteList());
}
}
// Storage Index Revision Mapping
if (this.StorageIndexRevisionMappingList != null)
{
foreach (StorageIndexRevisionMapping revisionMapping in this.StorageIndexRevisionMappingList)
{
byteList.AddRange(revisionMapping.SerializeToByteList());
}
}
return byteList;
}
/// <summary>
/// Used to de-serialize the data element.
/// </summary>
/// <param name="byteArray">Byte array</param>
/// <param name="startIndex">Start position</param>
/// <returns>The length of the element</returns>
public override int DeserializeDataElementDataFromByteArray(byte[] byteArray, int startIndex)
{
int index = startIndex;
int headerLength = 0;
StreamObjectHeaderStart header;
bool isStorageIndexManifestMappingExist = false;
while ((headerLength = StreamObjectHeaderStart.TryParse(byteArray, index, out header)) != 0)
{
index += headerLength;
if (header.Type == StreamObjectTypeHeaderStart.StorageIndexManifestMapping)
{
if (isStorageIndexManifestMappingExist)
{
throw new DataElementParseErrorException(index - headerLength, "Failed to parse StorageIndexDataElement, only can contain zero or one StorageIndexManifestMapping", null);
}
this.StorageIndexManifestMapping = StreamObject.ParseStreamObject(header, byteArray, ref index) as StorageIndexManifestMapping;
isStorageIndexManifestMappingExist = true;
}
else if (header.Type == StreamObjectTypeHeaderStart.StorageIndexCellMapping)
{
this.StorageIndexCellMappingList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as StorageIndexCellMapping);
}
else if (header.Type == StreamObjectTypeHeaderStart.StorageIndexRevisionMapping)
{
this.StorageIndexRevisionMappingList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as StorageIndexRevisionMapping);
}
else
{
throw new DataElementParseErrorException(index - headerLength, "Failed to parse StorageIndexDataElement, expect the inner object type StorageIndexCellMapping or StorageIndexRevisionMapping, but actual type value is " + header.Type, null);
}
}
return index - startIndex;
}
}
/// <summary>
/// Specifies the storage index manifest mappings (with manifest mapping extended GUID and serial number).
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Easy to maintain one group of classes in one .cs file.")]
public class StorageIndexManifestMapping : StreamObject
{
/// <summary>
/// Initializes a new instance of the StorageIndexManifestMapping class.
/// </summary>
public StorageIndexManifestMapping()
: base(StreamObjectTypeHeaderStart.StorageIndexManifestMapping)
{
}
/// <summary>
/// Gets or sets the extended GUID of the manifest mapping.
/// </summary>
public ExGuid ManifestMappingExtendedGUID { get; set; }
/// <summary>
/// Gets or sets the serial number of the manifest mapping.
/// </summary>
public SerialNumber ManifestMappingSerialNumber { get; set; }
/// <summary>
/// Used to Deserialize the items.
/// </summary>
/// <param name="byteArray">Byte array</param>
/// <param name="currentIndex">Start position</param>
/// <param name="lengthOfItems">The length of the items</param>
protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems)
{
int index = currentIndex;
this.ManifestMappingExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index);
this.ManifestMappingSerialNumber = BasicObject.Parse<SerialNumber>(byteArray, ref index);
if (index - currentIndex != lengthOfItems)
{
throw new StreamObjectParseErrorException(currentIndex, "StorageIndexManifestMapping", "Stream object over-parse error", null);
}
currentIndex = index;
}
/// <summary>
/// Used to convert the element into a byte List.
/// </summary>
/// <param name="byteList">A Byte list</param>
/// <returns>The length of list</returns>
protected override int SerializeItemsToByteList(List<byte> byteList)
{
int itemsIndex = byteList.Count;
byteList.AddRange(this.ManifestMappingExtendedGUID.SerializeToByteList());
byteList.AddRange(this.ManifestMappingSerialNumber.SerializeToByteList());
return byteList.Count - itemsIndex;
}
}
/// <summary>
/// Specifies the storage index cell mappings (with cell identifier, cell mapping extended GUID, and cell mapping serial number).
/// </summary>
public class StorageIndexCellMapping : StreamObject
{
/// <summary>
/// Initializes a new instance of the StorageIndexCellMapping class.
/// </summary>
public StorageIndexCellMapping()
: base(StreamObjectTypeHeaderStart.StorageIndexCellMapping)
{
}
/// <summary>
/// Gets or sets the cell identifier.
/// </summary>
public CellID CellID { get; set; }
/// <summary>
/// Gets or sets the extended GUID of the cell mapping.
/// </summary>
public ExGuid CellMappingExtendedGUID { get; set; }
/// <summary>
/// Gets or sets the serial number of the cell mapping.
/// </summary>
public SerialNumber CellMappingSerialNumber { get; set; }
/// <summary>
/// Used to de-serialize the items.
/// </summary>
/// <param name="byteArray">A Byte array</param>
/// <param name="currentIndex">Start position</param>
/// <param name="lengthOfItems">The length of the items</param>
protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems)
{
int index = currentIndex;
this.CellID = BasicObject.Parse<CellID>(byteArray, ref index);
this.CellMappingExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index);
this.CellMappingSerialNumber = BasicObject.Parse<SerialNumber>(byteArray, ref index);
if (index - currentIndex != lengthOfItems)
{
throw new StreamObjectParseErrorException(currentIndex, "StorageIndexCellMapping", "Stream object over-parse error", null);
}
currentIndex = index;
}
/// <summary>
/// Used to convert the element into a byte List.
/// </summary>
/// <param name="byteList">A Byte list</param>
/// <returns>The length of list</returns>
protected override int SerializeItemsToByteList(List<byte> byteList)
{
int itemsIndex = byteList.Count;
byteList.AddRange(this.CellID.SerializeToByteList());
byteList.AddRange(this.CellMappingExtendedGUID.SerializeToByteList());
byteList.AddRange(this.CellMappingSerialNumber.SerializeToByteList());
return byteList.Count - itemsIndex;
}
}
/// <summary>
/// Specifies the storage index revision mappings (with revision and revision mapping extended GUIDs, and revision mapping serial number).
/// </summary>
public class StorageIndexRevisionMapping : StreamObject
{
/// <summary>
/// Initializes a new instance of the StorageIndexRevisionMapping class.
/// </summary>
public StorageIndexRevisionMapping()
: base(StreamObjectTypeHeaderStart.StorageIndexRevisionMapping)
{
}
/// <summary>
/// Gets or sets the extended GUID of the revision.
/// </summary>
public ExGuid RevisionExtendedGUID { get; set; }
/// <summary>
/// Gets or sets the extended GUID of the revision mapping.
/// </summary>
public ExGuid RevisionMappingExtendedGUID { get; set; }
/// <summary>
/// Gets or sets the serial number of the revision mapping.
/// </summary>
public SerialNumber RevisionMappingSerialNumber { get; set; }
/// <summary>
/// Used to de-serialize the items
/// </summary>
/// <param name="byteArray">A Byte array</param>
/// <param name="currentIndex">Start position</param>
/// <param name="lengthOfItems">The length of the items</param>
protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems)
{
int index = currentIndex;
this.RevisionExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index);
this.RevisionMappingExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index);
this.RevisionMappingSerialNumber = BasicObject.Parse<SerialNumber>(byteArray, ref index);
if (index - currentIndex != lengthOfItems)
{
throw new StreamObjectParseErrorException(currentIndex, "StorageIndexRevisionMapping", "Stream object over-parse error", null);
}
currentIndex = index;
}
/// <summary>
/// Used to convert the element into a byte List.
/// </summary>
/// <param name="byteList">A Byte list</param>
/// <returns>The length of list</returns>
protected override int SerializeItemsToByteList(List<byte> byteList)
{
int itemsIndex = byteList.Count;
byteList.AddRange(this.RevisionExtendedGUID.SerializeToByteList());
byteList.AddRange(this.RevisionMappingExtendedGUID.SerializeToByteList());
byteList.AddRange(this.RevisionMappingSerialNumber.SerializeToByteList());
return byteList.Count - itemsIndex;
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (http://www.novell.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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
namespace NDesk.Options {
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split ('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
for (int i = 0; i < names.Length; i++)
names[i] = names[i].ToLower();
}
public string Prototype { get { return prototype; } }
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
TypeConverter conv = TypeDescriptor.GetConverter (typeof (T));
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, typeof (T).Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
[Serializable]
public class OptionException : Exception {
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
public string OptionName {
get {return this.option;}
}
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet ()
: this (delegate (string f) {return f;})
{
}
public OptionSet (Converter<string, string> localizer)
{
this.localizer = localizer;
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer {
get {return localizer;}
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
base.RemoveItem (index);
Option p = Items [index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
RemoveItem (index);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
#if LINQ
public List<string> Parse (IEnumerable<string> arguments)
{
bool process = true;
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
var def = GetOptionForName ("<>");
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse (argument, c)
? def != null
? Unprocessed (null, def, c, argument)
: true
: false
: def != null
? Unprocessed (null, def, c, argument)
: true
: true
select argument;
List<string> r = unprocessed.ToList ();
if (c.Option != null)
c.Option.Invoke (c);
return r;
}
#else
public List<string> Parse (IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
foreach (string argument in arguments) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
#endif
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
List<string> lines = GetLines (localizer (GetDescription (p.Description)));
o.WriteLine (lines [0]);
string prefix = new string (' ', OptionWidth+2);
for (int i = 1; i < lines.Count; ++i) {
o.Write (prefix);
o.WriteLine (lines [i]);
}
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static List<string> GetLines (string description)
{
List<string> lines = new List<string> ();
if (string.IsNullOrEmpty (description)) {
lines.Add (string.Empty);
return lines;
}
int length = 80 - OptionWidth - 2;
int start = 0, end;
do {
end = GetLineEnd (start, length, description);
bool cont = false;
if (end < description.Length) {
char c = description [end];
if (c == '-' || (char.IsWhiteSpace (c) && c != '\n'))
++end;
else if (c != '\n') {
cont = true;
--end;
}
}
lines.Add (description.Substring (start, end - start));
if (cont) {
lines [lines.Count-1] += "-";
}
start = end;
if (start < description.Length && description [start] == '\n')
++start;
} while (end < description.Length);
return lines;
}
private static int GetLineEnd (int start, int length, string description)
{
int end = Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i) {
switch (description [i]) {
case ' ':
case '\t':
case '\v':
case '-':
case ',':
case '.':
case ';':
sep = i;
break;
case '\n':
return i;
}
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
// 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 Xunit;
namespace System.Numerics.Tests
{
public class modpowTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void ModPowValidSmallNumbers()
{
BigInteger result;
bool b = BigInteger.TryParse("22", out result);
// ModPow Method - with small numbers - valid
for (int i = 1; i <= 1; i++)//-2
{
for (int j = 0; j <= 1; j++)//2
{
for (int k = 1; k <= 1; k++)
{
if (k != 0)
{
VerifyModPowString(k.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow");
}
}
}
}
}
[Fact]
public static void ModPowNegative()
{
byte[] tempByteArray1;
byte[] tempByteArray2;
byte[] tempByteArray3;
// ModPow Method - with small numbers - invalid - zero modulus
for (int i = -2; i <= 2; i++)
{
for (int j = 0; j <= 2; j++)
{
Assert.Throws<DivideByZeroException>(() =>
{
VerifyModPowString(BigInteger.Zero.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow");
});
}
}
// ModPow Method - with small numbers - invalid - negative exponent
for (int i = -2; i <= 2; i++)
{
for (int j = -2; j <= -1; j++)
{
for (int k = -2; k <= 2; k++)
{
if (k != 0)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyModPowString(k.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow");
});
}
}
}
}
// ModPow Method - Negative Exponent
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomNegByteArray(s_random, 2);
tempByteArray3 = GetRandomByteArray(s_random);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
});
}
// ModPow Method - Zero Modulus
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomPosByteArray(s_random, 1);
Assert.Throws<DivideByZeroException>(() =>
{
VerifyModPowString(BigInteger.Zero.ToString() + " " + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
});
}
}
[Fact]
public static void ModPow3SmallInt()
{
byte[] tempByteArray1;
byte[] tempByteArray2;
byte[] tempByteArray3;
// ModPow Method - Three Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random, 2);
tempByteArray3 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
}
}
[Fact]
public static void ModPow1Large2SmallInt()
{
byte[] tempByteArray1;
byte[] tempByteArray2;
byte[] tempByteArray3;
// ModPow Method - One large and two small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random);
tempByteArray3 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomPosByteArray(s_random, 2);
tempByteArray3 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random, 1);
tempByteArray3 = GetRandomByteArray(s_random);
VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void ModPow1Large2SmallInt_Threshold()
{
// Again, with lower threshold
BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, ModPow1Large2SmallInt);
}
[Fact]
public static void ModPow2Large1SmallInt()
{
byte[] tempByteArray1;
byte[] tempByteArray2;
byte[] tempByteArray3;
// ModPow Method - Two large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomPosByteArray(s_random);
tempByteArray3 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void ModPow2Large1SmallInt_Threshold()
{
// Again, with lower threshold
BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, ModPow2Large1SmallInt);
}
// InlineData randomly generated using a new Random(0) and the same logic as is used in MyBigIntImp
// When using the VerifyModPowString approach, these tests were taking over 100s to execute.
[Theory]
[OuterLoop]
[InlineData("16152447169612934532253858872860101823992426489763666485380167221632010974596350526903901586786157942589749704137347759619657187784260082814484793173551647870373927196771852", "81750440863317178198977948957223170296434385667401518194303765341584160931262254891905182291359611229458113456891057547210603179481274334549407149567413965138338569615186383", "-7196805437625531929619339290119232497987723600413951949478998858079935202962418871178150151495255147489121599998392939293913217145771279946557062800866475934948778", "5616380469802854111883204613624062553120851412450654399190717359559254034938493684003207209263083893212739965150170342564431867389596229480294680122528026782956958")]
[InlineData("-19804882257271871615998867413310154569092691610863183900352723872936597192840601413521317416195627481021453523098672122338092864102790996172", "5005126326020660905045117276428380928616741884628331700680598638081087432348216495484429178211470872172882902036752474804904132643", "-103139435102033366056363338063498713727200190198435", "-4559679593639479333979462122256288215243720737403")]
[InlineData("-2263742881720266366742488789295767051326353176981812961528848101545308514727342989711034207353102864275894987436688194776201313772226059035143797121004935923223042331190890429211181925543749113890129660515170733848725", "313166794469483345944045915670847620773229708424183728974404367769353433443313247319899209581239311758905801464781585268041623664425", "3984523819293796257818294503433333109083365267654089093971156331037874112339941681299823291492643701164442964256327008451060278818307268485187524722068240", "-1502346344475556570236985614111713440763176490652894928852811056060906839905964408583918853958610145894621840382970373570196361549098246030413222124498085")]
[InlineData("-342701069914551895507647608205424602441707687704978754182486401529587201154652163656221404036731562708712821963465111719289193200432064875769386559645346920", "247989781302056934762335026151076445832166884867735502165354252207668083157132317377069604102049233014316799294014890817943261246892765157594412634897440785353202366563028", "121555428622583377664148832113619145387775383377032217138159544127299380518157949963314283123957062240152711187509503414343", "87578369862034238407481381238856926729112161247036763388287150463197193460326629595765471822752579542310337770783772458710")]
[InlineData("-282593950368131775131360433563237877977879464854725217398276355042086422366377452969365517205334520940629323311057746859", "5959258935361466196732788139899933762310441595693546573755448590100882267274831199165902682626769861372370905838130200967035", "6598019436100687108279703832125132357070343951841815860721553173215685978621505459125000339496396952653080051757197617932586296524960251609958919233462530", "-4035534917213670830138661334307123840766321272945538719146336835321463334263841831803093764143165039453996360590495570418141622764990299884920213157241339")]
[InlineData("-283588760164723199492097446398514238808996680579814508529658395835708678571214111525627362048679162021949222615325057958783388520044013697149834530411072380435126870273057157745943859", "1042611904427950637176782337251399378305726352782300537151930702574076654415735617544217054055762002017753284951033975382044655538090809873113604", "11173562248848713955826639654969725554069867375462328112124015145073186375237811117727665778232780449525476829715663254692620996726130822561707626585790443774041565237684936409844925424596571418502946", "6662129352542591544500713232459850446949913817909326081510506555775206102887692404112984526760120407457772674917650956873499346517965094865621779695963015030158124625116211104048940313058280680420919")]
[InlineData("683399436848090272429540515929404372035986606104192913128573936597145312908480564700882440819526500604918037963508399983297602351856208190565527", "223751878996658298590720798129833935741775535718632942242965085592936259576946732440406302671204348239437556817289012497483482656", "1204888420642360606571457515385663952017382888522547766961071698778167608427220546474854934298311882921224875807375321847274969073309433075566441363244101914489524538123410250010519308563731930923389473186", "1136631484875680074951300738594593722168933395227758228596156355418704717505715681950525129323209331607163560404958604424924870345828742295978850144844693079191828839673460389985036424301333691983679427765")]
[InlineData("736513799451968530811005754031332418210960966881742655756522735504778110620671049112529346250333710388060811959329786494662578020803", "2461175085563866950903873687720858523536520498137697316698237108626602445202960480677695918813575265778826908481129155012799", "-4722693720735888562993277045098354134891725536023070176847814685098361292027040929352405620815883795027263132404351040", "4351573186631261607388198896754285562669240685903971199359912143458682154189588696264319780329366022294935204028039787")]
[InlineData("1596188639947986471148999794547338", "685242191738212089917782567856594513073397739443", "41848166029740752457613562518205823134173790454761036532025758411484449588176128053901271638836032557551179866133091058357374964041641117585422447497779410336188602585660372002644517668041207657383104649333118253", "39246949850380693159338034407642149926180988060650630387722725303281343126585456713282439764667310808891687831648451269002447916277601468727040185218264602698691553232132525542650964722093335105211816394635493987")]
[InlineData("-1506852741293695463963822334869441845197951776565891060639754936248401744065969556756496718308248025911048010080232290368562210204958094544173209793990218122", "64905085725614938357105826012272472070910693443851911667721848542473785070747281964799379996923261457185847459711", "2740467233603031668807697475486217767705051", "-1905434239471820365929630558127219204166613")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void ModPow3LargeInt(string value, string exponent, string modulus, string expected)
{
BigInteger valueInt = BigInteger.Parse(value);
BigInteger exponentInt = BigInteger.Parse(exponent);
BigInteger modulusInt = BigInteger.Parse(modulus);
BigInteger resultInt = BigInteger.Parse(expected);
// Once with default threshold
Assert.Equal(resultInt, BigInteger.ModPow(valueInt, exponentInt, modulusInt));
// Once with reduced threshold
BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, () =>
{
Assert.Equal(resultInt, BigInteger.ModPow(valueInt, exponentInt, modulusInt));
});
}
[Fact]
public static void ModPow0Power()
{
byte[] tempByteArray1;
byte[] tempByteArray2;
// ModPow Method - zero power
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow");
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow");
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow");
}
}
[Fact]
public static void ModPow0Base()
{
byte[] tempByteArray1;
byte[] tempByteArray2;
// ModPow Method - zero base
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow");
tempByteArray1 = GetRandomPosByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow");
tempByteArray1 = GetRandomPosByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow");
tempByteArray1 = GetRandomPosByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow");
}
}
[Fact]
public static void ModPowAxiom()
{
byte[] tempByteArray1;
byte[] tempByteArray2;
byte[] tempByteArray3;
// Axiom (x^y)%z = modpow(x,y,z)
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random, 1);
tempByteArray3 = GetRandomByteArray(s_random);
VerifyIdentityString(
Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow",
Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "bPow" + " bRemainder"
);
}
}
[Fact]
public static void ModPowBoundary()
{
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyModPowString(Math.Pow(2, 35) + " " + Math.Pow(2, 32) + " 2 tModPow");
// 32 bit boundary n1=0 n2=1
VerifyModPowString(Math.Pow(2, 35) + " " + Math.Pow(2, 33) + " 2 tModPow");
}
private static void VerifyModPowString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(1, 100));
}
private static byte[] GetRandomPosByteArray(Random random)
{
return GetRandomPosByteArray(random, random.Next(1, 100));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetNonZeroRandomByteArray(random, size);
}
private static byte[] GetRandomPosByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] &= 0x7F;
return value;
}
private static byte[] GetRandomNegByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] |= 0x80;
return value;
}
private static string Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| |
// 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
//
// 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.
using Google.Cloud.EntityFrameworkCore.Spanner.IntegrationTests.Model;
using Google.Cloud.Spanner.Data;
using System;
using System.Collections.Generic;
using Xunit;
using System.Text;
using System.Linq;
using Google.Cloud.EntityFrameworkCore.Spanner.Storage;
using Google.Cloud.Spanner.V1;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace Google.Cloud.EntityFrameworkCore.Spanner.IntegrationTests
{
public class ScaffoldingTests : IClassFixture<SpannerSampleFixture>
{
private readonly SpannerSampleFixture _fixture;
public ScaffoldingTests(SpannerSampleFixture fixture) => _fixture = fixture;
[Fact]
public async void AllTablesAreGenerated()
{
using var connection = _fixture.GetConnection();
var tableNames = new string[] {
"Singers", "Albums", "Tracks", "Venues", "Concerts", "Performances", "TableWithAllColumnTypes"
};
var tables = new SpannerParameterCollection
{
{ "tables", SpannerDbType.ArrayOf(SpannerDbType.String), tableNames }
};
var cmd = connection.CreateSelectCommand(
"SELECT COUNT(*) " +
"FROM INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_CATALOG='' AND TABLE_SCHEMA='' AND TABLE_NAME IN UNNEST (@tables)", tables);
using var reader = await cmd.ExecuteReaderAsync();
Assert.True(await reader.ReadAsync());
Assert.Equal(tableNames.Length, reader.GetInt64(0));
Assert.False(await reader.ReadAsync());
}
[InlineData("ColInt64", "INT64")]
[InlineData("ColInt64Array", "ARRAY<INT64>")]
[InlineData("ColFloat64", "FLOAT64")]
[InlineData("ColFloat64Array", "ARRAY<FLOAT64>")]
[InlineData("ColNumeric", "NUMERIC")]
[InlineData("ColNumericArray", "ARRAY<NUMERIC>")]
[InlineData("ColString", "STRING(100)")]
[InlineData("ColStringArray", "ARRAY<STRING(100)>")]
[InlineData("ColBytes", "BYTES(100)")]
[InlineData("ColBytesArray", "ARRAY<BYTES(100)>")]
[InlineData("ColStringMax", "STRING(MAX)")]
[InlineData("ColStringMaxArray", "ARRAY<STRING(MAX)>")]
[InlineData("ColBytesMax", "BYTES(MAX)")]
[InlineData("ColBytesMaxArray", "ARRAY<BYTES(MAX)>")]
[InlineData("ColJson", "JSON")]
[InlineData("ColJsonArray", "ARRAY<JSON>")]
[InlineData("ColBool", "BOOL")]
[InlineData("ColBoolArray", "ARRAY<BOOL>")]
[InlineData("ColDate", "DATE")]
[InlineData("ColDateArray", "ARRAY<DATE>")]
[InlineData("ColTimestamp", "TIMESTAMP")]
[InlineData("ColTimestampArray", "ARRAY<TIMESTAMP>")]
[SkippableTheory]
public async void AllColumnTypesAreGenerated(string name, string type)
{
Skip.If(SpannerFixtureBase.IsEmulator && type.Contains("JSON"), "Emulator does not the JSON data type yet");
using var connection = _fixture.GetConnection();
var parameters = new SpannerParameterCollection
{
{ "name", SpannerDbType.String, name }
};
var cmd = connection.CreateSelectCommand(
"SELECT SPANNER_TYPE " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_CATALOG='' AND TABLE_SCHEMA='' AND TABLE_NAME='TableWithAllColumnTypes' " +
"AND COLUMN_NAME=@name", parameters);
var foundType = await cmd.ExecuteScalarAsync<string>();
Assert.Equal(type, foundType);
}
[Fact]
public async void CanInsertAndUpdateVenue()
{
var code = _fixture.RandomString(4);
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var venue = new Venues
{
Code = code,
Name = "Concert Hall",
Active = true,
Capacity = 2000,
Ratings = new List<double?> { 8.9, 6.5, 8.0 },
};
db.Venues.Add(venue);
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the venue from the database.
var venue = await db.Venues.FindAsync(code);
Assert.Equal("Concert Hall", venue.Name);
Assert.Equal(2000, venue.Capacity);
Assert.Equal(new List<double?> { 8.9, 6.5, 8.0 }, venue.Ratings);
// Update the venue.
venue.Name = "Concert Hall - Refurbished";
venue.Capacity = 3000;
// TODO: Preferably it should be possible to just call List.AddRange(...) to
// update a list.
venue.Ratings = new List<double?>(venue.Ratings.Union(new double?[] { 9.5, 9.8, 10.0 }));
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the venue from the database.
var venue = await db.Venues.FindAsync(code);
Assert.Equal("Concert Hall - Refurbished", venue.Name);
Assert.Equal(3000, venue.Capacity);
Assert.Equal(new List<double?> { 8.9, 6.5, 8.0, 9.5, 9.8, 10.0 }, venue.Ratings);
}
}
[Fact]
public async void CanInsertAndUpdateSinger()
{
var singerId = _fixture.RandomLong();
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var singer = new Singers
{
SingerId = singerId,
FirstName = "Rob",
LastName = "Morrison",
BirthDate = new SpannerDate(2002, 10, 1),
Picture = new byte[] { 1, 2, 3 },
};
db.Singers.Add(singer);
await db.SaveChangesAsync();
// Check that the calculated field was also automatically updated.
Assert.Equal("Rob Morrison", singer.FullName);
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the singer from the database.
var singer = await db.Singers.FindAsync(singerId);
Assert.Equal("Rob", singer.FirstName);
Assert.Equal("Morrison", singer.LastName);
Assert.Equal(new SpannerDate(2002, 10, 1), singer.BirthDate);
Assert.Equal(new byte[] { 1, 2, 3 }, singer.Picture);
Assert.Equal("Rob Morrison", singer.FullName);
// Update the singer.
singer.FirstName = "Alice";
singer.LastName = "Morrison - Chine";
singer.BirthDate = new SpannerDate(2002, 10, 15);
singer.Picture = new byte[] { 3, 2, 1 };
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the singer from the database.
var singer = await db.Singers.FindAsync(singerId);
Assert.Equal("Alice", singer.FirstName);
Assert.Equal("Morrison - Chine", singer.LastName);
Assert.Equal(new SpannerDate(2002, 10, 15), singer.BirthDate);
Assert.Equal(new byte[] { 3, 2, 1 }, singer.Picture);
if (!SpannerFixtureBase.IsEmulator)
{
// The emulator does not support generated columns, and the simulation in the
// test setup only works for INSERT and not for UPDATE.
Assert.Equal("Alice Morrison - Chine", singer.FullName);
}
}
}
[Fact]
public async void CanInsertAndUpdateAlbum()
{
var singerId = _fixture.RandomLong();
var albumId = _fixture.RandomLong();
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var singer = new Singers
{
SingerId = singerId,
FirstName = "Pete",
LastName = "Henderson",
BirthDate = new SpannerDate(1997, 2, 20),
};
db.Singers.Add(singer);
var album = new Albums
{
SingerId = singer.SingerId,
AlbumId = albumId,
Title = "Pete Henderson's first album",
ReleaseDate = new SpannerDate(2019, 04, 19),
};
db.Albums.Add(album);
await db.SaveChangesAsync();
// Check that we can use the Singer reference.
Assert.Equal("Pete Henderson", album.Singer.FullName);
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the album from the database.
var album = await db.Albums.FindAsync(albumId);
Assert.Equal("Pete Henderson's first album", album.Title);
Assert.Equal(new SpannerDate(2019, 4, 19), album.ReleaseDate);
Assert.Equal(singerId, album.SingerId);
Assert.NotNull(album.Singer);
// Update the album.
album.Title = "Pete Henderson's first album - Refurbished";
album.ReleaseDate = new SpannerDate(2020, 2, 29);
await db.SaveChangesAsync();
}
var newSingerId = _fixture.RandomLong();
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the album from the database.
var album = await db.Albums.FindAsync(albumId);
Assert.Equal("Pete Henderson's first album - Refurbished", album.Title);
Assert.Equal(new SpannerDate(2020, 2, 29), album.ReleaseDate);
// Insert another singer and update the album to that singer.
var singer = new Singers
{
SingerId = newSingerId,
FirstName = "Alice",
LastName = "Robertson",
};
db.Singers.Add(singer);
album.Singer = singer;
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the album from the database and check that the singer was updated.
var album = await db.Albums.FindAsync(albumId);
Assert.Equal(newSingerId, album.SingerId);
Assert.Equal("Alice Robertson", album.Singer.FullName);
}
}
[Fact]
public async void CanInsertAndUpdateTrack()
{
var singerId = _fixture.RandomLong();
var albumId = _fixture.RandomLong();
var trackId = _fixture.RandomLong();
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var singer = new Singers
{
SingerId = singerId,
FirstName = "Allis",
LastName = "Morrison",
BirthDate = new SpannerDate(1968, 5, 4),
};
db.Singers.Add(singer);
var album = new Albums
{
SingerId = singer.SingerId,
AlbumId = albumId,
Title = "Allis Morrison's second album",
ReleaseDate = new SpannerDate(1987, 12, 24),
};
db.Albums.Add(album);
var track = new Tracks
{
AlbumId = albumId,
TrackId = trackId,
Title = "Track 1",
Duration = (SpannerNumeric?)4.32m,
Lyrics = new List<string> { "Song lyrics", "Liedtext" },
LyricsLanguages = new List<string> { "EN", "DE" },
};
db.Tracks.Add(track);
await db.SaveChangesAsync();
// Check that we can use the album reference.
Assert.Equal("Allis Morrison's second album", track.Album.Title);
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the track from the database.
var track = await db.Tracks.FindAsync(albumId, trackId);
Assert.Equal("Track 1", track.Title);
Assert.Equal((SpannerNumeric?)4.32m, track.Duration);
Assert.Equal(new List<string> { "Song lyrics", "Liedtext" }, track.Lyrics);
Assert.Equal(new List<string> { "EN", "DE" }, track.LyricsLanguages);
// Check that the link with album works.
Assert.NotNull(track.Album);
Assert.Equal("Allis Morrison's second album", track.Album.Title);
// Update the track.
track.Title = "Track 1 - Refurbished";
track.Duration = (SpannerNumeric?)4.35m;
track.Lyrics = new List<string>(track.Lyrics.Union(new string[] { "Sangtekst" }));
track.LyricsLanguages = new List<string>(track.LyricsLanguages.Union(new string[] { "NO" }));
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the track from the database.
var track = await db.Tracks.FindAsync(albumId, trackId);
Assert.Equal("Track 1 - Refurbished", track.Title);
Assert.Equal((SpannerNumeric?)4.35m, track.Duration);
Assert.Equal(new List<string> { "Song lyrics", "Liedtext", "Sangtekst" }, track.Lyrics);
Assert.Equal(new List<string> { "EN", "DE", "NO" }, track.LyricsLanguages);
}
}
[Fact]
public async void CanInsertAndUpdateConcertsAndPerformances()
{
var singerId = _fixture.RandomLong();
var albumId = _fixture.RandomLong();
var trackId = _fixture.RandomLong();
var venueCode = _fixture.RandomString(4);
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var singer = new Singers
{
SingerId = singerId,
FirstName = "Rob",
LastName = "Morrison",
};
db.Singers.Add(singer);
var album = new Albums
{
SingerId = singer.SingerId,
AlbumId = albumId,
Title = "Rob Morrison's first album",
};
db.Albums.Add(album);
var track = new Tracks
{
AlbumId = album.AlbumId,
TrackId = trackId,
Title = "Rob Morrison's first track",
};
db.Tracks.Add(track);
var venue = new Venues
{
Code = venueCode,
Name = "Central Park",
};
db.Venues.Add(venue);
var concert = new Concerts
{
VenueCode = venueCode,
StartTime = new DateTime(2020, 12, 28, 10, 0, 0),
SingerId = singerId,
Title = "End of year concert",
};
db.Concerts.Add(concert);
var performance = new Performances
{
VenueCode = concert.VenueCode,
ConcertStartTime = concert.StartTime,
SingerId = concert.SingerId,
StartTime = concert.StartTime.AddHours(1),
AlbumId = track.AlbumId,
TrackId = track.TrackId,
Rating = 9.8D,
};
db.Performances.Add(performance);
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the concert from the database.
var concert = await db.Concerts.FindAsync(venueCode, new DateTime(2020, 12, 28, 10, 0, 0), singerId);
Assert.Equal("End of year concert", concert.Title);
Assert.Equal(singerId, concert.SingerId);
// Check that the concert turns up in the collections of other entities.
var singer = await db.Singers.FindAsync(singerId);
Assert.Collection(singer.Concerts, c => c.Equals(concert));
Assert.Equal(1, singer.Concerts.Count);
var venue = await db.Venues.FindAsync(venueCode);
Assert.Collection(venue.Concerts, c => c.Equals(concert));
Assert.Equal(1, venue.Concerts.Count);
// Check the track
var track = await db.Tracks.FindAsync(albumId, trackId);
Assert.Equal("Rob Morrison's first track", track.Title);
// Reget the performance from the database.
var performance = await db.Performances.FindAsync(venue.Code, singer.SingerId, concert.StartTime.AddHours(1));
Assert.Equal(9.8D, performance.Rating);
Assert.NotNull(performance.Tracks);
Assert.NotNull(performance.Tracks.Album);
Assert.Equal("Rob Morrison's first album", performance.Tracks.Album.Title);
// Update the concert.
concert.Title = "End of year concert - Postponed until next year";
// Update the performance.
performance.Rating = 8.9D;
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var concert = await db.Concerts.FindAsync(venueCode, new DateTime(2020, 12, 28, 10, 0, 0), singerId);
Assert.Equal("End of year concert - Postponed until next year", concert.Title);
var performance = await db.Performances.FindAsync(concert.VenueCode, concert.SingerId, concert.StartTime.AddHours(1));
Assert.Equal(8.9D, performance.Rating);
}
}
[Fact]
public async void CanInsertAndUpdateRowWithAllDataTypes()
{
var id = _fixture.RandomLong();
var today = SpannerDate.FromDateTime(DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Unspecified));
var now = DateTime.UtcNow;
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var row = new TableWithAllColumnTypes
{
ColBool = true,
ColBoolArray = new List<bool?> { true, false, true },
ColBytes = new byte[] { 1, 2, 3 },
ColBytesMax = Encoding.UTF8.GetBytes("This is a long string"),
ColBytesArray = new List<byte[]> { new byte[] { 3, 2, 1 }, new byte[] { }, new byte[] { 4, 5, 6 } },
ColBytesMaxArray = new List<byte[]> { Encoding.UTF8.GetBytes("string 1"), Encoding.UTF8.GetBytes("string 2"), Encoding.UTF8.GetBytes("string 3") },
ColDate = new SpannerDate(2020, 12, 28),
ColDateArray = new List<SpannerDate?> { new SpannerDate(2020, 12, 28), new SpannerDate(2010, 1, 1), today },
ColFloat64 = 3.14D,
ColFloat64Array = new List<double?> { 3.14D, 6.626D },
ColInt64 = id,
ColInt64Array = new List<long?> { 1L, 2L, 4L, 8L },
ColJson = JsonDocument.Parse("{\"key\": \"value\"}"),
ColJsonArray = new List<JsonDocument>
{
JsonDocument.Parse("{\"key1\": \"value1\"}"),
JsonDocument.Parse("{}"),
JsonDocument.Parse("[]"),
JsonDocument.Parse("{\"key2\": \"value2\"}")
},
ColNumeric = (SpannerNumeric?)3.14m,
ColNumericArray = new List<SpannerNumeric?> { (SpannerNumeric)3.14m, (SpannerNumeric)6.626m },
ColString = "some string",
ColStringArray = new List<string> { "string1", "string2", "string3" },
ColStringMax = "some longer string",
ColStringMaxArray = new List<string> { "longer string1", "longer string2", "longer string3" },
ColTimestamp = new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288),
ColTimestampArray = new List<DateTime?> { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), now },
};
db.TableWithAllColumnTypes.Add(row);
await db.SaveChangesAsync();
}
DateTime? insertedCommitTimestamp = null;
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the row from the database.
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.True(row.ColBool);
Assert.Equal(new List<bool?> { true, false, true }, row.ColBoolArray);
Assert.Equal(new byte[] { 1, 2, 3 }, row.ColBytes);
Assert.Equal(Encoding.UTF8.GetBytes("This is a long string"), row.ColBytesMax);
Assert.Equal(new List<byte[]> { new byte[] { 3, 2, 1 }, new byte[] { }, new byte[] { 4, 5, 6 } }, row.ColBytesArray);
Assert.Equal(new List<byte[]> { Encoding.UTF8.GetBytes("string 1"), Encoding.UTF8.GetBytes("string 2"), Encoding.UTF8.GetBytes("string 3") }, row.ColBytesMaxArray);
Assert.Equal(new SpannerDate(2020, 12, 28), row.ColDate);
Assert.Equal(new List<SpannerDate?> { new SpannerDate(2020, 12, 28), new SpannerDate(2010, 1, 1), today }, row.ColDateArray);
Assert.Equal(3.14D, row.ColFloat64);
Assert.Equal(new List<double?> { 3.14D, 6.626D }, row.ColFloat64Array);
Assert.Equal((SpannerNumeric?)3.14m, row.ColNumeric);
Assert.Equal(new List<SpannerNumeric?> { (SpannerNumeric)3.14m, (SpannerNumeric)6.626m }, row.ColNumericArray);
Assert.Equal(id, row.ColInt64);
Assert.Equal(new List<long?> { 1L, 2L, 4L, 8L }, row.ColInt64Array);
Assert.Equal("{\"key\":\"value\"}", row.ColJson.RootElement.ToString());
Assert.Equal(new List<string>
{
"{\"key1\":\"value1\"}",
"{}",
"[]",
"{\"key2\":\"value2\"}"
}, row.ColJsonArray.Select(v => v?.RootElement.ToString()).ToList());
Assert.Equal("some string", row.ColString);
Assert.Equal(new List<string> { "string1", "string2", "string3" }, row.ColStringArray);
Assert.Equal("some longer string", row.ColStringMax);
Assert.Equal(new List<string> { "longer string1", "longer string2", "longer string3" }, row.ColStringMaxArray);
Assert.Equal(new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), row.ColTimestamp);
Assert.Equal(new List<DateTime?> { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), now }, row.ColTimestampArray);
// The commit timestamp was automatically set by Cloud Spanner.
Assert.NotEqual(new DateTime(), row.ColCommitTs);
// This assumes that the local time does not differ more than 10 minutes with TrueTime.
if (!SpannerFixtureBase.IsEmulator)
{
// The emulator seems to return a commit timestamp that is skewed by 1 hour compared to what Cloud Spanner returns.
Assert.True(Math.Abs(DateTime.UtcNow.Subtract(row.ColCommitTs.GetValueOrDefault()).TotalMinutes) < 10, $"Commit timestamp {row.ColCommitTs} differs with more than 10 minutes from now ({DateTime.UtcNow})");
}
insertedCommitTimestamp = row.ColCommitTs;
// Update the row.
row.ColBool = false;
row.ColBoolArray = new List<bool?> { false, true, false };
row.ColBytes = new byte[] { 3, 2, 1 };
row.ColBytesMax = Encoding.UTF8.GetBytes("This string has changed");
row.ColBytesArray = new List<byte[]> { new byte[] { 10, 20, 30 }, new byte[] { 40, 50, 60 } };
row.ColBytesMaxArray = new List<byte[]> { Encoding.UTF8.GetBytes("changed string 1"), Encoding.UTF8.GetBytes("changed string 2"), Encoding.UTF8.GetBytes("changed string 3") };
row.ColDate = new SpannerDate(2020, 12, 30);
row.ColDateArray = new List<SpannerDate?> { today, new SpannerDate(2020, 12, 30), new SpannerDate(2010, 2, 28) };
row.ColFloat64 = 1.234D;
row.ColFloat64Array = new List<double?> { 1.0D, 1.1D, 1.11D };
row.ColNumeric = (SpannerNumeric?)1.234m;
row.ColNumericArray = new List<SpannerNumeric?> { (SpannerNumeric)1.0m, (SpannerNumeric)1.1m, (SpannerNumeric)1.11m };
row.ColInt64Array = new List<long?> { 500L, 1000L };
row.ColJson = JsonDocument.Parse("{}");
row.ColJsonArray = new List<JsonDocument> { JsonDocument.Parse("[]"), JsonDocument.Parse("{}"), null };
row.ColString = "some changed string";
row.ColStringArray = new List<string> { "changed string1", "changed string2", "changed string3" };
row.ColStringMax = "some longer changed string";
row.ColStringMaxArray = new List<string> { "changed longer string1", "changed longer string2", "changed longer string3" };
row.ColTimestamp = new DateTime(2020, 12, 30, 15, 16, 28, 148).AddTicks(5498);
row.ColTimestampArray = new List<DateTime?> { now, new DateTime(2020, 12, 30, 15, 16, 28, 148).AddTicks(5498) };
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the row from the database.
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.False(row.ColBool);
Assert.Equal(new List<bool?> { false, true, false }, row.ColBoolArray);
Assert.Equal(new byte[] { 3, 2, 1 }, row.ColBytes);
Assert.Equal(Encoding.UTF8.GetBytes("This string has changed"), row.ColBytesMax);
Assert.Equal(new List<byte[]> { new byte[] { 10, 20, 30 }, new byte[] { 40, 50, 60 } }, row.ColBytesArray);
Assert.Equal(new List<byte[]> { Encoding.UTF8.GetBytes("changed string 1"), Encoding.UTF8.GetBytes("changed string 2"), Encoding.UTF8.GetBytes("changed string 3") }, row.ColBytesMaxArray);
Assert.Equal(new SpannerDate(2020, 12, 30), row.ColDate);
Assert.Equal(new List<SpannerDate?> { today, new SpannerDate(2020, 12, 30), new SpannerDate(2010, 2, 28) }, row.ColDateArray);
Assert.Equal(1.234D, row.ColFloat64);
Assert.Equal(new List<double?> { 1.0D, 1.1D, 1.11D }, row.ColFloat64Array);
Assert.Equal((SpannerNumeric?)1.234m, row.ColNumeric);
Assert.Equal(new List<SpannerNumeric?> { (SpannerNumeric)1.0m, (SpannerNumeric)1.1m, (SpannerNumeric)1.11m }, row.ColNumericArray);
Assert.Equal(new List<long?> { 500L, 1000L }, row.ColInt64Array);
Assert.Equal("{}", row.ColJson.RootElement.ToString());
Assert.Equal(new List<string> { "[]", "{}", null }, row.ColJsonArray.Select(v => v?.RootElement.ToString()));
Assert.Equal("some changed string", row.ColString);
Assert.Equal(new List<string> { "changed string1", "changed string2", "changed string3" }, row.ColStringArray);
Assert.Equal("some longer changed string", row.ColStringMax);
Assert.Equal(new List<string> { "changed longer string1", "changed longer string2", "changed longer string3" }, row.ColStringMaxArray);
Assert.Equal(new DateTime(2020, 12, 30, 15, 16, 28, 148).AddTicks(5498), row.ColTimestamp);
Assert.Equal(new List<DateTime?> { now, new DateTime(2020, 12, 30, 15, 16, 28, 148).AddTicks(5498) }, row.ColTimestampArray);
// Do an update. This should also update the commit timestamp.
row.ColBool = !row.ColBool;
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Reget the row from the database and check that the new commit timestamp is later than the initial.
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.True(row.ColCommitTs.GetValueOrDefault().CompareTo(insertedCommitTimestamp) > 0);
}
}
[Fact]
public async void CanInsertAndUpdateNullValues()
{
var id = _fixture.RandomLong();
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
// Create a row with all null values except for the primary key.
// Cloud Spanner does support rows with a null value for the PK,
// but EFCore does not support that.
var row = new TableWithAllColumnTypes { ColInt64 = id };
db.TableWithAllColumnTypes.Add(row);
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.Null(row.ColBool);
Assert.Null(row.ColBoolArray);
Assert.Null(row.ColBytes);
Assert.Null(row.ColBytesArray);
Assert.Null(row.ColBytesMax);
Assert.Null(row.ColBytesMaxArray);
Assert.NotNull(row.ColCommitTs); // Automatically filled on commit.
Assert.Null(row.ColComputed);
Assert.Null(row.ColDate);
Assert.Null(row.ColDateArray);
Assert.Null(row.ColFloat64);
Assert.Null(row.ColFloat64Array);
Assert.Null(row.ColNumeric);
Assert.Null(row.ColNumericArray);
Assert.Null(row.ColInt64Array);
Assert.Null(row.ColJson);
Assert.Null(row.ColJsonArray);
Assert.Null(row.ColString);
Assert.Null(row.ColStringArray);
Assert.Null(row.ColStringMax);
Assert.Null(row.ColStringMaxArray);
Assert.Null(row.ColTimestamp);
Assert.Null(row.ColTimestampArray);
// Update from null to non-null.
row.ColBool = true;
row.ColBoolArray = new List<bool?> { };
row.ColBytes = new byte[0];
row.ColBytesArray = new List<byte[]> { };
row.ColBytesMax = new byte[0];
row.ColBytesMaxArray = new List<byte[]> { };
row.ColDate = new SpannerDate(1, 1, 1);
row.ColDateArray = new List<SpannerDate?> { };
row.ColFloat64 = 0.0D;
row.ColFloat64Array = new List<double?> { };
row.ColNumeric = (SpannerNumeric?)0.0m;
row.ColNumericArray = new List<SpannerNumeric?> { };
row.ColInt64Array = new List<long?> { };
row.ColJson = JsonDocument.Parse("{}");
row.ColJsonArray = new List<JsonDocument>();
row.ColString = "";
row.ColStringArray = new List<string> { };
row.ColStringMax = "";
row.ColStringMaxArray = new List<string> { };
row.ColTimestamp = new DateTime(1, 1, 1, 0, 0, 0);
row.ColTimestampArray = new List<DateTime?> { };
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.NotNull(row.ColBool);
Assert.NotNull(row.ColBoolArray);
Assert.NotNull(row.ColBytes);
Assert.NotNull(row.ColBytesArray);
Assert.NotNull(row.ColBytesMax);
Assert.NotNull(row.ColBytesMaxArray);
Assert.NotNull(row.ColCommitTs);
if (!SpannerFixtureBase.IsEmulator)
{
Assert.NotNull(row.ColComputed);
}
Assert.NotNull(row.ColDate);
Assert.NotNull(row.ColDateArray);
Assert.NotNull(row.ColFloat64);
Assert.NotNull(row.ColFloat64Array);
Assert.NotNull(row.ColNumeric);
Assert.NotNull(row.ColNumericArray);
Assert.NotNull(row.ColInt64Array);
Assert.NotNull(row.ColJson);
Assert.NotNull(row.ColJsonArray);
Assert.NotNull(row.ColString);
Assert.NotNull(row.ColStringArray);
Assert.NotNull(row.ColStringMax);
Assert.NotNull(row.ColStringMaxArray);
Assert.NotNull(row.ColTimestamp);
Assert.NotNull(row.ColTimestampArray);
// Update from non-null back to null.
row.ColBool = null;
row.ColBoolArray = null;
row.ColBytes = null;
row.ColBytesArray = null;
row.ColBytesMax = null;
row.ColBytesMaxArray = null;
row.ColDate = null;
row.ColDateArray = null;
row.ColFloat64 = null;
row.ColFloat64Array = null;
row.ColNumeric = null;
row.ColNumericArray = null;
row.ColInt64Array = null;
row.ColJson = null;
row.ColJsonArray = null;
row.ColString = null;
row.ColStringArray = null;
row.ColStringMax = null;
row.ColStringMaxArray = null;
row.ColTimestamp = null;
row.ColTimestampArray = null;
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.Null(row.ColBool);
Assert.Null(row.ColBoolArray);
Assert.Null(row.ColBytes);
Assert.Null(row.ColBytesArray);
Assert.Null(row.ColBytesMax);
Assert.Null(row.ColBytesMaxArray);
Assert.NotNull(row.ColCommitTs); // Automatically filled on commit.
Assert.Null(row.ColComputed);
Assert.Null(row.ColDate);
Assert.Null(row.ColDateArray);
Assert.Null(row.ColFloat64);
Assert.Null(row.ColFloat64Array);
Assert.Null(row.ColNumeric);
Assert.Null(row.ColNumericArray);
Assert.Null(row.ColInt64Array);
Assert.Null(row.ColJson);
Assert.Null(row.ColJsonArray);
Assert.Null(row.ColString);
Assert.Null(row.ColStringArray);
Assert.Null(row.ColStringMax);
Assert.Null(row.ColStringMaxArray);
Assert.Null(row.ColTimestamp);
Assert.Null(row.ColTimestampArray);
}
}
[Fact]
public async void CanInsertAndUpdateNullValuesInArrays()
{
var id = _fixture.RandomLong();
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var row = new TableWithAllColumnTypes
{
ColInt64 = id,
ColBoolArray = new List<bool?> { true, null, false },
ColBytesArray = new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } },
ColBytesMaxArray = new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } },
ColDateArray = new List<SpannerDate?> { new SpannerDate(2020, 1, 13), null, new SpannerDate(2021, 1, 13) },
ColFloat64Array = new List<double?> { 3.14, null, 6.662 },
ColInt64Array = new List<long?> { 100, null, 200 },
ColJsonArray = new List<JsonDocument>{JsonDocument.Parse("{}"), null, JsonDocument.Parse("[]")},
ColNumericArray = new List<SpannerNumeric?> { (SpannerNumeric)3.14m, null, (SpannerNumeric)6.662m },
ColStringArray = new List<string> { "string1", null, "string2" },
ColStringMaxArray = new List<string> { "long string 1", null, "long string 2" },
ColTimestampArray = new List<DateTime?> { new DateTime(2021, 1, 13, 15, 24, 19), null },
};
db.TableWithAllColumnTypes.Add(row);
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.Equal(new List<bool?> { true, null, false }, row.ColBoolArray);
Assert.Equal(new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } }, row.ColBytesArray);
Assert.Equal(new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } }, row.ColBytesMaxArray);
Assert.Equal(new List<SpannerDate?> { new SpannerDate(2020, 1, 13), null, new SpannerDate(2021, 1, 13) }, row.ColDateArray);
Assert.Equal(new List<double?> { 3.14, null, 6.662 }, row.ColFloat64Array);
Assert.Equal(new List<long?> { 100, null, 200 }, row.ColInt64Array);
Assert.Equal(new List<string> { "{}", null, "[]" }, row.ColJsonArray.Select(v => v?.RootElement.ToString()).ToList());
Assert.Equal(new List<SpannerNumeric?> { (SpannerNumeric)3.14m, null, (SpannerNumeric)6.662m }, row.ColNumericArray);
Assert.Equal(new List<string> { "string1", null, "string2" }, row.ColStringArray);
Assert.Equal(new List<string> { "long string 1", null, "long string 2" }, row.ColStringMaxArray);
Assert.Equal(new List<DateTime?> { new DateTime(2021, 1, 13, 15, 24, 19), null }, row.ColTimestampArray);
row.ColBoolArray = new List<bool?> { null, true, null };
row.ColBytesArray = new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } };
row.ColBytesMaxArray = new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } };
row.ColDateArray = new List<SpannerDate?> { new SpannerDate(2020, 1, 13), null, new SpannerDate(2021, 1, 13) };
row.ColFloat64Array = new List<double?> { 3.14, null, 6.662 };
row.ColInt64Array = new List<long?> { 100, null, 200 };
row.ColJsonArray = new List<JsonDocument> { JsonDocument.Parse("{}"), null, JsonDocument.Parse("[]") };
row.ColNumericArray = new List<SpannerNumeric?> { (SpannerNumeric)3.14m, null, (SpannerNumeric)6.662m };
row.ColStringArray = new List<string> { "string1", null, "string2" };
row.ColStringMaxArray = new List<string> { "long string 1", null, "long string 2" };
row.ColTimestampArray = new List<DateTime?> { new DateTime(2021, 1, 13, 15, 24, 19), null };
await db.SaveChangesAsync();
}
using (var db = new TestSpannerSampleDbContext(_fixture.DatabaseName))
{
var row = await db.TableWithAllColumnTypes.FindAsync(id);
Assert.Equal(new List<bool?> { null, true, null }, row.ColBoolArray);
Assert.Equal(new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } }, row.ColBytesArray);
Assert.Equal(new List<byte[]> { new byte[] { 1 }, null, new byte[] { 2 } }, row.ColBytesMaxArray);
Assert.Equal(new List<SpannerDate?> { new SpannerDate(2020, 1, 13), null, new SpannerDate(2021, 1, 13) }, row.ColDateArray);
Assert.Equal(new List<double?> { 3.14, null, 6.662 }, row.ColFloat64Array);
Assert.Equal(new List<long?> { 100, null, 200 }, row.ColInt64Array);
Assert.Equal(new List<string> { "{}", null, "[]" }, row.ColJsonArray.Select(v => v?.RootElement.ToString()).ToList());
Assert.Equal(new List<SpannerNumeric?> { (SpannerNumeric)3.14m, null, (SpannerNumeric)6.662m }, row.ColNumericArray);
Assert.Equal(new List<string> { "string1", null, "string2" }, row.ColStringArray);
Assert.Equal(new List<string> { "long string 1", null, "long string 2" }, row.ColStringMaxArray);
Assert.Equal(new List<DateTime?> { new DateTime(2021, 1, 13, 15, 24, 19), null }, row.ColTimestampArray);
}
}
[Fact]
public async void CanDeleteData()
{
var singerId = _fixture.RandomLong();
var albumId = _fixture.RandomLong();
var trackId = _fixture.RandomLong();
var venueCode = _fixture.RandomString(4);
using var db = new TestSpannerSampleDbContext(_fixture.DatabaseName);
var singer = new Singers
{
SingerId = singerId,
LastName = "To be deleted",
};
db.Singers.Add(singer);
var album = new Albums
{
AlbumId = albumId,
Title = "To be deleted",
SingerId = singer.SingerId,
};
db.Albums.Add(album);
var track = new Tracks
{
AlbumId = album.AlbumId,
TrackId = trackId,
Title = "To be deleted",
};
db.Tracks.Add(track);
var venue = new Venues
{
Code = venueCode,
Name = "To be deleted",
};
db.Venues.Add(venue);
var concert = new Concerts
{
VenueCode = venue.Code,
StartTime = new DateTime(2020, 12, 30, 10, 00, 30),
SingerId = singer.SingerId,
};
db.Concerts.Add(concert);
var performance = new Performances
{
VenueCode = venue.Code,
ConcertStartTime = concert.StartTime,
SingerId = singer.SingerId,
AlbumId = album.AlbumId,
TrackId = track.TrackId,
StartTime = concert.StartTime.AddMinutes(30),
};
db.Performances.Add(performance);
var id = _fixture.RandomLong();
var row = new TableWithAllColumnTypes { ColInt64 = id };
db.TableWithAllColumnTypes.Add(row);
await db.SaveChangesAsync();
// Delete all rows.
db.TableWithAllColumnTypes.Remove(row);
db.Performances.Remove(performance);
db.Concerts.Remove(concert);
db.Venues.Remove(venue);
db.Tracks.Remove(track);
db.Albums.Remove(album);
db.Singers.Remove(singer);
await db.SaveChangesAsync();
// Verify that all rows were deleted.
Assert.Null(await db.Singers.FindAsync(singer.SingerId));
Assert.Null(await db.Albums.FindAsync(album.AlbumId));
Assert.Null(await db.Tracks.FindAsync(album.AlbumId, track.TrackId));
Assert.Null(await db.Venues.FindAsync(venue.Code));
Assert.Null(await db.Concerts.FindAsync(concert.VenueCode, concert.StartTime, concert.SingerId));
Assert.Null(await db.Performances.FindAsync(performance.VenueCode, performance.SingerId, performance.StartTime));
// Getting this row the normal way does not work on the emulator because of the ARRAY<NUMERIC> column.
if (SpannerFixtureBase.IsEmulator)
{
Assert.Equal(0, await db.TableWithAllColumnTypes
.Where(r => r.ColInt64 == row.ColInt64)
.Select(r => r.ColInt64)
.FirstOrDefaultAsync());
}
else
{
Assert.Null(await db.TableWithAllColumnTypes.FindAsync(row.ColInt64));
}
}
}
}
| |
// 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.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.ErrorReporting.V1Beta1
{
/// <summary>
/// Settings for a <see cref="ReportErrorsServiceClient"/>.
/// </summary>
public sealed partial class ReportErrorsServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ReportErrorsServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="ReportErrorsServiceSettings"/>.
/// </returns>
public static ReportErrorsServiceSettings GetDefault() => new ReportErrorsServiceSettings();
/// <summary>
/// Constructs a new <see cref="ReportErrorsServiceSettings"/> object with default settings.
/// </summary>
public ReportErrorsServiceSettings() { }
private ReportErrorsServiceSettings(ReportErrorsServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
ReportErrorEventSettings = existing.ReportErrorEventSettings;
OnCopy(existing);
}
partial void OnCopy(ReportErrorsServiceSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="ReportErrorsServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="ReportErrorsServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 20000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(20000),
maxDelay: TimeSpan.FromMilliseconds(20000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ReportErrorsServiceClient.ReportErrorEvent</c> and <c>ReportErrorsServiceClient.ReportErrorEventAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ReportErrorsServiceClient.ReportErrorEvent</c> and
/// <c>ReportErrorsServiceClient.ReportErrorEventAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description>No status codes</description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings ReportErrorEventSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: NonIdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="ReportErrorsServiceSettings"/> object.</returns>
public ReportErrorsServiceSettings Clone() => new ReportErrorsServiceSettings(this);
}
/// <summary>
/// ReportErrorsService client wrapper, for convenient use.
/// </summary>
public abstract partial class ReportErrorsServiceClient
{
/// <summary>
/// The default endpoint for the ReportErrorsService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouderrorreporting.googleapis.com", 443);
/// <summary>
/// The default ReportErrorsService scopes.
/// </summary>
/// <remarks>
/// The default ReportErrorsService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="ReportErrorsServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="ReportErrorsServiceClient"/>.</returns>
public static async Task<ReportErrorsServiceClient> CreateAsync(ServiceEndpoint endpoint = null, ReportErrorsServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="ReportErrorsServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param>
/// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns>
public static ReportErrorsServiceClient Create(ServiceEndpoint endpoint = null, ReportErrorsServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="ReportErrorsServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param>
/// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns>
public static ReportErrorsServiceClient Create(Channel channel, ReportErrorsServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
ReportErrorsService.ReportErrorsServiceClient grpcClient = new ReportErrorsService.ReportErrorsServiceClient(channel);
return new ReportErrorsServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ReportErrorsServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ReportErrorsServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ReportErrorsServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ReportErrorsServiceSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC ReportErrorsService client.
/// </summary>
public virtual ReportErrorsService.ReportErrorsServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Report an individual error event.
///
/// This endpoint accepts <strong>either</strong> an OAuth token,
/// <strong>or</strong> an
/// <a href="https://support.google.com/cloud/answer/6158862">API key</a>
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
/// <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="event">
/// [Required] The error event to be reported.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ReportErrorEventResponse> ReportErrorEventAsync(
ProjectName projectName,
ReportedErrorEvent @event,
CallSettings callSettings = null) => ReportErrorEventAsync(
new ReportErrorEventRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
Event = GaxPreconditions.CheckNotNull(@event, nameof(@event)),
},
callSettings);
/// <summary>
/// Report an individual error event.
///
/// This endpoint accepts <strong>either</strong> an OAuth token,
/// <strong>or</strong> an
/// <a href="https://support.google.com/cloud/answer/6158862">API key</a>
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
/// <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="event">
/// [Required] The error event to be reported.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ReportErrorEventResponse> ReportErrorEventAsync(
ProjectName projectName,
ReportedErrorEvent @event,
CancellationToken cancellationToken) => ReportErrorEventAsync(
projectName,
@event,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report an individual error event.
///
/// This endpoint accepts <strong>either</strong> an OAuth token,
/// <strong>or</strong> an
/// <a href="https://support.google.com/cloud/answer/6158862">API key</a>
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
/// <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="event">
/// [Required] The error event to be reported.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ReportErrorEventResponse ReportErrorEvent(
ProjectName projectName,
ReportedErrorEvent @event,
CallSettings callSettings = null) => ReportErrorEvent(
new ReportErrorEventRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
Event = GaxPreconditions.CheckNotNull(@event, nameof(@event)),
},
callSettings);
/// <summary>
/// Report an individual error event.
///
/// This endpoint accepts <strong>either</strong> an OAuth token,
/// <strong>or</strong> an
/// <a href="https://support.google.com/cloud/answer/6158862">API key</a>
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
/// <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<ReportErrorEventResponse> ReportErrorEventAsync(
ReportErrorEventRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Report an individual error event.
///
/// This endpoint accepts <strong>either</strong> an OAuth token,
/// <strong>or</strong> an
/// <a href="https://support.google.com/cloud/answer/6158862">API key</a>
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
/// <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual ReportErrorEventResponse ReportErrorEvent(
ReportErrorEventRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// ReportErrorsService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class ReportErrorsServiceClientImpl : ReportErrorsServiceClient
{
private readonly ApiCall<ReportErrorEventRequest, ReportErrorEventResponse> _callReportErrorEvent;
/// <summary>
/// Constructs a client wrapper for the ReportErrorsService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ReportErrorsServiceSettings"/> used within this client </param>
public ReportErrorsServiceClientImpl(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings settings)
{
GrpcClient = grpcClient;
ReportErrorsServiceSettings effectiveSettings = settings ?? ReportErrorsServiceSettings.GetDefault();
ClientHelper clientHelper = new ClientHelper(effectiveSettings);
_callReportErrorEvent = clientHelper.BuildApiCall<ReportErrorEventRequest, ReportErrorEventResponse>(
GrpcClient.ReportErrorEventAsync, GrpcClient.ReportErrorEvent, effectiveSettings.ReportErrorEventSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void OnConstruction(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings effectiveSettings, ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC ReportErrorsService client.
/// </summary>
public override ReportErrorsService.ReportErrorsServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_ReportErrorEventRequest(ref ReportErrorEventRequest request, ref CallSettings settings);
/// <summary>
/// Report an individual error event.
///
/// This endpoint accepts <strong>either</strong> an OAuth token,
/// <strong>or</strong> an
/// <a href="https://support.google.com/cloud/answer/6158862">API key</a>
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
/// <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<ReportErrorEventResponse> ReportErrorEventAsync(
ReportErrorEventRequest request,
CallSettings callSettings = null)
{
Modify_ReportErrorEventRequest(ref request, ref callSettings);
return _callReportErrorEvent.Async(request, callSettings);
}
/// <summary>
/// Report an individual error event.
///
/// This endpoint accepts <strong>either</strong> an OAuth token,
/// <strong>or</strong> an
/// <a href="https://support.google.com/cloud/answer/6158862">API key</a>
/// for authentication. To use an API key, append it to the URL as the value of
/// a `key` parameter. For example:
/// <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override ReportErrorEventResponse ReportErrorEvent(
ReportErrorEventRequest request,
CallSettings callSettings = null)
{
Modify_ReportErrorEventRequest(ref request, ref callSettings);
return _callReportErrorEvent.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using OpenSource.UPnP;
using OpenSource.UPnP.AV;
using OpenSource.UPnP.AV.CdsMetadata;
using OpenSource.UPnP.AV.MediaServer;
using OpenSource.UPnP.AV.MediaServer.CP;
using System.Windows.Forms;
namespace OpenSource.UPnP.AV.MediaServer.CP
{
public class ContextInfo : ICloneable
{
internal Stack m_Context = new Stack();
internal CpMediaServer m_ServerContext = null;
/// <summary>
/// Returns the server that is currently being browsed.
/// </summary>
public CpMediaServer ServerContext
{
get
{
return this.m_ServerContext;
}
}
public IMediaContainer ContainerContext
{
get
{
return (IMediaContainer) this.m_Context.Peek();
}
}
/// <summary>
/// Returns the entire stack context as an array.
/// Returned value is a shallow copy.
/// </summary>
public IMediaContainer[] EntireContext
{
get
{
IMediaContainer[] retVal = new IMediaContainer[this.m_Context.Count];
this.m_Context.CopyTo(retVal, 0);
return retVal;
}
}
/// <summary>
/// Provides a listing of the available contexts that could be added
/// to the entire/current context. (Essentially, all child containers.)
/// </summary>
public IMediaContainer[] ForwardContexts
{
get
{
IMediaContainer[] mcs = null;
IList containers = this.ContainerContext.Containers;
mcs = new IMediaContainer[containers.Count];
for (int i=0; i < containers.Count; i++)
{
mcs[i] = (IMediaContainer) containers[i];
}
return mcs;
}
}
/// <summary>
/// Provides the list of legal contexts that this browser can change to.
/// Essentially, a merging of <see cref="MediaBrowser.ForwardContexts"/> and
/// <see cref="MediaBrowser.EntireContext"/>
/// </summary>
public IMediaContainer[] AvailableContexts
{
get
{
int i;
IMediaContainer[] mcs = null;
IList containers = this.ContainerContext.Containers;
IMediaContainer[] ec = this.EntireContext;
mcs = new IMediaContainer[containers.Count + ec.Length];
for (i=0; i < containers.Count; i++)
{
mcs[i] = (IMediaContainer) containers[i];
}
for (int j=0; j < ec.Length; j++)
{
mcs[i] = (IMediaContainer) ec[j];
i++;
}
return mcs;
}
}
#region ICloneable Members
public object Clone()
{
ContextInfo ci = new ContextInfo();
ci.m_Context = this.m_Context;
ci.m_ServerContext = this.m_ServerContext;
return ci;
}
#endregion
}
/// <summary>
/// Summary description for MediaBrowser.
/// </summary>
public class MediaBrowser
{
public delegate void Delegate_ContentFound(MediaBrowser sender, IUPnPMedia[] added);
public event Delegate_ContentFound OnIncrementalUpdate;
public event Delegate_ContentFound OnRefreshComplete;
private ContainerDiscovery m_Roots = null;
private ContextInfo m_Context = null;
private ContextInfo m_TargetContext = null;
private ContextInfo m_PendingContext = null;
private uint m_CurrentIndex = 0;
private uint m_BrowseSize = 20;
private string m_Filter = "*";
private string m_SortString = "";
private ArrayList m_Children = null;
private ArrayList m_History = null;
private int m_HistorySize = -1;
private void Init(int capacity)
{
this.m_Children = new ArrayList();
this.m_Roots = ContainerDiscovery.GetInstance();
this.m_Context = new ContextInfo();
this.m_Context.m_Context.Push(this.m_Roots.AllRoots);
this.m_HistorySize = capacity;
if (this.m_HistorySize > 0)
{
this.m_History = new ArrayList(capacity);
}
else
{
this.m_History = new ArrayList();
}
}
public MediaBrowser()
{
Init(-1);
}
public MediaBrowser(int historyCapacity)
{
Init(historyCapacity);
}
/// <summary>
/// Returns the current browsing context.
/// </summary>
public ContextInfo CurrentContext
{
get
{
return (ContextInfo) this.m_Context.Clone();
}
}
/// <summary>
/// Provides the list of contexts that the browser has been used.
/// Unlike other properties of this class that return contexts,
/// this property can return contexts from other MediaServers.
/// </summary>
public ContextInfo[] ContextHistory
{
get
{
return (ContextInfo[]) this.m_History.ToArray(typeof(ContextInfo));
}
}
/// <summary>
/// Go back/up to the previous context/container.
/// </summary>
public void Back()
{
if (!(this.CurrentContext is CpRootCollectionContainer))
{
lock (this)
{
this.m_Context.m_Context.Pop();
if (this.m_Context.m_Context.Count == 1)
{
this.m_Context.m_ServerContext = null;
}
this.RefreshChildren();
}
}
}
/// <summary>
/// Go back/up to the previous context/container.
/// </summary>
/// <param name="thisMany">Go back this many times.</param>
public void Back(int thisMany)
{
if (!(this.CurrentContext is CpRootCollectionContainer))
{
lock (this)
{
if (thisMany >= this.m_Context.m_Context.Count)
{
thisMany = this.m_Context.m_Context.Count - 1;
}
while ((thisMany > 0) && (this.m_Context.m_Context.Count > 1))
{
this.m_Context.m_Context.Pop();
thisMany--;
}
if (this.m_Context.m_Context.Count == 1)
{
this.m_Context.m_ServerContext = null;
}
this.RefreshChildren();
}
}
}
private bool IsValidContext(IMediaContainer checkThis, object[] againstThis, bool isContextInfo)
{
for (int i=0; i < againstThis.Length; i++)
{
if (isContextInfo)
{
ContextInfo ci = (ContextInfo) againstThis[i];
if ((IMediaContainer)(ci.m_Context.Peek()) == checkThis)
{
return true;
}
}
else if (againstThis[i] == checkThis)
{
return true;
}
}
return false;
}
public void SetContext(ContextInfo ci)
{
// we'll track our progress using m_PendingContext
this.m_PendingContext = new ContextInfo();
this.m_PendingContext.m_Context.Push(this.m_Roots.AllRoots);
this.m_TargetContext = ci;
// iterate through the container context in reverse order,
// try to change context each time
IList list = ci.EntireContext;
for (int i= list.Count-1; i > 0; i--)
{
//TODO:
}
}
private bool SetContainerContext(ContextInfo ci, IMediaContainer context)
{
bool retVal = false;
bool fwd = false, bk = false;
// check against forward contexts
fwd = IsValidContext(context, ci.ForwardContexts, false);
// check against current/entire context
if (fwd == false)
{
bk = IsValidContext(context, ci.EntireContext, false);
}
// if selecting a valid context...
if (fwd)
{
// going forward, so push the desired context
// to our stack context
lock (this)
{
ci.m_Context.Push(context);
// if new context is a root container, set the server context
if ((context.IsRootContainer) && (!(context is CpRootCollectionContainer)))
{
CpRootContainer root = context as CpRootContainer;
if (root != null)
{
ci.m_ServerContext = root.Server;
}
}
}
retVal = true;
}
else if (bk)
{
lock(this)
{
// going back, so pop the stack until
// we get to the desired context
// and then refresh
while ((this.CurrentContext != context) && (this.m_Context.m_Context.Count > 1))
{
this.m_Context.m_Context.Pop();
}
if (this.m_Context.m_Context.Count == 1)
{
this.m_Context.m_ServerContext = null;
}
}
retVal = true;
}
return retVal;
}
/// <summary>
/// Sets the current context. The specified context
/// must be from <see cref="MediaBrowser.AvailableContexts"/>.
/// If it is not, then nothing will happen.
/// </summary>
/// <param name="context"></param>
public void SetContainerContext(IMediaContainer context)
{
if (this.SetContainerContext(this.m_Context, context))
{
this.RefreshChildren();
}
}
/// <summary>
/// Refreshes the children associated with the current context.
/// </summary>
public void RefreshChildren()
{
if (!(this.CurrentContext is CpRootCollectionContainer))
{
// rebrowse current container
lock (this)
{
this.m_CurrentIndex = 0;
IMediaContainer[] ec = this.CurrentContext.EntireContext;
// clear listing of current children, since we're rebrowsing
this.m_Children.Clear();
this.CurrentContext.ServerContext.RequestBrowse(
this.CurrentContext.ContainerContext.ID,
CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN,
this.m_Filter,
this.m_CurrentIndex,
this.m_BrowseSize,
this.m_SortString,
ec,
new CpMediaServer.Delegate_OnBrowseDone1 (Sink_OnBrowse)
);
}
}
else
{
// update servers
}
}
private void Sink_OnBrowse(CpMediaServer server, System.String ObjectID, OpenSource.UPnP.AV.CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, UPnPInvokeException e, Exception parseError, object _Tag, IUPnPMedia[] Result, System.UInt32 NumberReturned, System.UInt32 TotalMatches, System.UInt32 UpdateID)
{
IMediaContainer[] tagC, ec;
bool ok = true;
bool nomore = false;
// ensure we're processing results for the current context
lock (this)
{
tagC = (IMediaContainer[]) _Tag;
ec = this.CurrentContext.EntireContext;
for (int i=0; i < ec.Length; i++)
{
if (ec[i] != tagC[i])
{
ok = false;
break;
}
}
}
if (ok)
{
// results are for current context, merge metadata results
// with existing child list
if ((e == null) && (parseError == null))
{
lock (this)
{
// add to our media object
this.m_Children.AddRange(Result);
this.CurrentContext.ContainerContext.AddObjects(Result, true);
if (
((this.m_Children.Count < TotalMatches) && (NumberReturned > 0)) ||
((TotalMatches == 0) && (NumberReturned > 0))
)
{
// more items to come
this.m_CurrentIndex = NumberReturned;
}
else
{
// no more items, prune children from m_Container
ArrayList remove = new ArrayList();
foreach (IUPnPMedia m1 in this.CurrentContext.ContainerContext.CompleteList)
{
bool found = false;
foreach (IUPnPMedia m2 in this.m_Children)
{
if (m1 == m2)
{
found = true;
break;
}
}
if (found == false)
{
remove.Add(m1);
}
}
this.CurrentContext.ContainerContext.RemoveObjects(remove);
nomore = true;
}
}
if (this.OnIncrementalUpdate != null)
{
this.OnIncrementalUpdate(this, Result);
}
if (nomore)
{
if (this.OnRefreshComplete != null)
{
IUPnPMedia[] list = (IUPnPMedia[]) this.m_Children.ToArray(typeof(IUPnPMedia));
this.OnRefreshComplete(this, list);
}
}
}
else
{
// error occurred with the results...
// how should we report this?
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MvcApplicationTest.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Commons.Music.Midi
{
public class SmfMusic
{
List<SmfTrack> tracks = new List<SmfTrack> ();
public SmfMusic ()
{
Format = 1;
}
public short DeltaTimeSpec { get; set; }
public byte Format { get; set; }
public void AddTrack (SmfTrack track)
{
this.tracks.Add (track);
}
public IList<SmfTrack> Tracks {
get { return tracks; }
}
public int GetTotalPlayTimeMilliseconds ()
{
if (Format != 0)
throw new NotSupportedException ("Format 1 is not suitable to compute total play time within a song");
return GetTotalPlayTimeMilliseconds (Tracks [0].Events, DeltaTimeSpec);
}
public static int GetTotalPlayTimeMilliseconds (IList<SmfEvent> events, int deltaTimeSpec)
{
if (deltaTimeSpec < 0)
throw new NotSupportedException ("non-tick based DeltaTime");
else {
int tempo = SmfMetaType.DefaultTempo;
int v = 0;
foreach (var e in events) {
v += (int) (tempo / 1000 * e.DeltaTime / deltaTimeSpec);
if (e.Message.MessageType == SmfMessage.Meta && e.Message.Msb == SmfMetaType.Tempo)
tempo = SmfMetaType.GetTempo (e.Message.Data);
}
return v;
}
}
}
public class SmfTrack
{
public SmfTrack ()
: this (new List<SmfEvent> ())
{
}
public SmfTrack (IList<SmfEvent> events)
{
if (events == null)
throw new ArgumentNullException ("events");
this.events = events as List<SmfEvent> ?? new List<SmfEvent> (events);
}
List<SmfEvent> events;
public void AddEvent (SmfEvent evt)
{
events.Add (evt);
}
public IList<SmfEvent> Events {
get { return events; }
}
}
public struct SmfEvent
{
public SmfEvent (int deltaTime, SmfMessage msg)
{
DeltaTime = deltaTime;
Message = msg;
}
public readonly int DeltaTime;
public readonly SmfMessage Message;
public override string ToString ()
{
return String.Format ("[dt{0}]{1}", DeltaTime, Message);
}
}
public static class SmfCC
{
public const byte BankSelect = 0x00;
public const byte Modulation = 0x01;
public const byte Breath = 0x02;
public const byte Foot = 0x04;
public const byte PortamentTime = 0x05;
public const byte DteMsb = 0x06;
public const byte Volume = 0x07;
public const byte Balance = 0x08;
public const byte Pan = 0x0A;
public const byte Expression = 0x0B;
public const byte Effect1 = 0x0C;
public const byte Effect2 = 0x0D;
public const byte General1 = 0x10;
public const byte General2 = 0x11;
public const byte General3 = 0x12;
public const byte General4 = 0x13;
public const byte BankSelectLsb = 0x20;
public const byte ModulationLsb = 0x21;
public const byte BreathLsb = 0x22;
public const byte FootLsb = 0x24;
public const byte PortamentTimeLsb = 0x25;
public const byte DteLsb = 0x26;
public const byte VolumeLsb = 0x27;
public const byte BalanceLsb = 0x28;
public const byte PanLsb = 0x2A;
public const byte ExpressionLsb = 0x2B;
public const byte Effect1Lsb = 0x2C;
public const byte Effect2Lsb = 0x2D;
public const byte General1Lsb = 0x30;
public const byte General2Lsb = 0x31;
public const byte General3Lsb = 0x32;
public const byte General4Lsb = 0x33;
public const byte Hold = 0x40;
public const byte PortamentoSwitch = 0x41;
public const byte Sostenuto = 0x42;
public const byte SoftPedal = 0x43;
public const byte Legato = 0x44;
public const byte Hold2 = 0x45;
public const byte SoundController1 = 0x46;
public const byte SoundController2 = 0x47;
public const byte SoundController3 = 0x48;
public const byte SoundController4 = 0x49;
public const byte SoundController5 = 0x4A;
public const byte SoundController6 = 0x4B;
public const byte SoundController7 = 0x4C;
public const byte SoundController8 = 0x4D;
public const byte SoundController9 = 0x4E;
public const byte SoundController10 = 0x4F;
public const byte General5 = 0x50;
public const byte General6 = 0x51;
public const byte General7 = 0x52;
public const byte General8 = 0x53;
public const byte PortamentoControl = 0x54;
public const byte Rsd = 0x5B;
public const byte Tremolo = 0x5C;
public const byte Csd = 0x5D;
public const byte Celeste = 0x5E;
public const byte Phaser = 0x5F;
public const byte DteIncrement = 0x60;
public const byte DteDecrement = 0x61;
public const byte NrpnLsb = 0x62;
public const byte NrpnMsb = 0x63;
public const byte RpnLsb = 0x64;
public const byte RpnMsb = 0x65;
// Channel mode messages
public const byte AllSoundOff = 0x78;
public const byte ResetAllControllers = 0x79;
public const byte LocalControl = 0x7A;
public const byte AllNotesOff = 0x7B;
public const byte OmniModeOff = 0x7C;
public const byte OmniModeOn = 0x7D;
public const byte PolyModeOnOff = 0x7E;
public const byte PolyModeOn = 0x7F;
}
public static class SmfRpnType
{
public const short PitchBendSensitivity = 0;
public const short FineTuning = 1;
public const short CoarseTuning = 2;
public const short TuningProgram = 3;
public const short TuningBankSelect = 4;
public const short ModulationDepth = 5;
}
public static class SmfMetaType
{
public const byte SequenceNumber = 0x00;
public const byte Text = 0x01;
public const byte Copyright = 0x02;
public const byte TrackName = 0x03;
public const byte InstrumentName = 0x04;
public const byte Lyric = 0x05;
public const byte Marker = 0x06;
public const byte Cue = 0x07;
public const byte ChannelPrefix = 0x20;
public const byte EndOfTrack = 0x2F;
public const byte Tempo = 0x51;
public const byte SmpteOffset = 0x54;
public const byte TimeSignature = 0x58;
public const byte KeySignature = 0x59;
public const byte SequencerSpecific = 0x7F;
public const int DefaultTempo = 500000;
public static int GetTempo (byte [] data)
{
return (data [0] << 16) + (data [1] << 8) + data [2];
}
}
public struct SmfMessage
{
public const byte NoteOff = 0x80;
public const byte NoteOn = 0x90;
public const byte PAf = 0xA0;
public const byte CC = 0xB0;
public const byte Program = 0xC0;
public const byte CAf = 0xD0;
public const byte Pitch = 0xE0;
public const byte SysEx1 = 0xF0;
public const byte SysEx2 = 0xF7;
public const byte Meta = 0xFF;
public const byte EndSysEx = 0xF7;
public SmfMessage (int value)
{
Value = value;
Data = null;
}
public SmfMessage (byte type, byte arg1, byte arg2, byte [] data)
{
Value = type + (arg1 << 8) + (arg2 << 16);
Data = data;
}
public readonly int Value;
// This expects EndSysEx byte _inclusive_ for F0 message.
public readonly byte [] Data;
public byte StatusByte {
get { return (byte) (Value & 0xFF); }
}
public byte MessageType {
get {
switch (StatusByte) {
case Meta:
case SysEx1:
case SysEx2:
return StatusByte;
default:
return (byte) (Value & 0xF0);
}
}
}
public byte Msb {
get { return (byte) ((Value & 0xFF00) >> 8); }
}
public byte Lsb {
get { return (byte) ((Value & 0xFF0000) >> 16); }
}
public byte MetaType {
get { return Msb; }
}
public byte Channel {
get { return (byte) (Value & 0x0F); }
}
public static byte FixedDataSize (byte statusByte)
{
switch (statusByte & 0xF0) {
case 0xF0: // and 0xF7, 0xFF
return 0; // no fixed data
case Program: // ProgramChg
case CAf: // CAf
return 1;
default:
return 2;
}
}
public override string ToString ()
{
return String.Format ("{0:X02}:{1:X02}:{2:X02}{3}", StatusByte, Msb, Lsb, Data != null ? Data.Length + "[data]" : "");
}
}
public class SmfWriter
{
Stream stream;
public SmfWriter (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
this.stream = stream;
// default meta event writer.
meta_event_writer = SmfWriterExtension.DefaultMetaEventWriter;
}
public bool DisableRunningStatus { get; set; }
void WriteShort (short v)
{
stream.WriteByte ((byte) (v / 0x100));
stream.WriteByte ((byte) (v % 0x100));
}
void WriteInt (int v)
{
stream.WriteByte ((byte) (v / 0x1000000));
stream.WriteByte ((byte) (v / 0x10000 & 0xFF));
stream.WriteByte ((byte) (v / 0x100 & 0xFF));
stream.WriteByte ((byte) (v % 0x100));
}
public void WriteMusic (SmfMusic music)
{
WriteHeader (music.Format, (short) music.Tracks.Count, music.DeltaTimeSpec);
foreach (var track in music.Tracks)
WriteTrack (track);
}
public void WriteHeader (short format, short tracks, short deltaTimeSpec)
{
stream.Write (Encoding.UTF8.GetBytes ("MThd"), 0, 4);
WriteShort (0);
WriteShort (6);
WriteShort (format);
WriteShort (tracks);
WriteShort (deltaTimeSpec);
}
Func<bool,SmfEvent,Stream,int> meta_event_writer;
public Func<bool,SmfEvent,Stream,int> MetaEventWriter {
get { return meta_event_writer; }
set {
if (value == null)
throw new ArgumentNullException ("value");
meta_event_writer = value;
}
}
public void WriteTrack (SmfTrack track)
{
stream.Write (Encoding.UTF8.GetBytes ("MTrk"), 0, 4);
WriteInt (GetTrackDataSize (track));
byte running_status = 0;
foreach (SmfEvent e in track.Events) {
Write7BitVariableInteger (e.DeltaTime);
switch (e.Message.MessageType) {
case SmfMessage.Meta:
meta_event_writer (false, e, stream);
break;
case SmfMessage.SysEx1:
case SmfMessage.SysEx2:
stream.WriteByte (e.Message.MessageType);
Write7BitVariableInteger (e.Message.Data.Length);
stream.Write (e.Message.Data, 0, e.Message.Data.Length);
break;
default:
if (DisableRunningStatus || e.Message.StatusByte != running_status)
stream.WriteByte (e.Message.StatusByte);
int len = SmfMessage.FixedDataSize (e.Message.MessageType);
stream.WriteByte (e.Message.Msb);
if (len > 1)
stream.WriteByte (e.Message.Lsb);
if (len > 2)
throw new Exception ("Unexpected data size: " + len);
break;
}
running_status = e.Message.StatusByte;
}
}
int GetVariantLength (int value)
{
if (value < 0)
throw new ArgumentOutOfRangeException (String.Format ("Length must be non-negative integer: {0}", value));
if (value == 0)
return 1;
int ret = 0;
for (int x = value; x != 0; x >>= 7)
ret++;
return ret;
}
int GetTrackDataSize (SmfTrack track)
{
int size = 0;
byte running_status = 0;
foreach (SmfEvent e in track.Events) {
// delta time
size += GetVariantLength (e.DeltaTime);
// arguments
switch (e.Message.MessageType) {
case SmfMessage.Meta:
size += meta_event_writer (true, e, null);
break;
case SmfMessage.SysEx1:
case SmfMessage.SysEx2:
size++;
size += GetVariantLength (e.Message.Data.Length);
size += e.Message.Data.Length;
break;
default:
// message type & channel
if (DisableRunningStatus || running_status != e.Message.StatusByte)
size++;
size += SmfMessage.FixedDataSize (e.Message.MessageType);
break;
}
running_status = e.Message.StatusByte;
}
return size;
}
void Write7BitVariableInteger (int value)
{
Write7BitVariableInteger (value, false);
}
void Write7BitVariableInteger (int value, bool shifted)
{
if (value == 0) {
stream.WriteByte ((byte) (shifted ? 0x80 : 0));
return;
}
if (value >= 0x80)
Write7BitVariableInteger (value >> 7, true);
stream.WriteByte ((byte) ((value & 0x7F) + (shifted ? 0x80 : 0)));
}
}
public static class SmfWriterExtension
{
static readonly Func<bool, SmfEvent, Stream, int> default_meta_writer, vsq_meta_text_splitter;
static SmfWriterExtension ()
{
default_meta_writer = delegate (bool lengthMode, SmfEvent e, Stream stream) {
if (lengthMode) {
if (e.Message.Data.Length == 0)
return 3; // 0xFF, metaType, 0
// [0x00] 0xFF metaType size ... (note that for more than one meta event it requires step count of 0).
int repeatCount = e.Message.Data.Length / 0x7F;
if (repeatCount == 0)
return 3 + e.Message.Data.Length;
int mod = e.Message.Data.Length % 0x7F;
return repeatCount * (4 + 0x7F) - 1 + (mod > 0 ? 4 + mod : 0);
}
int written = 0;
int total = e.Message.Data.Length;
do {
if (written > 0)
stream.WriteByte (0); // step
stream.WriteByte (0xFF);
stream.WriteByte (e.Message.MetaType);
int size = Math.Min (0x7F, total - written);
stream.WriteByte ((byte) size);
stream.Write (e.Message.Data, written, size);
written += size;
} while (written < total);
return 0;
};
vsq_meta_text_splitter = delegate (bool lengthMode, SmfEvent e, Stream stream) {
// The split should not be applied to "Master Track"
if (e.Message.Data.Length < 0x80) {
return default_meta_writer (lengthMode, e, stream);
}
if (lengthMode) {
if (e.Message.Data.Length == 0)
return 11; // 0xFF, metaType, 8, "DM:0000:"
// { [0x00] 0xFF metaType DM:xxxx:... } * repeat + 0x00 0xFF metaType DM:xxxx:mod...
// (note that for more than one meta event it requires step count of 0).
int repeatCount = e.Message.Data.Length / 0x77;
int mod = e.Message.Data.Length % 0x77;
return repeatCount * (12 + 0x77) - (repeatCount > 0 ? 1 : 0) + (mod > 0 ? 12 + mod : 0) - 1;
}
int written = 0;
int total = e.Message.Data.Length;
int idx = 0;
do {
if (written > 0)
stream.WriteByte (0); // step
stream.WriteByte (0xFF);
stream.WriteByte (e.Message.MetaType);
int size = Math.Min (0x77, total - written);
stream.WriteByte ((byte) (size + 8));
stream.Write (Encoding.ASCII.GetBytes (String.Format ("DM:{0:D04}:", idx++)), 0, 8);
stream.Write (e.Message.Data, written, size);
written += size;
} while (written < total);
return 0;
};
}
public static Func<bool, SmfEvent, Stream, int> DefaultMetaEventWriter {
get { return default_meta_writer; }
}
public static Func<bool, SmfEvent, Stream, int> VsqMetaTextSplitter {
get { return vsq_meta_text_splitter; }
}
}
public class SmfReader
{
public SmfReader (Stream stream)
{
this.stream = stream;
}
Stream stream;
SmfMusic data = new SmfMusic ();
public SmfMusic Music { get { return data; } }
public void Parse ()
{
if (
ReadByte () != 'M'
|| ReadByte () != 'T'
|| ReadByte () != 'h'
|| ReadByte () != 'd')
throw ParseError ("MThd is expected");
if (ReadInt32 () != 6)
throw ParseError ("Unexpeted data size (should be 6)");
data.Format = (byte) ReadInt16 ();
int tracks = ReadInt16 ();
data.DeltaTimeSpec = ReadInt16 ();
try {
for (int i = 0; i < tracks; i++)
data.Tracks.Add (ReadTrack ());
} catch (FormatException ex) {
throw ParseError ("Unexpected data error", ex);
}
}
SmfTrack ReadTrack ()
{
var tr = new SmfTrack ();
if (
ReadByte () != 'M'
|| ReadByte () != 'T'
|| ReadByte () != 'r'
|| ReadByte () != 'k')
throw ParseError ("MTrk is expected");
int trackSize = ReadInt32 ();
current_track_size = 0;
int total = 0;
while (current_track_size < trackSize) {
int delta = ReadVariableLength ();
tr.Events.Add (ReadEvent (delta));
total += delta;
}
if (current_track_size != trackSize)
throw ParseError ("Size information mismatch");
return tr;
}
int current_track_size;
byte running_status;
SmfEvent ReadEvent (int deltaTime)
{
byte b = PeekByte ();
running_status = b < 0x80 ? running_status : ReadByte ();
int len;
switch (running_status) {
case SmfMessage.SysEx1:
case SmfMessage.SysEx2:
case SmfMessage.Meta:
byte metaType = running_status == SmfMessage.Meta ? ReadByte () : (byte) 0;
len = ReadVariableLength ();
byte [] args = new byte [len];
if (len > 0)
ReadBytes (args);
return new SmfEvent (deltaTime, new SmfMessage (running_status, metaType, 0, args));
default:
int value = running_status;
value += ReadByte () << 8;
if (SmfMessage.FixedDataSize (running_status) == 2)
value += ReadByte () << 16;
return new SmfEvent (deltaTime, new SmfMessage (value));
}
}
void ReadBytes (byte [] args)
{
current_track_size += args.Length;
int start = 0;
if (peek_byte >= 0) {
args [0] = (byte) peek_byte;
peek_byte = -1;
start = 1;
}
int len = stream.Read (args, start, args.Length - start);
try {
if (len < args.Length - start)
throw ParseError (String.Format ("The stream is insufficient to read {0} bytes specified in the SMF event. Only {1} bytes read.", args.Length, len));
} finally {
stream_position += len;
}
}
int ReadVariableLength ()
{
int val = 0;
for (int i = 0; i < 4; i++) {
byte b = ReadByte ();
val = (val << 7) + b;
if (b < 0x80)
return val;
val -= 0x80;
}
throw ParseError ("Delta time specification exceeds the 4-byte limitation.");
}
int peek_byte = -1;
int stream_position;
byte PeekByte ()
{
if (peek_byte < 0)
peek_byte = stream.ReadByte ();
if (peek_byte < 0)
throw ParseError ("Insufficient stream. Failed to read a byte.");
return (byte) peek_byte;
}
byte ReadByte ()
{
try {
current_track_size++;
if (peek_byte >= 0) {
byte b = (byte) peek_byte;
peek_byte = -1;
return b;
}
int ret = stream.ReadByte ();
if (ret < 0)
throw ParseError ("Insufficient stream. Failed to read a byte.");
return (byte) ret;
} finally {
stream_position++;
}
}
short ReadInt16 ()
{
return (short) ((ReadByte () << 8) + ReadByte ());
}
int ReadInt32 ()
{
return (((ReadByte () << 8) + ReadByte () << 8) + ReadByte () << 8) + ReadByte ();
}
Exception ParseError (string msg)
{
return ParseError (msg, null);
}
Exception ParseError (string msg, Exception innerException)
{
throw new SmfParserException (String.Format (msg + "(at {0})", stream_position), innerException);
}
}
public class SmfParserException : Exception
{
public SmfParserException () : this ("SMF parser error") {}
public SmfParserException (string message) : base (message) {}
public SmfParserException (string message, Exception innerException) : base (message, innerException) {}
}
public class SmfTrackMerger
{
public static SmfMusic Merge (SmfMusic source)
{
return new SmfTrackMerger (source).GetMergedEvents ();
}
SmfTrackMerger (SmfMusic source)
{
this.source = source;
}
SmfMusic source;
// FIXME: it should rather be implemented to iterate all
// tracks with index to events, pick the track which contains
// the nearest event and push the events into the merged queue.
// It's simpler, and costs less by removing sort operation
// over thousands of events.
SmfMusic GetMergedEvents ()
{
IList<SmfEvent> l = new List<SmfEvent> ();
foreach (var track in source.Tracks) {
int delta = 0;
foreach (var mev in track.Events) {
delta += mev.DeltaTime;
l.Add (new SmfEvent (delta, mev.Message));
}
}
if (l.Count == 0)
return new SmfMusic () { DeltaTimeSpec = source.DeltaTimeSpec }; // empty (why did you need to sort your song file?)
// Sort() does not always work as expected.
// For example, it does not always preserve event
// orders on the same channels when the delta time
// of event B after event A is 0. It could be sorted
// either as A->B or B->A.
//
// To resolve this ieeue, we have to sort "chunk"
// of events, not all single events themselves, so
// that order of events in the same chunk is preserved
// i.e. [AB] at 48 and [CDE] at 0 should be sorted as
// [CDE] [AB].
var idxl = new List<int> (l.Count);
idxl.Add (0);
int prev = 0;
for (int i = 0; i < l.Count; i++) {
if (l [i].DeltaTime != prev) {
idxl.Add (i);
prev = l [i].DeltaTime;
}
}
idxl.Sort (delegate (int i1, int i2) {
return l [i1].DeltaTime - l [i2].DeltaTime;
});
// now build a new event list based on the sorted blocks.
var l2 = new List<SmfEvent> (l.Count);
int idx;
for (int i = 0; i < idxl.Count; i++)
for (idx = idxl [i], prev = l [idx].DeltaTime; idx < l.Count && l [idx].DeltaTime == prev; idx++)
l2.Add (l [idx]);
//if (l.Count != l2.Count) throw new Exception (String.Format ("Internal eror: count mismatch: l1 {0} l2 {1}", l.Count, l2.Count));
l = l2;
// now events should be sorted correctly.
var waitToNext = l [0].DeltaTime;
for (int i = 0; i < l.Count - 1; i++) {
if (l [i].Message.Value != 0) { // if non-dummy
var tmp = l [i + 1].DeltaTime - l [i].DeltaTime;
l [i] = new SmfEvent (waitToNext, l [i].Message);
waitToNext = tmp;
}
}
l [l.Count - 1] = new SmfEvent (waitToNext, l [l.Count - 1].Message);
var m = new SmfMusic ();
m.DeltaTimeSpec = source.DeltaTimeSpec;
m.Format = 0;
m.Tracks.Add (new SmfTrack (l));
return m;
}
}
public class SmfTrackSplitter
{
public static SmfMusic Split (IList<SmfEvent> source, short deltaTimeSpec)
{
return new SmfTrackSplitter (source, deltaTimeSpec).Split ();
}
SmfTrackSplitter (IList<SmfEvent> source, short deltaTimeSpec)
{
if (source == null)
throw new ArgumentNullException ("source");
this.source = source;
delta_time_spec = deltaTimeSpec;
var mtr = new SplitTrack (-1);
tracks.Add (-1, mtr);
}
IList<SmfEvent> source;
short delta_time_spec;
Dictionary<int,SplitTrack> tracks = new Dictionary<int,SplitTrack> ();
class SplitTrack
{
public SplitTrack (int trackID)
{
TrackID = trackID;
Track = new SmfTrack ();
}
public int TrackID;
public int TotalDeltaTime;
public SmfTrack Track;
public void AddEvent (int deltaInsertAt, SmfEvent e)
{
e = new SmfEvent (deltaInsertAt - TotalDeltaTime, e.Message);
Track.Events.Add (e);
TotalDeltaTime = deltaInsertAt;
}
}
SplitTrack GetTrack (int track)
{
SplitTrack t;
if (!tracks.TryGetValue (track, out t)) {
t = new SplitTrack (track);
tracks [track] = t;
}
return t;
}
// Override it to customize track dispatcher. It would be
// useful to split note messages out from non-note ones,
// to ease data reading.
public virtual int GetTrackID (SmfEvent e)
{
switch (e.Message.MessageType) {
case SmfMessage.Meta:
case SmfMessage.SysEx1:
case SmfMessage.SysEx2:
return -1;
default:
return e.Message.Channel;
}
}
public SmfMusic Split ()
{
int totalDeltaTime = 0;
foreach (var e in source) {
totalDeltaTime += e.DeltaTime;
int id = GetTrackID (e);
GetTrack (id).AddEvent (totalDeltaTime, e);
}
var m = new SmfMusic ();
m.DeltaTimeSpec = delta_time_spec;
foreach (var t in tracks.Values)
m.Tracks.Add (t.Track);
return m;
}
}
}
| |
// 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;
using System.IO.Pipes;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Net.Sockets.Tests
{
public partial class CreateSocket
{
public static object[][] DualModeSuccessInputs = {
new object[] { SocketType.Stream, ProtocolType.Tcp },
new object[] { SocketType.Dgram, ProtocolType.Udp },
};
public static object[][] DualModeFailureInputs = {
new object[] { SocketType.Dgram, ProtocolType.Tcp },
new object[] { SocketType.Rdm, ProtocolType.Tcp },
new object[] { SocketType.Seqpacket, ProtocolType.Tcp },
new object[] { SocketType.Unknown, ProtocolType.Tcp },
new object[] { SocketType.Rdm, ProtocolType.Udp },
new object[] { SocketType.Seqpacket, ProtocolType.Udp },
new object[] { SocketType.Stream, ProtocolType.Udp },
new object[] { SocketType.Unknown, ProtocolType.Udp },
};
private static bool SupportsRawSockets => AdminHelpers.IsProcessElevated();
private static bool NotSupportsRawSockets => !SupportsRawSockets;
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(DualModeSuccessInputs))]
public void DualMode_Success(SocketType socketType, ProtocolType protocolType)
{
using (new Socket(socketType, protocolType))
{
}
}
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(DualModeFailureInputs))]
public void DualMode_Failure(SocketType socketType, ProtocolType protocolType)
{
Assert.Throws<SocketException>(() => new Socket(socketType, protocolType));
}
public static object[][] CtorSuccessInputs = {
new object[] { AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp },
new object[] { AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp },
new object[] { AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp },
new object[] { AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp },
};
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(CtorSuccessInputs))]
public void Ctor_Success(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
using (new Socket(addressFamily, socketType, protocolType))
{
}
}
public static object[][] CtorFailureInputs = {
new object[] { AddressFamily.Unknown, SocketType.Stream, ProtocolType.Tcp },
new object[] { AddressFamily.Unknown, SocketType.Dgram, ProtocolType.Udp },
new object[] { AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Tcp },
new object[] { AddressFamily.InterNetwork, SocketType.Rdm, ProtocolType.Tcp },
new object[] { AddressFamily.InterNetwork, SocketType.Seqpacket, ProtocolType.Tcp },
new object[] { AddressFamily.InterNetwork, SocketType.Unknown, ProtocolType.Tcp },
new object[] { AddressFamily.InterNetwork, SocketType.Rdm, ProtocolType.Udp },
new object[] { AddressFamily.InterNetwork, SocketType.Seqpacket, ProtocolType.Udp },
new object[] { AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp },
new object[] { AddressFamily.InterNetwork, SocketType.Unknown, ProtocolType.Udp },
};
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(CtorFailureInputs))]
public void Ctor_Failure(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
Assert.Throws<SocketException>(() => new Socket(addressFamily, socketType, protocolType));
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[InlineData(AddressFamily.InterNetwork, ProtocolType.Tcp)]
[InlineData(AddressFamily.InterNetwork, ProtocolType.Udp)]
[InlineData(AddressFamily.InterNetwork, ProtocolType.Icmp)]
[InlineData(AddressFamily.InterNetworkV6, ProtocolType.Tcp)]
[InlineData(AddressFamily.InterNetworkV6, ProtocolType.Udp)]
[InlineData(AddressFamily.InterNetworkV6, ProtocolType.IcmpV6)]
[ConditionalTheory(nameof(SupportsRawSockets))]
public void Ctor_Raw_Supported_Success(AddressFamily addressFamily, ProtocolType protocolType)
{
using (new Socket(addressFamily, SocketType.Raw, protocolType))
{
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[InlineData(AddressFamily.InterNetwork, ProtocolType.Tcp)]
[InlineData(AddressFamily.InterNetwork, ProtocolType.Udp)]
[InlineData(AddressFamily.InterNetwork, ProtocolType.Icmp)]
[InlineData(AddressFamily.InterNetworkV6, ProtocolType.Tcp)]
[InlineData(AddressFamily.InterNetworkV6, ProtocolType.Udp)]
[InlineData(AddressFamily.InterNetworkV6, ProtocolType.IcmpV6)]
[ConditionalTheory(nameof(NotSupportsRawSockets))]
public void Ctor_Raw_NotSupported_ExpectedError(AddressFamily addressFamily, ProtocolType protocolType)
{
SocketException e = Assert.Throws<SocketException>(() => new Socket(addressFamily, SocketType.Raw, protocolType));
Assert.Contains(e.SocketErrorCode, new[] { SocketError.AccessDenied, SocketError.ProtocolNotSupported });
}
[Theory]
[InlineData(true, 0)] // Accept
[InlineData(false, 0)]
[InlineData(true, 1)] // AcceptAsync
[InlineData(false, 1)]
[InlineData(true, 2)] // Begin/EndAccept
[InlineData(false, 2)]
public void CtorAndAccept_SocketNotKeptAliveViaInheritance(bool validateClientOuter, int acceptApiOuter)
{
// Run the test in another process so as to not have trouble with other tests
// launching child processes that might impact inheritance.
RemoteExecutor.Invoke((validateClientString, acceptApiString) =>
{
bool validateClient = bool.Parse(validateClientString);
int acceptApi = int.Parse(acceptApiString);
// Create a listening server.
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(int.MaxValue);
EndPoint ep = listener.LocalEndPoint;
// Create a client and connect to that listener.
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
client.Connect(ep);
// Accept the connection using one of multiple accept mechanisms.
Socket server =
acceptApi == 0 ? listener.Accept() :
acceptApi == 1 ? listener.AcceptAsync().GetAwaiter().GetResult() :
acceptApi == 2 ? Task.Factory.FromAsync(listener.BeginAccept, listener.EndAccept, null).GetAwaiter().GetResult() :
throw new Exception($"Unexpected {nameof(acceptApi)}: {acceptApi}");
// Get streams for the client and server, and create a pipe that we'll use
// to communicate with a child process.
using (var serverStream = new NetworkStream(server, ownsSocket: true))
using (var clientStream = new NetworkStream(client, ownsSocket: true))
using (var serverPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
{
// Create a child process that blocks waiting to receive a signal on the anonymous pipe.
// The whole purpose of the child is to test whether handles are inherited, so we
// keep the child process alive until we're done validating that handles close as expected.
using (RemoteExecutor.Invoke(clientPipeHandle =>
{
using (var clientPipe = new AnonymousPipeClientStream(PipeDirection.In, clientPipeHandle))
{
Assert.Equal(42, clientPipe.ReadByte());
}
}, serverPipe.GetClientHandleAsString()))
{
if (validateClient) // Validate that the child isn't keeping alive the "new Socket" for the client
{
// Send data from the server to client, then validate the client gets EOF when the server closes.
serverStream.WriteByte(84);
Assert.Equal(84, clientStream.ReadByte());
serverStream.Close();
Assert.Equal(-1, clientStream.ReadByte());
}
else // Validate that the child isn't keeping alive the "listener.Accept" for the server
{
// Send data from the client to server, then validate the server gets EOF when the client closes.
clientStream.WriteByte(84);
Assert.Equal(84, serverStream.ReadByte());
clientStream.Close();
Assert.Equal(-1, serverStream.ReadByte());
}
// And validate that we after closing the listening socket, we're not able to connect.
listener.Dispose();
using (var tmpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.ThrowsAny<SocketException>(() => tmpClient.Connect(ep));
}
// Let the child process terminate.
serverPipe.WriteByte(42);
}
}
}
}
}, validateClientOuter.ToString(), acceptApiOuter.ToString()).Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Sockets;
using System.Net.Test.Common;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.NetworkInformation.Tests
{
[PlatformSpecific(TestPlatforms.Windows)]
public class IPInterfacePropertiesTest_Windows
{
private readonly ITestOutputHelper _log;
public IPInterfacePropertiesTest_Windows()
{
_log = TestLogging.GetInstance();
}
[Fact]
public void IPInfoTest_AccessAllProperties_NoErrors()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
_log.WriteLine("- Supports IPv4: " + nic.Supports(NetworkInterfaceComponent.IPv4));
_log.WriteLine("- Supports IPv6: " + nic.Supports(NetworkInterfaceComponent.IPv6));
IPInterfaceProperties ipProperties = nic.GetIPProperties();
Assert.NotNull(ipProperties);
Assert.NotNull(ipProperties.AnycastAddresses);
_log.WriteLine("- Anycast Addresses: " + ipProperties.AnycastAddresses.Count);
foreach (IPAddressInformation anyAddr in ipProperties.AnycastAddresses)
{
_log.WriteLine("-- " + anyAddr.Address.ToString());
_log.WriteLine("--- Dns Eligible: " + anyAddr.IsDnsEligible);
_log.WriteLine("--- Transient: " + anyAddr.IsTransient);
}
Assert.NotNull(ipProperties.DhcpServerAddresses);
_log.WriteLine("- Dhcp Server Addresses: " + ipProperties.DhcpServerAddresses.Count);
foreach (IPAddress dhcp in ipProperties.DhcpServerAddresses)
{
_log.WriteLine("-- " + dhcp.ToString());
}
Assert.NotNull(ipProperties.DnsAddresses);
_log.WriteLine("- Dns Addresses: " + ipProperties.DnsAddresses.Count);
foreach (IPAddress dns in ipProperties.DnsAddresses)
{
_log.WriteLine("-- " + dns.ToString());
}
Assert.NotNull(ipProperties.DnsSuffix);
_log.WriteLine("- Dns Suffix: " + ipProperties.DnsSuffix);
Assert.NotNull(ipProperties.GatewayAddresses);
_log.WriteLine("- Gateway Addresses: " + ipProperties.GatewayAddresses.Count);
foreach (GatewayIPAddressInformation gateway in ipProperties.GatewayAddresses)
{
_log.WriteLine("-- " + gateway.Address.ToString());
}
_log.WriteLine("- Dns Enabled: " + ipProperties.IsDnsEnabled);
_log.WriteLine("- Dynamic Dns Enabled: " + ipProperties.IsDynamicDnsEnabled);
Assert.NotNull(ipProperties.MulticastAddresses);
_log.WriteLine("- Multicast Addresses: " + ipProperties.MulticastAddresses.Count);
foreach (IPAddressInformation multi in ipProperties.MulticastAddresses)
{
_log.WriteLine("-- " + multi.Address.ToString());
_log.WriteLine("--- Dns Eligible: " + multi.IsDnsEligible);
_log.WriteLine("--- Transient: " + multi.IsTransient);
}
Assert.NotNull(ipProperties.UnicastAddresses);
_log.WriteLine("- Unicast Addresses: " + ipProperties.UnicastAddresses.Count);
foreach (UnicastIPAddressInformation uni in ipProperties.UnicastAddresses)
{
_log.WriteLine("-- " + uni.Address.ToString());
_log.WriteLine("--- Preferred Lifetime: " + uni.AddressPreferredLifetime);
_log.WriteLine("--- Valid Lifetime: " + uni.AddressValidLifetime);
_log.WriteLine("--- Dhcp lease Lifetime: " + uni.DhcpLeaseLifetime);
_log.WriteLine("--- Duplicate Address Detection State: " + uni.DuplicateAddressDetectionState);
Assert.NotNull(uni.IPv4Mask);
_log.WriteLine("--- IPv4 Mask: " + uni.IPv4Mask);
_log.WriteLine("--- Dns Eligible: " + uni.IsDnsEligible);
_log.WriteLine("--- Transient: " + uni.IsTransient);
_log.WriteLine("--- Prefix Origin: " + uni.PrefixOrigin);
_log.WriteLine("--- Suffix Origin: " + uni.SuffixOrigin);
// Prefix Length
_log.WriteLine("--- Prefix Length: " + uni.PrefixLength);
Assert.NotEqual(0, uni.PrefixLength);
}
Assert.NotNull(ipProperties.WinsServersAddresses);
_log.WriteLine("- Wins Addresses: " + ipProperties.WinsServersAddresses.Count);
foreach (IPAddress wins in ipProperties.WinsServersAddresses)
{
_log.WriteLine("-- " + wins.ToString());
}
}
}
[Fact]
public void IPInfoTest_AccessAllIPv4Properties_NoErrors()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
IPInterfaceProperties ipProperties = nic.GetIPProperties();
_log.WriteLine("IPv4 Properties:");
if (!nic.Supports(NetworkInterfaceComponent.IPv4))
{
var nie = Assert.Throws<NetworkInformationException>(() => ipProperties.GetIPv4Properties());
Assert.Equal(SocketError.ProtocolNotSupported, (SocketError)nie.ErrorCode);
continue;
}
IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties();
_log.WriteLine("Index: " + ipv4Properties.Index);
_log.WriteLine("IsAutomaticPrivateAddressingActive: " + ipv4Properties.IsAutomaticPrivateAddressingActive);
_log.WriteLine("IsAutomaticPrivateAddressingEnabled: " + ipv4Properties.IsAutomaticPrivateAddressingEnabled);
_log.WriteLine("IsDhcpEnabled: " + ipv4Properties.IsDhcpEnabled);
_log.WriteLine("IsForwardingEnabled: " + ipv4Properties.IsForwardingEnabled);
_log.WriteLine("Mtu: " + ipv4Properties.Mtu);
_log.WriteLine("UsesWins: " + ipv4Properties.UsesWins);
}
}
[Fact]
public void IPInfoTest_AccessAllIPv6Properties_NoErrors()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
IPInterfaceProperties ipProperties = nic.GetIPProperties();
_log.WriteLine("IPv6 Properties:");
if (!nic.Supports(NetworkInterfaceComponent.IPv6))
{
var nie = Assert.Throws<NetworkInformationException>(() => ipProperties.GetIPv6Properties());
Assert.Equal(SocketError.ProtocolNotSupported, (SocketError)nie.ErrorCode);
continue;
}
IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties();
if (ipv6Properties == null)
{
_log.WriteLine("IPv6Properties is null");
continue;
}
_log.WriteLine("Index: " + ipv6Properties.Index);
_log.WriteLine("Mtu: " + ipv6Properties.Mtu);
_log.WriteLine("ScopeID: " + ipv6Properties.GetScopeId(ScopeLevel.Link));
}
}
[Fact]
[Trait("IPv6", "true")]
public void IPv6ScopeId_GetLinkLevel_MatchesIndex()
{
Assert.True(Capability.IPv6Support());
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProperties = nic.GetIPProperties();
if (!nic.Supports(NetworkInterfaceComponent.IPv6))
{
continue;
}
IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties();
// This is not officially guaranteed by Windows, but it's what gets used.
Assert.Equal(ipv6Properties.Index, ipv6Properties.GetScopeId(ScopeLevel.Link));
}
}
[Fact]
[Trait("IPv6", "true")]
public void IPv6ScopeId_AccessAllValues_Success()
{
Assert.True(Capability.IPv6Support());
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
if (!nic.Supports(NetworkInterfaceComponent.IPv6))
{
continue;
}
IPInterfaceProperties ipProperties = nic.GetIPProperties();
_log.WriteLine("- IPv6 Scope levels:");
IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties();
Array values = Enum.GetValues(typeof(ScopeLevel));
foreach (ScopeLevel level in values)
{
_log.WriteLine("-- Level: " + level + "; " + ipv6Properties.GetScopeId(level));
}
}
}
}
}
| |
using System;
using System.Xml;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
/**
* Inventory service
*
* Responsible for running the agent when the various hooks are
* pulled.
*
* @access public
* @package synd.core.module
*/
namespace Inventory {
public class Service : ServiceBase {
public static Service Instance = null;
public const string Name = "Inventory Agent";
private System.ComponentModel.Container components = null;
private XmlDocument _config = null;
private Thread _worker = null;
private Agent _agent = null;
private AutoResetEvent _lock = null;
private Timer _timer = null;
private IChannel Channel = null;
/**
* Contructor is run once on computer/serviceprocess startup
*/
public Service() {
Instance = this;
ServiceName = Name;
}
/**
* The main entry point for the process
*
* This method is run when the program is executed from the
* commandline or when the serviceprocess starts
*/
static void Main(string[] args) {
if (_hasArgument(args, "install")) {
_install();
if (_hasArgument(args, "start"))
_start();
}
else if (_hasArgument(args, "uninstall"))
_uninstall();
else if (_hasArgument(args, "start"))
_start();
else if (_hasArgument(args, "stop"))
_stop();
else {
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service() };
ServiceBase.Run(ServicesToRun);
}
}
static private bool _hasArgument(string[] args, string arg) {
for (int i=0; i<args.Length; i++) {
if ("/" == args[i].Substring(0,1) && args[i].Substring(1).ToLower() == arg.ToLower() ||
"--" == args[i].Substring(0,2) && args[i].Substring(2).ToLower() == arg.ToLower())
return true;
}
return false;
}
protected override void Dispose(bool disposing) {
if (disposing && null != components)
components.Dispose();
base.Dispose(disposing);
}
protected void LoadConfig() {
string cwd = System.Reflection.Assembly.GetExecutingAssembly().Location;
XmlTextReader reader = new XmlTextReader(
cwd.Substring(0, cwd.LastIndexOf("\\")) + "\\Inventory.xml");
reader.WhitespaceHandling = WhitespaceHandling.None;
_config = new XmlDocument();
_config.Load(reader);
}
protected ITransport GetTransport() {
XmlNode agent = _config.SelectSingleNode("/Inventory/Agent");
XmlNode method = agent.Attributes.GetNamedItem("Transport");
switch (method.Value.ToUpper()) {
case "SOAP":
XmlNode location = agent.Attributes.GetNamedItem("Location");
if (null == location)
throw new ArgumentException("Attribute 'Location' missing from Agent element in config");
IInventoryModule inventory = (IInventoryModule)Activator.GetObject(typeof(IInventoryModule), location.Value);
return new SoapTransport(inventory, new XmlFormatter());
case "MAIL":
XmlNode server = agent.Attributes.GetNamedItem("Server");
XmlNode address = agent.Attributes.GetNamedItem("Address");
if (null == server)
throw new ArgumentException("Attribute 'Server' missing from Agent element in config");
if (null == address)
throw new ArgumentException("Attribute 'Address' missing from Agent element in config");
return new MailTransport(server.Value, address.Value, new XmlFormatter());
}
throw new ArgumentException("Invalid transport method '" + method.Value + "'");
}
/**
* Service startup hook
*/
protected override void OnStart(string[] args) {
try {
// Load Inventory.xml from current directory
LoadConfig();
// Attempt to start the remote control listener
string uri = InitializeChannel();
// Set to signalled (true) to run agent on startup
_lock = new AutoResetEvent(true);
_agent = new Agent(GetTransport(), _config.SelectSingleNode("/Inventory/Agent"), uri);
_worker = new Thread(new ThreadStart(WorkerThread));
_worker.Start();
// Setup a timer to run every 24h
_timer = new Timer(new TimerCallback(this._callback_timer), new object(),
this.AgentInterval, this.AgentInterval);
}
catch (Exception e) {
Log(e.ToString(), EventLogEntryType.Warning);
}
}
/**
* Service stop hook
*/
protected override void OnStop() {
// Abort worker thread
_worker.Abort();
// Unregister remoting channels
if (null != Channel) {
try {
ChannelServices.UnregisterChannel(Channel);
}
catch (RemotingException) {
}
finally {
Channel = null;
}
}
// Wait for worker to exit
_worker.Join();
}
private TimeSpan AgentInterval {
get {
try {
XmlNode timer = _config.SelectSingleNode("/Inventory/Agent/Timer");
int hours = Convert.ToInt32(timer.Attributes.GetNamedItem("Interval").Value);
return new TimeSpan(hours, 0, 0);
}
catch (Exception) {
return new TimeSpan(24, 0, 0);
}
}
}
/**
* Attempt to start the RPC service
*
* If a port has been configured in inventory.xml the remote
* service will start allowing for remote control of the agent,
* otherwise no listening port will be opened and the regular
* outbound HTTP channel will be registered.
*
* @return string Return the URI of the remote service or null
*/
protected string InitializeChannel() {
string uri = null;
try {
int port = 0;
XmlNode remote = _config.SelectSingleNode("/Inventory/RemoteService");
if (null == remote || 0 == (port = Convert.ToInt32(remote.Attributes.GetNamedItem("Port").Value)))
throw new Exception("No port specified for remote service.");
// Register the listening server channel
HttpServerChannel server = new HttpServerChannel(port);
ChannelServices.RegisterChannel(server, true);
// Register the remote control interface
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteService), "agent", WellKnownObjectMode.SingleCall);
Channel = server;
uri = server.GetChannelUri() + "/agent";
}
catch (Exception e) {
Log(e.ToString(), EventLogEntryType.Information);
// Attempt to register a normal client channel
try {
Channel = new HttpClientChannel();
ChannelServices.RegisterChannel(Channel, true);
}
catch (RemotingException) { }
}
return uri;
}
/**
* Timer callback, run every XX hours
*/
private void _callback_timer(object state) {
RunAgent();
}
/**
* Launch the agent
*/
public bool RunAgent() {
// Check if worker is running
if (!Monitor.TryEnter(_worker))
return false;
// Release lock and signal worker
Monitor.Exit(_worker);
return _lock.Set();
}
/**
* Agent worker thread
*/
private void WorkerThread() {
try {
for (;;) {
// Wait for signal to run agent
_lock.WaitOne();
lock (_worker) {
_agent.Run();
}
}
}
catch (ThreadAbortException) {
// Exit nicely on abort requests
}
catch (Exception e) {
Log(e.ToString(), EventLogEntryType.Warning);
}
}
/**
* Attempts to start the service
*/
private static void _start() {
try {
ServiceController controller = new ServiceController(Name);
if (ServiceControllerStatus.Stopped == controller.Status)
controller.Start();
}
catch (Exception e) {
Log(e.ToString(), EventLogEntryType.Warning);
}
}
/**
* Attempts to stop the service
*/
private static void _stop() {
try {
ServiceController controller = new ServiceController(Name);
if (ServiceControllerStatus.Stopped != controller.Status &&
ServiceControllerStatus.StopPending != controller.Status)
controller.Stop();
}
catch (Exception e) {
Log(e.ToString(), EventLogEntryType.Warning);
}
}
/**
* Attempts to install the service
*/
private static void _install() {
try {
TransactedInstaller transaction = new TransactedInstaller();
transaction.Installers.Add(new InventoryInstaller(Name));
String path = String.Format("/assemblypath={0}",
System.Reflection.Assembly.GetExecutingAssembly().Location);
String[] cmdline = {path};
transaction.Context = new InstallContext("", cmdline);
transaction.Install(new Hashtable());
Log("Inventory service installed");
}
catch (Exception e) {
Log("Could not install service: "+e.ToString(), EventLogEntryType.Warning);
}
}
/**
* Attempts to uninstall the service
*/
private static void _uninstall() {
try {
TransactedInstaller transaction = new TransactedInstaller();
transaction.Installers.Add(new InventoryInstaller(Name));
String path = String.Format("/assemblypath={0}",
System.Reflection.Assembly.GetExecutingAssembly().Location);
String[] cmdline = {path};
InstallContext context = new InstallContext("", cmdline);
transaction.Context = context;
transaction.Uninstall(null);
Log("Inventory service uninstalled");
}
catch (Exception e) {
Log("Could not uninstall service: "+e.ToString(), EventLogEntryType.Warning);
}
}
/**
* Writes an Information type message to the syslog
*/
public static void Log(string message) {
Log(message, EventLogEntryType.Information);
}
/**
* Writes a message to the syslog
*/
public static void Log(string message, EventLogEntryType type) {
const string source = Name;
if (!EventLog.SourceExists(source))
EventLog.CreateEventSource(source, "Application");
EventLog.WriteEntry(source, message, type);
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BillingPlanInformation
/// </summary>
[DataContract]
public partial class BillingPlanInformation : IEquatable<BillingPlanInformation>, IValidatableObject
{
public BillingPlanInformation()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BillingPlanInformation" /> class.
/// </summary>
/// <param name="AppStoreReceipt">AppStoreReceipt.</param>
/// <param name="BillingAddress">BillingAddress.</param>
/// <param name="CreditCardInformation">CreditCardInformation.</param>
/// <param name="DowngradeReason">.</param>
/// <param name="EnableSupport">.</param>
/// <param name="IncludedSeats">The number of seats (users) included..</param>
/// <param name="IncrementalSeats">Reserved: TBD.</param>
/// <param name="PaymentProcessorInformation">PaymentProcessorInformation.</param>
/// <param name="PlanInformation">PlanInformation.</param>
/// <param name="ReferralInformation">ReferralInformation.</param>
/// <param name="RenewalStatus">.</param>
/// <param name="SaleDiscountAmount">.</param>
/// <param name="SaleDiscountFixedAmount">.</param>
/// <param name="SaleDiscountPercent">.</param>
/// <param name="SaleDiscountPeriods">.</param>
/// <param name="SaleDiscountSeatPriceOverride">.</param>
public BillingPlanInformation(AppStoreReceipt AppStoreReceipt = default(AppStoreReceipt), AccountAddress BillingAddress = default(AccountAddress), CreditCardInformation CreditCardInformation = default(CreditCardInformation), string DowngradeReason = default(string), string EnableSupport = default(string), string IncludedSeats = default(string), string IncrementalSeats = default(string), PaymentProcessorInformation PaymentProcessorInformation = default(PaymentProcessorInformation), PlanInformation PlanInformation = default(PlanInformation), ReferralInformation ReferralInformation = default(ReferralInformation), string RenewalStatus = default(string), string SaleDiscountAmount = default(string), string SaleDiscountFixedAmount = default(string), string SaleDiscountPercent = default(string), string SaleDiscountPeriods = default(string), string SaleDiscountSeatPriceOverride = default(string))
{
this.AppStoreReceipt = AppStoreReceipt;
this.BillingAddress = BillingAddress;
this.CreditCardInformation = CreditCardInformation;
this.DowngradeReason = DowngradeReason;
this.EnableSupport = EnableSupport;
this.IncludedSeats = IncludedSeats;
this.IncrementalSeats = IncrementalSeats;
this.PaymentProcessorInformation = PaymentProcessorInformation;
this.PlanInformation = PlanInformation;
this.ReferralInformation = ReferralInformation;
this.RenewalStatus = RenewalStatus;
this.SaleDiscountAmount = SaleDiscountAmount;
this.SaleDiscountFixedAmount = SaleDiscountFixedAmount;
this.SaleDiscountPercent = SaleDiscountPercent;
this.SaleDiscountPeriods = SaleDiscountPeriods;
this.SaleDiscountSeatPriceOverride = SaleDiscountSeatPriceOverride;
}
/// <summary>
/// Gets or Sets AppStoreReceipt
/// </summary>
[DataMember(Name="appStoreReceipt", EmitDefaultValue=false)]
public AppStoreReceipt AppStoreReceipt { get; set; }
/// <summary>
/// Gets or Sets BillingAddress
/// </summary>
[DataMember(Name="billingAddress", EmitDefaultValue=false)]
public AccountAddress BillingAddress { get; set; }
/// <summary>
/// Gets or Sets CreditCardInformation
/// </summary>
[DataMember(Name="creditCardInformation", EmitDefaultValue=false)]
public CreditCardInformation CreditCardInformation { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="downgradeReason", EmitDefaultValue=false)]
public string DowngradeReason { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="enableSupport", EmitDefaultValue=false)]
public string EnableSupport { get; set; }
/// <summary>
/// The number of seats (users) included.
/// </summary>
/// <value>The number of seats (users) included.</value>
[DataMember(Name="includedSeats", EmitDefaultValue=false)]
public string IncludedSeats { get; set; }
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="incrementalSeats", EmitDefaultValue=false)]
public string IncrementalSeats { get; set; }
/// <summary>
/// Gets or Sets PaymentProcessorInformation
/// </summary>
[DataMember(Name="paymentProcessorInformation", EmitDefaultValue=false)]
public PaymentProcessorInformation PaymentProcessorInformation { get; set; }
/// <summary>
/// Gets or Sets PlanInformation
/// </summary>
[DataMember(Name="planInformation", EmitDefaultValue=false)]
public PlanInformation PlanInformation { get; set; }
/// <summary>
/// Gets or Sets ReferralInformation
/// </summary>
[DataMember(Name="referralInformation", EmitDefaultValue=false)]
public ReferralInformation ReferralInformation { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="renewalStatus", EmitDefaultValue=false)]
public string RenewalStatus { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="saleDiscountAmount", EmitDefaultValue=false)]
public string SaleDiscountAmount { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="saleDiscountFixedAmount", EmitDefaultValue=false)]
public string SaleDiscountFixedAmount { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="saleDiscountPercent", EmitDefaultValue=false)]
public string SaleDiscountPercent { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="saleDiscountPeriods", EmitDefaultValue=false)]
public string SaleDiscountPeriods { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="saleDiscountSeatPriceOverride", EmitDefaultValue=false)]
public string SaleDiscountSeatPriceOverride { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BillingPlanInformation {\n");
sb.Append(" AppStoreReceipt: ").Append(AppStoreReceipt).Append("\n");
sb.Append(" BillingAddress: ").Append(BillingAddress).Append("\n");
sb.Append(" CreditCardInformation: ").Append(CreditCardInformation).Append("\n");
sb.Append(" DowngradeReason: ").Append(DowngradeReason).Append("\n");
sb.Append(" EnableSupport: ").Append(EnableSupport).Append("\n");
sb.Append(" IncludedSeats: ").Append(IncludedSeats).Append("\n");
sb.Append(" IncrementalSeats: ").Append(IncrementalSeats).Append("\n");
sb.Append(" PaymentProcessorInformation: ").Append(PaymentProcessorInformation).Append("\n");
sb.Append(" PlanInformation: ").Append(PlanInformation).Append("\n");
sb.Append(" ReferralInformation: ").Append(ReferralInformation).Append("\n");
sb.Append(" RenewalStatus: ").Append(RenewalStatus).Append("\n");
sb.Append(" SaleDiscountAmount: ").Append(SaleDiscountAmount).Append("\n");
sb.Append(" SaleDiscountFixedAmount: ").Append(SaleDiscountFixedAmount).Append("\n");
sb.Append(" SaleDiscountPercent: ").Append(SaleDiscountPercent).Append("\n");
sb.Append(" SaleDiscountPeriods: ").Append(SaleDiscountPeriods).Append("\n");
sb.Append(" SaleDiscountSeatPriceOverride: ").Append(SaleDiscountSeatPriceOverride).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as BillingPlanInformation);
}
/// <summary>
/// Returns true if BillingPlanInformation instances are equal
/// </summary>
/// <param name="other">Instance of BillingPlanInformation to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BillingPlanInformation other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AppStoreReceipt == other.AppStoreReceipt ||
this.AppStoreReceipt != null &&
this.AppStoreReceipt.Equals(other.AppStoreReceipt)
) &&
(
this.BillingAddress == other.BillingAddress ||
this.BillingAddress != null &&
this.BillingAddress.Equals(other.BillingAddress)
) &&
(
this.CreditCardInformation == other.CreditCardInformation ||
this.CreditCardInformation != null &&
this.CreditCardInformation.Equals(other.CreditCardInformation)
) &&
(
this.DowngradeReason == other.DowngradeReason ||
this.DowngradeReason != null &&
this.DowngradeReason.Equals(other.DowngradeReason)
) &&
(
this.EnableSupport == other.EnableSupport ||
this.EnableSupport != null &&
this.EnableSupport.Equals(other.EnableSupport)
) &&
(
this.IncludedSeats == other.IncludedSeats ||
this.IncludedSeats != null &&
this.IncludedSeats.Equals(other.IncludedSeats)
) &&
(
this.IncrementalSeats == other.IncrementalSeats ||
this.IncrementalSeats != null &&
this.IncrementalSeats.Equals(other.IncrementalSeats)
) &&
(
this.PaymentProcessorInformation == other.PaymentProcessorInformation ||
this.PaymentProcessorInformation != null &&
this.PaymentProcessorInformation.Equals(other.PaymentProcessorInformation)
) &&
(
this.PlanInformation == other.PlanInformation ||
this.PlanInformation != null &&
this.PlanInformation.Equals(other.PlanInformation)
) &&
(
this.ReferralInformation == other.ReferralInformation ||
this.ReferralInformation != null &&
this.ReferralInformation.Equals(other.ReferralInformation)
) &&
(
this.RenewalStatus == other.RenewalStatus ||
this.RenewalStatus != null &&
this.RenewalStatus.Equals(other.RenewalStatus)
) &&
(
this.SaleDiscountAmount == other.SaleDiscountAmount ||
this.SaleDiscountAmount != null &&
this.SaleDiscountAmount.Equals(other.SaleDiscountAmount)
) &&
(
this.SaleDiscountFixedAmount == other.SaleDiscountFixedAmount ||
this.SaleDiscountFixedAmount != null &&
this.SaleDiscountFixedAmount.Equals(other.SaleDiscountFixedAmount)
) &&
(
this.SaleDiscountPercent == other.SaleDiscountPercent ||
this.SaleDiscountPercent != null &&
this.SaleDiscountPercent.Equals(other.SaleDiscountPercent)
) &&
(
this.SaleDiscountPeriods == other.SaleDiscountPeriods ||
this.SaleDiscountPeriods != null &&
this.SaleDiscountPeriods.Equals(other.SaleDiscountPeriods)
) &&
(
this.SaleDiscountSeatPriceOverride == other.SaleDiscountSeatPriceOverride ||
this.SaleDiscountSeatPriceOverride != null &&
this.SaleDiscountSeatPriceOverride.Equals(other.SaleDiscountSeatPriceOverride)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AppStoreReceipt != null)
hash = hash * 59 + this.AppStoreReceipt.GetHashCode();
if (this.BillingAddress != null)
hash = hash * 59 + this.BillingAddress.GetHashCode();
if (this.CreditCardInformation != null)
hash = hash * 59 + this.CreditCardInformation.GetHashCode();
if (this.DowngradeReason != null)
hash = hash * 59 + this.DowngradeReason.GetHashCode();
if (this.EnableSupport != null)
hash = hash * 59 + this.EnableSupport.GetHashCode();
if (this.IncludedSeats != null)
hash = hash * 59 + this.IncludedSeats.GetHashCode();
if (this.IncrementalSeats != null)
hash = hash * 59 + this.IncrementalSeats.GetHashCode();
if (this.PaymentProcessorInformation != null)
hash = hash * 59 + this.PaymentProcessorInformation.GetHashCode();
if (this.PlanInformation != null)
hash = hash * 59 + this.PlanInformation.GetHashCode();
if (this.ReferralInformation != null)
hash = hash * 59 + this.ReferralInformation.GetHashCode();
if (this.RenewalStatus != null)
hash = hash * 59 + this.RenewalStatus.GetHashCode();
if (this.SaleDiscountAmount != null)
hash = hash * 59 + this.SaleDiscountAmount.GetHashCode();
if (this.SaleDiscountFixedAmount != null)
hash = hash * 59 + this.SaleDiscountFixedAmount.GetHashCode();
if (this.SaleDiscountPercent != null)
hash = hash * 59 + this.SaleDiscountPercent.GetHashCode();
if (this.SaleDiscountPeriods != null)
hash = hash * 59 + this.SaleDiscountPeriods.GetHashCode();
if (this.SaleDiscountSeatPriceOverride != null)
hash = hash * 59 + this.SaleDiscountSeatPriceOverride.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Rynchodon.Autopilot;
using Rynchodon.Update;
using Rynchodon.Utility.Network;
using Sandbox.ModAPI;
using VRage.Game.ModAPI;
using VRage.ModAPI;
namespace Rynchodon.AntennaRelay
{
public class Message
{
[Serializable]
public class Builder_Message
{
[XmlAttribute]
public long DestCubeBlock, SourceCubeBlock;
public string Content, SourceGridName, SourceBlockName;
public SerializableGameTime created;
public long destOwnerID;
public override bool Equals(object obj)
{
return this == obj || GetHashCode() == obj.GetHashCode();
}
public override int GetHashCode()
{
return (DestCubeBlock + SourceCubeBlock + created.Value).GetHashCode();
}
}
private class StaticVariables
{
public readonly TimeSpan MaximumLifetime = new TimeSpan(1, 0, 0);
public readonly Logger logger = new Logger();
public readonly List<byte> bytes = new List<byte>();
}
private static StaticVariables Static = new StaticVariables();
static Message()
{
MessageHandler.AddHandler(MessageHandler.SubMod.Message, FromClient);
}
/// <summary>
/// Message needs to be explicitly initialized because there may be none in the world.
/// </summary>
public static void Init()
{
}
#region Create & Send
/// <summary>
/// Inform the server to send message to autopilot block.
/// </summary>
private static void ToServer(long sender, string recipientGrid, string recipientBlock, string message)
{
Static.bytes.Clear();
ByteConverter.AppendBytes(Static.bytes, MessageHandler.SubMod.Message);
ByteConverter.AppendBytes(Static.bytes, sender);
ByteConverter.AppendBytes(Static.bytes, recipientGrid);
ByteConverter.AppendBytes(Static.bytes, recipientBlock);
ByteConverter.AppendBytes(Static.bytes, message);
if (MyAPIGateway.Multiplayer.SendMessageToServer(Static.bytes.ToArray()))
Static.logger.debugLog("Sent message to server");
else
{
Static.logger.alwaysLog("Message too long", Logger.severity.WARNING);
IMyEntity entity;
if (MyAPIGateway.Entities.TryGetEntityById(sender, out entity))
{
IMyTerminalBlock block = entity as IMyTerminalBlock;
if (block != null)
block.AppendCustomInfo("Failed to send message:\nMessage too long (" + Static.bytes.Count + " > 4096 bytes)\n");
}
}
}
private static void FromClient(byte[] bytes, int pos)
{
if (!MyAPIGateway.Multiplayer.IsServer)
{
Static.logger.alwaysLog("Not the server!", Logger.severity.WARNING);
return;
}
long sender = ByteConverter.GetLong(bytes, ref pos);
string recipientGrid = ByteConverter.GetString(bytes, ref pos);
string recipientBlock = ByteConverter.GetString(bytes, ref pos);
string message = ByteConverter.GetString(bytes, ref pos);
CreateAndSendMessage_Autopilot(sender, recipientGrid, recipientBlock, message);
}
private static void GetStorage(long entityId, out IMyCubeBlock block, out RelayStorage storage)
{
IMyEntity entity;
if (!MyAPIGateway.Entities.TryGetEntityById(entityId, out entity))
{
Static.logger.alwaysLog("Failed to get entity id for " + entityId, Logger.severity.WARNING);
block = null;
storage = null;
return;
}
block = entity as IMyCubeBlock;
if (block == null)
{
Static.logger.alwaysLog("Entity is not a block: " + entityId, Logger.severity.WARNING);
storage = null;
return;
}
storage = RelayClient.GetOrCreateRelayPart(block).GetStorage();
}
/// <summary>
/// Creates a message and sends it.
/// </summary>
/// <param name="sender">Block sending the message.</param>
/// <param name="recipientGrid">Grid that will receive the message.</param>
/// <param name="recipientBlock">Block that will receive the message.</param>
/// <param name="message">The content of the message.</param>
/// <returns>The number of blocks that will receive the message.</returns>
public static int CreateAndSendMessage(long sender, string recipientGrid, string recipientBlock, string message)
{
Static.logger.debugLog("sender: " + sender + ", recipientGrid: " + recipientGrid + ", recipientBlock: " + recipientBlock + ", message: " + message);
int count = CreateAndSendMessage_Autopilot(sender, recipientGrid, recipientBlock, message);
if (count != 0 && !MyAPIGateway.Multiplayer.IsServer)
ToServer(sender, recipientGrid, recipientBlock, message);
count += CreateAndSendMessage_Program(sender, recipientGrid, recipientBlock, message);
return count;
}
private static int CreateAndSendMessage_Autopilot(long sender, string recipientGrid, string recipientBlock, string message)
{
int count = 0;
IMyCubeBlock senderBlock;
RelayStorage storage;
GetStorage(sender, out senderBlock, out storage);
if (storage == null)
{
Static.logger.debugLog("No storage");
return 0;
}
Registrar.ForEach((ShipAutopilot autopilot) => {
IMyCubeBlock block = autopilot.m_block.CubeBlock;
IMyCubeGrid grid = block.CubeGrid;
if (senderBlock.canControlBlock(block) && grid.DisplayName.looseContains(recipientGrid) && block.DisplayNameText.looseContains(recipientBlock))
{
count++;
if (MyAPIGateway.Multiplayer.IsServer)
storage.Receive(new Message(message, block, senderBlock));
}
});
return count;
}
private static int CreateAndSendMessage_Program(long sender, string recipientGrid, string recipientBlock, string message)
{
int count = 0;
IMyCubeBlock senderBlock;
RelayStorage storage;
GetStorage(sender, out senderBlock, out storage);
if (storage == null)
{
Static.logger.debugLog("No storage");
return 0;
}
Registrar.ForEach((ProgrammableBlock pb) => {
IMyCubeBlock block = pb.m_block;
IMyCubeGrid grid = block.CubeGrid;
if (senderBlock.canControlBlock(block) && grid.DisplayName.looseContains(recipientGrid) && block.DisplayNameText.looseContains(recipientBlock))
{
count++;
storage.Receive(new Message(message, block, senderBlock));
}
});
return count;
}
#endregion Create & Send
public readonly string Content, SourceGridName, SourceBlockName;
public readonly IMyCubeBlock DestCubeBlock, SourceCubeBlock;
public readonly TimeSpan created;
private readonly long destOwnerID;
private Message(string Content, IMyCubeBlock DestCubeblock, IMyCubeBlock SourceCubeBlock, string SourceBlockName = null)
{
this.Content = Content;
this.DestCubeBlock = DestCubeblock;
this.SourceCubeBlock = SourceCubeBlock;
this.SourceGridName = SourceCubeBlock.CubeGrid.DisplayName;
if (SourceBlockName == null)
this.SourceBlockName = SourceCubeBlock.DisplayNameText;
else
this.SourceBlockName = SourceBlockName;
this.destOwnerID = DestCubeblock.OwnerId;
created = Globals.ElapsedTime;
}
public Message(Builder_Message builder)
{
this.Content = builder.Content;
this.SourceGridName = builder.SourceGridName;
this.SourceBlockName = builder.SourceBlockName;
IMyEntity entity;
if (!MyAPIGateway.Entities.TryGetEntityById(builder.DestCubeBlock, out entity) || !(entity is IMyCubeBlock))
{
(new Logger()).alwaysLog("Entity does not exist in world: " + builder.DestCubeBlock, Logger.severity.WARNING);
return;
}
this.DestCubeBlock = (IMyCubeBlock)entity;
if (!MyAPIGateway.Entities.TryGetEntityById(builder.SourceCubeBlock, out entity) || !(entity is IMyCubeBlock))
{
(new Logger()).alwaysLog("Entity does not exist in world: " + builder.SourceCubeBlock, Logger.severity.WARNING);
return;
}
this.SourceCubeBlock = (IMyCubeBlock)entity;
this.created = builder.created.ToTimeSpan();
this.destOwnerID = builder.destOwnerID;
}
private bool value_isValid = true;
/// <summary>
/// can only be set to false, once invalid always invalid
/// </summary>
public bool IsValid
{
get
{
if (value_isValid &&
(DestCubeBlock == null
|| SourceCubeBlock == null
|| DestCubeBlock.Closed
|| destOwnerID != DestCubeBlock.OwnerId // dest owner changed
|| (Globals.ElapsedTime - created).CompareTo(Static.MaximumLifetime) > 0)) // expired
value_isValid = false;
return value_isValid;
}
set
{
if (value == false)
value_isValid = false;
}
}
public Builder_Message GetBuilder()
{
return new Builder_Message()
{
DestCubeBlock = DestCubeBlock.EntityId,
SourceCubeBlock = SourceCubeBlock.EntityId,
created = new SerializableGameTime(created),
destOwnerID = destOwnerID,
Content = Content,
SourceGridName = SourceGridName,
SourceBlockName = SourceBlockName
};
}
}
}
| |
//
// 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure.Management.SiteRecovery;
using Microsoft.Azure.Management.SiteRecovery.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of alert settings operations for the Site Recovery extension.
/// </summary>
internal partial class AlertSettingsOperations : IServiceOperations<SiteRecoveryManagementClient>, IAlertSettingsOperations
{
/// <summary>
/// Initializes a new instance of the AlertSettingsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AlertSettingsOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Updates the alert settings for the vault.
/// </summary>
/// <param name='alertSettingsName'>
/// Required. Alert Settings name.
/// </param>
/// <param name='input'>
/// Required. Configure Alerts Request.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Model class for alerts response.
/// </returns>
public async Task<AlertSettingsResponse> ConfigureAsync(string alertSettingsName, ConfigureAlertSettingsRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (alertSettingsName == null)
{
throw new ArgumentNullException("alertSettingsName");
}
if (input == null)
{
throw new ArgumentNullException("input");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("alertSettingsName", alertSettingsName);
tracingParameters.Add("input", input);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ConfigureAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationAlertSettings/";
url = url + Uri.EscapeDataString(alertSettingsName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject configureAlertSettingsRequestValue = new JObject();
requestDoc = configureAlertSettingsRequestValue;
if (input.Properties != null)
{
JObject propertiesValue = new JObject();
configureAlertSettingsRequestValue["properties"] = propertiesValue;
if (input.Properties.SendToOwners != null)
{
propertiesValue["sendToOwners"] = input.Properties.SendToOwners;
}
if (input.Properties.CustomEmailAddresses != null)
{
if (input.Properties.CustomEmailAddresses is ILazyCollection == false || ((ILazyCollection)input.Properties.CustomEmailAddresses).IsInitialized)
{
JArray customEmailAddressesArray = new JArray();
foreach (string customEmailAddressesItem in input.Properties.CustomEmailAddresses)
{
customEmailAddressesArray.Add(customEmailAddressesItem);
}
propertiesValue["customEmailAddresses"] = customEmailAddressesArray;
}
}
if (input.Properties.Locale != null)
{
propertiesValue["locale"] = input.Properties.Locale;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AlertSettingsResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AlertSettingsResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AlertSettings alertInstance = new AlertSettings();
result.Alert = alertInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
AlertSettingsProperties propertiesInstance = new AlertSettingsProperties();
alertInstance.Properties = propertiesInstance;
JToken sendToOwnersValue = propertiesValue2["sendToOwners"];
if (sendToOwnersValue != null && sendToOwnersValue.Type != JTokenType.Null)
{
string sendToOwnersInstance = ((string)sendToOwnersValue);
propertiesInstance.SendToOwners = sendToOwnersInstance;
}
JToken customEmailAddressesArray2 = propertiesValue2["customEmailAddresses"];
if (customEmailAddressesArray2 != null && customEmailAddressesArray2.Type != JTokenType.Null)
{
foreach (JToken customEmailAddressesValue in ((JArray)customEmailAddressesArray2))
{
propertiesInstance.CustomEmailAddresses.Add(((string)customEmailAddressesValue));
}
}
JToken localeValue = propertiesValue2["locale"];
if (localeValue != null && localeValue.Type != JTokenType.Null)
{
string localeInstance = ((string)localeValue);
propertiesInstance.Locale = localeInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
alertInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
alertInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
alertInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
alertInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
alertInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates the alert settings for the vault.
/// </summary>
/// <param name='alertSettingsName'>
/// Required. Alert Settings name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Model class for alerts response.
/// </returns>
public async Task<AlertSettingsResponse> GetAsync(string alertSettingsName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (alertSettingsName == null)
{
throw new ArgumentNullException("alertSettingsName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("alertSettingsName", alertSettingsName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationAlertSettings/";
url = url + Uri.EscapeDataString(alertSettingsName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AlertSettingsResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AlertSettingsResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AlertSettings alertInstance = new AlertSettings();
result.Alert = alertInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
AlertSettingsProperties propertiesInstance = new AlertSettingsProperties();
alertInstance.Properties = propertiesInstance;
JToken sendToOwnersValue = propertiesValue["sendToOwners"];
if (sendToOwnersValue != null && sendToOwnersValue.Type != JTokenType.Null)
{
string sendToOwnersInstance = ((string)sendToOwnersValue);
propertiesInstance.SendToOwners = sendToOwnersInstance;
}
JToken customEmailAddressesArray = propertiesValue["customEmailAddresses"];
if (customEmailAddressesArray != null && customEmailAddressesArray.Type != JTokenType.Null)
{
foreach (JToken customEmailAddressesValue in ((JArray)customEmailAddressesArray))
{
propertiesInstance.CustomEmailAddresses.Add(((string)customEmailAddressesValue));
}
}
JToken localeValue = propertiesValue["locale"];
if (localeValue != null && localeValue.Type != JTokenType.Null)
{
string localeInstance = ((string)localeValue);
propertiesInstance.Locale = localeInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
alertInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
alertInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
alertInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
alertInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
alertInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of events under the vault.
/// </summary>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Model class for list alerts response.
/// </returns>
public async Task<AlertSettingsListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationAlertSettings";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AlertSettingsListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AlertSettingsListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
AlertSettings alertSettingsInstance = new AlertSettings();
result.Alerts.Add(alertSettingsInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
AlertSettingsProperties propertiesInstance = new AlertSettingsProperties();
alertSettingsInstance.Properties = propertiesInstance;
JToken sendToOwnersValue = propertiesValue["sendToOwners"];
if (sendToOwnersValue != null && sendToOwnersValue.Type != JTokenType.Null)
{
string sendToOwnersInstance = ((string)sendToOwnersValue);
propertiesInstance.SendToOwners = sendToOwnersInstance;
}
JToken customEmailAddressesArray = propertiesValue["customEmailAddresses"];
if (customEmailAddressesArray != null && customEmailAddressesArray.Type != JTokenType.Null)
{
foreach (JToken customEmailAddressesValue in ((JArray)customEmailAddressesArray))
{
propertiesInstance.CustomEmailAddresses.Add(((string)customEmailAddressesValue));
}
}
JToken localeValue = propertiesValue["locale"];
if (localeValue != null && localeValue.Type != JTokenType.Null)
{
string localeInstance = ((string)localeValue);
propertiesInstance.Locale = localeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
alertSettingsInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
alertSettingsInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
alertSettingsInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
alertSettingsInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
alertSettingsInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.TeleTrust;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
namespace Org.BouncyCastle.Security
{
public sealed class PrivateKeyFactory
{
private PrivateKeyFactory()
{
}
public static AsymmetricKeyParameter CreateKey(
byte[] privateKeyInfoData)
{
return CreateKey(
PrivateKeyInfo.GetInstance(
Asn1Object.FromByteArray(privateKeyInfoData)));
}
public static AsymmetricKeyParameter CreateKey(
Stream inStr)
{
return CreateKey(
PrivateKeyInfo.GetInstance(
Asn1Object.FromStream(inStr)));
}
public static AsymmetricKeyParameter CreateKey(
PrivateKeyInfo keyInfo)
{
AlgorithmIdentifier algID = keyInfo.AlgorithmID;
DerObjectIdentifier algOid = algID.ObjectID;
// TODO See RSAUtil.isRsaOid in Java build
if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption)
|| algOid.Equals(X509ObjectIdentifiers.IdEARsa)
|| algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss)
|| algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
{
RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure(
Asn1Sequence.GetInstance(keyInfo.PrivateKey));
return new RsaPrivateCrtKeyParameters(
keyStructure.Modulus,
keyStructure.PublicExponent,
keyStructure.PrivateExponent,
keyStructure.Prime1,
keyStructure.Prime2,
keyStructure.Exponent1,
keyStructure.Exponent2,
keyStructure.Coefficient);
}
else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
{
DHParameter para = new DHParameter(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
DerInteger derX = (DerInteger)keyInfo.PrivateKey;
BigInteger lVal = para.L;
int l = lVal == null ? 0 : lVal.IntValue;
DHParameters dhParams = new DHParameters(para.P, para.G, null, l);
return new DHPrivateKeyParameters(derX.Value, dhParams);
}
else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
{
ElGamalParameter para = new ElGamalParameter(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
DerInteger derX = (DerInteger)keyInfo.PrivateKey;
return new ElGamalPrivateKeyParameters(
derX.Value,
new ElGamalParameters(para.P, para.G));
}
else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
{
DerInteger derX = (DerInteger) keyInfo.PrivateKey;
Asn1Encodable ae = algID.Parameters;
DsaParameters parameters = null;
if (ae != null)
{
DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
parameters = new DsaParameters(para.P, para.Q, para.G);
}
return new DsaPrivateKeyParameters(derX.Value, parameters);
}
else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
{
X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());
X9ECParameters ecP;
if (para.IsNamedCurve)
{
// TODO ECGost3410NamedCurves support (returns ECDomainParameters though)
DerObjectIdentifier oid = (DerObjectIdentifier) para.Parameters;
ecP = X962NamedCurves.GetByOid(oid);
if (ecP == null)
{
ecP = SecNamedCurves.GetByOid(oid);
if (ecP == null)
{
ecP = NistNamedCurves.GetByOid(oid);
if (ecP == null)
{
ecP = TeleTrusTNamedCurves.GetByOid(oid);
}
}
}
}
else
{
ecP = new X9ECParameters((Asn1Sequence) para.Parameters);
}
ECDomainParameters dParams = new ECDomainParameters(
ecP.Curve,
ecP.G,
ecP.N,
ecP.H,
ecP.GetSeed());
ECPrivateKeyStructure ec = new ECPrivateKeyStructure(
Asn1Sequence.GetInstance(keyInfo.PrivateKey));
return new ECPrivateKeyParameters(ec.GetKey(), dParams);
}
else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
{
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
ECPrivateKeyStructure ec = new ECPrivateKeyStructure(
Asn1Sequence.GetInstance(keyInfo.PrivateKey));
ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);
if (ecP == null)
return null;
return new ECPrivateKeyParameters(ec.GetKey(), gostParams.PublicKeyParamSet);
}
else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
{
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
DerOctetString derX = (DerOctetString) keyInfo.PrivateKey;
byte[] keyEnc = derX.GetOctets();
byte[] keyBytes = new byte[keyEnc.Length];
for (int i = 0; i != keyEnc.Length; i++)
{
keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
}
BigInteger x = new BigInteger(1, keyBytes);
return new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet);
}
else
{
throw new SecurityUtilityException("algorithm identifier in key not recognised");
}
}
public static AsymmetricKeyParameter DecryptKey(
char[] passPhrase,
EncryptedPrivateKeyInfo encInfo)
{
return CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(passPhrase, encInfo));
}
public static AsymmetricKeyParameter DecryptKey(
char[] passPhrase,
byte[] encryptedPrivateKeyInfoData)
{
return DecryptKey(passPhrase, Asn1Object.FromByteArray(encryptedPrivateKeyInfoData));
}
public static AsymmetricKeyParameter DecryptKey(
char[] passPhrase,
Stream encryptedPrivateKeyInfoStream)
{
return DecryptKey(passPhrase, Asn1Object.FromStream(encryptedPrivateKeyInfoStream));
}
private static AsymmetricKeyParameter DecryptKey(
char[] passPhrase,
Asn1Object asn1Object)
{
return DecryptKey(passPhrase, EncryptedPrivateKeyInfo.GetInstance(asn1Object));
}
}
}
| |
// 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.Immutable;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeProperty2))]
public sealed partial class CodeProperty : AbstractCodeMember, ICodeElementContainer<CodeParameter>, ICodeElementContainer<CodeAttribute>, EnvDTE.CodeProperty, EnvDTE80.CodeProperty2
{
internal static EnvDTE.CodeProperty Create(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
{
var element = new CodeProperty(state, fileCodeModel, nodeKey, nodeKind);
var result = (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element);
fileCodeModel.OnElementCreated(nodeKey, (EnvDTE.CodeElement)result);
return result;
}
internal static EnvDTE.CodeProperty CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
{
var element = new CodeProperty(state, fileCodeModel, nodeKind, name);
return (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element);
}
private CodeProperty(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
: base(state, fileCodeModel, nodeKey, nodeKind)
{
}
private CodeProperty(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind, name)
{
}
private IPropertySymbol PropertySymbol
{
get { return (IPropertySymbol)LookupSymbol(); }
}
EnvDTE.CodeElements ICodeElementContainer<CodeParameter>.GetCollection()
{
return this.Parameters;
}
EnvDTE.CodeElements ICodeElementContainer<CodeAttribute>.GetCollection()
{
return this.Attributes;
}
internal override ImmutableArray<SyntaxNode> GetParameters()
{
return ImmutableArray.CreateRange(CodeModelService.GetParameterNodes(LookupNode()));
}
protected override object GetExtenderNames()
{
return CodeModelService.GetPropertyExtenderNames();
}
protected override object GetExtender(string name)
{
return CodeModelService.GetPropertyExtender(name, LookupNode(), LookupSymbol());
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementProperty; }
}
public override object Parent
{
get
{
EnvDTE80.CodeProperty2 codeProperty = this;
return codeProperty.Parent2;
}
}
public EnvDTE.CodeElement Parent2
{
get
{
var containingTypeNode = GetContainingTypeNode();
if (containingTypeNode == null)
{
throw Exceptions.ThrowEUnexpected();
}
return FileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(containingTypeNode);
}
}
EnvDTE.CodeClass EnvDTE.CodeProperty.Parent
{
get
{
EnvDTE.CodeClass parentClass = this.Parent as EnvDTE.CodeClass;
if (parentClass != null)
{
return parentClass;
}
else
{
throw new InvalidOperationException();
}
}
}
EnvDTE.CodeClass EnvDTE80.CodeProperty2.Parent
{
get
{
EnvDTE.CodeProperty property = this;
return property.Parent;
}
}
public override EnvDTE.CodeElements Children
{
get { return this.Attributes; }
}
private bool HasAccessorNode(MethodKind methodKind)
{
SyntaxNode accessorNode;
return CodeModelService.TryGetAccessorNode(LookupNode(), methodKind, out accessorNode);
}
public EnvDTE.CodeFunction Getter
{
get
{
if (!HasAccessorNode(MethodKind.PropertyGet))
{
return null;
}
return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertyGet);
}
set
{
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.CodeFunction Setter
{
get
{
if (!HasAccessorNode(MethodKind.PropertySet))
{
return null;
}
return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertySet);
}
set
{
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
return CodeTypeRef.Create(this.State, this, GetProjectId(), PropertySymbol.Type);
}
set
{
// The type is sometimes part of the node key, so we should be sure to reacquire
// it after updating it. Note that we pass trackKinds: false because it's possible
// that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function).
UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false);
}
}
public bool IsDefault
{
get
{
return CodeModelService.GetIsDefault(LookupNode());
}
set
{
UpdateNode(FileCodeModel.UpdateIsDefault, value);
}
}
public EnvDTE80.vsCMPropertyKind ReadWrite
{
get { return CodeModelService.GetReadWrite(LookupNode()); }
}
}
}
| |
// 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.Globalization;
using System.Runtime.Tests.Common;
using Xunit;
public static class Int64Tests
{
[Fact]
public static void TestCtorEmpty()
{
long i = new long();
Assert.Equal(0, i);
}
[Fact]
public static void TestCtorValue()
{
long i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void TestMaxValue()
{
Assert.Equal(0x7FFFFFFFFFFFFFFF, long.MaxValue);
}
[Fact]
public static void TestMinValue()
{
Assert.Equal(unchecked((long)0x8000000000000000), long.MinValue);
}
[Theory]
[InlineData((long)234, 0)]
[InlineData(long.MinValue, 1)]
[InlineData((long)(-123), 1)]
[InlineData((long)0, 1)]
[InlineData((long)45, 1)]
[InlineData((long)123, 1)]
[InlineData((long)456, -1)]
[InlineData(long.MaxValue, -1)]
public static void TestCompareTo(long value, long expected)
{
long i = 234;
long result = CompareHelper.NormalizeCompare(i.CompareTo(value));
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null, 1)]
[InlineData((long)234, 0)]
[InlineData(long.MinValue, 1)]
[InlineData((long)(-123), 1)]
[InlineData((long)0, 1)]
[InlineData((long)45, 1)]
[InlineData((long)123, 1)]
[InlineData((long)456, -1)]
[InlineData(long.MaxValue, -1)]
public static void TestCompareToObject(object obj, long expected)
{
IComparable comparable = (long)234;
long i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj));
Assert.Equal(expected, i);
}
[Fact]
public static void TestCompareToObjectInvalid()
{
IComparable comparable = (long)234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a long
}
[Theory]
[InlineData((long)789, true)]
[InlineData((long)(-789), false)]
[InlineData((long)0, false)]
public static void TestEqualsObject(object obj, bool expected)
{
long i = 789;
Assert.Equal(expected, i.Equals(obj));
}
[Theory]
[InlineData((long)789, true)]
[InlineData((long)(-789), false)]
[InlineData((long)0, false)]
public static void TestEquals(long i2, bool expected)
{
long i = 789;
Assert.Equal(expected, i.Equals(i2));
}
[Fact]
public static void TestGetHashCode()
{
long i1 = 123;
long i2 = 654;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
long i1 = 6310;
Assert.Equal("6310", i1.ToString());
long i2 = -8249;
Assert.Equal("-8249", i2.ToString());
Assert.Equal(long.MaxValue.ToString(), "9223372036854775807");
Assert.Equal(long.MinValue.ToString(), "-9223372036854775808");
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new NumberFormatInfo();
long i1 = 6310;
Assert.Equal("6310", i1.ToString(numberFormat));
long i2 = -8249;
Assert.Equal("-8249", i2.ToString(numberFormat));
long i3 = -2468;
// Changing the negative pattern doesn't do anything without also passing in a format string
numberFormat.NumberNegativePattern = 0;
Assert.Equal("-2468", i3.ToString(numberFormat));
}
[Fact]
public static void TestToStringFormat()
{
long i1 = 6310;
Assert.Equal("6310", i1.ToString("G"));
long i2 = -8249;
Assert.Equal("-8249", i2.ToString("g"));
long i3 = -2468;
Assert.Equal(string.Format("{0:N}", -2468.00), i3.ToString("N"));
long i4 = 0x248;
Assert.Equal("248", i4.ToString("x"));
Assert.Equal(long.MinValue.ToString("X"), "8000000000000000");
Assert.Equal(long.MaxValue.ToString("X"), "7FFFFFFFFFFFFFFF");
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new NumberFormatInfo();
long i1 = 6310;
Assert.Equal("6310", i1.ToString("G", numberFormat));
long i2 = -8249;
Assert.Equal("-8249", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
long i3 = -2468;
Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat));
}
public static IEnumerable<object[]> ParseValidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
yield return new object[] { "-9223372036854775808", defaultStyle, defaultFormat, -9223372036854775808 };
yield return new object[] { "-123", defaultStyle, defaultFormat, (long)-123 };
yield return new object[] { "0", defaultStyle, defaultFormat, (long)0 };
yield return new object[] { "123", defaultStyle, defaultFormat, (long)123 };
yield return new object[] { " 123 ", defaultStyle, defaultFormat, (long)123 };
yield return new object[] { "9223372036854775807", defaultStyle, defaultFormat, 9223372036854775807 };
yield return new object[] { "123", NumberStyles.HexNumber, defaultFormat, (long)0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, defaultFormat, (long)0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, defaultFormat, (long)1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, (long)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyNfi, (long)123 };
yield return new object[] { "123", NumberStyles.Any, emptyNfi, (long)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, (long)0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, testNfi, (long)1000 };
}
public static IEnumerable<object[]> ParseInvalidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
testNfi.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, defaultFormat, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { " ", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, defaultFormat, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, defaultFormat, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, defaultFormat, typeof(FormatException) }; // Parentheses
yield return new object[] { 1000.ToString("C0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, defaultFormat, typeof(FormatException) }; //Decimal
yield return new object[] { "abc", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Negative hex value
yield return new object[] { " 123 ", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, testNfi, typeof(FormatException) }; // Decimal
yield return new object[] { "-9223372036854775809", defaultStyle, defaultFormat, typeof(OverflowException) }; // < min value
yield return new object[] { "9223372036854775808", defaultStyle, defaultFormat, typeof(OverflowException) }; // > max value
}
[Theory, MemberData("ParseValidData")]
public static void TestParse(string value, NumberStyles style, NumberFormatInfo nfi, long expected)
{
long i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(true, long.TryParse(value, out i));
Assert.Equal(expected, i);
Assert.Equal(expected, long.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Equal(expected, long.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(true, long.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(expected, i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Equal(expected, long.Parse(value, style));
}
Assert.Equal(expected, long.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
[Theory, MemberData("ParseInvalidData")]
public static void TestParseInvalid(string value, NumberStyles style, NumberFormatInfo nfi, Type exceptionType)
{
long i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(false, long.TryParse(value, out i));
Assert.Equal(default(long), i);
Assert.Throws(exceptionType, () => long.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Throws(exceptionType, () => long.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(false, long.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(default(long), i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Throws(exceptionType, () => long.Parse(value, style));
}
Assert.Throws(exceptionType, () => long.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
namespace OpenSim.Server.Handlers.Inventory
{
public class InventoryServiceInConnector : ServiceConnector
{
protected string m_ConfigName = "InventoryService";
protected IInventoryService m_InventoryService;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_doLookup = false;
//private static readonly int INVENTORY_DEFAULT_SESSION_TIME = 30; // secs
//private AuthedSessionCache m_session_cache = new AuthedSessionCache(INVENTORY_DEFAULT_SESSION_TIME);
private string m_userserver_url;
public InventoryServiceInConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
if (configName != string.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string inventoryService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (inventoryService == String.Empty)
throw new Exception("No LocalServiceModule in config file");
Object[] args = new Object[] { config };
m_InventoryService =
ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args);
m_userserver_url = serverConfig.GetString("UserServerURI", String.Empty);
m_doLookup = serverConfig.GetBoolean("SessionAuthentication", false);
AddHttpHandlers(server);
m_log.Debug("[INVENTORY HANDLER]: handlers initialized");
}
/// <summary>
/// Check that the source of an inventory request for a particular agent is a current session belonging to
/// that agent.
/// </summary>
/// <param name="session_id"></param>
/// <param name="avatar_id"></param>
/// <returns></returns>
public virtual bool CheckAuthSession(string session_id, string avatar_id)
{
return true;
}
/// <summary>
/// Check that the source of an inventory request is one that we trust.
/// </summary>
/// <param name="peer"></param>
/// <returns></returns>
public bool CheckTrustSource(IPEndPoint peer)
{
if (m_doLookup)
{
m_log.InfoFormat("[INVENTORY IN CONNECTOR]: Checking trusted source {0}", peer);
UriBuilder ub = new UriBuilder(m_userserver_url);
IPAddress[] uaddrs = Dns.GetHostAddresses(ub.Host);
foreach (IPAddress uaddr in uaddrs)
{
if (uaddr.Equals(peer.Address))
{
return true;
}
}
m_log.WarnFormat(
"[INVENTORY IN CONNECTOR]: Rejecting request since source {0} was not in the list of trusted sources",
peer);
return false;
}
else
{
return true;
}
}
protected virtual void AddHttpHandlers(IHttpServer m_httpServer)
{
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<Guid, List<InventoryFolderBase>>(
"POST", "/SystemFolders/", GetSystemFolders, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<Guid, InventoryCollection>(
"POST", "/GetFolderContent/", GetFolderContent, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryFolderBase, bool>(
"POST", "/UpdateFolder/", m_InventoryService.UpdateFolder, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryFolderBase, bool>(
"POST", "/MoveFolder/", m_InventoryService.MoveFolder, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryFolderBase, bool>(
"POST", "/PurgeFolder/", m_InventoryService.PurgeFolder, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<List<Guid>, bool>(
"POST", "/DeleteFolders/", DeleteFolders, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<List<Guid>, bool>(
"POST", "/DeleteItem/", DeleteItems, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryItemBase, InventoryItemBase>(
"POST", "/QueryItem/", m_InventoryService.GetItem, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryFolderBase, InventoryFolderBase>(
"POST", "/QueryFolder/", m_InventoryService.GetFolder, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseTrustedHandler<Guid, bool>(
"POST", "/CreateInventory/", CreateUsersInventory, CheckTrustSource));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryFolderBase, bool>(
"POST", "/NewFolder/", m_InventoryService.AddFolder, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryFolderBase, bool>(
"POST", "/CreateFolder/", m_InventoryService.AddFolder, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryItemBase, bool>(
"POST", "/NewItem/", m_InventoryService.AddItem, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseTrustedHandler<InventoryItemBase, bool>(
"POST", "/AddNewItem/", m_InventoryService.AddItem, CheckTrustSource));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<Guid, List<InventoryItemBase>>(
"POST", "/GetItems/", GetFolderItems, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<List<InventoryItemBase>, bool>(
"POST", "/MoveItems/", MoveItems, CheckAuthSession));
m_httpServer.AddStreamHandler(new InventoryServerMoveItemsHandler(m_InventoryService));
// for persistent active gestures
m_httpServer.AddStreamHandler(
new RestDeserialiseTrustedHandler<Guid, List<InventoryItemBase>>
("POST", "/ActiveGestures/", GetActiveGestures, CheckTrustSource));
// WARNING: Root folders no longer just delivers the root and immediate child folders (e.g
// system folders such as Objects, Textures), but it now returns the entire inventory skeleton.
// It would have been better to rename this request, but complexities in the BaseHttpServer
// (e.g. any http request not found is automatically treated as an xmlrpc request) make it easier
// to do this for now.
m_httpServer.AddStreamHandler(
new RestDeserialiseTrustedHandler<Guid, List<InventoryFolderBase>>
("POST", "/RootFolders/", GetInventorySkeleton, CheckTrustSource));
}
#region Wrappers for converting the Guid parameter
public bool CreateUsersInventory(Guid rawUserID)
{
UUID userID = new UUID(rawUserID);
return m_InventoryService.CreateUserInventory(userID);
}
public bool DeleteFolders(List<Guid> items)
{
List<UUID> uuids = new List<UUID>();
foreach (Guid g in items)
uuids.Add(new UUID(g));
// oops we lost the user info here. Bad bad handlers
return m_InventoryService.DeleteFolders(UUID.Zero, uuids);
}
public bool DeleteItems(List<Guid> items)
{
List<UUID> uuids = new List<UUID>();
foreach (Guid g in items)
uuids.Add(new UUID(g));
// oops we lost the user info here. Bad bad handlers
return m_InventoryService.DeleteItems(UUID.Zero, uuids);
}
public List<InventoryItemBase> GetActiveGestures(Guid rawUserID)
{
UUID userID = new UUID(rawUserID);
return m_InventoryService.GetActiveGestures(userID);
}
public InventoryCollection GetFolderContent(Guid guid)
{
return m_InventoryService.GetFolderContent(UUID.Zero, new UUID(guid));
}
public List<InventoryItemBase> GetFolderItems(Guid folderID)
{
List<InventoryItemBase> allItems = new List<InventoryItemBase>();
// TODO: UUID.Zero is passed as the userID here, making the old assumption that the OpenSim
// inventory server only has a single inventory database and not per-user inventory databases.
// This could be changed but it requirs a bit of hackery to pass another parameter into this
// callback
List<InventoryItemBase> items = m_InventoryService.GetFolderItems(UUID.Zero, new UUID(folderID));
if (items != null)
{
allItems.InsertRange(0, items);
}
return allItems;
}
public List<InventoryFolderBase> GetInventorySkeleton(Guid rawUserID)
{
UUID userID = new UUID(rawUserID);
return m_InventoryService.GetInventorySkeleton(userID);
}
public List<InventoryFolderBase> GetSystemFolders(Guid guid)
{
UUID userID = new UUID(guid);
return new List<InventoryFolderBase>(GetSystemFolders(userID).Values);
}
public bool MoveItems(List<InventoryItemBase> items)
{
// oops we lost the user info here. Bad bad handlers
// let's peek at one item
UUID ownerID = UUID.Zero;
if (items.Count > 0)
ownerID = items[0].Owner;
return m_InventoryService.MoveItems(ownerID, items);
}
// This shouldn't be here, it should be in the inventory service.
// But I don't want to deal with types and dependencies for now.
private Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID)
{
InventoryFolderBase root = m_InventoryService.GetRootFolder(userID);
if (root != null)
{
InventoryCollection content = m_InventoryService.GetFolderContent(userID, root.ID);
if (content != null)
{
Dictionary<AssetType, InventoryFolderBase> folders = new Dictionary<AssetType, InventoryFolderBase>();
foreach (InventoryFolderBase folder in content.Folders)
{
if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown))
folders[(AssetType)folder.Type] = folder;
}
// Put the root folder there, as type Folder
folders[AssetType.Folder] = root;
return folders;
}
}
m_log.WarnFormat("[INVENTORY SERVICE]: System folders for {0} not found", userID);
return new Dictionary<AssetType, InventoryFolderBase>();
}
#endregion Wrappers for converting the Guid parameter
}
}
| |
/* New BSD License
-------------------------------------------------------------------------------
Copyright (c) 2006-2012, EntitySpaces, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the EntitySpaces, LLC nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL EntitySpaces, LLC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Data;
using Tiraggo.DynamicQuery;
using Tiraggo.Interfaces;
using VistaDB.Diagnostic;
using VistaDB.Provider;
namespace Tiraggo.VistaDB5Provider
{
class Shared
{
static public VistaDBCommand BuildDynamicInsertCommand(tgDataRequest request, List<string> modifiedColumns)
{
string sql = String.Empty;
string defaults = String.Empty;
string into = String.Empty;
string values = String.Empty;
string comma = String.Empty;
string defaultComma = String.Empty;
string where = String.Empty;
string whereComma = String.Empty;
PropertyCollection props = new PropertyCollection();
VistaDBParameter p = null;
Dictionary<string, VistaDBParameter> types = Cache.GetParameters(request);
VistaDBCommand cmd = new VistaDBCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = modifiedColumns == null ? false : modifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + p.ParameterName;
comma = ", ";
}
else if (col.IsAutoIncrement)
{
props["AutoInc"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
p = CloneParameter(types[col.Name]);
p.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p);
}
else if (col.IsConcurrency)
{
props["Timestamp"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
p = CloneParameter(types[col.Name]);
p.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p);
}
else if (col.IsTiraggoConcurrency)
{
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + "1";
comma = ", ";
p = CloneParameter(types[col.Name]);
p.Direction = ParameterDirection.Output;
p.Value = 1; // Seems to work, We'll take it ...
cmd.Parameters.Add(p);
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
defaults += defaultComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
defaultComma = ",";
string def = col.Default.ToLower();
if (def.Contains("guid") || def.Contains("newid"))
{
p = CloneParameter(types[col.Name]);
p.Direction = ParameterDirection.Output;
p.SourceVersion = DataRowVersion.Current;
cmd.Parameters.Add(p);
sql += " IF " + Delimiters.Param + col.Name + " IS NULL SET " +
Delimiters.Param + col.Name + " = NEWID();";
into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
values += comma + p.ParameterName;
comma = ", ";
}
}
if (col.IsInPrimaryKey)
{
where += whereComma + col.Name;
whereComma = ",";
}
}
#region Special Columns
if (cols.DateAdded != null && cols.DateAdded.IsServerSide &&
cols.FindByColumnName(cols.DateAdded.ColumnName) != null)
{
into += comma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateAdded.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.DateModified != null && cols.DateModified.IsServerSide &&
cols.FindByColumnName(cols.DateModified.ColumnName) != null)
{
into += comma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["DateModified.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.AddedBy != null && cols.AddedBy.IsServerSide &&
cols.FindByColumnName(cols.AddedBy.ColumnName) != null)
{
into += comma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["AddedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide &&
cols.FindByColumnName(cols.ModifiedBy.ColumnName) != null)
{
into += comma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
values += comma + request.ProviderMetadata["ModifiedBy.ServerSideText"];
comma = ", ";
defaults += defaultComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultComma = ",";
}
#endregion
if (defaults.Length > 0)
{
comma = String.Empty;
props["Defaults"] = defaults;
props["Where"] = where;
}
sql += " INSERT INTO " + CreateFullName(request);
if (into.Length != 0)
{
sql += "(" + into + ") VALUES (" + values + ")";
}
else
{
sql += "DEFAULT VALUES";
}
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public VistaDBCommand BuildDynamicUpdateCommand(tgDataRequest request, List<string> modifiedColumns)
{
string where = String.Empty;
string scomma = String.Empty;
string wcomma = String.Empty;
string defaults = String.Empty;
string defaultsWhere = String.Empty;
string defaultsComma = String.Empty;
string defaultsWhereComma = String.Empty;
string sql = "UPDATE " + CreateFullName(request) + " SET ";
PropertyCollection props = new PropertyCollection();
VistaDBParameter p = null;
Dictionary<string, VistaDBParameter> types = Cache.GetParameters(request);
VistaDBCommand cmd = new VistaDBCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
tgColumnMetadataCollection cols = request.Columns;
foreach (tgColumnMetadata col in cols)
{
bool isModified = modifiedColumns == null ? false : modifiedColumns.Contains(col.Name);
if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency))
{
p = CloneParameter(types[col.Name]);
cmd.Parameters.Add(p);
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
scomma = ", ";
}
else if (col.IsAutoIncrement)
{
// Nothing to do but leave this here
}
else if (col.IsConcurrency)
{
props["Timestamp"] = col.Name;
props["Source"] = request.ProviderMetadata.Source;
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
p.Direction = ParameterDirection.InputOutput;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsTiraggoConcurrency)
{
props["EntitySpacesConcurrency"] = col.Name;
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
p.Direction = ParameterDirection.InputOutput;
cmd.Parameters.Add(p);
sql += scomma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " + 1";
scomma = ", ";
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
}
else if (col.IsComputed)
{
// Do nothing but leave this here
}
else if (cols.IsSpecialColumn(col))
{
// Do nothing but leave this here
}
else if (col.HasDefault)
{
// defaults += defaultsComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose;
// defaultsComma = ",";
}
if (col.IsInPrimaryKey)
{
p = CloneParameter(types[col.Name]);
p.SourceVersion = DataRowVersion.Original;
cmd.Parameters.Add(p);
where += wcomma;
where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
wcomma = " AND ";
defaultsWhere += defaultsWhereComma + col.Name;
defaultsWhereComma = ",";
}
}
#region Special Columns
if (cols.DateModified != null && cols.DateModified.IsServerSide &&
cols.FindByColumnName(cols.DateModified.ColumnName) != null)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["DateModified.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide &&
cols.FindByColumnName(cols.ModifiedBy.ColumnName) != null)
{
sql += scomma;
sql += Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["ModifiedBy.ServerSideText"];
scomma = ", ";
defaults += defaultsComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose;
defaultsComma = ",";
}
#endregion
if (defaults.Length > 0)
{
props["Defaults"] = defaults;
props["Where"] = defaultsWhere;
}
sql += " WHERE " + where + ";";
request.Properties = props;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public VistaDBCommand BuildDynamicDeleteCommand(tgDataRequest request, List<string> modifiedColumns)
{
Dictionary<string, VistaDBParameter> types = Cache.GetParameters(request);
VistaDBCommand cmd = new VistaDBCommand();
if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
string sql = "DELETE FROM " + CreateFullName(request) + " ";
string comma = String.Empty;
comma = String.Empty;
sql += " WHERE ";
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsInPrimaryKey || col.IsTiraggoConcurrency || col.IsConcurrency)
{
VistaDBParameter p = types[col.Name];
cmd.Parameters.Add(CloneParameter(p));
sql += comma;
sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName;
comma = " AND ";
}
}
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return cmd;
}
static public VistaDBCommand BuildStoredProcInsertCommand(tgDataRequest request)
{
VistaDBCommand cmd = new VistaDBCommand();
if(request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spInsert + Delimiters.StoredProcNameClose;
PopulateStoredProcParameters(cmd, request);
foreach (tgColumnMetadata col in request.Columns)
{
if (col.HasDefault && col.Default.ToLower() == "GUID()")
{
VistaDBParameter p = cmd.Parameters[Delimiters.Param + col.PropertyName];
p.Direction = ParameterDirection.InputOutput;
}
else if (col.IsComputed || col.IsAutoIncrement)
{
VistaDBParameter p = cmd.Parameters[Delimiters.Param + col.PropertyName];
p.Direction = ParameterDirection.Output;
}
}
return cmd;
}
static public VistaDBCommand BuildStoredProcUpdateCommand(tgDataRequest request)
{
VistaDBCommand cmd = new VistaDBCommand();
if(request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spUpdate + Delimiters.StoredProcNameClose;
PopulateStoredProcParameters(cmd, request);
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsComputed)
{
VistaDBParameter p = cmd.Parameters[Delimiters.Param + col.PropertyName];
p.Direction = ParameterDirection.InputOutput;
}
}
return cmd;
}
static public VistaDBCommand BuildStoredProcDeleteCommand(tgDataRequest request)
{
VistaDBCommand cmd = new VistaDBCommand();
if(request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spDelete + Delimiters.StoredProcNameClose;
Dictionary<string, VistaDBParameter> types = Cache.GetParameters(request);
VistaDBParameter p;
foreach (tgColumnMetadata col in request.Columns)
{
if (col.IsInPrimaryKey)
{
p = types[col.Name];
p = CloneParameter(p);
p.SourceVersion = DataRowVersion.Current;
cmd.Parameters.Add(p);
}
}
return cmd;
}
static public void PopulateStoredProcParameters(VistaDBCommand cmd, tgDataRequest request)
{
Dictionary<string, VistaDBParameter> types = Cache.GetParameters(request);
VistaDBParameter p;
foreach (tgColumnMetadata col in request.Columns)
{
p = types[col.Name];
p = CloneParameter(p);
p.SourceVersion = DataRowVersion.Current;
if (col.IsComputed && col.CharacterMaxLength > 0)
{
p.Size = (int)col.CharacterMaxLength;
}
cmd.Parameters.Add(p);
}
}
static private VistaDBParameter CloneParameter(VistaDBParameter p)
{
ICloneable param = p as ICloneable;
return param.Clone() as VistaDBParameter;
}
static public string CreateFullName(tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
tgProviderSpecificMetadata providerMetadata = iQuery.ProviderMetadata as tgProviderSpecificMetadata;
string name = String.Empty;
name += Delimiters.TableOpen;
if (query.tg.QuerySource != null)
name += query.tg.QuerySource;
else
name += providerMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public string CreateFullName(tgDataRequest request)
{
string name = String.Empty;
name += Delimiters.TableOpen;
if(request.DynamicQuery != null && request.DynamicQuery.tg.QuerySource != null)
name += request.DynamicQuery.tg.QuerySource;
else
name += request.QueryText != null ? request.QueryText : request.ProviderMetadata.Destination;
name += Delimiters.TableClose;
return name;
}
static public string CreateFullName(tgProviderSpecificMetadata providerMetadata)
{
return Delimiters.TableOpen + providerMetadata.Destination + Delimiters.TableClose;
}
static public tgConcurrencyException CheckForConcurrencyException(VistaDBException ex)
{
tgConcurrencyException ce = null;
return ce;
}
static public void AddParameters(VistaDBCommand cmd, tgDataRequest request)
{
if (request.QueryType == tgQueryType.Text && request.QueryText != null && request.QueryText.Contains("{0}"))
{
int i = 0;
string token = String.Empty;
string sIndex = String.Empty;
string param = String.Empty;
foreach (tgParameter esParam in request.Parameters)
{
sIndex = i.ToString();
token = '{' + sIndex + '}';
param = Delimiters.Param + "p" + sIndex;
request.QueryText = request.QueryText.Replace(token, param);
i++;
cmd.Parameters.Add(Delimiters.Param + esParam.Name, esParam.Value);
}
}
else
{
VistaDBParameter param;
foreach (tgParameter esParam in request.Parameters)
{
param = cmd.Parameters.Add(Delimiters.Param + esParam.Name, esParam.Value);
switch (esParam.Direction)
{
case tgParameterDirection.InputOutput:
param.Direction = ParameterDirection.InputOutput;
break;
case tgParameterDirection.Output:
param.Direction = ParameterDirection.Output;
param.DbType = esParam.DbType;
param.Size = esParam.Size;
break;
case tgParameterDirection.ReturnValue:
param.Direction = ParameterDirection.ReturnValue;
break;
// The default is ParameterDirection.Input;
}
}
}
}
static public void GatherReturnParameters(VistaDBCommand cmd, tgDataRequest request, tgDataResponse response)
{
if (cmd.Parameters.Count > 0)
{
if (request.Parameters != null && request.Parameters.Count > 0)
{
response.Parameters = new tgParameters();
foreach (tgParameter esParam in request.Parameters)
{
if (esParam.Direction != tgParameterDirection.Input)
{
response.Parameters.Add(esParam);
VistaDBParameter p = cmd.Parameters[Delimiters.Param + esParam.Name];
esParam.Value = p.Value;
}
}
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using NDesk.Options;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator inventory archives
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryArchiverModule")]
public class InventoryArchiverModule : ISharedRegionModule, IInventoryArchiverModule
{
/// <summary>
/// The file to load and save inventory if no filename has been specified
/// </summary>
protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar";
/// <value>
/// Pending save completions initiated from the console
/// </value>
protected List<Guid> m_pendingConsoleSaves = new List<Guid>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Enable or disable checking whether the iar user is actually logged in
/// </value>
// public bool DisablePresenceChecks { get; set; }
private Scene m_aScene;
/// <value>
/// All scenes that this module knows about
/// </value>
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
private IUserAccountService m_UserAccountService;
public InventoryArchiverModule()
{
}
public event InventoryArchiveSaved OnInventoryArchiveSaved;
protected IUserAccountService UserAccountService
{
get
{
if (m_UserAccountService == null)
// What a strange thing to do...
foreach (Scene s in m_scenes.Values)
{
m_UserAccountService = s.RequestModuleInterface<IUserAccountService>();
break;
}
return m_UserAccountService;
}
}
// public InventoryArchiverModule(bool disablePresenceChecks)
// {
// DisablePresenceChecks = disablePresenceChecks;
// }
#region ISharedRegionModule
public string Name { get { return "Inventory Archiver Module"; } }
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (m_scenes.Count == 0)
{
scene.RegisterModuleInterface<IInventoryArchiverModule>(this);
OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted;
scene.AddCommand(
"Archiving", this, "load iar",
"load iar [-m|--merge] <first> <last> <inventory path> <password> [<IAR path>]",
"Load user inventory archive (IAR).",
"-m|--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones"
+ "<first> is user's first name." + Environment.NewLine
+ "<last> is user's last name." + Environment.NewLine
+ "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine
+ "<password> is the user's password." + Environment.NewLine
+ "<IAR path> is the filesystem path or URI from which to load the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME),
HandleLoadInvConsoleCommand);
scene.AddCommand(
"Archiving", this, "save iar",
"save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]",
"Save user inventory archive (IAR).",
"<first> is the user's first name.\n"
+ "<last> is the user's last name.\n"
+ "<inventory path> is the path inside the user's inventory for the folder/item to be saved.\n"
+ "<IAR path> is the filesystem path at which to save the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used.\n", DEFAULT_INV_BACKUP_FILENAME)
+ "-h|--home=<url> adds the url of the profile service to the saved user information.\n"
+ "-c|--creators preserves information about foreign creators.\n"
+ "-e|--exclude=<name/uuid> don't save the inventory item in archive" + Environment.NewLine
+ "-f|--excludefolder=<folder/uuid> don't save contents of the folder in archive" + Environment.NewLine
+ "-v|--verbose extra debug messages.\n"
+ "--noassets stops assets being saved to the IAR.",
HandleSaveInvConsoleCommand);
m_aScene = scene;
}
m_scenes[scene.RegionInfo.RegionID] = scene;
}
public void Close()
{
}
public void Initialise(IConfigSource source)
{
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
#endregion ISharedRegionModule
public bool ArchiveInventory(
Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream)
{
return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>());
}
public bool ArchiveInventory(
Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool ArchiveInventory(
Guid id, string firstName, string lastName, string invPath, string pass, string savePath,
Dictionary<string, object> options)
{
// if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, savePath))
// return false;
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream)
{
return DearchiveInventory(firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>());
}
public bool DearchiveInventory(
string firstName, string lastName, string invPath, string pass, Stream loadStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadStream, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
else
m_log.ErrorFormat("[INVENTORY ARCHIVER]: User {0} {1} not found",
firstName, lastName);
}
return false;
}
public bool DearchiveInventory(
string firstName, string lastName, string invPath, string pass, string loadPath,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadPath, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
/// <summary>
/// Trigger the inventory archive saved event.
/// </summary>
protected internal void TriggerInventoryArchiveSaved(
Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException)
{
InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved;
if (handlerInventoryArchiveSaved != null)
handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException);
}
/// <summary>
/// Get user information for the given name.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="pass">User password</param>
/// <returns></returns>
protected UserAccount GetUserInfo(string firstName, string lastName, string pass)
{
UserAccount account
= m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName);
if (null == account)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}",
firstName, lastName);
return null;
}
try
{
string encpass = Util.Md5Hash(pass);
if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty)
{
return account;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.",
firstName, lastName);
return null;
}
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e);
return null;
}
}
/// <summary>
/// Load inventory from an inventory file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
{
try
{
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet optionSet = new OptionSet().Add("m|merge", delegate(string v) { options["merge"] = v != null; });
List<string> mainParams = optionSet.Parse(cmdparams);
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: usage is load iar [-m|--merge] <first name> <last name> <inventory path> <user password> [<load file path>]");
return;
}
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
loadPath, invPath, firstName, lastName);
if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath, options))
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}",
loadPath, firstName, lastName);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
/// <summary>
/// Save inventory to a file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
{
Guid id = Guid.NewGuid();
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet ops = new OptionSet();
//ops.Add("v|version=", delegate(string v) { options["version"] = v; });
ops.Add("h|home=", delegate(string v) { options["home"] = v; });
ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; });
ops.Add("c|creators", delegate(string v) { options["creators"] = v; });
ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
ops.Add("e|exclude=", delegate(string v)
{
if (!options.ContainsKey("exclude"))
options["exclude"] = new List<String>();
((List<String>)options["exclude"]).Add(v);
});
ops.Add("f|excludefolder=", delegate(string v)
{
if (!options.ContainsKey("excludefolders"))
options["excludefolders"] = new List<String>();
((List<String>)options["excludefolders"]).Add(v);
});
List<string> mainParams = ops.Parse(cmdparams);
try
{
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]");
return;
}
if (options.ContainsKey("home"))
m_log.WarnFormat("[INVENTORY ARCHIVER]: Please be aware that inventory archives with creator information are not compatible with OpenSim 0.7.0.2 and earlier. Do not use the -home option if you want to produce a compatible IAR");
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string savePath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
savePath, invPath, firstName, lastName);
lock (m_pendingConsoleSaves)
m_pendingConsoleSaves.Add(id);
ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
private void SaveInvConsoleCommandCompleted(
Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException)
{
lock (m_pendingConsoleSaves)
{
if (m_pendingConsoleSaves.Contains(id))
m_pendingConsoleSaves.Remove(id);
else
return;
}
if (succeeded)
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0} {1}", userInfo.FirstName, userInfo.LastName);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}",
userInfo.FirstName, userInfo.LastName, reportedException.Message);
}
}
/// <summary>
/// Notify the client of loaded nodes if they are logged in
/// </summary>
/// <param name="loadedNodes">Can be empty. In which case, nothing happens</param>
private void UpdateClientWithLoadedNodes(UserAccount userInfo, HashSet<InventoryNodeBase> loadedNodes)
{
if (loadedNodes.Count == 0)
return;
foreach (Scene scene in m_scenes.Values)
{
ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID);
if (user != null && !user.IsChildAgent)
{
foreach (InventoryNodeBase node in loadedNodes)
{
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}",
// user.Name, node.Name);
user.ControllingClient.SendBulkUpdateInventory(node);
}
break;
}
}
}
// /// <summary>
// /// Check if the given user is present in any of the scenes.
// /// </summary>
// /// <param name="userId">The user to check</param>
// /// <returns>true if the user is in any of the scenes, false otherwise</returns>
// protected bool CheckPresence(UUID userId)
// {
// if (DisablePresenceChecks)
// return true;
//
// foreach (Scene scene in m_scenes.Values)
// {
// ScenePresence p;
// if ((p = scene.GetScenePresence(userId)) != null)
// {
// p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false);
// return true;
// }
// }
//
// return false;
// }
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/logging/v2/logging_metrics.proto
// Original file comments:
// Copyright 2017 Google 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.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Google.Cloud.Logging.V2 {
/// <summary>
/// Service for configuring logs-based metrics.
/// </summary>
public static partial class MetricsServiceV2
{
static readonly string __ServiceName = "google.logging.v2.MetricsServiceV2";
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogMetricsRequest> __Marshaller_ListLogMetricsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogMetricsRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> __Marshaller_ListLogMetricsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogMetricsResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.GetLogMetricRequest> __Marshaller_GetLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.GetLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.LogMetric> __Marshaller_LogMetric = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.LogMetric.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.CreateLogMetricRequest> __Marshaller_CreateLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.CreateLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest> __Marshaller_UpdateLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.UpdateLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest> __Marshaller_DeleteLogMetricRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.DeleteLogMetricRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.ListLogMetricsRequest, global::Google.Cloud.Logging.V2.ListLogMetricsResponse> __Method_ListLogMetrics = new grpc::Method<global::Google.Cloud.Logging.V2.ListLogMetricsRequest, global::Google.Cloud.Logging.V2.ListLogMetricsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListLogMetrics",
__Marshaller_ListLogMetricsRequest,
__Marshaller_ListLogMetricsResponse);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.GetLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_GetLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.GetLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>(
grpc::MethodType.Unary,
__ServiceName,
"GetLogMetric",
__Marshaller_GetLogMetricRequest,
__Marshaller_LogMetric);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.CreateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_CreateLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.CreateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>(
grpc::MethodType.Unary,
__ServiceName,
"CreateLogMetric",
__Marshaller_CreateLogMetricRequest,
__Marshaller_LogMetric);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_UpdateLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>(
grpc::MethodType.Unary,
__ServiceName,
"UpdateLogMetric",
__Marshaller_UpdateLogMetricRequest,
__Marshaller_LogMetric);
static readonly grpc::Method<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteLogMetric = new grpc::Method<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"DeleteLogMetric",
__Marshaller_DeleteLogMetricRequest,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of MetricsServiceV2</summary>
public abstract partial class MetricsServiceV2Base
{
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for MetricsServiceV2</summary>
public partial class MetricsServiceV2Client : grpc::ClientBase<MetricsServiceV2Client>
{
/// <summary>Creates a new client for MetricsServiceV2</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public MetricsServiceV2Client(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for MetricsServiceV2 that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public MetricsServiceV2Client(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected MetricsServiceV2Client() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected MetricsServiceV2Client(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListLogMetrics(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListLogMetrics, null, options, request);
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListLogMetricsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListLogMetrics, null, options, request);
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetLogMetric, null, options, request);
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetLogMetric, null, options, request);
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateLogMetric, null, options, request);
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateLogMetric, null, options, request);
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Logging.V2.LogMetric UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UpdateLogMetric, null, options, request);
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UpdateLogMetric, null, options, request);
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteLogMetric(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeleteLogMetric, null, options, request);
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteLogMetricAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeleteLogMetric, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override MetricsServiceV2Client NewInstance(ClientBaseConfiguration configuration)
{
return new MetricsServiceV2Client(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(MetricsServiceV2Base serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_ListLogMetrics, serviceImpl.ListLogMetrics)
.AddMethod(__Method_GetLogMetric, serviceImpl.GetLogMetric)
.AddMethod(__Method_CreateLogMetric, serviceImpl.CreateLogMetric)
.AddMethod(__Method_UpdateLogMetric, serviceImpl.UpdateLogMetric)
.AddMethod(__Method_DeleteLogMetric, serviceImpl.DeleteLogMetric).Build();
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using SimpleContainer.Configuration;
using SimpleContainer.Infection;
using SimpleContainer.Interface;
using SimpleContainer.Tests.Helpers;
namespace SimpleContainer.Tests.Contracts
{
public abstract class ContractsUnionTest : SimpleContainerTestBase
{
public class WrapExceptionsFromConfigurators : ContractsUnionTest
{
public class AWrap
{
public readonly A a;
public AWrap(A a)
{
this.a = a;
}
}
public class A
{
}
public class AConfigurator : IServiceConfigurator<A>
{
public void Configure(ConfigurationContext context, ServiceConfigurationBuilder<A> builder)
{
throw new InvalidOperationException("my exception");
}
}
[Test]
public void Test()
{
var container = Container();
var error = Assert.Throws<SimpleContainerException>(() => container.Get<AWrap>());
Assert.That(error.Message, Is.EqualTo(TestHelpers.FormatMessage(@"
service [A] construction exception
!AWrap
!A <---------------")));
Assert.That(error.InnerException, Is.InstanceOf<SimpleContainerException>());
Assert.That(error.InnerException.Message, Is.EqualTo("error executing configurator [AConfigurator]"));
Assert.That(error.InnerException.InnerException, Is.InstanceOf<InvalidOperationException>());
Assert.That(error.InnerException.InnerException.Message, Is.EqualTo("my exception"));
}
}
public class UnionOfAppliedToManyContracts_CorrectException : ContractsUnionTest
{
[Test]
public void Test()
{
var error = Assert.Throws<SimpleContainerException>(() => Container(
b => b.Contract("c1").Contract("c2").UnionOf("x1", "x2")));
Assert.That(error.Message, Is.EqualTo("UnionOf can be applied to single contract, current contracts [c1, c2]"));
}
}
public class NestedUnions : ContractsUnionTest
{
public class A
{
public readonly BWrap[] bWraps;
public A([TestContract("u1")] BWrap[] bWraps)
{
this.bWraps = bWraps;
}
}
public class BWrap
{
public readonly IB b;
public BWrap(IB b)
{
this.b = b;
}
}
public interface IB
{
}
public class B1 : IB
{
}
public class B2 : IB
{
}
public class B3 : IB
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.Contract("u1").UnionOf("c1", "c2");
b.Contract("c1").UnionOf("c3", "c4");
b.Contract("c2").UnionOf("c4", "c5");
b.Contract("c3").Bind<IB, B1>();
b.Contract("c4").Bind<IB, B2>();
b.Contract("c5").Bind<IB, B3>();
});
var instance = container.Resolve<A>();
Assert.That(instance.Single().bWraps.Length, Is.EqualTo(3));
}
}
public class CartesianProductAdjacentUnionedContracts : ContractsUnionTest
{
public class Host
{
public readonly A[] instances;
public Host([TestContract("union1")] A[] instances)
{
this.instances = instances;
}
}
[TestContract("union2")]
public class A
{
public readonly int parameter;
public readonly B b;
public A(int parameter, B b)
{
this.parameter = parameter;
this.b = b;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.Contract("union1").UnionOf("c1", "c2");
b.Contract("union2").UnionOf("c3", "c4");
b.Contract("c1").BindDependency<A>("parameter", 1);
b.Contract("c2").BindDependency<A>("parameter", 2);
b.Contract("c3").BindDependency<B>("parameter", 3);
b.Contract("c4").BindDependency<B>("parameter", 4);
});
var host = container.Get<Host>();
Assert.That(host.instances.Length, Is.EqualTo(4));
Assert.That(host.instances[0].parameter, Is.EqualTo(1));
Assert.That(host.instances[0].b.parameter, Is.EqualTo(3));
Assert.That(host.instances[1].parameter, Is.EqualTo(1));
Assert.That(host.instances[1].b.parameter, Is.EqualTo(4));
Assert.That(host.instances[2].parameter, Is.EqualTo(2));
Assert.That(host.instances[2].b.parameter, Is.EqualTo(3));
Assert.That(host.instances[3].parameter, Is.EqualTo(2));
Assert.That(host.instances[3].b.parameter, Is.EqualTo(4));
}
}
public class CanExplicitlyQueryForUnionedContract : ContractsUnionTest
{
public class Host
{
public readonly IA a;
public Host(IA a)
{
this.a = a;
}
}
public interface IA
{
}
public class A1 : IA
{
}
public class A2 : IA
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("unioned").UnionOf("c1", "c2");
builder.Contract("c1").Bind<IA, A1>();
builder.Contract("c2").Bind<IA, A2>();
});
var hosts = container.GetAll<Host>("unioned").ToArray();
Assert.That(hosts.Length, Is.EqualTo(2));
Assert.That(hosts[0].a, Is.InstanceOf<A1>());
Assert.That(hosts[1].a, Is.InstanceOf<A2>());
Assert.That(hosts[0].a, Is.SameAs(container.Get<IA>("c1")));
Assert.That(hosts[1].a, Is.SameAs(container.Get<IA>("c2")));
}
}
public class ContractsCanBeUnioned : ContractsUnionTest
{
public class AllWrapsHost
{
public readonly ServiceWrap[] wraps;
public AllWrapsHost([TestContract("composite-contract")] IEnumerable<ServiceWrap> wraps)
{
this.wraps = wraps.ToArray();
}
}
public class ServiceWrap
{
public readonly IService service;
public ServiceWrap(IService service)
{
this.service = service;
}
}
public interface IService
{
}
public class Service1 : IService
{
}
public class Service2 : IService
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("composite-contract").UnionOf("service1Contract", "service2Contract");
builder.Contract("service1Contract").Bind<IService, Service1>();
builder.Contract("service2Contract").Bind<IService, Service2>();
});
var wrap = container.Get<AllWrapsHost>();
Assert.That(wrap.wraps.Length, Is.EqualTo(2));
Assert.That(wrap.wraps[0].service, Is.InstanceOf<Service1>());
Assert.That(wrap.wraps[1].service, Is.InstanceOf<Service2>());
}
}
public class ContractUnionGeneric : ContractsUnionTest
{
public class Contract1 : RequireContractAttribute
{
public Contract1()
: base("c1")
{
}
}
public class Contract2 : RequireContractAttribute
{
public Contract2()
: base("c2")
{
}
}
public class AllWrapsHost
{
public readonly ServiceWrap[] wraps;
public AllWrapsHost([TestContract("composite-contract")] IEnumerable<ServiceWrap> wraps)
{
this.wraps = wraps.ToArray();
}
}
public class ServiceWrap
{
public readonly IService service;
public ServiceWrap(IService service)
{
this.service = service;
}
}
public interface IService
{
}
public class Service1 : IService
{
}
public class Service2 : IService
{
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("composite-contract").Union<Contract1>().Union<Contract2>();
builder.Contract<Contract1>().Bind<IService, Service1>();
builder.Contract<Contract2>().Bind<IService, Service2>();
});
var wrap = container.Get<AllWrapsHost>();
Assert.That(wrap.wraps.Length, Is.EqualTo(2));
Assert.That(wrap.wraps[0].service, Is.InstanceOf<Service1>());
Assert.That(wrap.wraps[1].service, Is.InstanceOf<Service2>());
}
}
public class UnionContractsWithNonContractDependentServices : ContractsUnionTest
{
public class ServiceWrap
{
public readonly Service[] wraps;
public ServiceWrap([TestContract("composite-contract")] IEnumerable<Service> wraps)
{
this.wraps = wraps.ToArray();
}
}
public class Service
{
}
public class OtherService
{
public readonly int parameter;
public OtherService(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder builder)
{
builder.Contract("composite-contract").UnionOf("service1Contract", "service2Contract");
builder.Contract("service1Contract").BindDependency<OtherService>("parameter", 1);
builder.Contract("service2Contract").BindDependency<OtherService>("parameter", 2);
});
var wrap = container.Get<ServiceWrap>();
Assert.That(wrap.wraps.Length, Is.EqualTo(1));
Assert.That(wrap.wraps[0], Is.SameAs(container.Get<Service>()));
}
}
public class RequiredUnionedContracts : ContractsUnionTest
{
public class A
{
public readonly B b;
public readonly C y1C;
public readonly C y2C;
public A([TestContract("x")] B b, [TestContract("y1")] C y1C, [TestContract("y2")] C y2C)
{
this.b = b;
this.y1C = y1C;
this.y2C = y2C;
}
}
public class B
{
public readonly IEnumerable<C> enumerable;
public B([TestContract("unioned")] IEnumerable<C> enumerable)
{
this.enumerable = enumerable;
}
}
public class C
{
public readonly int parameter;
public C(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.Contract("x");
b.Contract("unioned").UnionOf("y1", "y2");
b.Contract("x", "y1").BindDependency<C>("parameter", 1);
b.Contract("x", "y2").BindDependency<C>("parameter", 2);
b.Contract("y1").BindDependency<C>("parameter", 3);
b.Contract("y2").BindDependency<C>("parameter", 4);
});
var a = container.Get<A>();
Assert.That(a.b.enumerable.Select(x => x.parameter).ToArray(), Is.EquivalentTo(new[] { 1, 2 }));
Assert.That(a.y1C.parameter, Is.EqualTo(3));
Assert.That(a.y2C.parameter, Is.EqualTo(4));
}
}
public class TrackUsageOfUnionedContract : ContractsUnionTest
{
public class A
{
public readonly IEnumerable<B> bs;
public A([TestContract("test-union-contract")] IEnumerable<B> bs)
{
this.bs = bs;
}
}
public class B
{
public readonly int parameter;
public B(int parameter)
{
this.parameter = parameter;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.Contract("test-union-contract").UnionOf("c1", "c2");
b.Contract("c1").BindDependencies<B>(new {parameter = 1});
b.Contract("c2").BindDependencies<B>(new {parameter = 2});
});
var a = container.Resolve<A>();
Assert.That(a.Single().bs.Select(x => x.parameter).ToArray(), Is.EqualTo(new[] {1, 2}));
var expectedConstructionLog = TestHelpers.FormatMessage(@"
A
B[test-union-contract]++
B[c1]
parameter -> 1
B[c2]
parameter -> 2");
Assert.That(a.GetConstructionLog(), Is.EqualTo(expectedConstructionLog));
}
}
public class ManyRequiredAndUnionedContracts : ContractsUnionTest
{
public class A
{
public readonly B b;
public A([TestContract("x")] B b)
{
this.b = b;
}
}
public class B
{
public readonly IEnumerable<C> enumerable;
public B([TestContract("unioned")] IEnumerable<C> enumerable)
{
this.enumerable = enumerable;
}
}
public class C
{
public readonly string context;
public C(string context)
{
this.context = context;
}
}
[Test]
public void Test()
{
var container = Container(delegate(ContainerConfigurationBuilder b)
{
b.Contract("x");
b.Contract("unioned").UnionOf("y");
b.Contract("y").BindDependency<C>("context", "x");
b.Contract("x", "y").BindDependency<C>("context", "xy");
});
var a = container.Get<A>();
Assert.That(a.b.enumerable.Single().context, Is.EqualTo("xy"));
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.WebsiteBuilder.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
using Frapid.WebApi;
namespace Frapid.WebsiteBuilder.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Contacts.
/// </summary>
[RoutePrefix("api/v1.0/website/contact")]
public class ContactController : FrapidApiController
{
/// <summary>
/// The Contact repository.
/// </summary>
private IContactRepository ContactRepository;
public ContactController()
{
}
public ContactController(IContactRepository repository)
{
this.ContactRepository = repository;
}
protected override void Initialize(HttpControllerContext context)
{
base.Initialize(context);
if (this.ContactRepository == null)
{
this.ContactRepository = new Frapid.WebsiteBuilder.DataAccess.Contact
{
_Catalog = this.MetaUser.Catalog,
_LoginId = this.MetaUser.LoginId,
_UserId = this.MetaUser.UserId
};
}
}
/// <summary>
/// Creates meta information of "contact" entity.
/// </summary>
/// <returns>Returns the "contact" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/website/contact/meta")]
[RestAuthorize]
public EntityView GetEntityView()
{
return new EntityView
{
PrimaryKey = "contact_id",
Columns = new List<EntityColumn>()
{
new EntityColumn
{
ColumnName = "contact_id",
PropertyName = "ContactId",
DataType = "int",
DbDataType = "int4",
IsNullable = false,
IsPrimaryKey = true,
IsSerial = true,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "title",
PropertyName = "Title",
DataType = "string",
DbDataType = "varchar",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "name",
PropertyName = "Name",
DataType = "string",
DbDataType = "varchar",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "position",
PropertyName = "Position",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "address",
PropertyName = "Address",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "city",
PropertyName = "City",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "state",
PropertyName = "State",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "country",
PropertyName = "Country",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 100
},
new EntityColumn
{
ColumnName = "postal_code",
PropertyName = "PostalCode",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "telephone",
PropertyName = "Telephone",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "details",
PropertyName = "Details",
DataType = "string",
DbDataType = "text",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "email",
PropertyName = "Email",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 500
},
new EntityColumn
{
ColumnName = "recipients",
PropertyName = "Recipients",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 1000
},
new EntityColumn
{
ColumnName = "display_email",
PropertyName = "DisplayEmail",
DataType = "bool",
DbDataType = "bool",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "display_contact_form",
PropertyName = "DisplayContactForm",
DataType = "bool",
DbDataType = "bool",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "sort",
PropertyName = "Sort",
DataType = "int",
DbDataType = "int4",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "status",
PropertyName = "Status",
DataType = "bool",
DbDataType = "bool",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "audit_user_id",
PropertyName = "AuditUserId",
DataType = "int",
DbDataType = "int4",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "audit_ts",
PropertyName = "AuditTs",
DataType = "DateTime",
DbDataType = "timestamptz",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
}
}
};
}
/// <summary>
/// Counts the number of contacts.
/// </summary>
/// <returns>Returns the count of the contacts.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/website/contact/count")]
[RestAuthorize]
public long Count()
{
try
{
return this.ContactRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of contact.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/website/contact/all")]
[RestAuthorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.Contact> GetAll()
{
try
{
return this.ContactRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of contact for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/website/contact/export")]
[RestAuthorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.ContactRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of contact.
/// </summary>
/// <param name="contactId">Enter ContactId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{contactId}")]
[Route("~/api/website/contact/{contactId}")]
[RestAuthorize]
public Frapid.WebsiteBuilder.Entities.Contact Get(int contactId)
{
try
{
return this.ContactRepository.Get(contactId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/website/contact/get")]
[RestAuthorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.Contact> Get([FromUri] int[] contactIds)
{
try
{
return this.ContactRepository.Get(contactIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of contact.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/website/contact/first")]
[RestAuthorize]
public Frapid.WebsiteBuilder.Entities.Contact GetFirst()
{
try
{
return this.ContactRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of contact.
/// </summary>
/// <param name="contactId">Enter ContactId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{contactId}")]
[Route("~/api/website/contact/previous/{contactId}")]
[RestAuthorize]
public Frapid.WebsiteBuilder.Entities.Contact GetPrevious(int contactId)
{
try
{
return this.ContactRepository.GetPrevious(contactId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of contact.
/// </summary>
/// <param name="contactId">Enter ContactId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{contactId}")]
[Route("~/api/website/contact/next/{contactId}")]
[RestAuthorize]
public Frapid.WebsiteBuilder.Entities.Contact GetNext(int contactId)
{
try
{
return this.ContactRepository.GetNext(contactId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of contact.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/website/contact/last")]
[RestAuthorize]
public Frapid.WebsiteBuilder.Entities.Contact GetLast()
{
try
{
return this.ContactRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 contacts on each page, sorted by the property ContactId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/website/contact")]
[RestAuthorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.Contact> GetPaginatedResult()
{
try
{
return this.ContactRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 contacts on each page, sorted by the property ContactId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/website/contact/page/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.Contact> GetPaginatedResult(long pageNumber)
{
try
{
return this.ContactRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of contacts using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered contacts.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/website/contact/count-where")]
[RestAuthorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ContactRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 contacts on each page, sorted by the property ContactId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/website/contact/get-where/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.Contact> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ContactRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of contacts using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered contacts.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/website/contact/count-filtered/{filterName}")]
[RestAuthorize]
public long CountFiltered(string filterName)
{
try
{
return this.ContactRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 contacts on each page, sorted by the property ContactId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/website/contact/get-filtered/{pageNumber}/{filterName}")]
[RestAuthorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.Contact> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.ContactRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of contacts.
/// </summary>
/// <returns>Returns an enumerable key/value collection of contacts.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/website/contact/display-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.ContactRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for contacts.
/// </summary>
/// <returns>Returns an enumerable custom field collection of contacts.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/website/contact/custom-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.ContactRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for contacts.
/// </summary>
/// <returns>Returns an enumerable custom field collection of contacts.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/website/contact/custom-fields/{resourceId}")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.ContactRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of Contact class.
/// </summary>
/// <param name="contact">Your instance of contacts class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/website/contact/add-or-edit")]
[RestAuthorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic contact = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (contact == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.ContactRepository.AddOrEdit(contact, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of Contact class.
/// </summary>
/// <param name="contact">Your instance of contacts class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{contact}")]
[Route("~/api/website/contact/add/{contact}")]
[RestAuthorize]
public void Add(Frapid.WebsiteBuilder.Entities.Contact contact)
{
if (contact == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ContactRepository.Add(contact);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of Contact class.
/// </summary>
/// <param name="contact">Your instance of Contact class to edit.</param>
/// <param name="contactId">Enter the value for ContactId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{contactId}")]
[Route("~/api/website/contact/edit/{contactId}")]
[RestAuthorize]
public void Edit(int contactId, [FromBody] Frapid.WebsiteBuilder.Entities.Contact contact)
{
if (contact == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ContactRepository.Update(contact, contactId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of Contact class.
/// </summary>
/// <param name="collection">Your collection of Contact class to bulk import.</param>
/// <returns>Returns list of imported contactIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any Contact class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/website/contact/bulk-import")]
[RestAuthorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> contactCollection = this.ParseCollection(collection);
if (contactCollection == null || contactCollection.Count.Equals(0))
{
return null;
}
try
{
return this.ContactRepository.BulkImport(contactCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of Contact class via ContactId.
/// </summary>
/// <param name="contactId">Enter the value for ContactId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{contactId}")]
[Route("~/api/website/contact/delete/{contactId}")]
[RestAuthorize]
public void Delete(int contactId)
{
try
{
this.ContactRepository.Delete(contactId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
// 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.Web.UI.WebControls.WebParts.WebZone.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 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.Web.UI.WebControls.WebParts
{
abstract public partial class WebZone : System.Web.UI.WebControls.CompositeControl
{
#region Methods and constructors
public virtual new PartChromeType GetEffectiveChromeType (Part part)
{
return default(PartChromeType);
}
protected override void LoadViewState (Object savedState)
{
}
protected internal override void OnInit (EventArgs e)
{
}
protected internal override void OnPreRender (EventArgs e)
{
}
public override void RenderBeginTag (System.Web.UI.HtmlTextWriter writer)
{
}
protected virtual new void RenderBody (System.Web.UI.HtmlTextWriter writer)
{
}
protected internal override void RenderContents (System.Web.UI.HtmlTextWriter writer)
{
}
protected virtual new void RenderFooter (System.Web.UI.HtmlTextWriter writer)
{
}
protected virtual new void RenderHeader (System.Web.UI.HtmlTextWriter writer)
{
}
protected override Object SaveViewState ()
{
return default(Object);
}
protected override void TrackViewState ()
{
}
#endregion
#region Properties and indexers
public virtual new string BackImageUrl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string EmptyZoneText
{
get
{
return default(string);
}
set
{
}
}
public System.Web.UI.WebControls.Style EmptyZoneTextStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null);
return default(System.Web.UI.WebControls.Style);
}
}
public System.Web.UI.WebControls.Style ErrorStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null);
return default(System.Web.UI.WebControls.Style);
}
}
public TitleStyle FooterStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.WebParts.TitleStyle>() != null);
return default(TitleStyle);
}
}
protected virtual new bool HasFooter
{
get
{
return default(bool);
}
}
protected virtual new bool HasHeader
{
get
{
return default(bool);
}
}
public TitleStyle HeaderStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.WebParts.TitleStyle>() != null);
return default(TitleStyle);
}
}
public virtual new string HeaderText
{
get
{
return default(string);
}
set
{
}
}
public virtual new int Padding
{
get
{
return default(int);
}
set
{
}
}
public System.Web.UI.WebControls.Unit PartChromePadding
{
get
{
return default(System.Web.UI.WebControls.Unit);
}
set
{
}
}
public System.Web.UI.WebControls.Style PartChromeStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null);
return default(System.Web.UI.WebControls.Style);
}
}
public virtual new PartChromeType PartChromeType
{
get
{
return default(PartChromeType);
}
set
{
}
}
public System.Web.UI.WebControls.TableStyle PartStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableStyle>() != null);
return default(System.Web.UI.WebControls.TableStyle);
}
}
public TitleStyle PartTitleStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.WebParts.TitleStyle>() != null);
return default(TitleStyle);
}
}
internal protected bool RenderClientScript
{
get
{
return default(bool);
}
}
protected override System.Web.UI.HtmlTextWriterTag TagKey
{
get
{
return default(System.Web.UI.HtmlTextWriterTag);
}
}
public virtual new System.Web.UI.WebControls.ButtonType VerbButtonType
{
get
{
return default(System.Web.UI.WebControls.ButtonType);
}
set
{
}
}
public System.Web.UI.WebControls.Style VerbStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null);
return default(System.Web.UI.WebControls.Style);
}
}
protected WebPartManager WebPartManager
{
get
{
return default(WebPartManager);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Reflection.Emit
{
public sealed partial class AssemblyBuilder : System.Reflection.Assembly
{
internal AssemblyBuilder() { }
public override string FullName { get { throw null; } }
public override bool IsDynamic { get { throw null; } }
public override System.Reflection.Module ManifestModule { get { throw null; } }
public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) { throw null; }
public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes) { throw null; }
public System.Reflection.Emit.ModuleBuilder DefineDynamicModule(string name) { throw null; }
public override bool Equals(object obj) { throw null; }
public System.Reflection.Emit.ModuleBuilder GetDynamicModule(string name) { throw null; }
public override int GetHashCode() { throw null; }
public override System.Reflection.ManifestResourceInfo GetManifestResourceInfo(string resourceName) { throw null; }
public override string[] GetManifestResourceNames() { throw null; }
public override System.IO.Stream GetManifestResourceStream(string name) { throw null; }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
}
[System.FlagsAttribute]
public enum AssemblyBuilderAccess
{
Run = 1,
RunAndCollect = 9,
}
public sealed partial class ConstructorBuilder : System.Reflection.ConstructorInfo
{
internal ConstructorBuilder() { }
public override System.Reflection.MethodAttributes Attributes { get { throw null; } }
public override System.Reflection.CallingConventions CallingConvention { get { throw null; } }
public override System.Type DeclaringType { get { throw null; } }
public bool InitLocals { get { throw null; } set { } }
public override System.RuntimeMethodHandle MethodHandle { get { throw null; } }
public override System.Reflection.Module Module { get { throw null; } }
public override string Name { get { throw null; } }
public override System.Type ReflectedType { get { throw null; } }
public System.Reflection.Emit.ParameterBuilder DefineParameter(int iSequence, System.Reflection.ParameterAttributes attributes, string strParamName) { throw null; }
public override object[] GetCustomAttributes(bool inherit) { throw null; }
public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
public System.Reflection.Emit.ILGenerator GetILGenerator() { throw null; }
public System.Reflection.Emit.ILGenerator GetILGenerator(int streamSize) { throw null; }
public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw null; }
public override System.Reflection.ParameterInfo[] GetParameters() { throw null; }
public override object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw null; }
public override object Invoke(System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw null; }
public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { }
public override string ToString() { throw null; }
}
public sealed partial class EnumBuilder : System.Type //TYPEINFO: System.Reflection.TypeInfo doesn't have a public ctor
{
internal EnumBuilder() { }
public override System.Reflection.Assembly Assembly { get { throw null; } }
public override string AssemblyQualifiedName { get { throw null; } }
public override System.Type BaseType { get { throw null; } }
public override System.Type DeclaringType { get { throw null; } }
public override string FullName { get { throw null; } }
public override System.Guid GUID { get { throw null; } }
public override bool IsConstructedGenericType { get { throw null; } }
public override System.Reflection.Module Module { get { throw null; } }
public override string Name { get { throw null; } }
public override string Namespace { get { throw null; } }
public override System.Type ReflectedType { get { throw null; } }
public override System.RuntimeTypeHandle TypeHandle { get { throw null; } }
public System.Reflection.Emit.FieldBuilder UnderlyingField { get { throw null; } }
public override System.Type UnderlyingSystemType { get { throw null; } }
public System.Reflection.TypeInfo CreateTypeInfo() { throw null; }
public System.Reflection.Emit.FieldBuilder DefineLiteral(string literalName, object literalValue) { throw null; }
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; }
protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override object[] GetCustomAttributes(bool inherit) { throw null; }
public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
public override System.Type GetElementType() { throw null; }
public override System.Type GetEnumUnderlyingType() { throw null; }
public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.EventInfo[] GetEvents() { throw null; }
public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type GetInterface(string name, bool ignoreCase) { throw null; }
public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; }
public override System.Type[] GetInterfaces() { throw null; }
public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; }
protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; }
protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type returnType, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
protected override bool HasElementTypeImpl() { throw null; }
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { throw null; }
protected override bool IsArrayImpl() { throw null; }
//TYPEINFO public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { throw null; }
protected override bool IsByRefImpl() { throw null; }
protected override bool IsCOMObjectImpl() { throw null; }
public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
protected override bool IsPointerImpl() { throw null; }
protected override bool IsPrimitiveImpl() { throw null; }
public override bool IsTypeDefinition { get { throw null; } }
public override bool IsSZArray { get { throw null; } }
public override bool IsVariableBoundArray { get { throw null; } }
protected override bool IsValueTypeImpl() { throw null; }
public override System.Type MakeArrayType() { throw null; }
public override System.Type MakeArrayType(int rank) { throw null; }
public override System.Type MakeByRefType() { throw null; }
public override System.Type MakePointerType() { throw null; }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
}
public sealed partial class EventBuilder
{
internal EventBuilder() { }
public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
public void SetAddOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
public void SetRaiseMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
public void SetRemoveOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
}
public sealed partial class FieldBuilder : System.Reflection.FieldInfo
{
internal FieldBuilder() { }
public override System.Reflection.FieldAttributes Attributes { get { throw null; } }
public override System.Type DeclaringType { get { throw null; } }
public override System.RuntimeFieldHandle FieldHandle { get { throw null; } }
public override System.Type FieldType { get { throw null; } }
public override string Name { get { throw null; } }
public override System.Type ReflectedType { get { throw null; } }
public override object[] GetCustomAttributes(bool inherit) { throw null; }
public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
public override object GetValue(object obj) { throw null; }
public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
public void SetConstant(object defaultValue) { }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
public void SetOffset(int iOffset) { }
public override void SetValue(object obj, object val, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Globalization.CultureInfo culture) { }
}
public sealed partial class GenericTypeParameterBuilder : System.Type //TYPEINFO: System.Reflection.TypeInfo
{
internal GenericTypeParameterBuilder() { }
public override System.Reflection.Assembly Assembly { get { throw null; } }
public override string AssemblyQualifiedName { get { throw null; } }
public override System.Type BaseType { get { throw null; } }
public override bool ContainsGenericParameters { get { throw null; } }
public override System.Reflection.MethodBase DeclaringMethod { get { throw null; } }
public override System.Type DeclaringType { get { throw null; } }
public override string FullName { get { throw null; } }
public override System.Reflection.GenericParameterAttributes GenericParameterAttributes { get { throw null; } }
public override int GenericParameterPosition { get { throw null; } }
public override System.Guid GUID { get { throw null; } }
public override bool IsConstructedGenericType { get { throw null; } }
public override bool IsGenericParameter { get { throw null; } }
public override bool IsGenericType { get { throw null; } }
public override bool IsGenericTypeDefinition { get { throw null; } }
public override System.Reflection.Module Module { get { throw null; } }
public override string Name { get { throw null; } }
public override string Namespace { get { throw null; } }
public override System.Type ReflectedType { get { throw null; } }
public override System.RuntimeTypeHandle TypeHandle { get { throw null; } }
public override System.Type UnderlyingSystemType { get { throw null; } }
public override bool Equals(object o) { throw null; }
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; }
protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override object[] GetCustomAttributes(bool inherit) { throw null; }
public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
public override System.Type GetElementType() { throw null; }
public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.EventInfo[] GetEvents() { throw null; }
public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type[] GetGenericArguments() { throw null; }
public override System.Type GetGenericTypeDefinition() { throw null; }
public override int GetHashCode() { throw null; }
public override System.Type GetInterface(string name, bool ignoreCase) { throw null; }
public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; }
public override System.Type[] GetInterfaces() { throw null; }
public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; }
protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; }
protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type returnType, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
protected override bool HasElementTypeImpl() { throw null; }
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { throw null; }
protected override bool IsArrayImpl() { throw null; }
//TYPEINFO: public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { throw null; }
public override bool IsAssignableFrom(System.Type c) { throw null; }
protected override bool IsByRefImpl() { throw null; }
protected override bool IsCOMObjectImpl() { throw null; }
public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
protected override bool IsPointerImpl() { throw null; }
protected override bool IsPrimitiveImpl() { throw null; }
public override bool IsSubclassOf(System.Type c) { throw null; }
public override bool IsTypeDefinition { get { throw null; } }
public override bool IsSZArray { get { throw null; } }
public override bool IsVariableBoundArray { get { throw null; } }
protected override bool IsValueTypeImpl() { throw null; }
public override System.Type MakeArrayType() { throw null; }
public override System.Type MakeArrayType(int rank) { throw null; }
public override System.Type MakeByRefType() { throw null; }
public override System.Type MakeGenericType(params System.Type[] typeArguments) { throw null; }
public override System.Type MakePointerType() { throw null; }
public void SetBaseTypeConstraint(System.Type baseTypeConstraint) { }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
public void SetGenericParameterAttributes(System.Reflection.GenericParameterAttributes genericParameterAttributes) { }
public void SetInterfaceConstraints(params System.Type[] interfaceConstraints) { }
public override string ToString() { throw null; }
}
public sealed partial class MethodBuilder : System.Reflection.MethodInfo
{
internal MethodBuilder() { }
public override System.Reflection.MethodAttributes Attributes { get { throw null; } }
public override System.Reflection.CallingConventions CallingConvention { get { throw null; } }
public override bool ContainsGenericParameters { get { throw null; } }
public override System.Type DeclaringType { get { throw null; } }
public bool InitLocals { get { throw null; } set { } }
public override bool IsGenericMethod { get { throw null; } }
public override bool IsGenericMethodDefinition { get { throw null; } }
public override bool IsConstructedGenericMethod { get { throw null; } }
public override System.RuntimeMethodHandle MethodHandle { get { throw null; } }
public override System.Reflection.Module Module { get { throw null; } }
public override string Name { get { throw null; } }
public override System.Type ReflectedType { get { throw null; } }
public override System.Reflection.ParameterInfo ReturnParameter { get { throw null; } }
public override System.Type ReturnType { get { throw null; } }
public override System.Reflection.ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw null; } }
public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { throw null; }
public System.Reflection.Emit.ParameterBuilder DefineParameter(int position, System.Reflection.ParameterAttributes attributes, string strParamName) { throw null; }
public override bool Equals(object obj) { throw null; }
public override System.Reflection.MethodInfo GetBaseDefinition() { throw null; }
public override object[] GetCustomAttributes(bool inherit) { throw null; }
public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
public override System.Type[] GetGenericArguments() { throw null; }
public override System.Reflection.MethodInfo GetGenericMethodDefinition() { throw null; }
public override int GetHashCode() { throw null; }
public System.Reflection.Emit.ILGenerator GetILGenerator() { throw null; }
public System.Reflection.Emit.ILGenerator GetILGenerator(int size) { throw null; }
public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw null; }
public override System.Reflection.ParameterInfo[] GetParameters() { throw null; }
public override object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw null; }
public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
public override System.Reflection.MethodInfo MakeGenericMethod(params System.Type[] typeArguments) { throw null; }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { }
public void SetParameters(params System.Type[] parameterTypes) { }
public void SetReturnType(System.Type returnType) { }
public void SetSignature(System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { }
public override string ToString() { throw null; }
}
public partial class ModuleBuilder : System.Reflection.Module
{
internal ModuleBuilder() { }
public override System.Reflection.Assembly Assembly { get { throw null; } }
public override string FullyQualifiedName { get { throw null; } }
public override string Name { get { throw null; } }
public void CreateGlobalFunctions() { }
public System.Reflection.Emit.EnumBuilder DefineEnum(string name, System.Reflection.TypeAttributes visibility, System.Type underlyingType) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] requiredReturnTypeCustomModifiers, System.Type[] optionalReturnTypeCustomModifiers, System.Type[] parameterTypes, System.Type[][] requiredParameterTypeCustomModifiers, System.Type[][] optionalParameterTypeCustomModifiers) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { throw null; }
public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineType(string name) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, int typesize) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packsize) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packingSize, int typesize) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Type[] interfaces) { throw null; }
public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { throw null; }
public override bool Equals(object obj) { throw null; }
public System.Reflection.MethodInfo GetArrayMethod(System.Type arrayClass, string methodName, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
public override int GetHashCode() { throw null; }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
}
public sealed partial class PropertyBuilder : System.Reflection.PropertyInfo
{
internal PropertyBuilder() { }
public override System.Reflection.PropertyAttributes Attributes { get { throw null; } }
public override bool CanRead { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public override System.Type DeclaringType { get { throw null; } }
public override System.Reflection.Module Module { get { throw null; } }
public override string Name { get { throw null; } }
public override System.Type PropertyType { get { throw null; } }
public override System.Type ReflectedType { get { throw null; } }
public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
public override System.Reflection.MethodInfo[] GetAccessors(bool nonPublic) { throw null; }
public override object[] GetCustomAttributes(bool inherit) { throw null; }
public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
public override System.Reflection.MethodInfo GetGetMethod(bool nonPublic) { throw null; }
public override System.Reflection.ParameterInfo[] GetIndexParameters() { throw null; }
public override System.Reflection.MethodInfo GetSetMethod(bool nonPublic) { throw null; }
public override object GetValue(object obj, object[] index) { throw null; }
public override object GetValue(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture) { throw null; }
public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
public void SetConstant(object defaultValue) { }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
public void SetGetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
public void SetSetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
public override void SetValue(object obj, object value, object[] index) { }
public override void SetValue(object obj, object value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture) { }
}
public sealed partial class TypeBuilder : System.Type //TYPEINFO: System.Reflection.TypeInfo
{
internal TypeBuilder() { }
public const int UnspecifiedTypeSize = 0;
public override System.Reflection.Assembly Assembly { get { throw null; } }
public override string AssemblyQualifiedName { get { throw null; } }
public override System.Type BaseType { get { throw null; } }
public override System.Reflection.MethodBase DeclaringMethod { get { throw null; } }
public override System.Type DeclaringType { get { throw null; } }
public override string FullName { get { throw null; } }
public override System.Reflection.GenericParameterAttributes GenericParameterAttributes { get { throw null; } }
public override int GenericParameterPosition { get { throw null; } }
public override System.Guid GUID { get { throw null; } }
public override bool IsConstructedGenericType { get { throw null; } }
public override bool IsGenericParameter { get { throw null; } }
public override bool IsGenericType { get { throw null; } }
public override bool IsGenericTypeDefinition { get { throw null; } }
public override bool IsSecurityCritical { get { throw null; } }
public override bool IsSecuritySafeCritical { get { throw null; } }
public override bool IsSecurityTransparent { get { throw null; } }
public override System.Reflection.Module Module { get { throw null; } }
public override string Name { get { throw null; } }
public override string Namespace { get { throw null; } }
public System.Reflection.Emit.PackingSize PackingSize { get { throw null; } }
public override System.Type ReflectedType { get { throw null; } }
public int Size { get { throw null; } }
public override System.RuntimeTypeHandle TypeHandle { get { throw null; } }
public override System.Type UnderlyingSystemType { get { throw null; } }
public void AddInterfaceImplementation(System.Type interfaceType) { }
public System.Type CreateType() { throw null; }
public System.Reflection.TypeInfo CreateTypeInfo() { throw null; }
public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes) { throw null; }
public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes, System.Type[][] requiredCustomModifiers, System.Type[][] optionalCustomModifiers) { throw null; }
public System.Reflection.Emit.ConstructorBuilder DefineDefaultConstructor(System.Reflection.MethodAttributes attributes) { throw null; }
public System.Reflection.Emit.EventBuilder DefineEvent(string name, System.Reflection.EventAttributes attributes, System.Type eventtype) { throw null; }
public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Reflection.FieldAttributes attributes) { throw null; }
public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Type[] requiredCustomModifiers, System.Type[] optionalCustomModifiers, System.Reflection.FieldAttributes attributes) { throw null; }
public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { throw null; }
public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { throw null; }
public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { throw null; }
public void DefineMethodOverride(System.Reflection.MethodInfo methodInfoBody, System.Reflection.MethodInfo methodInfoDeclaration) { }
public System.Reflection.Emit.TypeBuilder DefineNestedType(string name) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, int typeSize) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packSize) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packSize, int typeSize) { throw null; }
public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Type[] interfaces) { throw null; }
public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { throw null; }
public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { throw null; }
public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { throw null; }
public System.Reflection.Emit.ConstructorBuilder DefineTypeInitializer() { throw null; }
public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { throw null; }
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; }
public static System.Reflection.ConstructorInfo GetConstructor(System.Type type, System.Reflection.ConstructorInfo constructor) { throw null; }
protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override object[] GetCustomAttributes(bool inherit) { throw null; }
public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
public override System.Type GetElementType() { throw null; }
public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.EventInfo[] GetEvents() { throw null; }
public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public static System.Reflection.FieldInfo GetField(System.Type type, System.Reflection.FieldInfo field) { throw null; }
public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type[] GetGenericArguments() { throw null; }
public override System.Type GetGenericTypeDefinition() { throw null; }
public override System.Type GetInterface(string name, bool ignoreCase) { throw null; }
public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; }
public override System.Type[] GetInterfaces() { throw null; }
public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; }
public static System.Reflection.MethodInfo GetMethod(System.Type type, System.Reflection.MethodInfo method) { throw null; }
protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; }
public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; }
protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type returnType, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
protected override bool HasElementTypeImpl() { throw null; }
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { throw null; }
protected override bool IsArrayImpl() { throw null; }
//TYPEINFO: public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { throw null; }
public override bool IsAssignableFrom(System.Type c) { throw null; }
protected override bool IsByRefImpl() { throw null; }
protected override bool IsCOMObjectImpl() { throw null; }
public bool IsCreated() { throw null; }
public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
protected override bool IsPointerImpl() { throw null; }
protected override bool IsPrimitiveImpl() { throw null; }
public override bool IsSubclassOf(System.Type c) { throw null; }
public override bool IsTypeDefinition { get { throw null; } }
public override bool IsSZArray { get { throw null; } }
public override bool IsVariableBoundArray { get { throw null; } }
public override System.Type MakeArrayType() { throw null; }
public override System.Type MakeArrayType(int rank) { throw null; }
public override System.Type MakeByRefType() { throw null; }
public override System.Type MakeGenericType(params System.Type[] typeArguments) { throw null; }
public override System.Type MakePointerType() { throw null; }
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
public void SetParent(System.Type parent) { }
public override string ToString() { throw null; }
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// A simple symbol.
/// </summary>
public class SimpleSymbol : OutlinedSymbol, ISimpleSymbol
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class.
/// </summary>
public SimpleSymbol()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class with the specified color.
/// </summary>
/// <param name="color">The color of the symbol.</param>
public SimpleSymbol(Color color)
: this()
{
Color = color;
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class with the specified color and shape.
/// </summary>
/// <param name="color">The color of the symbol.</param>
/// <param name="shape">The shape of the symbol.</param>
public SimpleSymbol(Color color, PointShape shape)
: this(color)
{
PointShape = shape;
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleSymbol"/> class with the specified color, shape and size. The size is used for
/// both the horizontal and vertical directions.
/// </summary>
/// <param name="color">The color of the symbol.</param>
/// <param name="shape">The shape of the symbol.</param>
/// <param name="size">The size of the symbol.</param>
public SimpleSymbol(Color color, PointShape shape, double size)
: this(color, shape)
{
Size = new Size2D(size, size);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the Color.
/// </summary>
[XmlIgnore]
public Color Color { get; set; }
/// <summary>
/// Gets or sets the opacity as a floating point value ranging from 0 to 1, where
/// 0 is fully transparent and 1 is fully opaque. This actually adjusts the alpha of the color value.
/// </summary>
[Serialize("Opacity")]
[ShallowCopy]
public float Opacity
{
get
{
return Color.A / 255F;
}
set
{
int alpha = (int)(value * 255);
if (alpha > 255) alpha = 255;
if (alpha < 0) alpha = 0;
if (alpha != Color.A)
{
Color = Color.FromArgb(alpha, Color);
}
}
}
/// <summary>
/// Gets or sets the PointTypes enumeration that describes how to draw the simple symbol.
/// </summary>
[Serialize("PointShapes")]
public PointShape PointShape { get; set; }
/// <summary>
/// Gets or sets the xml color. This is only provided because XML Serialization doesn't work for colors.
/// </summary>
[XmlElement("Color")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Serialize("XmlColor")]
[ShallowCopy]
public string XmlColor
{
get
{
return ColorTranslator.ToHtml(Color);
}
set
{
Color = ColorTranslator.FromHtml(value);
}
}
#endregion
#region Methods
/// <summary>
/// Draws an ellipse on the specified graphics surface.
/// </summary>
/// <param name="gp">The GraphicsPath to add this shape to</param>
/// <param name="scaledSize">The size to fit the ellipse into (the ellipse will be centered at 0, 0)</param>
public static void AddEllipse(GraphicsPath gp, SizeF scaledSize)
{
PointF upperLeft = new PointF(-scaledSize.Width / 2, -scaledSize.Height / 2);
RectangleF destRect = new RectangleF(upperLeft, scaledSize);
gp.AddEllipse(destRect);
}
/// <summary>
/// Draws a regular polygon with equal sides. The first point will be located all the way to the right on the X axis.
/// </summary>
/// <param name="gp">Specifies the GraphicsPath surface to draw on</param>
/// <param name="scaledSize">Specifies the SizeF to fit the polygon into</param>
/// <param name="numSides">Specifies the integer number of sides that the polygon should have</param>
public static void AddRegularPoly(GraphicsPath gp, SizeF scaledSize, int numSides)
{
PointF[] polyPoints = new PointF[numSides + 1];
// Instead of figuring out the points in cartesian, figure them out in angles and re-convert them.
for (int i = 0; i <= numSides; i++)
{
double ang = i * (2 * Math.PI) / numSides;
float x = Convert.ToSingle(Math.Cos(ang)) * scaledSize.Width / 2f;
float y = Convert.ToSingle(Math.Sin(ang)) * scaledSize.Height / 2f;
polyPoints[i] = new PointF(x, y);
}
gp.AddPolygon(polyPoints);
}
/// <summary>
/// Draws a 5 pointed star with the points having twice the radius as the bends.
/// </summary>
/// <param name="gp">The GraphicsPath to add the start to</param>
/// <param name="scaledSize">The SizeF size to fit the Start to</param>
public static void AddStar(GraphicsPath gp, SizeF scaledSize)
{
PointF[] polyPoints = new PointF[11];
GetStars(scaledSize, polyPoints);
gp.AddPolygon(polyPoints);
}
/// <summary>
/// Draws an ellipse on the specified graphics surface.
/// </summary>
/// <param name="g">The graphics surface to draw on</param>
/// <param name="scaledBorderPen">The Pen to use for the border, or null if no border should be drawn</param>
/// <param name="fillBrush">The Brush to use for the fill, or null if no fill should be drawn</param>
/// <param name="scaledSize">The size to fit the ellipse into (the ellipse will be centered at 0, 0)</param>
public static void DrawEllipse(Graphics g, Pen scaledBorderPen, Brush fillBrush, SizeF scaledSize)
{
PointF upperLeft = new PointF(-scaledSize.Width / 2, -scaledSize.Height / 2);
RectangleF destRect = new RectangleF(upperLeft, scaledSize);
if (fillBrush != null)
{
g.FillEllipse(fillBrush, destRect);
}
if (scaledBorderPen != null)
{
g.DrawEllipse(scaledBorderPen, destRect);
}
}
/// <summary>
/// Draws a regular polygon with equal sides. The first point will be located all the way to the right on the X axis.
/// </summary>
/// <param name="g">Specifies the Graphics surface to draw on</param>
/// <param name="scaledBorderPen">Specifies the Pen to use for the border</param>
/// <param name="fillBrush">Specifies the Brush to use for to fill the shape</param>
/// <param name="scaledSize">Specifies the SizeF to fit the polygon into</param>
/// <param name="numSides">Specifies the integer number of sides that the polygon should have</param>
public static void DrawRegularPoly(Graphics g, Pen scaledBorderPen, Brush fillBrush, SizeF scaledSize, int numSides)
{
PointF[] polyPoints = new PointF[numSides + 1];
// Instead of figuring out the points in cartesian, figure them out in angles and re-convert them.
for (int i = 0; i <= numSides; i++)
{
double ang = i * (2 * Math.PI) / numSides;
float x = Convert.ToSingle(Math.Cos(ang)) * scaledSize.Width / 2f;
float y = Convert.ToSingle(Math.Sin(ang)) * scaledSize.Height / 2f;
polyPoints[i] = new PointF(x, y);
}
if (fillBrush != null)
{
g.FillPolygon(fillBrush, polyPoints, FillMode.Alternate);
}
if (scaledBorderPen != null)
{
g.DrawPolygon(scaledBorderPen, polyPoints);
}
}
/// <summary>
/// Draws a 5 pointed star with the points having twice the radius as the bends.
/// </summary>
/// <param name="g">The Graphics surface to draw on</param>
/// <param name="scaledBorderPen">The Pen to draw the border with</param>
/// <param name="fillBrush">The Brush to use to fill the Star</param>
/// <param name="scaledSize">The SizeF size to fit the Start to</param>
public static void DrawStar(Graphics g, Pen scaledBorderPen, Brush fillBrush, SizeF scaledSize)
{
PointF[] polyPoints = new PointF[11];
GetStars(scaledSize, polyPoints);
if (fillBrush != null)
{
g.FillPolygon(fillBrush, polyPoints, FillMode.Alternate);
}
if (scaledBorderPen != null)
{
g.DrawPolygon(scaledBorderPen, polyPoints);
}
}
/// <summary>
/// Gets the font color of this symbol to represent the color of this symbol
/// </summary>
/// <returns>The color of this symbol as a font</returns>
public override Color GetColor()
{
return Color;
}
/// <summary>
/// Sets the fill color of this symbol to the specified color.
/// </summary>
/// <param name="color">The Color.</param>
public override void SetColor(Color color)
{
Color = color;
}
/// <summary>
/// Handles the specific drawing for this symbol.
/// </summary>
/// <param name="g">The System.Drawing.Graphics surface to draw with.</param>
/// <param name="scaleSize">A double controling the scaling of the symbol.</param>
protected override void OnDraw(Graphics g, double scaleSize)
{
if (scaleSize == 0) return;
if (Size.Width == 0 || Size.Height == 0) return;
SizeF size = new SizeF((float)(scaleSize * Size.Width), (float)(scaleSize * Size.Height));
Brush fillBrush = new SolidBrush(Color);
GraphicsPath gp = new GraphicsPath();
switch (PointShape)
{
case PointShape.Diamond:
AddRegularPoly(gp, size, 4);
break;
case PointShape.Ellipse:
AddEllipse(gp, size);
break;
case PointShape.Hexagon:
AddRegularPoly(gp, size, 6);
break;
case PointShape.Pentagon:
AddRegularPoly(gp, size, 5);
break;
case PointShape.Rectangle:
gp.AddRectangle(new RectangleF(-size.Width / 2, -size.Height / 2, size.Width, size.Height));
break;
case PointShape.Star:
AddStar(gp, size);
break;
case PointShape.Triangle:
AddRegularPoly(gp, size, 3);
break;
}
g.FillPath(fillBrush, gp);
OnDrawOutline(g, scaleSize, gp);
gp.Dispose();
}
/// <summary>
/// Occurs during the randomizing process.
/// </summary>
/// <param name="generator">The random genrator to use.</param>
protected override void OnRandomize(Random generator)
{
Color = generator.NextColor();
Opacity = generator.NextFloat();
PointShape = generator.NextEnum<PointShape>();
base.OnRandomize(generator);
}
private static void GetStars(SizeF scaledSize, PointF[] polyPoints)
{
for (int i = 0; i <= 10; i++)
{
double ang = i * Math.PI / 5;
float x = Convert.ToSingle(Math.Cos(ang)) * scaledSize.Width / 2f;
float y = Convert.ToSingle(Math.Sin(ang)) * scaledSize.Height / 2f;
if (i % 2 == 0)
{
x /= 2; // the shorter radius points of the star
y /= 2;
}
polyPoints[i] = new PointF(x, y);
}
}
private void Configure()
{
SymbolType = SymbolType.Simple;
Color = SymbologyGlobal.RandomColor();
PointShape = PointShape.Rectangle;
}
#endregion
}
}
| |
// 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.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class NotEqualInstruction : Instruction
{
// Perf: EqualityComparer<T> but is 3/2 to 2 times slower.
private static Instruction s_reference, s_Boolean, s_SByte, s_Int16, s_Char, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double;
private static Instruction s_BooleanLiftedToNull, s_SByteLiftedToNull, s_Int16LiftedToNull, s_CharLiftedToNull, s_Int32LiftedToNull, s_Int64LiftedToNull, s_ByteLiftedToNull, s_UInt16LiftedToNull, s_UInt32LiftedToNull, s_UInt64LiftedToNull, s_SingleLiftedToNull, s_DoubleLiftedToNull;
public override int ConsumedStack => 2;
public override int ProducedStack => 1;
public override string InstructionName => "NotEqual";
private NotEqualInstruction() { }
private sealed class NotEqualBoolean : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((bool)left != (bool)right);
}
return 1;
}
}
private sealed class NotEqualSByte : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((sbyte)left != (sbyte)right);
}
return 1;
}
}
private sealed class NotEqualInt16 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((short)left != (short)right);
}
return 1;
}
}
private sealed class NotEqualChar : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((char)left != (char)right);
}
return 1;
}
}
private sealed class NotEqualInt32 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((int)left != (int)right);
}
return 1;
}
}
private sealed class NotEqualInt64 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((long)left != (long)right);
}
return 1;
}
}
private sealed class NotEqualByte : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((byte)left != (byte)right);
}
return 1;
}
}
private sealed class NotEqualUInt16 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((ushort)left != (ushort)right);
}
return 1;
}
}
private sealed class NotEqualUInt32 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((uint)left != (uint)right);
}
return 1;
}
}
private sealed class NotEqualUInt64 : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((ulong)left != (ulong)right);
}
return 1;
}
}
private sealed class NotEqualSingle : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((float)left != (float)right);
}
return 1;
}
}
private sealed class NotEqualDouble : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null)
{
frame.Push(right != null);
}
else if (right == null)
{
frame.Push(true);
}
else
{
frame.Push((double)left != (double)right);
}
return 1;
}
}
private sealed class NotEqualReference : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
frame.Push(frame.Pop() != frame.Pop());
return 1;
}
}
private sealed class NotEqualBooleanLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((bool)left != (bool)right);
}
return 1;
}
}
private sealed class NotEqualSByteLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((sbyte)left != (sbyte)right);
}
return 1;
}
}
private sealed class NotEqualInt16LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((short)left != (short)right);
}
return 1;
}
}
private sealed class NotEqualCharLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((char)left != (char)right);
}
return 1;
}
}
private sealed class NotEqualInt32LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((int)left != (int)right);
}
return 1;
}
}
private sealed class NotEqualInt64LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((long)left != (long)right);
}
return 1;
}
}
private sealed class NotEqualByteLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((byte)left != (byte)right);
}
return 1;
}
}
private sealed class NotEqualUInt16LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((ushort)left != (ushort)right);
}
return 1;
}
}
private sealed class NotEqualUInt32LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((uint)left != (uint)right);
}
return 1;
}
}
private sealed class NotEqualUInt64LiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((ulong)left != (ulong)right);
}
return 1;
}
}
private sealed class NotEqualSingleLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((float)left != (float)right);
}
return 1;
}
}
private sealed class NotEqualDoubleLiftedToNull : NotEqualInstruction
{
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(null);
}
else
{
frame.Push((double)left != (double)right);
}
return 1;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public static Instruction Create(Type type, bool liftedToNull)
{
if (liftedToNull)
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.Boolean: return s_BooleanLiftedToNull ?? (s_BooleanLiftedToNull = new NotEqualBooleanLiftedToNull());
case TypeCode.SByte: return s_SByteLiftedToNull ?? (s_SByteLiftedToNull = new NotEqualSByteLiftedToNull());
case TypeCode.Int16: return s_Int16LiftedToNull ?? (s_Int16LiftedToNull = new NotEqualInt16LiftedToNull());
case TypeCode.Char: return s_CharLiftedToNull ?? (s_CharLiftedToNull = new NotEqualCharLiftedToNull());
case TypeCode.Int32: return s_Int32LiftedToNull ?? (s_Int32LiftedToNull = new NotEqualInt32LiftedToNull());
case TypeCode.Int64: return s_Int64LiftedToNull ?? (s_Int64LiftedToNull = new NotEqualInt64LiftedToNull());
case TypeCode.Byte: return s_ByteLiftedToNull ?? (s_ByteLiftedToNull = new NotEqualByteLiftedToNull());
case TypeCode.UInt16: return s_UInt16LiftedToNull ?? (s_UInt16LiftedToNull = new NotEqualUInt16LiftedToNull());
case TypeCode.UInt32: return s_UInt32LiftedToNull ?? (s_UInt32LiftedToNull = new NotEqualUInt32LiftedToNull());
case TypeCode.UInt64: return s_UInt64LiftedToNull ?? (s_UInt64LiftedToNull = new NotEqualUInt64LiftedToNull());
case TypeCode.Single: return s_SingleLiftedToNull ?? (s_SingleLiftedToNull = new NotEqualSingleLiftedToNull());
default:
Debug.Assert(type.GetNonNullableType().GetTypeCode() == TypeCode.Double);
return s_DoubleLiftedToNull ?? (s_DoubleLiftedToNull = new NotEqualDoubleLiftedToNull());
}
}
else
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.Boolean: return s_Boolean ?? (s_Boolean = new NotEqualBoolean());
case TypeCode.SByte: return s_SByte ?? (s_SByte = new NotEqualSByte());
case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new NotEqualInt16());
case TypeCode.Char: return s_Char ?? (s_Char = new NotEqualChar());
case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new NotEqualInt32());
case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new NotEqualInt64());
case TypeCode.Byte: return s_Byte ?? (s_Byte = new NotEqualByte());
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new NotEqualUInt16());
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new NotEqualUInt32());
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new NotEqualUInt64());
case TypeCode.Single: return s_Single ?? (s_Single = new NotEqualSingle());
case TypeCode.Double: return s_Double ?? (s_Double = new NotEqualDouble());
default:
// Nullable only valid if one operand is constant null, so this assert is slightly too broad.
Debug.Assert(type.IsNullableOrReferenceType());
return s_reference ?? (s_reference = new NotEqualReference());
}
}
}
}
}
| |
//
// Header.cs:
//
// Author:
// Brian Nickel (brian.nickel@gmail.com)
//
// Original Source:
// id3v2header.cpp from TagLib
//
// Copyright (C) 2005-2007 Brian Nickel
// Copyright (C) 2002,2003 Scott Wheeler (Original Implementation)
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
namespace TagLib.Id3v2 {
/// <summary>
/// Indicates the flags applied to a <see cref="Header" /> object.
/// </summary>
[Flags]
public enum HeaderFlags : byte {
/// <summary>
/// The header contains no flags.
/// </summary>
None = 0,
/// <summary>
/// The tag described by the header has been unsynchronized.
/// </summary>
Unsynchronisation = 0x80,
/// <summary>
/// The tag described by the header has contains an extended
/// header.
/// </summary>
ExtendedHeader = 0x40,
/// <summary>
/// The tag described by the header is experimental.
/// </summary>
ExperimentalIndicator = 0x20,
/// <summary>
/// The tag described by the header contains a footer.
/// </summary>
FooterPresent = 0x10
}
/// <summary>
/// This structure provides a representation of an ID3v2 tag header
/// which can be read from and written to disk.
/// </summary>
public struct Header
{
#region Private Fields
/// <summary>
/// Contains the tag's major version.
/// </summary>
private byte major_version;
/// <summary>
/// Contains the tag's version revision.
/// </summary>
private byte revision_number;
/// <summary>
/// Contains tag's flags.
/// </summary>
private HeaderFlags flags;
/// <summary>
/// Contains the tag size.
/// </summary>
private uint tag_size;
#endregion
#region Public Fields
/// <summary>
/// The size of a ID3v2 header.
/// </summary>
public const uint Size = 10;
/// <summary>
/// The identifier used to recognize a ID3v2 headers.
/// </summary>
/// <value>
/// "ID3"
/// </value>
public static readonly ReadOnlyByteVector FileIdentifier = "ID3";
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="Header" /> by reading it from raw header data.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the raw
/// data to build the new instance from.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="data" /> is <see langword="null" />.
/// </exception>
/// <exception cref="CorruptFileException">
/// <paramref name="data" /> is smaller than <see
/// cref="Size" />, does not begin with <see
/// cref="FileIdentifier" />, contains invalid flag data,
/// or contains invalid size data.
/// </exception>
public Header (ByteVector data)
{
if (data == null)
throw new ArgumentNullException ("data");
if (data.Count < Size)
throw new CorruptFileException (
"Provided data is smaller than object size.");
if (!data.StartsWith (FileIdentifier))
throw new CorruptFileException (
"Provided data does not start with the file identifier");
major_version = data [3];
revision_number = data [4];
flags = (HeaderFlags) data [5];
if (major_version == 2 && ((int) flags & 127) != 0)
throw new CorruptFileException (
"Invalid flags set on version 2 tag.");
if (major_version == 3 && ((int) flags & 15) != 0)
throw new CorruptFileException (
"Invalid flags set on version 3 tag.");
if (major_version == 4 && ((int) flags & 7) != 0)
throw new CorruptFileException (
"Invalid flags set on version 4 tag.");
for (int i = 6; i < 10; i ++)
if (data [i] >= 128)
throw new CorruptFileException (
"One of the bytes in the header was greater than the allowed 128.");
tag_size = SynchData.ToUInt (data.Mid (6, 4));
}
#endregion
#region Public Properties
/// <summary>
/// Gets and sets the major version of the tag described by
/// the current instance.
/// </summary>
/// <value>
/// A <see cref="byte" /> value specifying the ID3v2 version
/// of tag described by the current instance.
/// </value>
/// <remarks>
/// When the version is set, unsupported header flags will
/// automatically be removed from the tag.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value" /> is less than 2 or more than 4.
/// </exception>
public byte MajorVersion {
get {
return major_version == 0 ? Tag.DefaultVersion :
major_version;
}
set {
if (value < 2 || value > 4)
throw new ArgumentException (
"Version unsupported");
if (value < 3)
flags &= ~(HeaderFlags.ExtendedHeader |
HeaderFlags.ExperimentalIndicator);
if (value < 4)
flags &= ~HeaderFlags.FooterPresent;
major_version = value;
}
}
/// <summary>
/// Gets and sets the version revision number of the tag
/// represented by the current instance.
/// </summary>
/// <value>
/// A <see cref="byte" /> value containing the version
/// revision number of the tag represented by the current
/// instance.
/// </value>
/// <remarks>
/// This value should always be zeroed. A non-zero value
/// indicates an experimental or new version of the format
/// which may not be completely understood by the current
/// implementation. Some software may refuse to read tags
/// with a non-zero value.
/// </remarks>
public byte RevisionNumber {
get {return revision_number;}
set {revision_number = value;}
}
/// <summary>
/// Gets and sets the flags applied to the current instance.
/// </summary>
/// <value>
/// A bitwise combined <see cref="HeaderFlags" /> value
/// containing the flags applied to the current instance.
/// </value>
/// <exception cref="ArgumentException">
/// <paramref name="value" /> contains a flag not supported
/// by the the ID3v2 version of the current instance.
/// </exception>
public HeaderFlags Flags {
get {return flags;}
set {
if (0 != (value & (HeaderFlags.ExtendedHeader |
HeaderFlags.ExperimentalIndicator)) &&
MajorVersion < 3)
throw new ArgumentException (
"Feature only supported in version 2.3+",
"value");
if (0 != (value & HeaderFlags.FooterPresent) &&
MajorVersion < 3)
throw new ArgumentException (
"Feature only supported in version 2.4+",
"value");
flags = value;
}
}
/// <summary>
/// Gets and sets the size of the tag described by the
/// current instance, minus the header and footer.
/// </summary>
/// <value>
/// A <see cref="uint" /> value containing the size of the
/// tag described by the current instance.
/// </value>
public uint TagSize {
get {return tag_size;}
set {tag_size = value;}
}
/// <summary>
/// Gets the complete size of the tag described by the
/// current instance, including the header and footer.
/// </summary>
/// <value>
/// A <see cref="uint" /> value containing the complete size
/// of the tag described by the current instance.
/// </value>
public uint CompleteTagSize {
get {
if ((flags & HeaderFlags.FooterPresent) != 0)
return TagSize + Size + Footer.Size;
else
return TagSize + Size;
}
}
#endregion
#region Public Methods
/// <summary>
/// Renders the current instance as a raw ID3v2 header.
/// </summary>
/// <returns>
/// A <see cref="ByteVector" /> object containing the
/// rendered header.
/// </returns>
public ByteVector Render ()
{
ByteVector v = new ByteVector ();
v.Add (FileIdentifier);
v.Add (MajorVersion);
v.Add (RevisionNumber);
v.Add ((byte)flags);
v.Add (SynchData.FromUInt (TagSize));
return v;
}
#endregion
}
}
| |
/*********************************************************************************
= Author: Michael Parsons
=
= Date: Jun 08/2010
= Assembly: ILPathways.Business
= Description:
= Notes:
=
=
= Copyright 2010, Illinois workNet All rights reserved.
********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace ILPathways.Business
{
///<summary>
///Represents an object that describes a resourceStore
///</summary>
[Serializable]
public class ApplicationResource : BaseBusinessDataEntity, IDocument
{
///<summary>
///Initializes a new instance of the ILPathways.Business.ApplicationResource class.
///</summary>
public ApplicationResource() { }
#region Properties
private string _title = "";
/// <summary>
/// Gets/Sets Title
/// </summary>
public string Title
{
get
{
return this._title;
}
set
{
if ( this._title == value )
{
//Ignore set
} else
{
this._title = value.Trim();
HasChanged = true;
}
}
}
private string _url = "";
/// <summary>
/// Gets/Sets URL - for retrieving the resource
/// </summary>
public string URL
{
get
{
return this._url;
}
set
{
if ( this._url == value )
{
//Ignore set
} else
{
this._url = value.Trim();
HasChanged = true;
}
}
}
/// <summary>
/// Gets/Sets the ResourceUrl - Alias for URL
/// </summary>
public string ResourceUrl
{
get
{
return this._url;
}
set
{
if ( this._url == value )
{
//Ignore set
}
else
{
this._url = value.Trim();
HasChanged = true;
}
}
}
private string _mimeType = "";
/// <summary>
/// Gets/Sets MimeType
/// </summary>
public string MimeType
{
get
{
return this._mimeType;
}
set
{
if ( this._mimeType == value )
{
//Ignore set
} else
{
this._mimeType = value.Trim();
HasChanged = true;
}
}
}
private string _fileName = "";
/// <summary>
/// Gets/Sets the File Name
/// </summary>
public string FileName
{
get
{
return this._fileName;
}
set
{
if ( this._fileName == value )
{
//Ignore set
} else
{
this._fileName = value.Trim();
HasChanged = true;
}
}
}
public string FilePath { get; set; }
private DateTime _modifiedDate = System.DateTime.Now;
/// <summary>
/// Gets/Sets FileDate - the modified date of the file at the time of upload
/// </summary>
public DateTime FileDate
{
get
{
return this._modifiedDate;
}
set
{
if ( this._modifiedDate == value )
{
//Ignore set
} else
{
this._modifiedDate = value;
HasChanged = true;
}
}
}//
private long _resourceBytes = 0;
/// <summary>
/// Gets/Sets ResourceBytes - length of the resource
/// </summary>
public long ResourceBytes
{
get
{
return this._resourceBytes;
}
set
{
if ( this._resourceBytes == value )
{
//Ignore set
} else
{
this._resourceBytes = value;
HasChanged = true;
}
}
}
private byte[] _resourceData;
/// <summary>
/// Gets/Sets ResourceData
/// </summary>
public byte[] ResourceData
{
get
{
return this._resourceData;
}
}
#endregion
#region Helper Methods
/// <summary>
/// There may be occasions when a documentVersion is retrieved with the byte array (for speed efficiency)). This property can be used to determine if the actual resource needs to be fetched.
/// </summary>
/// <returns></returns>
public bool HasDocument()
{
if ( ResourceBytes > 0 )
return true;
else
return false;
}
/// <summary>
/// Assign the resource data from an object
/// </summary>
/// <param name="bytes"></param>
/// <param name="data"></param>
public void SetResourceData( long bytes, object data )
{
if ( bytes > 0 )
{
_resourceData = new byte[ bytes ];
_resourceData = ( byte[] ) data;
}
}//
/// <summary>
/// Assign the resource data from a byte array
/// </summary>
/// <param name="bytes"></param>
/// <param name="resourceData"></param>
public void SetResourceData( long bytes, byte[] resourceData )
{
if ( bytes > 0 )
{
_resourceData = new byte[ bytes ];
_resourceData = resourceData;
}
}
public void CleanFileName()
{
if ( FileName == null || FileName.Trim() == "" )
return;
FileName = FileName.Replace( " & ", " and " );
FileName = FileName.Replace( " ", "_" );
FileName = FileName.Replace( "'", "" );
FileName = FileName.Replace( "+", "plus" );
FileName = FileName.Replace( "/", "_" );
FileName = FileName.Replace( "\\", "_" );
FileName = FileName.Replace( "#", "_" );
FileName = FileName.Replace( "&", "_" );
}
/// <summary>
/// Return absolute path to the file
/// </summary>
/// <returns></returns>
public string FileLocation()
{
if ( FileName == null || FileName.Trim() == "" )
return "";
if ( FilePath == null || FilePath.Trim() == "" )
return "";
if ( FilePath.Trim().EndsWith( "\\" ) )
return FilePath + FileName;
else
return FilePath + "\\" + FileName;
}
#endregion
} // end class
} // end Namespace
| |
// 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.ComponentModel;
using System.IO;
using System.Text;
namespace System.Security.Cryptography
{
[EditorBrowsable(EditorBrowsableState.Never)]
public partial class PasswordDeriveBytes : DeriveBytes
{
private int _extraCount;
private int _prefix;
private int _iterations;
private byte[] _baseValue;
private byte[] _extra;
private byte[] _salt;
private readonly byte[] _password;
private string _hashName;
private HashAlgorithm _hash;
private readonly CspParameters _cspParams;
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt) : this(strPassword, rgbSalt, new CspParameters()) { }
public PasswordDeriveBytes(byte[] password, byte[] salt) : this(password, salt, new CspParameters()) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations) :
this(strPassword, rgbSalt, strHashName, iterations, new CspParameters()) { }
public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations) :
this(password, salt, hashName, iterations, new CspParameters()) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, CspParameters cspParams) :
this(strPassword, rgbSalt, "SHA1", 100, cspParams) { }
public PasswordDeriveBytes(byte[] password, byte[] salt, CspParameters cspParams) :
this(password, salt, "SHA1", 100, cspParams) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations, CspParameters cspParams) :
this((new UTF8Encoding(false)).GetBytes(strPassword), rgbSalt, strHashName, iterations, cspParams) { }
public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations, CspParameters cspParams)
{
IterationCount = iterations;
Salt = salt;
HashName = hashName;
_password = password;
_cspParams = cspParams;
}
public string HashName
{
get { return _hashName; }
set
{
if (_baseValue != null)
throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_ValuesFixed, nameof(HashName));
_hashName = value;
_hash = (HashAlgorithm)CryptoConfig.CreateFromName(_hashName);
}
}
public int IterationCount
{
get { return _iterations; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedPosNum);
if (_baseValue != null)
throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_ValuesFixed, nameof(IterationCount));
_iterations = value;
}
}
public byte[] Salt
{
get
{
return (byte[])_salt?.Clone();
}
set
{
if (_baseValue != null)
throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_ValuesFixed, nameof(Salt));
_salt = (byte[])value?.Clone();
}
}
[Obsolete("Rfc2898DeriveBytes replaces PasswordDeriveBytes for deriving key material from a password and is preferred in new applications.")]
#pragma warning disable 0809 // obsolete member overrides non-obsolete member
public override byte[] GetBytes(int cb)
{
int ib = 0;
byte[] rgb;
byte[] rgbOut = new byte[cb];
if (_baseValue == null)
{
ComputeBaseValue();
}
else if (_extra != null)
{
ib = _extra.Length - _extraCount;
if (ib >= cb)
{
Buffer.BlockCopy(_extra, _extraCount, rgbOut, 0, cb);
if (ib > cb)
{
_extraCount += cb;
}
else
{
_extra = null;
}
return rgbOut;
}
else
{
// Note: The second parameter should really be _extraCount instead.
// However, changing this would constitute a breaking change.
Buffer.BlockCopy(_extra, ib, rgbOut, 0, ib);
_extra = null;
}
}
rgb = ComputeBytes(cb - ib);
Buffer.BlockCopy(rgb, 0, rgbOut, ib, cb - ib);
if (rgb.Length + ib > cb)
{
_extra = rgb;
_extraCount = cb - ib;
}
return rgbOut;
}
#pragma warning restore 0809
public override void Reset()
{
_prefix = 0;
_extra = null;
_baseValue = null;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_hash?.Dispose();
if (_baseValue != null)
{
Array.Clear(_baseValue, 0, _baseValue.Length);
}
if (_extra != null)
{
Array.Clear(_extra, 0, _extra.Length);
}
if (_password != null)
{
Array.Clear(_password, 0, _password.Length);
}
if (_salt != null)
{
Array.Clear(_salt, 0, _salt.Length);
}
}
}
private byte[] ComputeBaseValue()
{
_hash.Initialize();
_hash.TransformBlock(_password, 0, _password.Length, _password, 0);
if (_salt != null)
{
_hash.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
}
_hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
_baseValue = _hash.Hash;
_hash.Initialize();
for (int i = 1; i < (_iterations - 1); i++)
{
_hash.ComputeHash(_baseValue);
_baseValue = _hash.Hash;
}
return _baseValue;
}
private byte[] ComputeBytes(int cb)
{
int cbHash;
int ib = 0;
byte[] rgb;
_hash.Initialize();
cbHash = _hash.HashSize / 8;
rgb = new byte[((cb + cbHash - 1) / cbHash) * cbHash];
using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write))
{
HashPrefix(cs);
cs.Write(_baseValue, 0, _baseValue.Length);
cs.Close();
}
Buffer.BlockCopy(_hash.Hash, 0, rgb, ib, cbHash);
ib += cbHash;
while (cb > ib)
{
_hash.Initialize();
using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write))
{
HashPrefix(cs);
cs.Write(_baseValue, 0, _baseValue.Length);
cs.Close();
}
Buffer.BlockCopy(_hash.Hash, 0, rgb, ib, cbHash);
ib += cbHash;
}
return rgb;
}
private void HashPrefix(CryptoStream cs)
{
if (_prefix > 999)
throw new CryptographicException(SR.Cryptography_PasswordDerivedBytes_TooManyBytes);
int cb = 0;
byte[] rgb = { (byte)'0', (byte)'0', (byte)'0' };
if (_prefix >= 100)
{
rgb[0] += (byte)(_prefix / 100);
cb += 1;
}
if (_prefix >= 10)
{
rgb[cb] += (byte)((_prefix % 100) / 10);
cb += 1;
}
if (_prefix > 0)
{
rgb[cb] += (byte)(_prefix % 10);
cb += 1;
cs.Write(rgb, 0, cb);
}
_prefix += 1;
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.Globalization;
using System.ComponentModel;
using System.Threading;
#if GDI
using System.Drawing;
#endif
#if WPF
using System.Windows.Media;
#endif
using PdfSharp.Internal;
namespace PdfSharp.Drawing
{
///<summary>
/// Represents a set of 141 pre-defined RGB colors. Incidentally the values are the same
/// as in System.Drawing.Color.
/// </summary>
public static class XColors
{
///<summary>Gets a predefined color.</summary>
public static XColor AliceBlue { get { return new XColor(XKnownColor.AliceBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor AntiqueWhite { get { return new XColor(XKnownColor.AntiqueWhite); } }
///<summary>Gets a predefined color.</summary>
public static XColor Aqua { get { return new XColor(XKnownColor.Aqua); } }
///<summary>Gets a predefined color.</summary>
public static XColor Aquamarine { get { return new XColor(XKnownColor.Aquamarine); } }
///<summary>Gets a predefined color.</summary>
public static XColor Azure { get { return new XColor(XKnownColor.Azure); } }
///<summary>Gets a predefined color.</summary>
public static XColor Beige { get { return new XColor(XKnownColor.Beige); } }
///<summary>Gets a predefined color.</summary>
public static XColor Bisque { get { return new XColor(XKnownColor.Bisque); } }
///<summary>Gets a predefined color.</summary>
public static XColor Black { get { return new XColor(XKnownColor.Black); } }
///<summary>Gets a predefined color.</summary>
public static XColor BlanchedAlmond { get { return new XColor(XKnownColor.BlanchedAlmond); } }
///<summary>Gets a predefined color.</summary>
public static XColor Blue { get { return new XColor(XKnownColor.Blue); } }
///<summary>Gets a predefined color.</summary>
public static XColor BlueViolet { get { return new XColor(XKnownColor.BlueViolet); } }
///<summary>Gets a predefined color.</summary>
public static XColor Brown { get { return new XColor(XKnownColor.Brown); } }
///<summary>Gets a predefined color.</summary>
public static XColor BurlyWood { get { return new XColor(XKnownColor.BurlyWood); } }
///<summary>Gets a predefined color.</summary>
public static XColor CadetBlue { get { return new XColor(XKnownColor.CadetBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor Chartreuse { get { return new XColor(XKnownColor.Chartreuse); } }
///<summary>Gets a predefined color.</summary>
public static XColor Chocolate { get { return new XColor(XKnownColor.Chocolate); } }
///<summary>Gets a predefined color.</summary>
public static XColor Coral { get { return new XColor(XKnownColor.Coral); } }
///<summary>Gets a predefined color.</summary>
public static XColor CornflowerBlue { get { return new XColor(XKnownColor.CornflowerBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor Cornsilk { get { return new XColor(XKnownColor.Cornsilk); } }
///<summary>Gets a predefined color.</summary>
public static XColor Crimson { get { return new XColor(XKnownColor.Crimson); } }
///<summary>Gets a predefined color.</summary>
public static XColor Cyan { get { return new XColor(XKnownColor.Cyan); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkBlue { get { return new XColor(XKnownColor.DarkBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkCyan { get { return new XColor(XKnownColor.DarkCyan); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkGoldenrod { get { return new XColor(XKnownColor.DarkGoldenrod); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkGray { get { return new XColor(XKnownColor.DarkGray); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkGreen { get { return new XColor(XKnownColor.DarkGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkKhaki { get { return new XColor(XKnownColor.DarkKhaki); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkMagenta { get { return new XColor(XKnownColor.DarkMagenta); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkOliveGreen { get { return new XColor(XKnownColor.DarkOliveGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkOrange { get { return new XColor(XKnownColor.DarkOrange); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkOrchid { get { return new XColor(XKnownColor.DarkOrchid); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkRed { get { return new XColor(XKnownColor.DarkRed); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkSalmon { get { return new XColor(XKnownColor.DarkSalmon); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkSeaGreen { get { return new XColor(XKnownColor.DarkSeaGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkSlateBlue { get { return new XColor(XKnownColor.DarkSlateBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkSlateGray { get { return new XColor(XKnownColor.DarkSlateGray); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkTurquoise { get { return new XColor(XKnownColor.DarkTurquoise); } }
///<summary>Gets a predefined color.</summary>
public static XColor DarkViolet { get { return new XColor(XKnownColor.DarkViolet); } }
///<summary>Gets a predefined color.</summary>
public static XColor DeepPink { get { return new XColor(XKnownColor.DeepPink); } }
///<summary>Gets a predefined color.</summary>
public static XColor DeepSkyBlue { get { return new XColor(XKnownColor.DeepSkyBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor DimGray { get { return new XColor(XKnownColor.DimGray); } }
///<summary>Gets a predefined color.</summary>
public static XColor DodgerBlue { get { return new XColor(XKnownColor.DodgerBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor Firebrick { get { return new XColor(XKnownColor.Firebrick); } }
///<summary>Gets a predefined color.</summary>
public static XColor FloralWhite { get { return new XColor(XKnownColor.FloralWhite); } }
///<summary>Gets a predefined color.</summary>
public static XColor ForestGreen { get { return new XColor(XKnownColor.ForestGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor Fuchsia { get { return new XColor(XKnownColor.Fuchsia); } }
///<summary>Gets a predefined color.</summary>
public static XColor Gainsboro { get { return new XColor(XKnownColor.Gainsboro); } }
///<summary>Gets a predefined color.</summary>
public static XColor GhostWhite { get { return new XColor(XKnownColor.GhostWhite); } }
///<summary>Gets a predefined color.</summary>
public static XColor Gold { get { return new XColor(XKnownColor.Gold); } }
///<summary>Gets a predefined color.</summary>
public static XColor Goldenrod { get { return new XColor(XKnownColor.Goldenrod); } }
///<summary>Gets a predefined color.</summary>
public static XColor Gray { get { return new XColor(XKnownColor.Gray); } }
///<summary>Gets a predefined color.</summary>
public static XColor Green { get { return new XColor(XKnownColor.Green); } }
///<summary>Gets a predefined color.</summary>
public static XColor GreenYellow { get { return new XColor(XKnownColor.GreenYellow); } }
///<summary>Gets a predefined color.</summary>
public static XColor Honeydew { get { return new XColor(XKnownColor.Honeydew); } }
///<summary>Gets a predefined color.</summary>
public static XColor HotPink { get { return new XColor(XKnownColor.HotPink); } }
///<summary>Gets a predefined color.</summary>
public static XColor IndianRed { get { return new XColor(XKnownColor.IndianRed); } }
///<summary>Gets a predefined color.</summary>
public static XColor Indigo { get { return new XColor(XKnownColor.Indigo); } }
///<summary>Gets a predefined color.</summary>
public static XColor Ivory { get { return new XColor(XKnownColor.Ivory); } }
///<summary>Gets a predefined color.</summary>
public static XColor Khaki { get { return new XColor(XKnownColor.Khaki); } }
///<summary>Gets a predefined color.</summary>
public static XColor Lavender { get { return new XColor(XKnownColor.Lavender); } }
///<summary>Gets a predefined color.</summary>
public static XColor LavenderBlush { get { return new XColor(XKnownColor.LavenderBlush); } }
///<summary>Gets a predefined color.</summary>
public static XColor LawnGreen { get { return new XColor(XKnownColor.LawnGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor LemonChiffon { get { return new XColor(XKnownColor.LemonChiffon); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightBlue { get { return new XColor(XKnownColor.LightBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightCoral { get { return new XColor(XKnownColor.LightCoral); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightCyan { get { return new XColor(XKnownColor.LightCyan); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightGoldenrodYellow { get { return new XColor(XKnownColor.LightGoldenrodYellow); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightGray { get { return new XColor(XKnownColor.LightGray); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightGreen { get { return new XColor(XKnownColor.LightGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightPink { get { return new XColor(XKnownColor.LightPink); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightSalmon { get { return new XColor(XKnownColor.LightSalmon); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightSeaGreen { get { return new XColor(XKnownColor.LightSeaGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightSkyBlue { get { return new XColor(XKnownColor.LightSkyBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightSlateGray { get { return new XColor(XKnownColor.LightSlateGray); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightSteelBlue { get { return new XColor(XKnownColor.LightSteelBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor LightYellow { get { return new XColor(XKnownColor.LightYellow); } }
///<summary>Gets a predefined color.</summary>
public static XColor Lime { get { return new XColor(XKnownColor.Lime); } }
///<summary>Gets a predefined color.</summary>
public static XColor LimeGreen { get { return new XColor(XKnownColor.LimeGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor Linen { get { return new XColor(XKnownColor.Linen); } }
///<summary>Gets a predefined color.</summary>
public static XColor Magenta { get { return new XColor(XKnownColor.Magenta); } }
///<summary>Gets a predefined color.</summary>
public static XColor Maroon { get { return new XColor(XKnownColor.Maroon); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumAquamarine { get { return new XColor(XKnownColor.MediumAquamarine); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumBlue { get { return new XColor(XKnownColor.MediumBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumOrchid { get { return new XColor(XKnownColor.MediumOrchid); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumPurple { get { return new XColor(XKnownColor.MediumPurple); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumSeaGreen { get { return new XColor(XKnownColor.MediumSeaGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumSlateBlue { get { return new XColor(XKnownColor.MediumSlateBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumSpringGreen { get { return new XColor(XKnownColor.MediumSpringGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumTurquoise { get { return new XColor(XKnownColor.MediumTurquoise); } }
///<summary>Gets a predefined color.</summary>
public static XColor MediumVioletRed { get { return new XColor(XKnownColor.MediumVioletRed); } }
///<summary>Gets a predefined color.</summary>
public static XColor MidnightBlue { get { return new XColor(XKnownColor.MidnightBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor MintCream { get { return new XColor(XKnownColor.MintCream); } }
///<summary>Gets a predefined color.</summary>
public static XColor MistyRose { get { return new XColor(XKnownColor.MistyRose); } }
///<summary>Gets a predefined color.</summary>
public static XColor Moccasin { get { return new XColor(XKnownColor.Moccasin); } }
///<summary>Gets a predefined color.</summary>
public static XColor NavajoWhite { get { return new XColor(XKnownColor.NavajoWhite); } }
///<summary>Gets a predefined color.</summary>
public static XColor Navy { get { return new XColor(XKnownColor.Navy); } }
///<summary>Gets a predefined color.</summary>
public static XColor OldLace { get { return new XColor(XKnownColor.OldLace); } }
///<summary>Gets a predefined color.</summary>
public static XColor Olive { get { return new XColor(XKnownColor.Olive); } }
///<summary>Gets a predefined color.</summary>
public static XColor OliveDrab { get { return new XColor(XKnownColor.OliveDrab); } }
///<summary>Gets a predefined color.</summary>
public static XColor Orange { get { return new XColor(XKnownColor.Orange); } }
///<summary>Gets a predefined color.</summary>
public static XColor OrangeRed { get { return new XColor(XKnownColor.OrangeRed); } }
///<summary>Gets a predefined color.</summary>
public static XColor Orchid { get { return new XColor(XKnownColor.Orchid); } }
///<summary>Gets a predefined color.</summary>
public static XColor PaleGoldenrod { get { return new XColor(XKnownColor.PaleGoldenrod); } }
///<summary>Gets a predefined color.</summary>
public static XColor PaleGreen { get { return new XColor(XKnownColor.PaleGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor PaleTurquoise { get { return new XColor(XKnownColor.PaleTurquoise); } }
///<summary>Gets a predefined color.</summary>
public static XColor PaleVioletRed { get { return new XColor(XKnownColor.PaleVioletRed); } }
///<summary>Gets a predefined color.</summary>
public static XColor PapayaWhip { get { return new XColor(XKnownColor.PapayaWhip); } }
///<summary>Gets a predefined color.</summary>
public static XColor PeachPuff { get { return new XColor(XKnownColor.PeachPuff); } }
///<summary>Gets a predefined color.</summary>
public static XColor Peru { get { return new XColor(XKnownColor.Peru); } }
///<summary>Gets a predefined color.</summary>
public static XColor Pink { get { return new XColor(XKnownColor.Pink); } }
///<summary>Gets a predefined color.</summary>
public static XColor Plum { get { return new XColor(XKnownColor.Plum); } }
///<summary>Gets a predefined color.</summary>
public static XColor PowderBlue { get { return new XColor(XKnownColor.PowderBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor Purple { get { return new XColor(XKnownColor.Purple); } }
///<summary>Gets a predefined color.</summary>
public static XColor Red { get { return new XColor(XKnownColor.Red); } }
///<summary>Gets a predefined color.</summary>
public static XColor RosyBrown { get { return new XColor(XKnownColor.RosyBrown); } }
///<summary>Gets a predefined color.</summary>
public static XColor RoyalBlue { get { return new XColor(XKnownColor.RoyalBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor SaddleBrown { get { return new XColor(XKnownColor.SaddleBrown); } }
///<summary>Gets a predefined color.</summary>
public static XColor Salmon { get { return new XColor(XKnownColor.Salmon); } }
///<summary>Gets a predefined color.</summary>
public static XColor SandyBrown { get { return new XColor(XKnownColor.SandyBrown); } }
///<summary>Gets a predefined color.</summary>
public static XColor SeaGreen { get { return new XColor(XKnownColor.SeaGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor SeaShell { get { return new XColor(XKnownColor.SeaShell); } }
///<summary>Gets a predefined color.</summary>
public static XColor Sienna { get { return new XColor(XKnownColor.Sienna); } }
///<summary>Gets a predefined color.</summary>
public static XColor Silver { get { return new XColor(XKnownColor.Silver); } }
///<summary>Gets a predefined color.</summary>
public static XColor SkyBlue { get { return new XColor(XKnownColor.SkyBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor SlateBlue { get { return new XColor(XKnownColor.SlateBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor SlateGray { get { return new XColor(XKnownColor.SlateGray); } }
///<summary>Gets a predefined color.</summary>
public static XColor Snow { get { return new XColor(XKnownColor.Snow); } }
///<summary>Gets a predefined color.</summary>
public static XColor SpringGreen { get { return new XColor(XKnownColor.SpringGreen); } }
///<summary>Gets a predefined color.</summary>
public static XColor SteelBlue { get { return new XColor(XKnownColor.SteelBlue); } }
///<summary>Gets a predefined color.</summary>
public static XColor Tan { get { return new XColor(XKnownColor.Tan); } }
///<summary>Gets a predefined color.</summary>
public static XColor Teal { get { return new XColor(XKnownColor.Teal); } }
///<summary>Gets a predefined color.</summary>
public static XColor Thistle { get { return new XColor(XKnownColor.Thistle); } }
///<summary>Gets a predefined color.</summary>
public static XColor Tomato { get { return new XColor(XKnownColor.Tomato); } }
///<summary>Gets a predefined color.</summary>
public static XColor Transparent { get { return new XColor(XKnownColor.Transparent); } }
///<summary>Gets a predefined color.</summary>
public static XColor Turquoise { get { return new XColor(XKnownColor.Turquoise); } }
///<summary>Gets a predefined color.</summary>
public static XColor Violet { get { return new XColor(XKnownColor.Violet); } }
///<summary>Gets a predefined color.</summary>
public static XColor Wheat { get { return new XColor(XKnownColor.Wheat); } }
///<summary>Gets a predefined color.</summary>
public static XColor White { get { return new XColor(XKnownColor.White); } }
///<summary>Gets a predefined color.</summary>
public static XColor WhiteSmoke { get { return new XColor(XKnownColor.WhiteSmoke); } }
///<summary>Gets a predefined color.</summary>
public static XColor Yellow { get { return new XColor(XKnownColor.Yellow); } }
///<summary>Gets a predefined color.</summary>
public static XColor YellowGreen { get { return new XColor(XKnownColor.YellowGreen); } }
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Overlays.Settings;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.AccountCreation
{
public class ScreenEntry : AccountCreationScreen
{
private ErrorTextFlowContainer usernameDescription;
private ErrorTextFlowContainer emailAddressDescription;
private ErrorTextFlowContainer passwordDescription;
private OsuTextBox usernameTextBox;
private OsuTextBox emailTextBox;
private OsuPasswordTextBox passwordTextBox;
[Resolved]
private IAPIProvider api { get; set; }
private ShakeContainer registerShake;
private IEnumerable<Drawable> characterCheckText;
private OsuTextBox[] textboxes;
private LoadingLayer loadingLayer;
[Resolved]
private GameHost host { get; set; }
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
FillFlowContainer mainContent;
InternalChildren = new Drawable[]
{
mainContent = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Padding = new MarginPadding(20),
Spacing = new Vector2(0, 10),
Children = new Drawable[]
{
new OsuSpriteText
{
Margin = new MarginPadding { Vertical = 10 },
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Font = OsuFont.GetFont(size: 20),
Text = "Let's create an account!",
},
usernameTextBox = new OsuTextBox
{
PlaceholderText = "username",
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this
},
usernameDescription = new ErrorTextFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
},
emailTextBox = new OsuTextBox
{
PlaceholderText = "email address",
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this
},
emailAddressDescription = new ErrorTextFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
},
passwordTextBox = new OsuPasswordTextBox
{
PlaceholderText = "password",
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
},
passwordDescription = new ErrorTextFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
registerShake = new ShakeContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Child = new SettingsButton
{
Text = "Register",
Margin = new MarginPadding { Vertical = 20 },
Action = performRegistration
}
}
}
},
},
},
loadingLayer = new LoadingLayer(mainContent)
};
textboxes = new[] { usernameTextBox, emailTextBox, passwordTextBox };
usernameDescription.AddText("This will be your public presence. No profanity, no impersonation. Avoid exposing your own personal details, too!");
emailAddressDescription.AddText("Will be used for notifications, account verification and in the case you forget your password. No spam, ever.");
emailAddressDescription.AddText(" Make sure to get it right!", cp => cp.Font = cp.Font.With(Typeface.Exo, weight: FontWeight.Bold));
passwordDescription.AddText("At least ");
characterCheckText = passwordDescription.AddText("8 characters long");
passwordDescription.AddText(". Choose something long but also something you will remember, like a line from your favourite song.");
passwordTextBox.Current.ValueChanged += password => { characterCheckText.ForEach(s => s.Colour = password.NewValue.Length == 0 ? Color4.White : Interpolation.ValueAt(password.NewValue.Length, Color4.OrangeRed, Color4.YellowGreen, 0, 8, Easing.In)); };
}
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
loadingLayer.Hide();
if (host?.OnScreenKeyboardOverlapsGameWindow != true)
focusNextTextbox();
}
private void performRegistration()
{
if (focusNextTextbox())
{
registerShake.Shake();
return;
}
usernameDescription.ClearErrors();
emailAddressDescription.ClearErrors();
passwordDescription.ClearErrors();
loadingLayer.Show();
Task.Run(() =>
{
bool success;
RegistrationRequest.RegistrationRequestErrors errors = null;
try
{
errors = api.CreateAccount(emailTextBox.Text, usernameTextBox.Text, passwordTextBox.Text);
success = errors == null;
}
catch (Exception)
{
success = false;
}
Schedule(() =>
{
if (!success)
{
if (errors != null)
{
usernameDescription.AddErrors(errors.User.Username);
emailAddressDescription.AddErrors(errors.User.Email);
passwordDescription.AddErrors(errors.User.Password);
}
else
{
passwordDescription.AddErrors(new[] { "Something happened... but we're not sure what." });
}
registerShake.Shake();
loadingLayer.Hide();
return;
}
api.Login(usernameTextBox.Text, passwordTextBox.Text);
});
});
}
private bool focusNextTextbox()
{
var nextTextbox = nextUnfilledTextbox();
if (nextTextbox != null)
{
Schedule(() => GetContainingInputManager().ChangeFocus(nextTextbox));
return true;
}
return false;
}
private OsuTextBox nextUnfilledTextbox() => textboxes.FirstOrDefault(t => string.IsNullOrEmpty(t.Text));
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Msagl.Layout.LargeGraphLayout;
namespace Microsoft.Msagl.Core.Geometry {
/// <summary>
/// A search tree for rapid lookup of TData objects keyed by rectangles inside a given rectangular region
/// It is very similar to "R-TREES. A DYNAMIC INDEX STRUCTURE FOR SPATIAL SEARCHING" by Antonin Guttman
/// </summary>
public class IntervalRTree<TData> {
/// <summary>
///
/// </summary>
public IntervalNode<TData> RootNode
{
get { return rootNode; }
set { rootNode=value; }
}
IntervalNode<TData> rootNode;
/// <summary>
/// Create the query tree for a given enumerable of TData keyed by Intervals
/// </summary>
/// <param name="rectsAndData"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public IntervalRTree(IEnumerable<KeyValuePair<Interval, TData>> rectsAndData) {
rootNode = IntervalNode<TData>.CreateIntervalNodeOnEnumeration(GetNodeRects(rectsAndData));
}
/// <summary>
/// Create a query tree for a given root node
/// </summary>
/// <param name="rootNode"></param>
public IntervalRTree(IntervalNode<TData> rootNode) {
this.rootNode = rootNode;
}
///<summary>
///</summary>
public IntervalRTree() {
}
/// <summary>
/// The number of data elements in the tree (number of leaf nodes)
/// </summary>
public int Count {
get { return rootNode == null ? 0 : rootNode.Count; }
}
/// <summary>
/// Add the given key, value pair
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Add(Interval key, TData value) {
Add(new IntervalNode<TData>(value, key));
}
internal void Add(IntervalNode<TData> node) {
if (rootNode == null)
rootNode = node;
else if (Count <= 2)
rootNode = IntervalNode<TData>.CreateIntervalNodeOnEnumeration(rootNode.GetAllLeafNodes().Concat(new[] {node}));
else
AddNodeToTreeRecursive(node, rootNode);
}
/// <summary>
/// rebuild the whole tree
/// </summary>
public void Rebuild() {
rootNode = IntervalNode<TData>.CreateIntervalNodeOnEnumeration(rootNode.GetAllLeafNodes());
}
static IEnumerable<IntervalNode<TData>> GetNodeRects(IEnumerable<KeyValuePair<Interval, TData>> nodes) {
return nodes.Select(v => new IntervalNode<TData>(v.Value, v.Key));
}
static void AddNodeToTreeRecursive(IntervalNode<TData> newNode, IntervalNode<TData> existingNode) {
if (existingNode.IsLeaf) {
existingNode.Left = new IntervalNode<TData>(existingNode.UserData, existingNode.Interval);
existingNode.Right = newNode;
existingNode.Count = 2;
existingNode.UserData = default(TData);
} else {
existingNode.Count++;
Interval leftBox;
Interval rightBox;
if (2 * existingNode.Left.Count < existingNode.Right.Count) {
//keep the balance
AddNodeToTreeRecursive(newNode, existingNode.Left);
existingNode.Left.Interval = new Interval(existingNode.Left.Interval, newNode.Interval);
} else if (2 * existingNode.Right.Count < existingNode.Left.Count) {
//keep the balance
AddNodeToTreeRecursive(newNode, existingNode.Right);
existingNode.Right.Interval = new Interval(existingNode.Right.Interval, newNode.Interval);
} else { //decide basing on the boxes
leftBox = new Interval(existingNode.Left.Interval, newNode.Interval);
var delLeft = leftBox.Length - existingNode.Left.Interval.Length;
rightBox = new Interval(existingNode.Right.Interval, newNode.Interval);
var delRight = rightBox.Length - existingNode.Right.Interval.Length;
if (delLeft < delRight) {
AddNodeToTreeRecursive(newNode, existingNode.Left);
existingNode.Left.Interval = leftBox;
} else if(delLeft>delRight){
AddNodeToTreeRecursive(newNode, existingNode.Right);
existingNode.Right.Interval = rightBox;
} else { //the deltas are the same; add to the smallest
if(leftBox.Length<rightBox.Length) {
AddNodeToTreeRecursive(newNode, existingNode.Left);
existingNode.Left.Interval = leftBox;
}else {
AddNodeToTreeRecursive(newNode, existingNode.Right);
existingNode.Right.Interval = rightBox;
}
}
}
}
existingNode.Interval = new Interval(existingNode.Left.Interval, existingNode.Right.Interval);
}
/// <summary>
/// return all the data elements stored at the leaves of the BSPTree in an IEnumerable
/// </summary>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public IEnumerable<TData> GetAllLeaves() {
return rootNode!=null && Count>0 ? rootNode.GetAllLeaves():new TData[0];
}
/// <summary>
/// Get all data items with rectangles intersecting the specified rectangular region
/// </summary>
/// <param name="queryRegion"></param>
/// <returns></returns>
public IEnumerable<TData> GetAllIntersecting(Interval queryRegion)
{
return rootNode == null || Count == 0 ? new TData[0] : rootNode.GetNodeItemsIntersectingInterval(queryRegion);
}
/// <summary>
/// Does minimal work to determine if any objects in the tree intersect with the query region
/// </summary>
/// <param name="queryRegion"></param>
/// <returns></returns>
public bool IsIntersecting(Interval queryRegion) {
return GetAllIntersecting(queryRegion).Any();
}
/// <summary>
/// return true iff there is a node with the rectangle and UserData that equals to the parameter "userData"
/// </summary>
/// <param name="rectangle"></param>
/// <param name="userData"></param>
/// <returns></returns>
public bool Contains(Interval rectangle, TData userData) {
if (rootNode == null) return false;
return
rootNode.GetLeafIntervalNodesIntersectingInterval(rectangle)
.Any(node => node.UserData.Equals(userData));
}
///<summary>
///</summary>
///<param name="rectangle"></param>
///<param name="userData"></param>
///<returns></returns>
public TData Remove(Interval rectangle, TData userData) {
if (rootNode==null)
{
return default(TData);
}
var ret = rootNode.GetLeafIntervalNodesIntersectingInterval(rectangle).FirstOrDefault(node => node.UserData.Equals(userData));
if (ret == null)
return default(TData);
if (RootNode.Count == 1)
RootNode = null;
else
RemoveLeaf(ret);
return ret.UserData;
}
void RemoveLeaf(IntervalNode<TData> leaf) {
Debug.Assert(leaf.IsLeaf);
var unbalancedNode = FindTopUnbalancedNode(leaf);
if (unbalancedNode != null) {
RebuildUnderNodeWithoutLeaf(unbalancedNode, leaf);
UpdateParent(unbalancedNode);
} else {
//replace the parent with the sibling and update bounding boxes and counts
var parent = leaf.Parent;
if (parent == null) {
Debug.Assert(rootNode == leaf);
rootNode = new IntervalNode<TData>();
} else {
TransferFromSibling(parent, leaf.IsLeftChild ? parent.Right : parent.Left);
UpdateParent(parent);
}
}
Debug.Assert(TreeIsCorrect(RootNode));
}
static bool TreeIsCorrect(IntervalNode<TData> node)
{
if (node == null)
return true;
bool ret= node.Left != null && node.Right != null ||
node.Left == null && node.Right == null;
if (!ret)
return false;
return TreeIsCorrect(node.Left) && TreeIsCorrect(node.Right);
}
static void UpdateParent(IntervalNode<TData> parent) {
for(var node=parent.Parent; node!=null; node=node.Parent) {
node.Count--;
node.Interval=new Interval(node.Left.Interval, node.Right.Interval);
}
}
static void TransferFromSibling(IntervalNode<TData> parent, IntervalNode<TData> sibling) {
parent.UserData=sibling.UserData;
parent.Left = sibling.Left;
parent.Right=sibling.Right;
parent.Count--;
parent.Interval = sibling.Interval;
}
static void RebuildUnderNodeWithoutLeaf(IntervalNode<TData> nodeForRebuild, IntervalNode<TData> leaf)
{
Debug.Assert(leaf.IsLeaf);
Debug.Assert(!nodeForRebuild.IsLeaf);
var newNode =
IntervalNode<TData>.CreateIntervalNodeOnEnumeration(
nodeForRebuild.GetAllLeafNodes().Where(n => !(n.Equals(leaf))));
nodeForRebuild.Count = newNode.Count;
nodeForRebuild.Left = newNode.Left;
nodeForRebuild.Right = newNode.Right;
nodeForRebuild.Interval = new Interval(newNode.Left.interval, newNode.Right.interval);
}
static IntervalNode<TData> FindTopUnbalancedNode(IntervalNode<TData> node) {
for (var parent = node.Parent; parent != null; parent = parent.Parent)
if (! Balanced(parent))
return parent;
return null;
}
static bool Balanced(IntervalNode<TData> rectangleNode) {
return 2*rectangleNode.Left.Count >= rectangleNode.Right.Count &&
2*rectangleNode.Right.Count >= rectangleNode.Left.Count;
}
/// <summary>
/// Removes everything from the tree
/// </summary>
public void Clean()
{
RootNode = null;
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using Cosmos.IL2CPU.API;
namespace Cosmos.IL2CPU.IL.CustomImplementations.System
{
[Plug(Target = typeof(sbyte))]
public static class Int8Impl
{
public static string ToString(ref sbyte aThis)
{
bool bNegative = false;
sbyte aValue = aThis;
if (aValue < 0)
{
bNegative = true;
aValue *= -1;
}
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, bNegative);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out sbyte result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out sbyte result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch(Exception)
{
// Something wrong
}
return bCanParse;
}
public static sbyte Parse(string s)
{
Int64 result = GeneralIntegerImplByUInt64.ParseSignedInteger(s);
if (result > sbyte.MaxValue || result < sbyte.MinValue)
{
throw new OverflowException();
}
return (sbyte)result;
}
}
[Plug(Target = typeof(byte))]
public static class UInt8Impl
{
public static string ToString(ref byte aThis)
{
byte aValue = aThis;
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, false);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out byte result)
{
// Todo, consider how to implemente style and provider
// Exponent, "1E0", "1e3"...
// Decimal point "1.0", "3.5"
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out byte result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static byte Parse(string s)
{
UInt64 result = GeneralIntegerImplByUInt64.ParseUnsignedInteger(s);
if (result > byte.MaxValue)
{
throw new OverflowException();
}
return (byte)result;
}
}
[Plug(Target = typeof(short))]
public static class Int16Impl
{
public static string ToString(ref short aThis)
{
bool bNegative = false;
short aValue = aThis;
if (aValue < 0)
{
bNegative = true;
aValue *= -1;
}
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, bNegative);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out short result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out short result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static short Parse(string s)
{
Int64 result = GeneralIntegerImplByUInt64.ParseSignedInteger(s);
if (result > short.MaxValue || result < short.MinValue)
{
throw new OverflowException();
}
return (short)result;
}
}
[Plug(Target = typeof(ushort))]
public static class UInt16Impl
{
public static string ToString(ref ushort aThis)
{
ushort aValue = aThis;
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, false);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out ushort result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out ushort result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static ushort Parse(string s)
{
UInt64 result = GeneralIntegerImplByUInt64.ParseUnsignedInteger(s);
if (result > ushort.MaxValue)
{
throw new OverflowException();
}
return (ushort)result;
}
}
[Plug(Target = typeof(int))]
public static class Int32Impl
{
public static string ToString(ref int aThis)
{
bool bNegative = false;
int aValue = aThis;
if (aValue < 0)
{
bNegative = true;
aValue *= -1;
}
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, bNegative);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out short result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out int result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static int Parse(string s)
{
Int64 result = GeneralIntegerImplByUInt64.ParseSignedInteger(s);
if (result > int.MaxValue || result < int.MinValue)
{
throw new OverflowException();
}
return (int)result;
}
}
[Plug(Target = typeof(uint))]
public static class UInt32Impl
{
public static string ToString(ref uint aThis)
{
uint aValue = aThis;
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, false);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out uint result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out uint result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static uint Parse(string s)
{
UInt64 result = GeneralIntegerImplByUInt64.ParseUnsignedInteger(s);
if (result > uint.MaxValue)
{
throw new OverflowException();
}
return (uint)result;
}
}
internal static class GeneralIntegerImplByUInt64
{
internal static Int64 ParseSignedInteger(string s)
{
bool bNegative;
Int64 result = (Int64)ParseInteger(s, out bNegative);
if (bNegative)
result *= -1;
return result;
}
internal static UInt64 ParseUnsignedInteger(string s)
{
bool bNegative;
UInt64 result = ParseInteger(s, out bNegative);
if (bNegative && result != 0)
{
throw new OverflowException();
}
return result;
}
/// <summary>
/// ParseInteger
/// Sole algorithm implementation of "integer Parse(string)"
/// </summary>
/// <param name="s"></param>
/// <param name="bNegative"></param>
/// <returns></returns>
private static UInt64 ParseInteger(string s, out bool bNegative)
{
UInt64 result = 0;
int nParseStartPos = 0;
bNegative = false;
if (s.Length >= 1)
{
if (s[0] == '+')
{
nParseStartPos = 1;
}
else if (s[0] == '-')
{
nParseStartPos = 1;
bNegative = true;
}
}
for (int i = nParseStartPos; i < s.Length; i++)
{
sbyte ind = (sbyte)(s[i] - '0');
if (ind < 0 || ind > 9)
{
throw new FormatException("Digit " + s[i] + " not found");
}
result = (result * 10) + (UInt64)ind;
}
return result;
}
/// <summary>
/// ToString
/// Sole algorithm implementation of "string ToString(integer)"
/// </summary>
/// <param name="aValue"></param>
/// <param name="bIsNegative"></param>
/// <returns></returns>
internal static string ToString(UInt64 aValue, bool bIsNegative)
{
char[] xResultChars = new char[21]; // 64 bit UInteger convert to string, with sign symble, max length is 21.
int xCurrentPos = xResultChars.Length - 1;
while (aValue > 0)
{
byte xPos = (byte)(aValue % 10);
aValue /= 10;
xResultChars[xCurrentPos] = (char)('0' + xPos);
xCurrentPos -= 1;
}
if (bIsNegative)
{
xResultChars[xCurrentPos] = '-';
xCurrentPos -= 1;
}
return new String(xResultChars, xCurrentPos + 1, xResultChars.Length - xCurrentPos - 1);
}
}
}
| |
// 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.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class StopBits_Property : PortsTest
{
//The default ammount of time the a transfer should take at any given baud rate and stop bits combination.
//The bytes sent should be adjusted to take this ammount of time to transfer at the specified baud rate and stop bits combination.
private const int DEFAULT_TIME = 750;
//If the percentage difference between the expected time to transfer with the specified stopBits
//and the actual time found through Stopwatch is greater then 5% then the StopBits value was not correctly
//set and the testcase fails.
private const double MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE = .07;
//The default number of databits to use when testing StopBits
private const int DEFAULT_DATABITS = 8;
private const int NUM_TRYS = 5;
private enum ThrowAt { Set, Open };
#region Test Cases
[ConditionalFact(nameof(HasNullModem))]
public void StopBits_Default()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default StopBits");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyStopBits(com1);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void StopBits_1_BeforeOpen()
{
Debug.WriteLine("Verifying 1 StopBits before open");
VerifyStopBitsBeforeOpen((int)StopBits.One);
}
[ConditionalFact(nameof(HasNullModem))]
public void StopBits_2_BeforeOpen()
{
Debug.WriteLine("Verifying 2 StopBits before open");
VerifyStopBitsBeforeOpen((int)StopBits.Two);
}
[ConditionalFact(nameof(HasNullModem))]
public void StopBits_1_AfterOpen()
{
Debug.WriteLine("Verifying 1 StopBits after open");
VerifyStopBitsAfterOpen((int)StopBits.One);
}
[ConditionalFact(nameof(HasNullModem))]
public void StopBits_2_AfterOpen()
{
Debug.WriteLine("Verifying 2 StopBits after open");
VerifyStopBitsAfterOpen((int)StopBits.Two);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void StopBits_Int32MinValue()
{
Debug.WriteLine("Verifying Int32.MinValue StopBits");
VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void StopBits_Neg1()
{
Debug.WriteLine("Verifying -1 StopBits");
VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void StopBits_0()
{
Debug.WriteLine("Verifying 0 StopBits");
VerifyException(0, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void StopBits_4()
{
Debug.WriteLine("Verifying 4 StopBits");
VerifyException(4, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void StopBits_Int32MaxValue()
{
Debug.WriteLine("Verifying Int32.MaxValue StopBits");
VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
#endregion
#region Verification for Test Cases
private void VerifyException(int stopBits, ThrowAt throwAt, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
VerifyExceptionAtOpen(com, stopBits, throwAt, expectedException);
if (com.IsOpen)
com.Close();
VerifyExceptionAfterOpen(com, stopBits, expectedException);
}
}
private void VerifyExceptionAtOpen(SerialPort com, int stopBits, ThrowAt throwAt, Type expectedException)
{
int origStopBits = (int)com.StopBits;
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
if (ThrowAt.Open == throwAt)
serPortProp.SetProperty("StopBits", (StopBits)stopBits);
try
{
com.StopBits = (StopBits)stopBits;
if (ThrowAt.Open == throwAt)
com.Open();
if (null != expectedException)
{
Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
com.StopBits = (StopBits)origStopBits;
}
private void VerifyExceptionAfterOpen(SerialPort com, int stopBits, Type expectedException)
{
SerialPortProperties serPortProp = new SerialPortProperties();
com.Open();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
try
{
com.StopBits = (StopBits)stopBits;
if (null != expectedException)
{
Fail("ERROR!!! Expected setting the StopBits after Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected setting the StopBits after Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected setting the StopBits after Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
}
private void VerifyStopBitsBeforeOpen(int stopBits)
{
VerifyStopBitsBeforeOpen(stopBits, DEFAULT_DATABITS);
}
private void VerifyStopBitsBeforeOpen(int stopBits, int dataBits)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.DataBits = dataBits;
com1.StopBits = (StopBits)stopBits;
com1.Open();
serPortProp.SetProperty("DataBits", dataBits);
serPortProp.SetProperty("StopBits", (StopBits)stopBits);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyStopBits(com1);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyStopBitsAfterOpen(int stopBits)
{
VerifyStopBitsAfterOpen(stopBits, DEFAULT_DATABITS);
}
private void VerifyStopBitsAfterOpen(int stopBits, int dataBits)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.DataBits = dataBits;
com1.StopBits = (StopBits)stopBits;
serPortProp.SetProperty("DataBits", dataBits);
serPortProp.SetProperty("StopBits", (StopBits)stopBits);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyStopBits(com1);
serPortProp.VerifyPropertiesAndPrint(com1);
if (com1.IsOpen)
com1.Close();
}
}
private void VerifyStopBits(SerialPort com1)
{
Random rndGen = new Random(-55);
Stopwatch sw = new Stopwatch();
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
double expectedTime, actualTime, percentageDifference;
int numBytes = 0;
byte shiftMask = 0xFF;
double stopBits = -1;
switch ((int)com1.StopBits)
{
case (int)StopBits.One:
stopBits = 1.0;
break;
case (int)StopBits.OnePointFive:
stopBits = 1.5;
break;
case (int)StopBits.Two:
stopBits = 2.0;
break;
}
int numBytesToSend = (int)(((DEFAULT_TIME / 1000.0) * com1.BaudRate) / (stopBits + com1.DataBits + 1));
byte[] xmitBytes = new byte[numBytesToSend];
byte[] expectedBytes = new byte[numBytesToSend];
byte[] rcvBytes = new byte[numBytesToSend];
//Create a mask that when logicaly and'd with the transmitted byte will
//will result in the byte recievied due to the leading bits being chopped
//off due to DataBits less then 8
shiftMask >>= 8 - com1.DataBits;
//Generate some random bytes to read/write for this StopBits setting
for (int i = 0; i < xmitBytes.Length; i++)
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask);
}
com2.DataBits = com1.DataBits;
com2.StopBits = com1.StopBits;
com2.Open();
actualTime = 0;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
int initialNumBytes;
for (int i = 0; i < NUM_TRYS; i++)
{
com2.DiscardInBuffer();
IAsyncResult beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, numBytesToSend, null, null);
while (0 == (initialNumBytes = com2.BytesToRead))
{ }
sw.Start();
TCSupport.WaitForReadBufferToLoad(com2, numBytesToSend);
sw.Stop();
actualTime += sw.ElapsedMilliseconds;
actualTime += ((initialNumBytes * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000;
beginWriteResult.AsyncWaitHandle.WaitOne();
sw.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
expectedTime = ((xmitBytes.Length * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000;
percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime);
//If the percentageDifference between the expected time and the actual time is to high
//then the expected baud rate must not have been used and we should report an error
if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference)
{
Fail("ERROR!!! StopBits not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference, numBytes);
}
com2.Read(rcvBytes, 0, rcvBytes.Length);
//Verify that the bytes we sent were the same ones we received
for (int i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != rcvBytes[i])
{
Fail("ERROR!!! Expected to read {0} actual read {1}", expectedBytes[i], rcvBytes[i]);
}
}
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Client;
namespace OpenSim.Tests.Common.Mock
{
public class TestClient : IClientAPI, IClientCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Mock testing variables
public List<ImageDataPacket> sentdatapkt = new List<ImageDataPacket>();
public List<ImagePacketPacket> sentpktpkt = new List<ImagePacketPacket>();
EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
// TODO: This is a really nasty (and temporary) means of telling the test client which scene to invoke setup
// methods on when a teleport is requested
public Scene TeleportTargetScene;
private TestClient TeleportSceneClient;
private IScene m_scene;
// disable warning: public events, part of the public API
#pragma warning disable 67
public event Action<IClientAPI> OnLogout;
public event ObjectPermissions OnObjectPermissions;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event ParcelBuy OnParcelBuy;
public event Action<IClientAPI> OnConnectionClosed;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event SetAlwaysRun OnSetAlwaysRun;
public event DeRezObject OnDeRezObject;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall2 OnRequestWearables;
public event GenericCall1 OnCompleteMovementToRegion;
public event UpdateAgent OnPreAgentUpdate;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event ViewerEffectEventHandler OnViewerEffect;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event ObjectSelect OnObjectSelect;
public event ObjectRequest OnObjectRequest;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVector OnUpdatePrimGroupPosition;
public event UpdateVector OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<UUID> OnRemoveAvatar;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event GenericMessage OnGenericMessage;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event ObjectDeselect OnObjectDeselect;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event EstateChangeInfo OnEstateChangeInfo;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event UpdateVector OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event ActivateGesture OnActivateGesture;
public event DeactivateGesture OnDeactivateGesture;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event AvatarInterestUpdate OnAvatarInterestUpdate;
public event PlacesQuery OnPlacesQuery;
public event FindAgentUpdate OnFindAgent;
public event TrackAgentUpdate OnTrackAgent;
public event NewUserReport OnUserReport;
public event SaveStateHandler OnSaveState;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event ParcelBuyPass OnParcelBuyPass;
public event ParcelGodMark OnParcelGodMark;
public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SendPostcard OnSendPostcard;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event GodlikeMessage onGodlikeMessage;
public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
#pragma warning restore 67
/// <value>
/// This agent's UUID
/// </value>
private UUID m_agentId;
/// <value>
/// The last caps seed url that this client was given.
/// </value>
public string CapsSeedUrl;
private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2);
public virtual Vector3 StartPos
{
get { return startPos; }
set { }
}
public virtual UUID AgentId
{
get { return m_agentId; }
}
public UUID SessionId
{
get { return UUID.Zero; }
}
public UUID SecureSessionId
{
get { return UUID.Zero; }
}
public virtual string FirstName
{
get { return m_firstName; }
}
private string m_firstName;
public virtual string LastName
{
get { return m_lastName; }
}
private string m_lastName;
public virtual String Name
{
get { return FirstName + " " + LastName; }
}
public bool IsActive
{
get { return true; }
set { }
}
public bool IsLoggingOut
{
get { return false; }
set { }
}
public UUID ActiveGroupId
{
get { return UUID.Zero; }
}
public string ActiveGroupName
{
get { return String.Empty; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public bool IsGroupMember(UUID groupID)
{
return false;
}
public ulong GetGroupPowers(UUID groupID)
{
return 0;
}
public virtual int NextAnimationSequenceNumber
{
get { return 1; }
}
public IScene Scene
{
get { return m_scene; }
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
private uint m_circuitCode;
public uint CircuitCode
{
get { return m_circuitCode; }
set { m_circuitCode = value; }
}
public IPEndPoint RemoteEndPoint
{
get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="agentData"></param>
/// <param name="scene"></param>
public TestClient(AgentCircuitData agentData, IScene scene)
{
m_agentId = agentData.AgentID;
m_firstName = agentData.firstname;
m_lastName = agentData.lastname;
m_circuitCode = agentData.circuitcode;
m_scene = scene;
CapsSeedUrl = agentData.CapsPath;
}
/// <summary>
/// Attempt a teleport to the given region.
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="position"></param>
/// <param name="lookAt"></param>
public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt)
{
OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16);
}
public void CompleteMovement()
{
OnCompleteMovementToRegion(this);
}
public virtual void ActivateGesture(UUID assetId, UUID gestureId)
{
}
public virtual void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
{
}
public virtual void Kick(string message)
{
}
public virtual void SendStartPingCheck(byte seq)
{
}
public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public virtual void SendKillObject(ulong regionHandle, uint localID)
{
}
public virtual void SetChildAgentThrottle(byte[] throttle)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
{
}
public virtual void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, byte source, byte audible)
{
}
public virtual void SendChatMessage(byte[] message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, byte source, byte audible)
{
}
public void SendInstantMessage(GridInstantMessage im)
{
}
public void SendGenericMessage(string method, List<string> message)
{
}
public void SendGenericMessage(string method, List<byte[]> message)
{
}
public virtual void SendLayerData(float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map, bool track)
{
}
public virtual void SendWindData(Vector2[] windSpeeds) { }
public virtual void SendCloudData(float[] cloudCover) { }
public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
{
}
public virtual AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
agentData.SessionID = UUID.Zero;
agentData.SecureSessionID = UUID.Zero;
agentData.circuitcode = m_circuitCode;
agentData.child = false;
agentData.firstname = m_firstName;
agentData.lastname = m_lastName;
ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>();
agentData.CapsPath = capsModule.GetCapsPath(m_agentId);
agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId));
return agentData;
}
public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
{
m_log.DebugFormat("[TEST CLIENT]: Processing inform client of neighbour");
// In response to this message, we are going to make a teleport to the scene we've previous been told
// about by test code (this needs to be improved).
AgentCircuitData newAgent = RequestClientInfo();
// Stage 2: add the new client as a child agent to the scene
TeleportSceneClient = new TestClient(newAgent, TeleportTargetScene);
TeleportTargetScene.AddNewClient(TeleportSceneClient);
}
public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL)
{
m_log.DebugFormat("[TEST CLIENT]: Received SendRegionTeleport");
CapsSeedUrl = capsURL;
TeleportSceneClient.CompleteMovement();
//TeleportTargetScene.AgentCrossing(newAgent.AgentID, new Vector3(90, 90, 90), false);
}
public virtual void SendTeleportFailed(string reason)
{
m_log.DebugFormat("[TEST CLIENT]: Teleport failed with reason {0}", reason);
}
public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint, string capsURL)
{
// This is supposed to send a packet to the client telling it's ready to start region crossing.
// Instead I will just signal I'm ready, mimicking the communication behavior.
// It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs.
// Arthur V.
wh.Set();
}
public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
{
}
public virtual void SendTeleportLocationStart()
{
}
public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance)
{
}
public virtual void SendPayPrice(UUID objectID, int[] payPrice)
{
}
public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
{
}
public virtual void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
}
public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{
}
public void SendAvatarDataImmediate(ISceneEntity avatar)
{
}
public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
{
}
public void ReprioritizeUpdates()
{
}
public void FlushPrimUpdates()
{
}
public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID,
List<InventoryItemBase> items,
List<InventoryFolderBase> folders,
int version,
bool fetchFolders,
bool fetchItems)
{
}
public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
{
}
public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID)
{
}
public virtual void SendRemoveInventoryItem(UUID itemID)
{
}
public virtual void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public UUID GetDefaultAnimation(string name)
{
return UUID.Zero;
}
public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
{
}
public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
{
}
public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit,
int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor,
int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay,
int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public virtual void SendNameReply(UUID profileId, string firstname, string lastname)
{
}
public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
{
}
public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain,
byte flags)
{
}
public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(UUID objectID, float gain)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendSystemAlertMessage(string message)
{
}
public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message,
string url)
{
}
public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
if (OnRegionHandShakeReply != null)
{
OnRegionHandShakeReply(this);
}
if (OnCompleteMovementToRegion != null)
{
OnCompleteMovementToRegion(this);
}
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
ImageDataPacket im = new ImageDataPacket();
im.Header.Reliable = false;
im.ImageID.Packets = numParts;
im.ImageID.ID = ImageUUID;
if (ImageSize > 0)
im.ImageID.Size = ImageSize;
im.ImageData.Data = ImageData;
im.ImageID.Codec = imageCodec;
im.Header.Zerocoded = true;
sentdatapkt.Add(im);
}
public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
{
ImagePacketPacket im = new ImagePacketPacket();
im.Header.Reliable = false;
im.ImageID.Packet = partNumber;
im.ImageID.ID = imageUuid;
im.ImageData.Data = imageData;
sentpktpkt.Add(im);
}
public void SendImageNotFound(UUID imageid)
{
}
public void SendShutdownConnectionNotice()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID,
uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask,
uint NextOwnerMask, int OwnershipCost, byte SaleType,int SalePrice, uint Category,
UUID LastOwnerID, string ObjectName, string Description)
{
}
public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID,
UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID,
UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName,
string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask,
uint BaseMask, byte saleType, int salePrice)
{
}
public void SendAgentOffline(UUID[] agentIDs)
{
}
public void SendAgentOnline(UUID[] agentIDs)
{
}
public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot,
Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public bool AddMoney(int debit)
{
return false;
}
public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase)
{
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember,
string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL,
UUID partnerID)
{
}
public void SetDebugPacketLevel(int newDebug)
{
}
public void InPacket(object NewPack)
{
}
public void ProcessInPacket(Packet NewPack)
{
}
public void Close()
{
m_scene.RemoveClient(AgentId);
}
public void Start()
{
}
public void Stop()
{
}
public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message)
{
}
public void SendLogoutPacket()
{
}
public void Terminate()
{
}
public EndPoint GetClientEP()
{
return null;
}
public ClientInfo GetClientInfo()
{
return null;
}
public void SetClientInfo(ClientInfo info)
{
}
public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
{
}
public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(UUID covenant)
{
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendCameraConstraint(Vector4 ConstraintPlane)
{
}
public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType,
string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendGroupNameReply(UUID groupLLUID, string GroupName)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
{
}
public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
{
}
public void SendAsset(AssetRequestToClient req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties (UUID objectID)
{
}
public void SendRegionHandle (UUID regoinID, ulong handle)
{
}
public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return string.Empty;
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
}
public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void KillEndDone()
{
}
public void SendEventInfoReply (EventData info)
{
}
public void SendOfferCallingCard (UUID destID, UUID transactionID)
{
}
public void SendAcceptCallingCard (UUID transactionID)
{
}
public void SendDeclineCallingCard (UUID transactionID)
{
}
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
}
public void SendJoinGroupReply(UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss)
{
}
public void SendLeaveGroupReply(UUID groupID, bool success)
{
}
public void SendTerminateFriend(UUID exFriendID)
{
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
//throw new NotImplementedException();
return false;
}
public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
{
}
public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(UUID groupID)
{
}
public void SendAvatarNotesReply(UUID targetID, string text)
{
}
public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
{
}
public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendCreateGroupReply(UUID groupID, bool success, string message)
{
}
public void RefreshGroupMembership()
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public bool TryGet<T>(out T iface)
{
iface = default(T);
return false;
}
public T Get<T>()
{
return default(T);
}
public void Disconnect(string reason)
{
}
public void Disconnect()
{
}
public void SendRebakeAvatarTextures(UUID textureID)
{
}
public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
{
}
public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
{
}
public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
{
}
public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
{
}
public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes)
{
}
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
{
}
public void StopFlying(ISceneEntity presence)
{
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
/// <summary>
/// Display story text in a visual novel style dialog box.
/// </summary>
public class SayDialog : MonoBehaviour
{
[Tooltip("Duration to fade dialogue in/out")]
[SerializeField] protected float fadeDuration = 0.25f;
[Tooltip("The continue button UI object")]
[SerializeField] protected Button continueButton;
[Tooltip("The canvas UI object")]
[SerializeField] protected Canvas dialogCanvas;
[Tooltip("The name text UI object")]
[SerializeField] protected Text nameText;
[Tooltip("TextAdapter will search for appropriate output on this GameObject if nameText is null")]
[SerializeField] protected GameObject nameTextGO;
protected TextAdapter nameTextAdapter = new TextAdapter();
public virtual string NameText
{
get
{
return nameTextAdapter.Text;
}
set
{
nameTextAdapter.Text = value;
}
}
[Tooltip("The story text UI object")]
[SerializeField] protected Text storyText;
[Tooltip("TextAdapter will search for appropriate output on this GameObject if storyText is null")]
[SerializeField] protected GameObject storyTextGO;
protected TextAdapter storyTextAdapter = new TextAdapter();
public virtual string StoryText
{
get
{
return storyTextAdapter.Text;
}
set
{
storyTextAdapter.Text = value;
}
}
public virtual RectTransform StoryTextRectTrans
{
get
{
return storyText != null ? storyText.rectTransform : storyTextGO.GetComponent<RectTransform>();
}
}
[Tooltip("The character UI object")]
[SerializeField] protected Image characterImage;
public virtual Image CharacterImage { get { return characterImage; } }
[Tooltip("Adjust width of story text when Character Image is displayed (to avoid overlapping)")]
[SerializeField] protected bool fitTextWithImage = true;
[Tooltip("Close any other open Say Dialogs when this one is active")]
[SerializeField] protected bool closeOtherDialogs;
protected float startStoryTextWidth;
protected float startStoryTextInset;
protected WriterAudio writerAudio;
protected Writer writer;
protected CanvasGroup canvasGroup;
protected bool fadeWhenDone = true;
protected float targetAlpha = 0f;
protected float fadeCoolDownTimer = 0f;
protected Sprite currentCharacterImage;
// Most recent speaking character
protected static Character speakingCharacter;
protected StringSubstituter stringSubstituter = new StringSubstituter();
// Cache active Say Dialogs to avoid expensive scene search
protected static List<SayDialog> activeSayDialogs = new List<SayDialog>();
protected virtual void Awake()
{
if (!activeSayDialogs.Contains(this))
{
activeSayDialogs.Add(this);
}
nameTextAdapter.InitFromGameObject(nameText != null ? nameText.gameObject : nameTextGO);
storyTextAdapter.InitFromGameObject(storyText != null ? storyText.gameObject : storyTextGO);
}
protected virtual void OnDestroy()
{
activeSayDialogs.Remove(this);
}
protected virtual Writer GetWriter()
{
if (writer != null)
{
return writer;
}
writer = GetComponent<Writer>();
if (writer == null)
{
writer = gameObject.AddComponent<Writer>();
}
return writer;
}
protected virtual CanvasGroup GetCanvasGroup()
{
if (canvasGroup != null)
{
return canvasGroup;
}
canvasGroup = GetComponent<CanvasGroup>();
if (canvasGroup == null)
{
canvasGroup = gameObject.AddComponent<CanvasGroup>();
}
return canvasGroup;
}
protected virtual WriterAudio GetWriterAudio()
{
if (writerAudio != null)
{
return writerAudio;
}
writerAudio = GetComponent<WriterAudio>();
if (writerAudio == null)
{
writerAudio = gameObject.AddComponent<WriterAudio>();
}
return writerAudio;
}
protected virtual void Start()
{
// Dialog always starts invisible, will be faded in when writing starts
GetCanvasGroup().alpha = 0f;
// Add a raycaster if none already exists so we can handle dialog input
GraphicRaycaster raycaster = GetComponent<GraphicRaycaster>();
if (raycaster == null)
{
gameObject.AddComponent<GraphicRaycaster>();
}
// It's possible that SetCharacterImage() has already been called from the
// Start method of another component, so check that no image has been set yet.
// Same for nameText.
if (NameText == "")
{
SetCharacterName("", Color.white);
}
if (currentCharacterImage == null)
{
// Character image is hidden by default.
SetCharacterImage(null);
}
}
protected virtual void LateUpdate()
{
UpdateAlpha();
if (continueButton != null)
{
continueButton.gameObject.SetActive( GetWriter().IsWaitingForInput );
}
}
protected virtual void UpdateAlpha()
{
if (GetWriter().IsWriting)
{
targetAlpha = 1f;
fadeCoolDownTimer = 0.1f;
}
else if (fadeWhenDone && Mathf.Approximately(fadeCoolDownTimer, 0f))
{
targetAlpha = 0f;
}
else
{
// Add a short delay before we start fading in case there's another Say command in the next frame or two.
// This avoids a noticeable flicker between consecutive Say commands.
fadeCoolDownTimer = Mathf.Max(0f, fadeCoolDownTimer - Time.deltaTime);
}
CanvasGroup canvasGroup = GetCanvasGroup();
if (fadeDuration <= 0f)
{
canvasGroup.alpha = targetAlpha;
}
else
{
float delta = (1f / fadeDuration) * Time.deltaTime;
float alpha = Mathf.MoveTowards(canvasGroup.alpha, targetAlpha, delta);
canvasGroup.alpha = alpha;
if (alpha <= 0f)
{
// Deactivate dialog object once invisible
gameObject.SetActive(false);
}
}
}
protected virtual void ClearStoryText()
{
StoryText = "";
}
#region Public members
public Character SpeakingCharacter { get { return speakingCharacter; } }
/// <summary>
/// Currently active Say Dialog used to display Say text
/// </summary>
public static SayDialog ActiveSayDialog { get; set; }
/// <summary>
/// Returns a SayDialog by searching for one in the scene or creating one if none exists.
/// </summary>
public static SayDialog GetSayDialog()
{
if (ActiveSayDialog == null)
{
SayDialog sd = null;
// Use first active Say Dialog in the scene (if any)
if (activeSayDialogs.Count > 0)
{
sd = activeSayDialogs[0];
}
if (sd != null)
{
ActiveSayDialog = sd;
}
if (ActiveSayDialog == null)
{
// Auto spawn a say dialog object from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/SayDialog");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.SetActive(false);
go.name = "SayDialog";
ActiveSayDialog = go.GetComponent<SayDialog>();
}
}
}
return ActiveSayDialog;
}
/// <summary>
/// Stops all active portrait tweens.
/// </summary>
public static void StopPortraitTweens()
{
// Stop all tweening portraits
var activeCharacters = Character.ActiveCharacters;
for (int i = 0; i < activeCharacters.Count; i++)
{
var c = activeCharacters[i];
if (c.State.portraitImage != null)
{
if (LeanTween.isTweening(c.State.portraitImage.gameObject))
{
LeanTween.cancel(c.State.portraitImage.gameObject, true);
PortraitController.SetRectTransform(c.State.portraitImage.rectTransform, c.State.position);
if (c.State.dimmed == true)
{
c.State.portraitImage.color = new Color(0.5f, 0.5f, 0.5f, 1f);
}
else
{
c.State.portraitImage.color = Color.white;
}
}
}
}
}
/// <summary>
/// Sets the active state of the Say Dialog gameobject.
/// </summary>
public virtual void SetActive(bool state)
{
gameObject.SetActive(state);
}
/// <summary>
/// Sets the active speaking character.
/// </summary>
/// <param name="character">The active speaking character.</param>
public virtual void SetCharacter(Character character)
{
if (character == null)
{
if (characterImage != null)
{
characterImage.gameObject.SetActive(false);
}
if (NameText != null)
{
NameText = "";
}
speakingCharacter = null;
}
else
{
var prevSpeakingCharacter = speakingCharacter;
speakingCharacter = character;
// Dim portraits of non-speaking characters
var activeStages = Stage.ActiveStages;
for (int i = 0; i < activeStages.Count; i++)
{
var stage = activeStages[i];
if (stage.DimPortraits)
{
var charactersOnStage = stage.CharactersOnStage;
for (int j = 0; j < charactersOnStage.Count; j++)
{
var c = charactersOnStage[j];
if (prevSpeakingCharacter != speakingCharacter)
{
if (c != null && !c.Equals(speakingCharacter))
{
stage.SetDimmed(c, true);
}
else
{
stage.SetDimmed(c, false);
}
}
}
}
}
string characterName = character.NameText;
if (characterName == "")
{
// Use game object name as default
characterName = character.GetObjectName();
}
SetCharacterName(characterName, character.NameColor);
}
}
/// <summary>
/// Sets the character image to display on the Say Dialog.
/// </summary>
public virtual void SetCharacterImage(Sprite image)
{
if (characterImage == null)
{
return;
}
if (image != null)
{
characterImage.sprite = image;
characterImage.gameObject.SetActive(true);
currentCharacterImage = image;
}
else
{
characterImage.gameObject.SetActive(false);
if (startStoryTextWidth != 0)
{
StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth);
}
}
// Adjust story text box to not overlap image rect
if (fitTextWithImage &&
StoryText != null &&
characterImage.gameObject.activeSelf)
{
if (Mathf.Approximately(startStoryTextWidth, 0f))
{
startStoryTextWidth = StoryTextRectTrans.rect.width;
startStoryTextInset = StoryTextRectTrans.offsetMin.x;
}
// Clamp story text to left or right depending on relative position of the character image
if (StoryTextRectTrans.position.x < characterImage.rectTransform.position.x)
{
StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
else
{
StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
}
}
/// <summary>
/// Sets the character name to display on the Say Dialog.
/// Supports variable substitution e.g. John {$surname}
/// </summary>
public virtual void SetCharacterName(string name, Color color)
{
if (NameText != null)
{
var subbedName = stringSubstituter.SubstituteStrings(name);
NameText = subbedName;
nameTextAdapter.SetTextColor(color);
}
}
/// <summary>
/// Write a line of story text to the Say Dialog. Starts coroutine automatically.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual void Say(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, bool waitForVO, AudioClip voiceOverClip, Action onComplete)
{
StartCoroutine(DoSay(text, clearPrevious, waitForInput, fadeWhenDone, stopVoiceover, waitForVO, voiceOverClip, onComplete));
}
/// <summary>
/// Write a line of story text to the Say Dialog. Must be started as a coroutine.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual IEnumerator DoSay(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, bool waitForVO, AudioClip voiceOverClip, Action onComplete)
{
var writer = GetWriter();
if (writer.IsWriting || writer.IsWaitingForInput)
{
writer.Stop();
while (writer.IsWriting || writer.IsWaitingForInput)
{
yield return null;
}
}
if (closeOtherDialogs)
{
for (int i = 0; i < activeSayDialogs.Count; i++)
{
var sd = activeSayDialogs[i];
if (sd.gameObject != gameObject)
{
sd.SetActive(false);
}
}
}
gameObject.SetActive(true);
this.fadeWhenDone = fadeWhenDone;
// Voice over clip takes precedence over a character sound effect if provided
AudioClip soundEffectClip = null;
if (voiceOverClip != null)
{
WriterAudio writerAudio = GetWriterAudio();
writerAudio.OnVoiceover(voiceOverClip);
}
else if (speakingCharacter != null)
{
soundEffectClip = speakingCharacter.SoundEffect;
}
writer.AttachedWriterAudio = writerAudio;
yield return StartCoroutine(writer.Write(text, clearPrevious, waitForInput, stopVoiceover, waitForVO, soundEffectClip, onComplete));
}
/// <summary>
/// Tell the Say Dialog to fade out once writing and player input have finished.
/// </summary>
public virtual bool FadeWhenDone { get {return fadeWhenDone; } set { fadeWhenDone = value; } }
/// <summary>
/// Stop the Say Dialog while its writing text.
/// </summary>
public virtual void Stop()
{
fadeWhenDone = true;
GetWriter().Stop();
}
/// <summary>
/// Stops writing text and clears the Say Dialog.
/// </summary>
public virtual void Clear()
{
ClearStoryText();
// Kill any active write coroutine
StopAllCoroutines();
}
#endregion
}
}
| |
//---------------------------------------------------------------------------------------
// Copyright 2014 North Carolina State University
//
// Center for Educational Informatics
// http://www.cei.ncsu.edu/
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//---------------------------------------------------------------------------------------
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using IntelliMedia.Models;
namespace IntelliMedia.Utilities
{
/// <summary>
/// This provides static methods for recording trace data.
/// </summary>
public class TraceLog
{
public enum Action
{
/// <summary>
/// Denotes that an object that can be opened has been opened (e.g., Book,
/// GUI, ScanningDevice, door, or jar).
/// </summary>
Opened,
/// <summary>
/// Denotes that an object has been closed (e.g., Book, GUI, ScanningDevice,
/// door, or jar). The duration of how long the object was open will be logged.
/// </summary>
Closed,
/// <summary>
/// Denotes that something that has an on/off state has been turned on (e.g.,
/// AI agent, light switch)
/// </summary>
Enabled,
/// <summary>
/// Denotes that something that has been turned off (e.g.,
/// AI agent, light switch). The duration of how long the object was enabled
/// will be logged.
/// </summary>
Disabled,
/// <summary>
/// Denotes that an option from a list of 2 or more things has been chosen (e.g.,
/// scanning device setting, answer on concept matrix, or diagnosis worksheet
/// entry). NOTE: Prefer enabled/disable if the nature of the interaction is off/on.
/// </summary>
Selected,
/// <summary>
/// Denotes that an option from a list of 2 or more things has been un-chosen and
/// returned to the default state. (e.g., scanning device option, answer on
/// concept matrix, or diagnosis worksheet entry).
/// </summary>
Deselected,
/// <summary>
/// Indicates that a connection has been established (e.g., a network connection)
/// </summary>
ConnectedTo,
/// <summary>
/// A previously established connection has been disconnected. The duration of the
/// connection will be logged.
/// </summary>
DisconnectedFrom,
/// <summary>
/// Denote the start of general action or process. NOTE: Use
/// Open/Closed, Activated/Deactivated, or Selected/Deselected for
/// more specific actions.
/// </summary>
Started,
/// <summary>
/// Denote the end of general action that has a duration. Use
/// Open/Closed, Activated/Deactivated, or Selected/Deselected for
/// more specific actions.
/// </summary>
Ended,
/// <summary>
/// A long running action has been suspended.
/// </summary>
Paused,
/// <summary>
/// Something is shown or highlighted.
/// </summary>
Revealed,
/// <summary>
/// The player has moved to a new named location in the scene (e.g. Infirmary)
/// </summary>
Resumed,
/// <summary>
/// The player has moved to a new named location in the scene (e.g. Infirmary)
/// </summary>
MovedTo,
/// <summary>
/// The player has moved from a named location in the scene (e.g. Lab). The
/// duration at the location will be logged.
/// </summary>
MovedFrom,
/// <summary>
/// The actor has aquired an object and is now carrying it.
/// </summary>
PickedUp,
/// <summary>
/// The actor has released an object it was previously carrying.
/// </summary>
Dropped,
/// <summary>
/// Uses eye tracking to indicate that the player has looked at a 3D
/// object or GUI.
/// </summary>
LookedAt,
/// <summary>
/// Indicates when a player speaks to an NPC or an NPC speaks to a player.
/// This denotes face-to-face interaction.
/// </summary>
SpokeTo,
/// <summary>
/// Denotes that a one-shot activation has occurred. This is for logging actions
/// that are instantaneous and do not have state. (E.g., teleporting, indicating
/// a plot point has been achieved)
/// </summary>
Activated,
/// <summary>
/// Denotes that a sensor has been calibrated.
/// </summary>
Calibrated,
/// <summary>
/// This action is used to indicate that *content* has been 'viewed' by an actor.
/// However, whether the actor actually understood or read the content is unknown.
/// For example: text in virtual book or an assessment. NOTE: use Open/Closed to
/// indicate GUIs being displayed. This action should be used to indicate the
/// nature of information on the GUI or in the 3D world.
/// </summary>
ViewedContentOf,
/// <summary>
/// Indicates that a one-shot message has been sent or an indicator has been
/// displayed (e.g., message from a tutor, a message box)
/// </summary>
Alerted,
/// <summary>
/// Indicates that someting has had a one-shot check made. For example, grading
/// a player's answer to a question or an agent determining the next course of
/// action to take.
/// </summary>
Evaluated,
/// <summary>
/// Indicates that an actor has changed the state of an object. (e.g., the player
/// or NPC causes a state machine to transition to a new state).
/// </summary>
ChangedStateOf,
/// <summary>
/// A data sample has been recorded that is periodic in nature. For example,
/// biometric data such as eye tracking or GSR.
/// </summary>
Sampled,
/// <summary>
/// An action or task has been completed or finished.
/// </summary>
Completed,
/// <summary>
/// A player answer or response has been recorded
/// </summary>
Submitted,
}
public delegate void UpdateLogEntry(LogEntry entry);
public static string SessionId { get; private set; }
public static int SequenceNumber { get; private set; }
public static readonly List<ILogger> Loggers = new List<ILogger>();
public static readonly List<UpdateLogEntry> LogEntryModifiers = new List<UpdateLogEntry>();
public static void Open(string sessionId, params ILogger[] initialLoggers)
{
SessionId = sessionId;
SequenceNumber = 0;
Loggers.AddRange(initialLoggers);
}
public static void SetLoggerEnabled<T>(bool enabled) where T : ILogger
{
foreach (ILogger logger in TraceLog.Loggers)
{
if (logger is T)
{
logger.Enabled = enabled;
}
}
}
public static void Close(LoggerCloseCallback callback)
{
try
{
ILogger[] loggersToClose = Loggers.ToArray();
Loggers.Clear();
CallbackAccumulator accumulator = new CallbackAccumulator(loggersToClose.Length, callback);
foreach (ILogger logger in loggersToClose)
{
logger.Close(accumulator.Callback);
}
}
catch(Exception e)
{
callback(false, string.Format("Failed to close all trace logs. {0}", e.Message));
}
}
private class CallbackAccumulator
{
private readonly object syncLock = new object();
private int CallbacksExpected;
private LoggerCloseCallback CloseCallback { get; set; }
private StringBuilder ErrorMsg { get; set; }
public CallbackAccumulator(int callbacksExpected, LoggerCloseCallback callback)
{
Contract.Argument("Must be expecting at least one callback", "callbacksExpected", callbacksExpected > 0);
Contract.ArgumentNotNull("callback", callback);
ErrorMsg = new StringBuilder();
CallbacksExpected = callbacksExpected;
CloseCallback = callback;
}
public void Callback(bool success, string error)
{
lock(syncLock)
{
--CallbacksExpected;
if (error != null)
{
ErrorMsg.AppendFormat("{0}. ", error);
}
}
if (CallbacksExpected < 1)
{
bool allSuccess = ErrorMsg.Length == 0;
CloseCallback(allSuccess, (allSuccess ? null : ErrorMsg.ToString()));
}
}
}
public static LogEntry Player(Action action, string target, params object[] attributes)
{
return Write("Player", action, target, attributes);
}
public static LogEntry Player(LogEntry startEntry, Action action, string target, params object[] attributes)
{
return Write(startEntry, "Player", action, target, attributes);
}
public static LogEntry Write(string actor, Action action, string target, params object[] attributes)
{
return Write(action,
"Actor", actor,
"Target", target,
attributes);
}
public static LogEntry Write(LogEntry startEntry, string actor, Action action, string target, params object[] attributes)
{
if (startEntry != null)
{
return Write(action,
"Actor", actor,
"Target", target,
"Duration", (DateTime.Now - startEntry.TimeStamp).TotalSeconds,
attributes);
}
else
{
return Write(action,
"Actor", actor,
"Target", target,
attributes);
}
}
public static LogEntry Write(Action action, params object[] attributes)
{
LogEntry entry = new LogEntry(SessionId, SequenceNumber++, action.ToString(), attributes);
foreach (UpdateLogEntry modifier in LogEntryModifiers)
{
modifier(entry);
}
foreach (ILogger logger in Loggers)
{
logger.Write(entry);
}
return entry;
}
}
}
| |
#region Header
/*
* JsonMapper.cs
* JSON to .Net object and object to JSON conversions.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
if (reader.Token == JsonToken.Null) {
if (! inst_type.IsClass)
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
return null;
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
if (inst_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
custom_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
base_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (inst_type.IsEnum)
return Enum.ToObject (inst_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (inst_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (inst_type);
ObjectMetadata t_data = object_metadata[inst_type];
instance = Activator.CreateInstance (inst_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary)
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'", inst_type, property));
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
switch (reader.Token)
{
case JsonToken.String:
instance.SetString ((string) reader.Value);
break;
case JsonToken.Double:
instance.SetDouble ((double) reader.Value);
break;
case JsonToken.Int:
instance.SetInt ((int) reader.Value);
break;
case JsonToken.Long:
instance.SetLong ((long) reader.Value);
break;
case JsonToken.Boolean:
instance.SetBoolean ((bool) reader.Value);
break;
case JsonToken.ArrayStart:
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
break;
case JsonToken.ObjectStart:
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
break;
}
return instance;
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Internal;
using Orleans.Networking.Shared;
using Orleans.Runtime;
using Orleans.Runtime.Messaging;
using Orleans.Timers.Internal;
namespace Orleans.TestingHost.InMemoryTransport;
internal static class InMemoryTransportExtensions
{
public static ISiloBuilder UseInMemoryConnectionTransport(this ISiloBuilder siloBuilder, InMemoryTransportConnectionHub hub)
{
siloBuilder.ConfigureServices(services =>
{
services.AddSingletonKeyedService<object, IConnectionFactory>(SiloConnectionFactory.ServicesKey, CreateInMemoryConnectionFactory(hub));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(SiloConnectionListener.ServicesKey, CreateInMemoryConnectionListenerFactory(hub));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(GatewayConnectionListener.ServicesKey, CreateInMemoryConnectionListenerFactory(hub));
});
return siloBuilder;
}
public static IClientBuilder UseInMemoryConnectionTransport(this IClientBuilder clientBuilder, InMemoryTransportConnectionHub hub)
{
clientBuilder.ConfigureServices(services =>
{
services.AddSingletonKeyedService<object, IConnectionFactory>(ClientOutboundConnectionFactory.ServicesKey, CreateInMemoryConnectionFactory(hub));
});
return clientBuilder;
}
private static Func<IServiceProvider, object, IConnectionFactory> CreateInMemoryConnectionFactory(InMemoryTransportConnectionHub hub)
{
return (IServiceProvider sp, object key) =>
{
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
var sharedMemoryPool = sp.GetRequiredService<SharedMemoryPool>();
return new InMemoryTransportConnectionFactory(hub, loggerFactory, sharedMemoryPool);
};
}
private static Func<IServiceProvider, object, IConnectionListenerFactory> CreateInMemoryConnectionListenerFactory(InMemoryTransportConnectionHub hub)
{
return (IServiceProvider sp, object key) =>
{
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
var sharedMemoryPool = sp.GetRequiredService<SharedMemoryPool>();
return new InMemoryTransportListener(hub, loggerFactory, sharedMemoryPool);
};
}
}
internal class InMemoryTransportListener : IConnectionListenerFactory, IConnectionListener
{
private readonly Channel<(InMemoryTransportConnection Connection, TaskCompletionSource<bool> ConnectionAcceptedTcs)> _acceptQueue = Channel.CreateUnbounded<(InMemoryTransportConnection, TaskCompletionSource<bool>)>();
private readonly InMemoryTransportConnectionHub _hub;
private readonly ILoggerFactory _loggerFactory;
private readonly SharedMemoryPool _memoryPool;
private readonly CancellationTokenSource _disposedCts = new();
public InMemoryTransportListener(InMemoryTransportConnectionHub hub, ILoggerFactory loggerFactory, SharedMemoryPool memoryPool)
{
_hub = hub;
_loggerFactory = loggerFactory;
_memoryPool = memoryPool;
}
public CancellationToken OnDisposed => _disposedCts.Token;
public EndPoint EndPoint { get; set; }
public async Task ConnectAsync(InMemoryTransportConnection connection)
{
var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
if (_acceptQueue.Writer.TryWrite((connection, completion)))
{
var connected = await completion.Task;
if (connected)
{
return;
}
}
throw new ConnectionFailedException($"Unable to connect to {EndPoint} because its listener has terminated.");
}
public async ValueTask<ConnectionContext> AcceptAsync(CancellationToken cancellationToken = default)
{
if (await _acceptQueue.Reader.WaitToReadAsync(cancellationToken))
{
while (_acceptQueue.Reader.TryRead(out var item))
{
var remoteConnectionContext = item.Connection;
var localConnectionContext = InMemoryTransportConnection.Create(
_memoryPool.Pool,
_loggerFactory.CreateLogger<InMemoryTransportConnection>(),
other: remoteConnectionContext,
localEndPoint: EndPoint);
// Set the result to true to indicate that the connection was accepted.
item.ConnectionAcceptedTcs.TrySetResult(true);
return localConnectionContext;
}
}
return null;
}
public ValueTask<IConnectionListener> BindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
{
EndPoint = endpoint;
_hub.RegisterConnectionListenerFactory(endpoint, this);
return new ValueTask<IConnectionListener>(this);
}
public ValueTask DisposeAsync()
{
return UnbindAsync(default);
}
public ValueTask UnbindAsync(CancellationToken cancellationToken = default)
{
_acceptQueue.Writer.TryComplete();
while (_acceptQueue.Reader.TryRead(out var item))
{
// Set the result to false to indicate that the listener has terminated.
item.ConnectionAcceptedTcs.TrySetResult(false);
}
_disposedCts.Cancel();
return default;
}
}
internal class InMemoryTransportConnectionHub
{
private readonly ConcurrentDictionary<EndPoint, InMemoryTransportListener> _listeners = new();
public static InMemoryTransportConnectionHub Instance { get; } = new();
public void RegisterConnectionListenerFactory(EndPoint endPoint, InMemoryTransportListener listener)
{
_listeners[endPoint] = listener;
listener.OnDisposed.Register(() =>
{
((IDictionary<EndPoint, InMemoryTransportListener>)_listeners).Remove(new KeyValuePair<EndPoint, InMemoryTransportListener>(endPoint, listener));
});
}
public InMemoryTransportListener GetConnectionListenerFactory(EndPoint endPoint)
{
_listeners.TryGetValue(endPoint, out var listener);
return listener;
}
}
internal class InMemoryTransportConnectionFactory : IConnectionFactory
{
private readonly InMemoryTransportConnectionHub _hub;
private readonly ILoggerFactory _loggerFactory;
private readonly SharedMemoryPool _memoryPool;
private readonly IPEndPoint _localEndpoint;
public InMemoryTransportConnectionFactory(InMemoryTransportConnectionHub hub, ILoggerFactory loggerFactory, SharedMemoryPool memoryPool)
{
_hub = hub;
_loggerFactory = loggerFactory;
_memoryPool = memoryPool;
_localEndpoint = new IPEndPoint(IPAddress.Loopback, ThreadSafeRandom.Next(1024, ushort.MaxValue - 1024));
}
public async ValueTask<ConnectionContext> ConnectAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
{
var listener = _hub.GetConnectionListenerFactory(endpoint);
if (listener is null)
{
throw new ConnectionFailedException($"Unable to connect to endpoint {endpoint} because no such endpoint is currently registered.");
}
var connectionContext = InMemoryTransportConnection.Create(
_memoryPool.Pool,
_loggerFactory.CreateLogger<InMemoryTransportConnection>(),
_localEndpoint,
endpoint);
await listener.ConnectAsync(connectionContext).WithCancellation(cancellationToken);
return connectionContext;
}
}
| |
// 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.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.Isam.Esent;
using Microsoft.Isam.Esent.Interop;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Esent
{
internal partial class EsentPersistentStorage : AbstractPersistentStorage
{
private const string StorageExtension = "vbcs.cache";
private const string PersistentStorageFileName = "storage.ide";
// cache delegates so that we don't re-create it every times
private readonly Func<int, object, object, object, CancellationToken, Stream> _readStreamSolution;
private readonly Func<EsentStorage.Key, int, object, object, CancellationToken, Stream> _readStream;
private readonly Func<int, Stream, object, object, CancellationToken, bool> _writeStreamSolution;
private readonly Func<EsentStorage.Key, int, Stream, object, CancellationToken, bool> _writeStream;
private readonly ConcurrentDictionary<string, int> _nameTableCache;
private readonly EsentStorage _esentStorage;
public EsentPersistentStorage(
IOptionService optionService, string workingFolderPath, string solutionFilePath, Action<AbstractPersistentStorage> disposer) :
base(optionService, workingFolderPath, solutionFilePath, disposer)
{
// cache delegates
_readStreamSolution = ReadStreamSolution;
_readStream = ReadStream;
_writeStreamSolution = WriteStreamSolution;
_writeStream = WriteStream;
// solution must exist in disk. otherwise, we shouldn't be here at all.
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(solutionFilePath));
var databaseFile = GetDatabaseFile(workingFolderPath);
this.EsentDirectory = Path.GetDirectoryName(databaseFile);
if (!Directory.Exists(this.EsentDirectory))
{
Directory.CreateDirectory(this.EsentDirectory);
}
_nameTableCache = new ConcurrentDictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var enablePerformanceMonitor = optionService.GetOption(PersistentStorageOptions.EsentPerformanceMonitor);
_esentStorage = new EsentStorage(databaseFile, enablePerformanceMonitor);
}
public static string GetDatabaseFile(string workingFolderPath)
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(workingFolderPath));
return Path.Combine(workingFolderPath, StorageExtension, PersistentStorageFileName);
}
public void Initialize()
{
_esentStorage.Initialize();
}
public string EsentDirectory { get; }
public override Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
if (!TryGetProjectAndDocumentKey(document, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(key, nameId, _readStream, cancellationToken);
return SpecializedTasks.DefaultOrResult(stream);
}
public override Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
if (!TryGetProjectKey(project, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(key, nameId, _readStream, cancellationToken);
return SpecializedTasks.DefaultOrResult(stream);
}
public override Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
if (!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(nameId, _readStreamSolution, cancellationToken);
return SpecializedTasks.DefaultOrResult(stream);
}
private Stream ReadStream(EsentStorage.Key key, int nameId, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = GetAccessor(key))
using (var esentStream = accessor.GetReadStream(key, nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
private Stream ReadStreamSolution(int nameId, object unused1, object unused2, object unused3, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetReadStream(nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
public override Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
if (!TryGetProjectAndDocumentKey(document, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(key, nameId, stream, _writeStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
public override Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
if (!TryGetProjectKey(project, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(key, nameId, stream, _writeStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
public override Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
if (!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(nameId, stream, _writeStreamSolution, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
private bool WriteStream(EsentStorage.Key key, int nameId, Stream stream, object unused1, CancellationToken cancellationToken)
{
using (var accessor = GetAccessor(key))
using (var esentStream = accessor.GetWriteStream(key, nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
private bool WriteStreamSolution(int nameId, Stream stream, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetWriteStream(nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
public override void Close()
{
_esentStorage.Close();
}
private bool TryGetUniqueNameId(string name, out int id)
{
return TryGetUniqueId(name, false, out id);
}
private bool TryGetUniqueFileId(string path, out int id)
{
return TryGetUniqueId(path, true, out id);
}
private bool TryGetUniqueId(string value, bool fileCheck, out int id)
{
id = default(int);
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
// if we already know, get the id
if (_nameTableCache.TryGetValue(value, out id))
{
return true;
}
// we only persist for things that actually exist
if (fileCheck && !File.Exists(value))
{
return false;
}
try
{
var uniqueIdValue = fileCheck ? PathUtilities.GetRelativePath(Path.GetDirectoryName(SolutionFilePath), value) : value;
id = _nameTableCache.GetOrAdd(value, _esentStorage.GetUniqueId(uniqueIdValue));
return true;
}
catch (Exception ex)
{
// if we get fatal errors from esent such as disk out of space or log file corrupted by other process and etc
// don't crash VS, but let VS know it can't use esent. we will gracefully recover issue by using memory.
EsentLogger.LogException(ex);
return false;
}
}
private static void WriteToStream(Stream inputStream, Stream esentStream, CancellationToken cancellationToken)
{
var buffer = SharedPools.ByteArray.Allocate();
try
{
int bytesRead;
do
{
cancellationToken.ThrowIfCancellationRequested();
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
esentStream.Write(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);
// flush the data and trim column size of necessary
esentStream.Flush();
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
private EsentStorage.ProjectDocumentTableAccessor GetAccessor(EsentStorage.Key key)
{
return key.DocumentIdOpt.HasValue ?
_esentStorage.GetDocumentTableAccessor() :
(EsentStorage.ProjectDocumentTableAccessor)_esentStorage.GetProjectTableAccessor();
}
private bool TryGetProjectAndDocumentKey(Document document, out EsentStorage.Key key)
{
key = default(EsentStorage.Key);
if (!TryGetProjectId(document.Project, out var projectId, out var projectNameId) ||
!TryGetUniqueFileId(document.FilePath, out var documentId))
{
return false;
}
key = new EsentStorage.Key(projectId, projectNameId, documentId);
return true;
}
private bool TryGetProjectKey(Project project, out EsentStorage.Key key)
{
key = default(EsentStorage.Key);
if (!TryGetProjectId(project, out var projectId, out var projectNameId))
{
return false;
}
key = new EsentStorage.Key(projectId, projectNameId);
return true;
}
private bool TryGetProjectId(Project project, out int projectId, out int projectNameId)
{
projectId = default(int);
projectNameId = default(int);
return TryGetUniqueFileId(project.FilePath, out projectId) && TryGetUniqueNameId(project.Name, out projectNameId);
}
private TResult EsentExceptionWrapper<TArg1, TResult>(TArg1 arg1, Func<TArg1, object, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TResult>(
TArg1 arg1, TArg2 arg2, Func<TArg1, TArg2, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, Func<TArg1, TArg2, TArg3, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, arg3, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TArg4, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, Func<TArg1, TArg2, TArg3, TArg4, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
try
{
return func(arg1, arg2, arg3, arg4, cancellationToken);
}
catch (EsentInvalidSesidException)
{
// operation was in-fly when Esent instance was shutdown - ignore the error
}
catch (OperationCanceledException)
{
}
catch (EsentException ex)
{
if (!_esentStorage.IsClosed)
{
// ignore esent exception if underlying storage was closed
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Esent Failed : " + ex.Message);
}
}
catch (Exception ex)
{
// ignore exception
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Failed : " + ex.Message);
}
return default(TResult);
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
// [Overview] http://blogs.msdn.com/b/endpoint/archive/2010/03/24/windows-server-appfabric-architecture.aspx
// [Architecture] http://msdn.microsoft.com/en-us/library/ee677374.aspx
// http://msdn.microsoft.com/en-us/windowsserver/ee695849
using System;
using System.Linq;
using System.Abstract;
using Microsoft.ApplicationServer.Caching;
using System.Collections.Generic;
namespace Microsoft.ApplicationServer.Caching.Abstract
{
/// <summary>
/// IServerAppFabricServiceCache
/// </summary>
public interface IServerAppFabricServiceCache : IDistributedServiceCache
{
/// <summary>
/// Gets the cache.
/// </summary>
DataCache Cache { get; }
//
/// <summary>
/// Gets the and lock.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="lockHandle">The lock handle.</param>
/// <returns></returns>
object GetAndLock(string name, TimeSpan timeout, out DataCacheLockHandle lockHandle);
/// <summary>
/// Gets the and lock.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="lockHandle">The lock handle.</param>
/// <param name="forceLock">if set to <c>true</c> [force lock].</param>
/// <returns></returns>
object GetAndLock(string name, TimeSpan timeout, out DataCacheLockHandle lockHandle, bool forceLock);
/// <summary>
/// Unlocks the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="lockHandle">The lock handle.</param>
void Unlock(string name, DataCacheLockHandle lockHandle);
/// <summary>
/// Unlocks the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="lockHandle">The lock handle.</param>
/// <param name="timeout">The timeout.</param>
void Unlock(string name, DataCacheLockHandle lockHandle, TimeSpan timeout);
}
/// <summary>
/// ServerAppFabricServiceCache
/// </summary>
public class ServerAppFabricServiceCache : IServerAppFabricServiceCache, ServiceCacheManager.ISetupRegistration
{
/// <summary>
/// DefaultDataCacheFactory
/// </summary>
public static readonly DataCacheFactory DefaultCacheFactory = new DataCacheFactory();
static ServerAppFabricServiceCache() { ServiceCacheManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="ServerAppFabricServiceCache" /> class.
/// </summary>
public ServerAppFabricServiceCache()
: this(DefaultCacheFactory) { }
/// <summary>
/// Initializes a new instance of the <see cref="ServerAppFabricServiceCache" /> class.
/// </summary>
/// <param name="cacheName">Name of the cache.</param>
public ServerAppFabricServiceCache(string cacheName)
: this(DefaultCacheFactory, cacheName) { }
/// <summary>
/// Initializes a new instance of the <see cref="ServerAppFabricServiceCache" /> class.
/// </summary>
/// <param name="cache">The cache (DataCache or DataCacheFactory or DataCacheFactoryConfiguration).</param>
/// <param name="cacheName">Name of the cache.</param>
/// <exception cref="System.ArgumentNullException">cache</exception>
/// <exception cref="System.ArgumentOutOfRangeException">cache;Must be of type DataCache, DataCacheFactoryConfiguration or DataCacheFactory.</exception>
public ServerAppFabricServiceCache(object cache, string cacheName = null)
{
if (cache == null)
throw new ArgumentNullException("cache");
if (cache is DataCache)
Cache = (DataCache)cache;
else if (cache is DataCacheFactoryConfiguration)
{
CacheFactory = new DataCacheFactory((DataCacheFactoryConfiguration)cache);
Cache = (cacheName != null ? CacheFactory.GetCache(cacheName) : CacheFactory.GetDefaultCache());
}
else
throw new ArgumentOutOfRangeException("cache", "Must be of type DataCache, DataCacheFactoryConfiguration or DataCacheFactory.");
Settings = new ServiceCacheSettings(new DefaultTouchableCacheItem(this, null));
}
Action<IServiceLocator, string> ServiceCacheManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceCacheManager.RegisterInstance<IServerAppFabricServiceCache>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType" />.
/// -or-
/// null if there is no service object of type <paramref name="serviceType" />.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
/// <summary>
/// Gets or sets the <see cref="System.Object" /> with the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public object this[string name]
{
get { return Get(null, name); }
set { Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); }
}
/// <summary>
/// Adds the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The item policy.</param>
/// <param name="value">The value.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">itemPolicy</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// itemPolicy.SlidingExpiration;not supported.
/// or
/// itemPolicy.RemovedCallback;not supported.
/// </exception>
public object Add(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
//
if (itemPolicy.SlidingExpiration != ServiceCache.NoSlidingExpiration)
throw new ArgumentOutOfRangeException("itemPolicy.SlidingExpiration", "not supported.");
if (itemPolicy.RemovedCallback != null)
throw new ArgumentOutOfRangeException("itemPolicy.RemovedCallback", "not supported.");
//
var dataCacheTags = GetCacheDependency(tag, itemPolicy.Dependency, dispatch);
var timeout = GetTimeout(itemPolicy.AbsoluteExpiration);
string regionName;
if (timeout == TimeSpan.Zero && dataCacheTags == null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Add(name, value);
else Cache.Add(name, value, regionName);
}
else if (timeout != TimeSpan.Zero && dataCacheTags == null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Add(name, value, timeout);
else Cache.Add(name, value, timeout, regionName);
}
else if (timeout == TimeSpan.Zero && dataCacheTags != null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Add(name, value, dataCacheTags);
else Cache.Add(name, value, dataCacheTags, regionName);
}
else
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Add(name, value, timeout, dataCacheTags);
else Cache.Add(name, value, timeout, dataCacheTags, regionName);
}
//
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var header = dispatch.Header;
header.Item = name;
Add(tag, name + "#", CacheItemPolicy.Default, header, ServiceCacheByDispatcher.Empty);
}
return value;
}
/// <summary>
/// Gets the item from cache associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <returns>
/// The cached item.
/// </returns>
public object Get(object tag, string name)
{
var version = (tag as DataCacheItemVersion);
string regionName;
if (version == null)
return (!Settings.TryGetRegion(ref name, out regionName) ? Cache.Get(name) : Cache.Get(name, regionName));
return (!Settings.TryGetRegion(ref name, out regionName) ? Cache.GetIfNewer(name, ref version) : Cache.GetIfNewer(name, ref version, regionName));
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <param name="header">The header.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">registration</exception>
public object Get(object tag, string name, IServiceCacheRegistration registration, out CacheItemHeader header)
{
if (registration == null)
throw new ArgumentNullException("registration");
var version = (tag as DataCacheItemVersion);
string regionName;
if (!registration.UseHeaders)
header = null;
else if (version == null)
header = (CacheItemHeader)(!Settings.TryGetRegion(ref name, out regionName) ? Cache.Get(name + "#") : Cache.Get(name + "#", regionName));
else
header = (CacheItemHeader)(!Settings.TryGetRegion(ref name, out regionName) ? Cache.GetIfNewer(name + "#", ref version) : Cache.GetIfNewer(name + "#", ref version, regionName));
if (version == null)
return (!Settings.TryGetRegion(ref name, out regionName) ? Cache.Get(name) : Cache.Get(name, regionName));
return (!Settings.TryGetRegion(ref name, out regionName) ? Cache.GetIfNewer(name, ref version) : Cache.GetIfNewer(name, ref version, regionName));
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">names</exception>
public object Get(object tag, IEnumerable<string> names)
{
if (names == null)
throw new ArgumentNullException("names");
return names.Select(name => new { name, value = Get(null, name) }).ToDictionary(x => x.name, x => x.value);
}
/// <summary>
/// Gets the specified registration.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="registration">The registration.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">registration</exception>
/// <exception cref="System.NotImplementedException"></exception>
public IEnumerable<CacheItemHeader> Get(object tag, IServiceCacheRegistration registration)
{
if (registration == null)
throw new ArgumentNullException("registration");
throw new NotImplementedException();
}
/// <summary>
/// Tries the get.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <exception cref="System.NotSupportedException"></exception>
public bool TryGet(object tag, string name, out object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Adds an object into cache based on the parameters provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The itemPolicy object.</param>
/// <param name="value">The value to store in cache.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">itemPolicy</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// itemPolicy.SlidingExpiration;not supported.
/// or
/// itemPolicy.RemovedCallback;not supported.
/// </exception>
public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
//
if (itemPolicy.SlidingExpiration != ServiceCache.NoSlidingExpiration)
throw new ArgumentOutOfRangeException("itemPolicy.SlidingExpiration", "not supported.");
if (itemPolicy.RemovedCallback != null)
throw new ArgumentOutOfRangeException("itemPolicy.RemovedCallback", "not supported.");
//
var oldVersion = (tag as DataCacheItemVersion);
var lockHandle = (tag as DataCacheLockHandle);
var dataCacheTags = GetCacheDependency(tag, itemPolicy.Dependency, dispatch);
var timeout = GetTimeout(itemPolicy.AbsoluteExpiration);
string regionName;
if (timeout == TimeSpan.Zero && dataCacheTags == null)
if (oldVersion == null && lockHandle == null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value);
else Cache.Put(name, value, regionName);
}
else if (oldVersion != null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value, oldVersion);
else Cache.Put(name, value, oldVersion, regionName);
}
else
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.PutAndUnlock(name, value, lockHandle);
else Cache.PutAndUnlock(name, value, lockHandle, regionName);
}
else if (timeout != TimeSpan.Zero && dataCacheTags == null)
if ((oldVersion == null) && (lockHandle == null))
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value, timeout);
else Cache.Put(name, value, timeout, regionName);
}
else if (oldVersion != null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value, oldVersion, timeout);
else Cache.Put(name, value, oldVersion, timeout, regionName);
}
else
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.PutAndUnlock(name, value, lockHandle, timeout);
else Cache.PutAndUnlock(name, value, lockHandle, timeout, regionName);
}
else if (timeout == TimeSpan.Zero && dataCacheTags != null)
if ((oldVersion == null) && (lockHandle == null))
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value, dataCacheTags);
else Cache.Put(name, value, dataCacheTags, regionName);
}
else if (oldVersion != null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value, oldVersion, dataCacheTags);
else Cache.Put(name, value, oldVersion, dataCacheTags, regionName);
}
else
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.PutAndUnlock(name, value, lockHandle, dataCacheTags);
else Cache.PutAndUnlock(name, value, lockHandle, dataCacheTags, regionName);
}
else
if (oldVersion == null && lockHandle == null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value, timeout, dataCacheTags);
else Cache.Put(name, value, timeout, dataCacheTags, regionName);
}
else if (oldVersion != null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Put(name, value, oldVersion, timeout, dataCacheTags);
else Cache.Put(name, value, oldVersion, timeout, dataCacheTags, regionName);
}
else
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.PutAndUnlock(name, value, lockHandle, timeout, dataCacheTags);
else Cache.PutAndUnlock(name, value, lockHandle, timeout, dataCacheTags, regionName);
}
//
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var header = dispatch.Header;
header.Item = name;
Add(tag, name + "#", CacheItemPolicy.Default, header, ServiceCacheByDispatcher.Empty);
}
return value;
}
/// <summary>
/// Removes from cache the item associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <returns>
/// The item removed from the Cache. If the value in the key parameter is not found, returns null.
/// </returns>
public object Remove(object tag, string name, IServiceCacheRegistration registration)
{
if (registration != null && registration.UseHeaders)
Remove(tag, name + "#", null);
string regionName;
var value = ((Settings.Options & ServiceCacheOptions.ReturnsCachedValueOnRemove) == 0 ? null : (!Settings.TryGetRegion(ref name, out regionName) ? Cache.Get(name) : Cache.Get(name, regionName)));
//
var version = (tag as DataCacheItemVersion);
var lockHandle = (tag as DataCacheLockHandle);
if (version == null && lockHandle == null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Remove(name);
else Cache.Remove(name, regionName);
}
else if (version != null)
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Remove(name, version);
else Cache.Remove(name, version, regionName);
}
else
{
if (!Settings.TryGetRegion(ref name, out regionName)) Cache.Remove(name, lockHandle);
else Cache.Remove(name, lockHandle, regionName);
}
return value;
}
/// <summary>
/// Settings
/// </summary>
public ServiceCacheSettings Settings { get; private set; }
#region TouchableCacheItem
/// <summary>
/// DefaultTouchableCacheItem
/// </summary>
public class DefaultTouchableCacheItem : ITouchableCacheItem
{
private ServerAppFabricServiceCache _parent;
private ITouchableCacheItem _base;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTouchableCacheItem" /> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="base">The @base.</param>
public DefaultTouchableCacheItem(ServerAppFabricServiceCache parent, ITouchableCacheItem @base) { _parent = parent; _base = @base; }
/// <summary>
/// Touches the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
public void Touch(object tag, string[] names)
{
if (names == null || names.Length == 0)
return;
throw new NotSupportedException();
}
/// <summary>
/// Makes the dependency.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
public object MakeDependency(object tag, string[] names)
{
if (names == null || names.Length == 0)
return null;
var dataCacheTags = names.Select(x => new DataCacheTag(x));
return (_base == null ? dataCacheTags : dataCacheTags.Union(_base.MakeDependency(tag, names) as IEnumerable<DataCacheTag>));
}
}
#endregion
#region Domain-specific
/// <summary>
/// Gets the cache factory.
/// </summary>
/// <value>
/// The cache factory.
/// </value>
public DataCacheFactory CacheFactory { get; private set; }
/// <summary>
/// Gets the cache.
/// </summary>
public DataCache Cache { get; private set; }
/// <summary>
/// Gets the and lock.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="lockHandle">The lock handle.</param>
/// <returns></returns>
public object GetAndLock(string name, TimeSpan timeout, out DataCacheLockHandle lockHandle)
{
string region;
return (!Settings.TryGetRegion(ref name, out region) ? Cache.GetAndLock(name, timeout, out lockHandle) : Cache.GetAndLock(name, timeout, out lockHandle, region));
}
/// <summary>
/// Gets the and lock.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="lockHandle">The lock handle.</param>
/// <param name="forceLock">if set to <c>true</c> [force lock].</param>
/// <returns></returns>
public object GetAndLock(string name, TimeSpan timeout, out DataCacheLockHandle lockHandle, bool forceLock)
{
string region;
return (!Settings.TryGetRegion(ref name, out region) ? Cache.GetAndLock(name, timeout, out lockHandle, forceLock) : Cache.GetAndLock(name, timeout, out lockHandle, region, forceLock));
}
/// <summary>
/// Unlocks the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="lockHandle">The lock handle.</param>
public void Unlock(string name, DataCacheLockHandle lockHandle)
{
string region;
if (!Settings.TryGetRegion(ref name, out region)) Cache.Unlock(name, lockHandle);
else Cache.Unlock(name, lockHandle);
}
/// <summary>
/// Unlocks the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="lockHandle">The lock handle.</param>
/// <param name="timeout">The timeout.</param>
public void Unlock(string name, DataCacheLockHandle lockHandle, TimeSpan timeout)
{
string region;
if (!Settings.TryGetRegion(ref name, out region)) Cache.Unlock(name, lockHandle, timeout);
else Cache.Unlock(name, lockHandle, timeout);
}
#endregion
private IEnumerable<DataCacheTag> GetCacheDependency(object tag, CacheItemDependency dependency, ServiceCacheByDispatcher dispatch)
{
object value;
if (dependency == null || (value = dependency(this, dispatch.Registration, tag, dispatch.Values)) == null)
return null;
//
var names = (value as string[]);
var touchable = Settings.Touchable;
return ((touchable != null && names != null ? touchable.MakeDependency(tag, names) : value) as IEnumerable<DataCacheTag>);
}
private static TimeSpan GetTimeout(DateTime absoluteExpiration) { return (absoluteExpiration == ServiceCache.InfiniteAbsoluteExpiration ? TimeSpan.Zero : absoluteExpiration - DateTime.Now); }
/// <summary>
/// Gets the headers.
/// </summary>
/// <param name="registration">The registration.</param>
/// <returns></returns>
public IEnumerable<object> GetHeaders(ServiceCacheRegistration registration)
{
return null;
}
}
}
| |
// 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 gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedConversionUploadServiceClientTest
{
[Category("Autogenerated")][Test]
public void UploadClickConversionsRequestObject()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadClickConversionsRequest request = new UploadClickConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new ClickConversion(),
},
PartialFailure = false,
ValidateOnly = true,
};
UploadClickConversionsResponse expectedResponse = new UploadClickConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new ClickConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadClickConversions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadClickConversionsResponse response = client.UploadClickConversions(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task UploadClickConversionsRequestObjectAsync()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadClickConversionsRequest request = new UploadClickConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new ClickConversion(),
},
PartialFailure = false,
ValidateOnly = true,
};
UploadClickConversionsResponse expectedResponse = new UploadClickConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new ClickConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadClickConversionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UploadClickConversionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadClickConversionsResponse responseCallSettings = await client.UploadClickConversionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
UploadClickConversionsResponse responseCancellationToken = await client.UploadClickConversionsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void UploadClickConversions()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadClickConversionsRequest request = new UploadClickConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new ClickConversion(),
},
PartialFailure = false,
};
UploadClickConversionsResponse expectedResponse = new UploadClickConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new ClickConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadClickConversions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadClickConversionsResponse response = client.UploadClickConversions(request.CustomerId, request.Conversions, request.PartialFailure);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task UploadClickConversionsAsync()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadClickConversionsRequest request = new UploadClickConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new ClickConversion(),
},
PartialFailure = false,
};
UploadClickConversionsResponse expectedResponse = new UploadClickConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new ClickConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadClickConversionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UploadClickConversionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadClickConversionsResponse responseCallSettings = await client.UploadClickConversionsAsync(request.CustomerId, request.Conversions, request.PartialFailure, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
UploadClickConversionsResponse responseCancellationToken = await client.UploadClickConversionsAsync(request.CustomerId, request.Conversions, request.PartialFailure, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void UploadCallConversionsRequestObject()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadCallConversionsRequest request = new UploadCallConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new CallConversion(),
},
PartialFailure = false,
ValidateOnly = true,
};
UploadCallConversionsResponse expectedResponse = new UploadCallConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new CallConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadCallConversions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadCallConversionsResponse response = client.UploadCallConversions(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task UploadCallConversionsRequestObjectAsync()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadCallConversionsRequest request = new UploadCallConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new CallConversion(),
},
PartialFailure = false,
ValidateOnly = true,
};
UploadCallConversionsResponse expectedResponse = new UploadCallConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new CallConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadCallConversionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UploadCallConversionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadCallConversionsResponse responseCallSettings = await client.UploadCallConversionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
UploadCallConversionsResponse responseCancellationToken = await client.UploadCallConversionsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void UploadCallConversions()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadCallConversionsRequest request = new UploadCallConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new CallConversion(),
},
PartialFailure = false,
};
UploadCallConversionsResponse expectedResponse = new UploadCallConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new CallConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadCallConversions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadCallConversionsResponse response = client.UploadCallConversions(request.CustomerId, request.Conversions, request.PartialFailure);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task UploadCallConversionsAsync()
{
moq::Mock<ConversionUploadService.ConversionUploadServiceClient> mockGrpcClient = new moq::Mock<ConversionUploadService.ConversionUploadServiceClient>(moq::MockBehavior.Strict);
UploadCallConversionsRequest request = new UploadCallConversionsRequest
{
CustomerId = "customer_id3b3724cb",
Conversions =
{
new CallConversion(),
},
PartialFailure = false,
};
UploadCallConversionsResponse expectedResponse = new UploadCallConversionsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new CallConversionResult(),
},
};
mockGrpcClient.Setup(x => x.UploadCallConversionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UploadCallConversionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionUploadServiceClient client = new ConversionUploadServiceClientImpl(mockGrpcClient.Object, null);
UploadCallConversionsResponse responseCallSettings = await client.UploadCallConversionsAsync(request.CustomerId, request.Conversions, request.PartialFailure, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
UploadCallConversionsResponse responseCancellationToken = await client.UploadCallConversionsAsync(request.CustomerId, request.Conversions, request.PartialFailure, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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 Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order1.order1
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order1.order1;
// <Area>variance</Area>
// <Title> Order of Basic covariance on interfaces</Title>
// <Description> basic coavariance on interfaces with many parameters. Order does not matter</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<S, out T, U, V>
{
T Boo();
}
public class Variance<S, T, U, V> : iVariance<S, T, U, V> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v11 = new Variance<int, Tiger, string, long>();
iVariance<int, Animal, string, long> v12 = v11;
var x1 = v12.Boo();
Variance<int, Tiger, string, long> v21 = new Variance<int, Tiger, string, long>();
dynamic v22 = (iVariance<int, Animal, string, long>)v21;
var x2 = v22.Boo();
dynamic v31 = new Variance<int, Tiger, string, long>();
dynamic v32 = (iVariance<int, Animal, string, long>)v31;
var x3 = v32.Boo();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order2.order2
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order2.order2;
// <Area>variance</Area>
// <Title> Order of Basic covariance on interfaces</Title>
// <Description> basic coavariance on interfaces with many parameters.
// A second parameter is also used in a covariant way but is not covariant itself. this should fail
//</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<S, out T, U, V>
{
T Boo();
}
public class Variance<S, T, U, V> : iVariance<S, T, U, V> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0, count = 0;
dynamic v11 = new Variance<int, Tiger, string, Tiger>();
try
{
result++;
iVariance<int, Animal, string, Animal> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<int,Tiger,string,Tiger>", "iVariance<int,Animal,string,Animal>");
if (ret)
{
result--;
}
}
Variance<int, Tiger, string, Tiger> v21 = new Variance<int, Tiger, string, Tiger>();
try
{
result++;
dynamic v22 = (iVariance<int, Animal, string, Animal>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic v31 = new Variance<int, Tiger, string, Tiger>();
try
{
result++;
dynamic v32 = (iVariance<int, Animal, string, Animal>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order3.order3
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order3.order3;
// <Area>variance</Area>
// <Title> Order of Basic covariance on delegates</Title>
// <Description> basic coavariance on delegates with many parameters. Order does not matter</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<S, out T, U, V>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<int, Tiger, string, long>)(() =>
{
return new Tiger();
}
);
Foo<int, Animal, string, long> f12 = f11;
Tiger t1 = f11();
Foo<int, Tiger, string, long> f21 = () =>
{
return new Tiger();
}
;
dynamic f22 = (Foo<int, Animal, string, long>)f21;
Tiger t2 = f22();
dynamic f31 = (Foo<int, Tiger, string, long>)(() =>
{
return new Tiger();
}
);
dynamic f32 = (Foo<int, Animal, string, long>)f31;
Tiger t3 = f31();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order4.order4
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.order4.order4;
// <Area>variance</Area>
// <Title> Order of Basic covariance on delegates</Title>
// <Description> basic coavariance on delegates with many parameters. only one type param is variant</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<S, out T, U, V>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<int, Tiger, string, Tiger>)(() =>
{
return new Tiger();
}
);
try
{
result++;
Foo<int, Animal, string, Animal> f12 = f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
result--;
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, ex.Message, "C.Foo<int,Tiger,string,Tiger>", "C.Foo<int,Animal,string,Animal>");
if (!ret)
result++;
}
Foo<int, Tiger, string, Tiger> f21 = () =>
{
return new Tiger();
}
;
try
{
result++;
dynamic f22 = (Foo<int, Animal, string, Animal>)f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
result--;
ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<int,Tiger,string,Tiger>", "C.Foo<int,Animal,string,Animal>");
if (!ret)
result++;
}
dynamic f31 = (Foo<int, Tiger, string, Tiger>)(() =>
{
return new Tiger();
}
);
try
{
result++;
dynamic f32 = (Foo<int, Animal, string, Animal>)f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
result--;
ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<int,Tiger,string,Tiger>", "C.Foo<int,Animal,string,Animal>");
if (!ret)
result++;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.partial01.partial01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.partial01.partial01;
// <Area>variance</Area>
// <Title> Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type in a partial public class </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public partial class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Foo<Tiger> f1 = () =>
{
return new Tiger();
}
;
Foo<Animal> f2 = f1;
Animal t = f2();
return 0;
}
}
public partial class C
{
private delegate T Foo<out T>();
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype01.valtype01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype01.valtype01;
// <Area>variance</Area>
// <Title> Value types</Title>
// <Description> basic coavariance on interfaces with value types </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T>
{
public T Boo()
{
return default(T);
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int count = 0, result = 0;
dynamic v11 = new Variance<uint>();
try
{
result++;
iVariance<int> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<uint>", "iVariance<int>");
if (ret)
{
result--;
}
}
Variance<uint> v21 = new Variance<uint>();
try
{
result++;
dynamic v22 = (iVariance<int>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic v31 = new Variance<uint>();
try
{
result++;
dynamic v32 = (iVariance<int>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype02.valtype02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype02.valtype02;
// <Area>variance</Area>
// <Title> Value types</Title>
// <Description> basic coavariance on dynamic with value types </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int count = 0, result = 0;
bool ret = true;
dynamic f11 = (Foo<uint>)(() =>
{
return 0;
}
);
try
{
count++;
result++;
Foo<int> f12 = f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<int>");
if (ret)
{
result--;
}
}
//Foo<uint> f21 = () => { return 0; };
//try
//{
// result++;
// dynamic f22 = (Foo<int>)f21;
//}
//catch (System.InvalidCastException)
//{
// result--;
// System.Console.WriteLine("Scenario {0} passed. ", ++count);
//}
dynamic f31 = (Foo<uint>)(() =>
{
return 0;
}
);
try
{
count++;
result++;
dynamic f32 = (Foo<int>)f31;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<int>");
if (ret)
{
result--;
}
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype03.valtype03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype03.valtype03;
// <Area>variance</Area>
// <Title> Value types</Title>
// <Description> basic coavariance on interfaces with nullable value types </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T>
{
public T Boo()
{
return default(T);
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
dynamic v11 = new Variance<uint>();
try
{
result++;
iVariance<uint?> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<uint>", "iVariance<uint?>");
if (ret)
{
result--;
}
}
Variance<uint> v21 = new Variance<uint>();
try
{
result++;
dynamic v22 = (iVariance<uint?>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic v31 = new Variance<uint>();
try
{
result++;
dynamic v32 = (iVariance<uint?>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype04.valtype04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.decl.valtype04.valtype04;
// <Area>variance</Area>
// <Title> Value types</Title>
// <Description> basic coavariance on delegate with null value types </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int count = 0, result = 0;
bool ret = true;
dynamic f11 = (Foo<uint>)(() =>
{
return 0;
}
);
try
{
count++;
result++;
Foo<uint?> f12 = f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<uint?>");
if (ret)
{
result--;
}
}
//Foo<uint> f21 = () => { return 0; };
//try
//{
// result++;
// dynamic f22 = (Foo<uint?>)f21;
//}
//catch (System.InvalidCastException)
//{
// result--;
// System.Console.WriteLine("Scenario {0} passed. ", ++count);
//}
dynamic f31 = (Foo<uint>)(() =>
{
return 0;
}
);
try
{
count++;
result++;
dynamic f32 = (Foo<uint?>)f31;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoExplicitConv, ex.Message, "C.Foo<uint>", "C.Foo<uint?>");
if (ret)
{
result--;
}
}
return result;
}
}
//</Code>
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Text;
namespace System.Reflection.Metadata.Decoding.Tests
{
// Test implementation of ISignatureTypeProvider<TType> that uses strings in ilasm syntax as TType.
// A real provider in any sort of perf constraints would not want to allocate strings freely like this, but it keeps test code simple.
internal class DisassemblingTypeProvider : ISignatureTypeProvider<string>
{
public virtual string GetPrimitiveType(PrimitiveTypeCode typeCode)
{
switch (typeCode)
{
case PrimitiveTypeCode.Boolean:
return "bool";
case PrimitiveTypeCode.Byte:
return "uint8";
case PrimitiveTypeCode.Char:
return "char";
case PrimitiveTypeCode.Double:
return "float64";
case PrimitiveTypeCode.Int16:
return "int16";
case PrimitiveTypeCode.Int32:
return "int32";
case PrimitiveTypeCode.Int64:
return "int64";
case PrimitiveTypeCode.IntPtr:
return "native int";
case PrimitiveTypeCode.Object:
return "object";
case PrimitiveTypeCode.SByte:
return "int8";
case PrimitiveTypeCode.Single:
return "float32";
case PrimitiveTypeCode.String:
return "string";
case PrimitiveTypeCode.TypedReference:
return "typedref";
case PrimitiveTypeCode.UInt16:
return "uint16";
case PrimitiveTypeCode.UInt32:
return "uint32";
case PrimitiveTypeCode.UInt64:
return "uint64";
case PrimitiveTypeCode.UIntPtr:
return "native uint";
case PrimitiveTypeCode.Void:
return "void";
default:
Debug.Assert(false);
throw new ArgumentOutOfRangeException(nameof(typeCode));
}
}
public virtual string GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind = 0)
{
TypeDefinition definition = reader.GetTypeDefinition(handle);
string name = definition.Namespace.IsNil
? reader.GetString(definition.Name)
: reader.GetString(definition.Namespace) + "." + reader.GetString(definition.Name);
if (definition.Attributes.IsNested())
{
TypeDefinitionHandle declaringTypeHandle = definition.GetDeclaringType();
return GetTypeFromDefinition(reader, declaringTypeHandle, 0) + "/" + name;
}
return name;
}
public virtual string GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind = 0)
{
TypeReference reference = reader.GetTypeReference(handle);
Handle scope = reference.ResolutionScope;
string name = reference.Namespace.IsNil
? reader.GetString(reference.Name)
: reader.GetString(reference.Namespace) + "." + reader.GetString(reference.Name);
switch (scope.Kind)
{
case HandleKind.ModuleReference:
return "[.module " + reader.GetString(reader.GetModuleReference((ModuleReferenceHandle)scope).Name) + "]" + name;
case HandleKind.AssemblyReference:
var assemblyReferenceHandle = (AssemblyReferenceHandle)scope;
var assemblyReference = reader.GetAssemblyReference(assemblyReferenceHandle);
return "[" + reader.GetString(assemblyReference.Name) + "]" + name;
case HandleKind.TypeReference:
return GetTypeFromReference(reader, (TypeReferenceHandle)scope) + "/" + name;
default:
// rare cases: ModuleDefinition means search within defs of current module (used by WinMDs for projections)
// nil means search exported types of same module (haven't seen this in practice). For the test
// purposes here, it's sufficient to format both like defs.
Debug.Assert(scope == Handle.ModuleDefinition || scope.IsNil);
return name;
}
}
public virtual string GetTypeFromSpecification(MetadataReader reader, TypeSpecificationHandle handle, byte rawTypeKind = 0)
{
return reader.GetTypeSpecification(handle).DecodeSignature(this);
}
public virtual string GetSZArrayType(string elementType)
{
return elementType + "[]";
}
public virtual string GetPointerType(string elementType)
{
return elementType + "*";
}
public virtual string GetByReferenceType(string elementType)
{
return elementType + "&";
}
public virtual string GetGenericMethodParameter(int index)
{
return "!!" + index;
}
public virtual string GetGenericTypeParameter(int index)
{
return "!" + index;
}
public virtual string GetPinnedType(string elementType)
{
return elementType + " pinned";
}
public virtual string GetGenericInstance(string genericType, ImmutableArray<string> typeArguments)
{
return genericType + "<" + String.Join(",", typeArguments) + ">";
}
public virtual string GetArrayType(string elementType, ArrayShape shape)
{
var builder = new StringBuilder();
builder.Append(elementType);
builder.Append('[');
for (int i = 0; i < shape.Rank; i++)
{
int lowerBound = 0;
if (i < shape.LowerBounds.Length)
{
lowerBound = shape.LowerBounds[i];
builder.Append(lowerBound);
}
builder.Append("...");
if (i < shape.Sizes.Length)
{
builder.Append(lowerBound + shape.Sizes[i] - 1);
}
if (i < shape.Rank - 1)
{
builder.Append(',');
}
}
builder.Append(']');
return builder.ToString();
}
public virtual string GetTypeFromHandle(MetadataReader reader, EntityHandle handle)
{
switch (handle.Kind)
{
case HandleKind.TypeDefinition:
return GetTypeFromDefinition(reader, (TypeDefinitionHandle)handle);
case HandleKind.TypeReference:
return GetTypeFromReference(reader, (TypeReferenceHandle)handle);
case HandleKind.TypeSpecification:
return GetTypeFromSpecification(reader, (TypeSpecificationHandle)handle);
default:
throw new ArgumentOutOfRangeException(nameof(handle));
}
}
public virtual string GetModifiedType(MetadataReader reader, bool isRequired, string modifierType, string unmodifiedType)
{
return unmodifiedType + (isRequired ? " modreq(" : " modopt(") + modifierType + ")";
}
public virtual string GetFunctionPointerType(MethodSignature<string> signature)
{
ImmutableArray<string> parameterTypes = signature.ParameterTypes;
int requiredParameterCount = signature.RequiredParameterCount;
var builder = new StringBuilder();
builder.Append("method ");
builder.Append(signature.ReturnType);
builder.Append(" *(");
int i;
for (i = 0; i < requiredParameterCount; i++)
{
builder.Append(parameterTypes[i]);
if (i < parameterTypes.Length - 1)
{
builder.Append(", ");
}
}
if (i < parameterTypes.Length)
{
builder.Append("..., ");
for (; i < parameterTypes.Length; i++)
{
builder.Append(parameterTypes[i]);
if (i < parameterTypes.Length - 1)
{
builder.Append(", ");
}
}
}
builder.Append(')');
return builder.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 Newtonsoft.Json;
using System.Buffers;
using System.IO;
using System.IO.Pipelines;
using System.Text.JsonLab.Tests.Resources;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.JsonLab.Tests
{
public class ReadFromPipeTests : IDisposable
{
public ReadFromPipeTests()
{
string jsonString = TestJson.Json400KB;
_dataUtf8 = Encoding.UTF8.GetBytes(jsonString);
_written = 0;
_pipe = new Pipe();
Stream stream = new MemoryStream(_dataUtf8);
TextReader reader = new StreamReader(stream, Encoding.UTF8, false, 1024, true);
_expectedString = NewtonsoftReturnStringHelper(reader);
}
public void Dispose()
{
_pipe.Writer.Complete();
_pipe.Reader.Complete();
}
private readonly Pipe _pipe;
private readonly byte[] _dataUtf8;
private int _written;
private string _expectedString;
public static string NewtonsoftReturnStringHelper(TextReader reader)
{
var sb = new StringBuilder();
var json = new JsonTextReader(reader);
while (json.Read())
{
if (json.TokenType == JsonToken.PropertyName)
{
if (json.Value != null)
{
sb.Append(json.Value);
}
}
}
return sb.ToString();
}
[Fact]
public void ReadFromPipeUsingSequence()
{
string actual = "";
var taskReader = Task.Run(async () =>
{
JsonReaderState state = default;
string str = "";
while (true)
{
ReadResult result = await _pipe.Reader.ReadAsync();
ReadOnlySequence<byte> data = result.Buffer;
bool isFinalBlock = result.IsCompleted;
(state, str) = ProcessData(data, isFinalBlock, state);
_pipe.Reader.AdvanceTo(state.Position);
actual += str;
if (isFinalBlock)
break;
}
});
var taskWriter = Task.Run(async () =>
{
while (true)
{
Memory<byte> mem = default;
bool isLastSegment = false;
if (_written >= _dataUtf8.Length - 4_000)
{
isLastSegment = true;
mem = _dataUtf8.AsMemory(_written);
}
else
{
mem = _dataUtf8.AsMemory(_written, 4_000);
}
FlushResult result = await _pipe.Writer.WriteAsync(mem);
_written += 4000;
if (isLastSegment)
break;
}
_pipe.Writer.Complete();
});
Task[] tasks = new Task[] { taskReader, taskWriter };
Task.WaitAll(tasks, 30_000); // The test shouldn't take more than 30 seconds to finish.
Assert.Equal(_expectedString, actual);
}
private static (JsonReaderState, string) ProcessData(ReadOnlySequence<byte> ros, bool isFinalBlock, JsonReaderState state = default)
{
var builder = new StringBuilder();
var json = new JsonUtf8Reader(ros, isFinalBlock, state);
while (json.Read())
{
switch (json.TokenType)
{
case JsonTokenType.PropertyName:
json.TryGetValueAsString(out string value);
builder.Append(value);
break;
}
}
Assert.Equal(json.BytesConsumed, json.CurrentState.BytesConsumed);
Assert.Equal(json.Position, json.CurrentState.Position);
return (json.CurrentState, builder.ToString());
}
// (Expected a '"' to indicate end of string, but instead reached end of data. LineNumber: 12940 | BytePosition: 6.)
[Fact(Skip = "This needs to be fixed and re-enabled or removed. Fails specficially on Unix.")]
public void ReadFromPipeUsingSpan()
{
string actual = "";
var taskReader = Task.Run(async () =>
{
SequencePosition position = default;
JsonReaderState state = default;
string str = "";
while (true)
{
ReadResult result = await _pipe.Reader.ReadAsync();
ReadOnlySequence<byte> data = result.Buffer;
bool isFinalBlock = result.IsCompleted;
(state, position, str) = ProcessDataSpan(data, isFinalBlock, state);
_pipe.Reader.AdvanceTo(position);
actual += str;
if (isFinalBlock)
break;
}
});
var taskWriter = Task.Run(async () =>
{
while (true)
{
Memory<byte> mem = default;
bool isLastSegment = false;
if (_written >= _dataUtf8.Length - 4_000)
{
isLastSegment = true;
mem = _dataUtf8.AsMemory(_written);
}
else
{
mem = _dataUtf8.AsMemory(_written, 4_000);
}
FlushResult result = await _pipe.Writer.WriteAsync(mem);
_written += 4000;
if (isLastSegment)
break;
}
_pipe.Writer.Complete();
});
Task[] tasks = new Task[] { taskReader, taskWriter };
Task.WaitAll(tasks, 30_000); // The test shouldn't take more than 30 seconds to finish.
Assert.Equal(_expectedString, actual);
}
private static (JsonReaderState, SequencePosition, string) ProcessDataSpan(ReadOnlySequence<byte> ros, bool isFinalBlock, JsonReaderState state = default)
{
var builder = new StringBuilder();
ReadOnlySpan<byte> leftOver = default;
byte[] pooledArray = null;
JsonUtf8Reader json = default;
long totalConsumed = 0;
foreach (ReadOnlyMemory<byte> mem in ros)
{
ReadOnlySpan<byte> span = mem.Span;
if (leftOver.Length > int.MaxValue - span.Length)
throw new ArgumentOutOfRangeException("Current sequence segment size is too large to fit left over data from the previous segment into a 2 GB buffer.");
pooledArray = ArrayPool<byte>.Shared.Rent(span.Length + leftOver.Length); // This is guaranteed to not overflow
Span<byte> bufferSpan = pooledArray.AsSpan(0, leftOver.Length + span.Length);
leftOver.CopyTo(bufferSpan);
span.CopyTo(bufferSpan.Slice(leftOver.Length));
json = new JsonUtf8Reader(bufferSpan, isFinalBlock, state);
while (json.Read())
{
switch (json.TokenType)
{
case JsonTokenType.PropertyName:
json.TryGetValueAsString(out string value);
builder.Append(value);
break;
}
}
if (json.BytesConsumed < bufferSpan.Length)
{
leftOver = bufferSpan.Slice((int)json.BytesConsumed);
}
else
{
leftOver = default;
}
totalConsumed += json.BytesConsumed;
Assert.Equal(json.BytesConsumed, json.CurrentState.BytesConsumed);
Assert.Equal(json.Position, json.CurrentState.Position);
if (pooledArray != null) // TODO: Will this work if data spans more than two segments?
ArrayPool<byte>.Shared.Return(pooledArray);
state = json.CurrentState;
}
return (json.CurrentState, ros.GetPosition(totalConsumed), builder.ToString());
}
}
}
| |
/*
* CID0026.cs - lv culture handler.
*
* Copyright (c) 2003 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "lv.txt".
namespace I18N.Other
{
using System;
using System.Globalization;
using I18N.Common;
public class CID0026 : RootCulture
{
public CID0026() : base(0x0026) {}
public CID0026(int culture) : base(culture) {}
public override String Name
{
get
{
return "lv";
}
}
public override String ThreeLetterISOLanguageName
{
get
{
return "lav";
}
}
public override String ThreeLetterWindowsLanguageName
{
get
{
return "LVI";
}
}
public override String TwoLetterISOLanguageName
{
get
{
return "lv";
}
}
public override DateTimeFormatInfo DateTimeFormat
{
get
{
DateTimeFormatInfo dfi = base.DateTimeFormat;
dfi.AbbreviatedDayNames = new String[] {"Sv", "P", "O", "T", "C", "Pk", "S"};
dfi.DayNames = new String[] {"sv\u0113tdiena", "pirmdiena", "otrdiena", "tre\u0161diena", "ceturtdiena", "piektdiena", "sestdiena"};
dfi.AbbreviatedMonthNames = new String[] {"Jan", "Feb", "Mar", "Apr", "Maijs", "J\u016Bn", "J\u016Bl", "Aug", "Sep", "Okt", "Nov", "Dec", ""};
dfi.MonthNames = new String[] {"janv\u0101ris", "febru\u0101ris", "marts", "apr\u012Blis", "maijs", "j\u016Bnijs", "j\u016Blijs", "augusts", "septembris", "oktobris", "novembris", "decembris", ""};
dfi.DateSeparator = ".";
dfi.TimeSeparator = ":";
dfi.LongDatePattern = "dddd, yyyy, d MMMM";
dfi.LongTimePattern = "HH:mm:ss z";
dfi.ShortDatePattern = "yy.d.M";
dfi.ShortTimePattern = "HH:mm";
dfi.FullDateTimePattern = "dddd, yyyy, d MMMM HH:mm:ss z";
dfi.I18NSetDateTimePatterns(new String[] {
"d:yy.d.M",
"D:dddd, yyyy, d MMMM",
"f:dddd, yyyy, d MMMM HH:mm:ss z",
"f:dddd, yyyy, d MMMM HH:mm:ss z",
"f:dddd, yyyy, d MMMM HH:mm:ss",
"f:dddd, yyyy, d MMMM HH:mm",
"F:dddd, yyyy, d MMMM HH:mm:ss",
"g:yy.d.M HH:mm:ss z",
"g:yy.d.M HH:mm:ss z",
"g:yy.d.M HH:mm:ss",
"g:yy.d.M HH:mm",
"G:yy.d.M HH:mm:ss",
"m:MMMM dd",
"M:MMMM dd",
"r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"s:yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"t:HH:mm:ss z",
"t:HH:mm:ss z",
"t:HH:mm:ss",
"t:HH:mm",
"T:HH:mm:ss",
"u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
"U:dddd, dd MMMM yyyy HH:mm:ss",
"y:yyyy MMMM",
"Y:yyyy MMMM",
});
return dfi;
}
set
{
base.DateTimeFormat = value; // not used
}
}
public override NumberFormatInfo NumberFormat
{
get
{
NumberFormatInfo nfi = base.NumberFormat;
nfi.CurrencyDecimalSeparator = ",";
nfi.CurrencyGroupSeparator = "\u00A0";
nfi.NumberGroupSeparator = "\u00A0";
nfi.PercentGroupSeparator = "\u00A0";
nfi.NegativeSign = "-";
nfi.NumberDecimalSeparator = ",";
nfi.PercentDecimalSeparator = ",";
nfi.PercentSymbol = "%";
nfi.PerMilleSymbol = "\u2030";
return nfi;
}
set
{
base.NumberFormat = value; // not used
}
}
public override String ResolveLanguage(String name)
{
switch(name)
{
case "lv": return "Latvie\u0161u";
}
return base.ResolveLanguage(name);
}
public override String ResolveCountry(String name)
{
switch(name)
{
case "LV": return "Latvija";
}
return base.ResolveCountry(name);
}
private class PrivateTextInfo : _I18NTextInfo
{
public PrivateTextInfo(int culture) : base(culture) {}
public override int ANSICodePage
{
get
{
return 1257;
}
}
public override int EBCDICCodePage
{
get
{
return 500;
}
}
public override int MacCodePage
{
get
{
return 10029;
}
}
public override int OEMCodePage
{
get
{
return 775;
}
}
public override String ListSeparator
{
get
{
return ";";
}
}
}; // class PrivateTextInfo
public override TextInfo TextInfo
{
get
{
return new PrivateTextInfo(LCID);
}
}
}; // class CID0026
public class CNlv : CID0026
{
public CNlv() : base() {}
}; // class CNlv
}; // namespace I18N.Other
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PoliciesResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Trusthub.V1
{
public class PoliciesResource : Resource
{
public sealed class EndUserTypeEnum : StringEnum
{
private EndUserTypeEnum(string value) : base(value) {}
public EndUserTypeEnum() {}
public static implicit operator EndUserTypeEnum(string value)
{
return new EndUserTypeEnum(value);
}
public static readonly EndUserTypeEnum Individual = new EndUserTypeEnum("individual");
public static readonly EndUserTypeEnum Business = new EndUserTypeEnum("business");
}
private static Request BuildReadRequest(ReadPoliciesOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Trusthub,
"/v1/Policies",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Policys.
/// </summary>
/// <param name="options"> Read Policies parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Policies </returns>
public static ResourceSet<PoliciesResource> Read(ReadPoliciesOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<PoliciesResource>.FromJson("results", response.Content);
return new ResourceSet<PoliciesResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Policys.
/// </summary>
/// <param name="options"> Read Policies parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Policies </returns>
public static async System.Threading.Tasks.Task<ResourceSet<PoliciesResource>> ReadAsync(ReadPoliciesOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<PoliciesResource>.FromJson("results", response.Content);
return new ResourceSet<PoliciesResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Policys.
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Policies </returns>
public static ResourceSet<PoliciesResource> Read(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadPoliciesOptions(){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Policys.
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Policies </returns>
public static async System.Threading.Tasks.Task<ResourceSet<PoliciesResource>> ReadAsync(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadPoliciesOptions(){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<PoliciesResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<PoliciesResource>.FromJson("results", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<PoliciesResource> NextPage(Page<PoliciesResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Trusthub)
);
var response = client.Request(request);
return Page<PoliciesResource>.FromJson("results", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<PoliciesResource> PreviousPage(Page<PoliciesResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Trusthub)
);
var response = client.Request(request);
return Page<PoliciesResource>.FromJson("results", response.Content);
}
private static Request BuildFetchRequest(FetchPoliciesOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Trusthub,
"/v1/Policies/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch specific Policy Instance.
/// </summary>
/// <param name="options"> Fetch Policies parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Policies </returns>
public static PoliciesResource Fetch(FetchPoliciesOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch specific Policy Instance.
/// </summary>
/// <param name="options"> Fetch Policies parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Policies </returns>
public static async System.Threading.Tasks.Task<PoliciesResource> FetchAsync(FetchPoliciesOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch specific Policy Instance.
/// </summary>
/// <param name="pathSid"> The unique string that identifies the Policy resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Policies </returns>
public static PoliciesResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchPoliciesOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch specific Policy Instance.
/// </summary>
/// <param name="pathSid"> The unique string that identifies the Policy resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Policies </returns>
public static async System.Threading.Tasks.Task<PoliciesResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchPoliciesOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a PoliciesResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> PoliciesResource object represented by the provided JSON </returns>
public static PoliciesResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<PoliciesResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the Policy resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// A human-readable description of the Policy resource
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The sid of a Policy object that dictates requirements
/// </summary>
[JsonProperty("requirements")]
public object Requirements { get; private set; }
/// <summary>
/// The absolute URL of the Policy resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private PoliciesResource()
{
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using Greentube.Monitoring.Threading;
using Microsoft.Extensions.Logging;
namespace Greentube.Monitoring
{
/// <summary>
/// Resource Monitor: when started, raises events reporting the status of a resource
/// </summary>
/// <seealso cref="IResourceMonitor" />
/// <seealso cref="IDisposable" />
public class ResourceMonitor : AbstractStartable, IResourceMonitor, IDisposable
{
private readonly object _verificationLock = new object();
private readonly ITimer _timer;
private readonly ILogger<ResourceMonitor> _logger;
private readonly IHealthCheckStrategy _verificationStrategy;
/// <summary>
/// Gets the configuration.
/// </summary>
/// <value>
/// The configuration.
/// </value>
[PublicAPI]
public IResourceMonitorConfiguration Configuration { get; }
/// <summary>
/// Gets the name of the resource.
/// </summary>
/// <value>
/// The name of the resource.
/// </value>
public string ResourceName { get; }
/// <summary>
/// Gets a value indicating whether this resource is critical to the functioning of the system
/// </summary>
/// <value>
/// <c>true</c> if this instance is critical; otherwise, <c>false</c>.
/// </value>
public bool IsCritical { get; }
/// <summary>
/// Occurs when a verification is executed
/// </summary>
public event EventHandler<ResourceMonitorEventArgs> MonitoringEvent;
/// <summary>
/// Initializes a new instance of the <see cref="ResourceMonitor"/> class.
/// </summary>
/// <param name="resourceName">Name of the resource.</param>
/// <param name="verificationStrategy">The verify strategy.</param>
/// <param name="configuration">The configuration.</param>
/// <param name="logger">The logger.</param>
/// <param name="isCritical">if set to <c>true</c> [is critical].</param>
[PublicAPI]
public ResourceMonitor(
string resourceName,
IHealthCheckStrategy verificationStrategy,
IResourceMonitorConfiguration configuration,
ILogger<ResourceMonitor> logger,
bool isCritical = false)
: this(resourceName,
verificationStrategy,
configuration,
logger,
isCritical,
new TimerAdapterFactory())
{
}
internal ResourceMonitor(
string resourceName,
IHealthCheckStrategy verificationStrategy,
IResourceMonitorConfiguration configuration,
ILogger<ResourceMonitor> logger,
bool isCritical,
ITimerFactory timerFactory)
{
if (resourceName == null) throw new ArgumentNullException(nameof(resourceName));
if (verificationStrategy == null) throw new ArgumentNullException(nameof(verificationStrategy));
if (logger == null) throw new ArgumentNullException(nameof(logger));
if (timerFactory == null) throw new ArgumentNullException(nameof(timerFactory));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
_verificationStrategy = verificationStrategy;
_logger = logger;
ResourceName = resourceName;
Configuration = configuration;
IsCritical = isCritical;
_timer = timerFactory.Create(OnTimer);
if (_timer == null)
throw new InvalidOperationException("Expected TimerFactory to return a Timer.");
}
/// <summary>
/// Starts to Monitor the resource
/// </summary>
protected override void DoStart()
{
if (Configuration.StartSynchronously)
{
_logger.LogInformation("Starting ResourceMonitor - Executing the first check for: {ResourceName} synchronously", ResourceName);
Verify();
}
else
{
var period = Configuration.IntervalWhenUp;
_logger.LogInformation("Starting ResourceMonitor - Scheduling the first check for: {ResourceName} in {Period}", ResourceName, period);
_timer.Change(TimeSpan.Zero, period);
}
}
/// <summary>
/// Stops monitoring the resource
/// </summary>
protected override void DoStop()
{
_logger.LogInformation("Stopping ResourceMonitor: {ResourceName}", ResourceName);
_timer.Change(Timeout.Infinite, Timeout.Infinite);
}
private void OnTimer(object _)
{
// If the timer is faster than the verification, skip the check
if (Monitor.TryEnter(_verificationLock))
{
try
{
Verify();
}
finally
{
Monitor.Exit(_verificationLock);
}
}
}
internal void Verify() // Internal for testability
{
var sw = Stopwatch.StartNew();
var evt = CreateVerificationEvent();
var logLevelForDown = IsCritical ? LogLevel.Error : LogLevel.Warning;
var logLevel = evt.IsUp ? LogLevel.Trace : logLevelForDown;
_logger.Log(logLevel, 0, "{verificationTimeUtc}, {resource}, {critical}, {up}, {ex}", DateTime.UtcNow, ResourceName, IsCritical,
evt.IsUp, evt.Exception);
sw.Stop();
evt.Latency = sw.Elapsed;
var period = evt.IsUp
? Configuration.IntervalWhenUp
: Configuration.IntervalWhenDown;
_timer.Change(period, period);
OnMonitoringEvent(evt);
}
private ResourceMonitorEventArgs CreateVerificationEvent()
{
var evt = new ResourceMonitorEventArgs();
var timedOut = false;
try
{
var source = new CancellationTokenSource(Configuration.Timeout);
var verificationTask = _verificationStrategy.Check(source.Token);
timedOut = !verificationTask
.Wait(Configuration.Timeout)
|| source.Token.IsCancellationRequested;
// It's up if it didn't timeout and the check was OK.
evt.IsUp = !timedOut && verificationTask.Result;
}
catch (Exception ex)
{
evt.IsUp = false;
evt.Exception = ex;
}
finally
{
if (timedOut) // To avoid throwing from the try block
evt.Exception = new TimeoutException();
}
return evt;
}
private void OnMonitoringEvent(ResourceMonitorEventArgs e)
{
try
{
MonitoringEvent?.Invoke(this, e);
}
catch (Exception ex)
{
_logger.LogCritical(0, ex, "The event handler has thrown an exception. The Exception will be re-thrown and the Monitoring will stop.");
throw;
}
}
/// <summary>
/// Disposes the inner timer, stopping the resource monitoring
/// </summary>
public void Dispose()
{
_timer.Dispose();
}
}
}
| |
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Abp.Application.Editions;
using Abp.Application.Features;
using Abp.Auditing;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.BackgroundJobs;
using Abp.EntityFramework.Extensions;
using Abp.MultiTenancy;
using Abp.Notifications;
namespace Abp.Zero.EntityFramework
{
/// <summary>
/// Base DbContext for ABP zero.
/// Derive your DbContext from this class to have base entities.
/// </summary>
public abstract class AbpZeroDbContext<TTenant, TRole, TUser> : AbpZeroCommonDbContext<TRole, TUser>
where TTenant : AbpTenant<TUser>
where TRole : AbpRole<TUser>
where TUser : AbpUser<TUser>
{
/// <summary>
/// Tenants
/// </summary>
public virtual IDbSet<TTenant> Tenants { get; set; }
/// <summary>
/// Editions.
/// </summary>
public virtual IDbSet<Edition> Editions { get; set; }
/// <summary>
/// FeatureSettings.
/// </summary>
public virtual IDbSet<FeatureSetting> FeatureSettings { get; set; }
/// <summary>
/// TenantFeatureSetting.
/// </summary>
public virtual IDbSet<TenantFeatureSetting> TenantFeatureSettings { get; set; }
/// <summary>
/// EditionFeatureSettings.
/// </summary>
public virtual IDbSet<EditionFeatureSetting> EditionFeatureSettings { get; set; }
/// <summary>
/// Background jobs.
/// </summary>
public virtual IDbSet<BackgroundJobInfo> BackgroundJobs { get; set; }
/// <summary>
/// User accounts
/// </summary>
public virtual IDbSet<UserAccount> UserAccounts { get; set; }
protected AbpZeroDbContext()
{
}
protected AbpZeroDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected AbpZeroDbContext(DbCompiledModel model)
: base(model)
{
}
protected AbpZeroDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected AbpZeroDbContext(string nameOrConnectionString, DbCompiledModel model)
: base(nameOrConnectionString, model)
{
}
protected AbpZeroDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
: base(objectContext, dbContextOwnsObjectContext)
{
}
protected AbpZeroDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
: base(existingConnection, model, contextOwnsConnection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region BackgroundJobInfo.IX_IsAbandoned_NextTryTime
modelBuilder.Entity<BackgroundJobInfo>()
.Property(j => j.IsAbandoned)
.CreateIndex("IX_IsAbandoned_NextTryTime", 1);
modelBuilder.Entity<BackgroundJobInfo>()
.Property(j => j.NextTryTime)
.CreateIndex("IX_IsAbandoned_NextTryTime", 2);
#endregion
#region NotificationSubscriptionInfo.IX_NotificationName_EntityTypeName_EntityId_UserId
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(ns => ns.NotificationName)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 1);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(ns => ns.EntityTypeName)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 2);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(ns => ns.EntityId)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 3);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(ns => ns.UserId)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 4);
#endregion
#region UserNotificationInfo.IX_UserId_State_CreationTime
modelBuilder.Entity<UserNotificationInfo>()
.Property(un => un.UserId)
.CreateIndex("IX_UserId_State_CreationTime", 1);
modelBuilder.Entity<UserNotificationInfo>()
.Property(un => un.State)
.CreateIndex("IX_UserId_State_CreationTime", 2);
modelBuilder.Entity<UserNotificationInfo>()
.Property(un => un.CreationTime)
.CreateIndex("IX_UserId_State_CreationTime", 3);
#endregion
#region UserLoginAttempt.IX_TenancyName_UserNameOrEmailAddress_Result
modelBuilder.Entity<UserLoginAttempt>()
.Property(ula => ula.TenancyName)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 1);
modelBuilder.Entity<UserLoginAttempt>()
.Property(ula => ula.UserNameOrEmailAddress)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 2);
modelBuilder.Entity<UserLoginAttempt>()
.Property(ula => ula.Result)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 3);
#endregion
#region UserLoginAttempt.IX_UserId_TenantId
modelBuilder.Entity<UserLoginAttempt>()
.Property(ula => ula.UserId)
.CreateIndex("IX_UserId_TenantId", 1);
modelBuilder.Entity<UserLoginAttempt>()
.Property(ula => ula.TenantId)
.CreateIndex("IX_UserId_TenantId", 2);
#endregion
#region AuditLog.Set_MaxLengths
modelBuilder.Entity<AuditLog>()
.Property(e => e.ServiceName)
.HasMaxLength(AuditLog.MaxServiceNameLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.MethodName)
.HasMaxLength(AuditLog.MaxMethodNameLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.Parameters)
.HasMaxLength(AuditLog.MaxParametersLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ClientIpAddress)
.HasMaxLength(AuditLog.MaxClientIpAddressLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ClientName)
.HasMaxLength(AuditLog.MaxClientNameLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.BrowserInfo)
.HasMaxLength(AuditLog.MaxBrowserInfoLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.Exception)
.HasMaxLength(AuditLog.MaxExceptionLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.CustomData)
.HasMaxLength(AuditLog.MaxCustomDataLength);
#endregion
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.VPSForPC {
public partial class VpsToolsReinstallServer {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// breadcrumb control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPSForPC.UserControls.Breadcrumb breadcrumb;
/// <summary>
/// menu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPSForPC.UserControls.Menu menu;
/// <summary>
/// imgIcon control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image imgIcon;
/// <summary>
/// locTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPSForPC.UserControls.FormTitle locTitle;
/// <summary>
/// tabs control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPSForPC.UserControls.ServerTabs tabs;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// validatorsSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ValidationSummary validatorsSummary;
/// <summary>
/// locSubTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locSubTitle;
/// <summary>
/// locDescription control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDescription;
/// <summary>
/// chkConfirmReinstall control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkConfirmReinstall;
/// <summary>
/// locPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPassword;
/// <summary>
/// password control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.PasswordControl password;
/// <summary>
/// chkPreserveExistingFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkPreserveExistingFiles;
/// <summary>
/// locPreserveHelp control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPreserveHelp;
/// <summary>
/// AdminOptionsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable AdminOptionsPanel;
/// <summary>
/// chkSaveVhd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkSaveVhd;
/// <summary>
/// chkExport control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkExport;
/// <summary>
/// txtExportPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtExportPath;
/// <summary>
/// ExportPathValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator ExportPathValidator;
/// <summary>
/// btnReinstall control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnReinstall;
/// <summary>
/// btnCancel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancel;
/// <summary>
/// FormComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize FormComments;
}
}
| |
#region License
// Copyright 2014 MorseCode Software
// 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
namespace MorseCode.RxMvvm.Reactive
{
using System;
using System.Diagnostics.Contracts;
using MorseCode.RxMvvm.Common.DiscriminatedUnion;
/// <summary>
/// Provides <see langword="static"/> extension methods for <see cref="IObservable{T}"/>.
/// </summary>
public static partial class ObservableExtensionMethods
{
/// <summary>
/// Notifies the observable that an observer is to receive notifications.
/// </summary>
/// <typeparam name="TCommon">
/// Common type of the notification channels.
/// </typeparam>
/// <typeparam name="T1">
/// Type of the first notification channel.
/// </typeparam>
/// <typeparam name="T2">
/// Type of the second notification channel.
/// </typeparam>
/// <typeparam name="T3">
/// Type of the third notification channel.
/// </typeparam>
/// <param name="source">
/// The observable for which a subscription is created.
/// </param>
/// <param name="onNextFirst">
/// The handler of notifications in the first channel.
/// </param>
/// <param name="onNextSecond">
/// The handler of notifications in the second channel.
/// </param>
/// <param name="onNextThird">
/// The handler of notifications in the third channel.
/// </param>
/// <returns>
/// The observer's interface that enables cancellation of the subscription so that it stops receiving notifications.
/// </returns>
public static IDisposable SubscribeDiscriminatedUnion<TCommon, T1, T2, T3>(
this IObservable<IDiscriminatedUnion<TCommon, T1, T2, T3>> source,
Action<T1> onNextFirst,
Action<T2> onNextSecond,
Action<T3> onNextThird)
where T1 : TCommon
where T2 : TCommon
where T3 : TCommon
where TCommon : class
{
Contract.Requires<ArgumentNullException>(source != null, "source");
Contract.Requires<ArgumentNullException>(onNextFirst != null, "onNextFirst");
Contract.Requires<ArgumentNullException>(onNextSecond != null, "onNextSecond");
Contract.Requires<ArgumentNullException>(onNextThird != null, "onNextThird");
Contract.Ensures(Contract.Result<IDisposable>() != null);
return source.Subscribe(ObservableRxMvvm.CreateDiscriminatedUnion<TCommon, T1, T2, T3>(onNextFirst, onNextSecond, onNextThird));
}
/// <summary>
/// Notifies the observable that an observer is to receive notifications.
/// </summary>
/// <typeparam name="TCommon">
/// Common type of the notification channels.
/// </typeparam>
/// <typeparam name="T1">
/// Type of the first notification channel.
/// </typeparam>
/// <typeparam name="T2">
/// Type of the second notification channel.
/// </typeparam>
/// <typeparam name="T3">
/// Type of the third notification channel.
/// </typeparam>
/// <param name="source">
/// The observable for which a subscription is created.
/// </param>
/// <param name="onNextFirst">
/// The handler of notifications in the first channel.
/// </param>
/// <param name="onNextSecond">
/// The handler of notifications in the second channel.
/// </param>
/// <param name="onNextThird">
/// The handler of notifications in the third channel.
/// </param>
/// <param name="onError">
/// The handler of an error notification.
/// </param>
/// <returns>
/// The observer's interface that enables cancellation of the subscription so that it stops receiving notifications.
/// </returns>
public static IDisposable SubscribeDiscriminatedUnion<TCommon, T1, T2, T3>(
this IObservable<IDiscriminatedUnion<TCommon, T1, T2, T3>> source,
Action<T1> onNextFirst,
Action<T2> onNextSecond,
Action<T3> onNextThird,
Action<Exception> onError)
where T1 : TCommon
where T2 : TCommon
where T3 : TCommon
where TCommon : class
{
Contract.Requires<ArgumentNullException>(source != null, "source");
Contract.Requires<ArgumentNullException>(onNextFirst != null, "onNextFirst");
Contract.Requires<ArgumentNullException>(onNextSecond != null, "onNextSecond");
Contract.Requires<ArgumentNullException>(onNextThird != null, "onNextThird");
Contract.Requires<ArgumentNullException>(onError != null, "onError");
Contract.Ensures(Contract.Result<IDisposable>() != null);
return source.Subscribe(ObservableRxMvvm.CreateDiscriminatedUnion<TCommon, T1, T2, T3>(onNextFirst, onNextSecond, onNextThird, onError));
}
/// <summary>
/// Notifies the observable that an observer is to receive notifications.
/// </summary>
/// <typeparam name="TCommon">
/// Common type of the notification channels.
/// </typeparam>
/// <typeparam name="T1">
/// Type of the first notification channel.
/// </typeparam>
/// <typeparam name="T2">
/// Type of the second notification channel.
/// </typeparam>
/// <typeparam name="T3">
/// Type of the third notification channel.
/// </typeparam>
/// <param name="source">
/// The observable for which a subscription is created.
/// </param>
/// <param name="onNextFirst">
/// The handler of notifications in the first channel.
/// </param>
/// <param name="onNextSecond">
/// The handler of notifications in the second channel.
/// </param>
/// <param name="onNextThird">
/// The handler of notifications in the third channel.
/// </param>
/// <param name="onCompleted">
/// The handler of a completion notification.
/// </param>
/// <returns>
/// The observer's interface that enables cancellation of the subscription so that it stops receiving notifications.
/// </returns>
public static IDisposable SubscribeDiscriminatedUnion<TCommon, T1, T2, T3>(
this IObservable<IDiscriminatedUnion<TCommon, T1, T2, T3>> source,
Action<T1> onNextFirst,
Action<T2> onNextSecond,
Action<T3> onNextThird,
Action onCompleted)
where T1 : TCommon
where T2 : TCommon
where T3 : TCommon
where TCommon : class
{
Contract.Requires<ArgumentNullException>(source != null, "source");
Contract.Requires<ArgumentNullException>(onNextFirst != null, "onNextFirst");
Contract.Requires<ArgumentNullException>(onNextSecond != null, "onNextSecond");
Contract.Requires<ArgumentNullException>(onNextThird != null, "onNextThird");
Contract.Requires<ArgumentNullException>(onCompleted != null, "onCompleted");
Contract.Ensures(Contract.Result<IDisposable>() != null);
return source.Subscribe(ObservableRxMvvm.CreateDiscriminatedUnion<TCommon, T1, T2, T3>(onNextFirst, onNextSecond, onNextThird, onCompleted));
}
/// <summary>
/// Notifies the observable that an observer is to receive notifications.
/// </summary>
/// <typeparam name="TCommon">
/// Common type of the notification channels.
/// </typeparam>
/// <typeparam name="T1">
/// Type of the first notification channel.
/// </typeparam>
/// <typeparam name="T2">
/// Type of the second notification channel.
/// </typeparam>
/// <typeparam name="T3">
/// Type of the third notification channel.
/// </typeparam>
/// <param name="source">
/// The observable for which a subscription is created.
/// </param>
/// <param name="onNextFirst">
/// The handler of notifications in the first channel.
/// </param>
/// <param name="onNextSecond">
/// The handler of notifications in the second channel.
/// </param>
/// <param name="onNextThird">
/// The handler of notifications in the third channel.
/// </param>
/// <param name="onError">
/// The handler of an error notification.
/// </param>
/// <param name="onCompleted">
/// The handler of a completion notification.
/// </param>
/// <returns>
/// The observer's interface that enables cancellation of the subscription so that it stops receiving notifications.
/// </returns>
public static IDisposable SubscribeDiscriminatedUnion<TCommon, T1, T2, T3>(
this IObservable<IDiscriminatedUnion<TCommon, T1, T2, T3>> source,
Action<T1> onNextFirst,
Action<T2> onNextSecond,
Action<T3> onNextThird,
Action<Exception> onError,
Action onCompleted)
where T1 : TCommon
where T2 : TCommon
where T3 : TCommon
where TCommon : class
{
Contract.Requires<ArgumentNullException>(source != null, "source");
Contract.Requires<ArgumentNullException>(onNextFirst != null, "onNextFirst");
Contract.Requires<ArgumentNullException>(onNextSecond != null, "onNextSecond");
Contract.Requires<ArgumentNullException>(onNextThird != null, "onNextThird");
Contract.Requires<ArgumentNullException>(onError != null, "onError");
Contract.Requires<ArgumentNullException>(onCompleted != null, "onCompleted");
Contract.Ensures(Contract.Result<IDisposable>() != null);
return
source.Subscribe(
ObservableRxMvvm.CreateDiscriminatedUnion<TCommon, T1, T2, T3>(onNextFirst, onNextSecond, onNextThird, onError, onCompleted));
}
}
}
| |
// 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.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
public class Shared
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public void TestSorting()
{
var initial = "namespace [|N|] { }";
var generationSource = @"
using System;
namespace N
{
public class [|C|]
{
private delegate void DAccessA();
internal delegate void DAccessB();
protected internal delegate void DAccessC();
protected delegate void DAccessD();
public delegate void DAccessE();
public delegate void DGeneric<T1, T2>(T1 a, T2 b);
public delegate void DGeneric<T>(T t, int i);
public class CNotStatic { }
public static class CStatic { }
private class CAccessA { }
internal class CAccessB { }
protected internal class CAccessC { }
protected class CAccessD { }
public class CAccessE { }
public class CGeneric<T1, T2> { }
public class CGeneric<T> { }
private struct SAccessA { }
internal struct SAccessB { }
protected internal struct SAccessC { }
protected struct SAccessD { }
public struct SAccessE { }
public struct SGeneric<T1, T2> { }
public struct SGeneric<T> { }
public struct SNameB { }
public struct SNameA { }
private enum EAccessA { }
internal enum EAccessB { }
protected internal enum EAccessC { }
protected enum EAccessD { }
public enum EAccessE { }
public enum ENameB { }
public enum ENameA { }
private interface IAccessA { }
internal interface IAccessB { }
protected internal interface IAccessC { }
protected interface IAccessD { }
public interface IAccessE { }
public interface IGeneric<T1, T2> { }
public interface IGeneric<T> { }
public static C operator !(C c) { return c; }
public static C operator +(C c) { return c; }
public void MNotStatic() { }
public static void MStatic() { }
private void MAccessA() { }
internal void MAccessB() { }
protected internal void MAccessC() { }
protected void MAccessD() { }
public void MAccessE() { }
public void MGeneric<T1, T2>() { }
public void MGeneric<T>(int param) { }
public void MGeneric<T>() { }
public int M2NotStatic() { return 0; }
public static int M2Static() { return 0; }
private int M2AccessA() { return 0; }
internal int M2AccessB() { return 0; }
protected internal int M2AccessC() { return 0; }
protected int M2AccessD() { return 0; }
public int M2AccessE() { return 0; }
public int M2Generic<T1, T2>() { return 0; }
public int M2Generic<T>(int param) { return 0; }
public int M2Generic<T>() { return 0; }
public int PNotStatic { get { return 0; } }
public static int PStatic { get { return 0; } }
private int PAccessA { get { return 0; } }
internal int PAccessB { get { return 0; } }
protected internal int PAccessC { get { return 0; } }
protected int PAccessD { get { return 0; } }
public int PAccessE { get { return 0; } }
public int this[int index1, int index2] { get { return 0; } }
public int this[int index] { get { return 0; } }
public event Action EFNotStatic;
public static event Action EFStatic;
private event Action EFAccessA;
internal event Action EFAccessB;
protected event Action EFAccessC;
protected internal event Action EFAccessD;
public event Action EFAccessE;
private C(string s);
internal C(long l);
protected C(char c);
protected internal C(short s);
public C(int a);
public C(int a, int b);
public C();
public string FNotStatic;
public static string FStatic;
public string FNotConst;
public const string FConst = ""Const, Indeed"";
private string FAccessA;
internal string FAccessB;
protected string FAccessC;
protected internal string FAccessD;
public string FAccessE;
}
}";
var expected = @"
namespace N
{
public class C
{
public const string FConst;
public static string FStatic;
public string FAccessE;
public string FNotConst;
public string FNotStatic;
protected string FAccessC;
protected internal string FAccessD;
internal string FAccessB;
private string FAccessA;
public C();
public C(int a);
public C(int a, int b);
protected C(char c);
protected internal C(short s);
internal C(long l);
private C(string s);
public int this[int index] { get; }
public int this[int index1, int index2] { get; }
public static int PStatic { get; }
public int PAccessE { get; }
public int PNotStatic { get; }
protected int PAccessD { get; }
protected internal int PAccessC { get; }
internal int PAccessB { get; }
private int PAccessA { get; }
public static event Action EFStatic;
public event Action EFAccessE;
public event Action EFNotStatic;
protected event Action EFAccessC;
protected internal event Action EFAccessD;
internal event Action EFAccessB;
private event Action EFAccessA;
public static int M2Static();
public static void MStatic();
public int M2AccessE();
public int M2Generic<T>();
public int M2Generic<T>(int param);
public int M2Generic<T1, T2>();
public int M2NotStatic();
public void MAccessE();
public void MGeneric<T>();
public void MGeneric<T>(int param);
public void MGeneric<T1, T2>();
public void MNotStatic();
protected int M2AccessD();
protected void MAccessD();
protected internal int M2AccessC();
protected internal void MAccessC();
internal int M2AccessB();
internal void MAccessB();
private int M2AccessA();
private void MAccessA();
public static C operator +(C c);
public static C operator !(C c);
public enum EAccessE { }
public enum ENameA { }
public enum ENameB { }
protected enum EAccessD { }
protected internal enum EAccessC { }
internal enum EAccessB { }
private enum EAccessA { }
public interface IAccessE { }
public interface IGeneric<T> { }
public interface IGeneric<T1, T2> { }
protected interface IAccessD { }
protected internal interface IAccessC { }
internal interface IAccessB { }
private interface IAccessA { }
public struct SAccessE { }
public struct SGeneric<T> { }
public struct SGeneric<T1, T2> { }
public struct SNameA { }
public struct SNameB { }
protected struct SAccessD { }
protected internal struct SAccessC { }
internal struct SAccessB { }
private struct SAccessA { }
public static class CStatic { }
public class CAccessE { }
public class CGeneric<T> { }
public class CGeneric<T1, T2> { }
public class CNotStatic { }
protected class CAccessD { }
protected internal class CAccessC { }
internal class CAccessB { }
private class CAccessA { }
public delegate void DAccessE();
public delegate void DGeneric<T>(T t, int i);
public delegate void DGeneric<T1, T2>(T1 a, T2 b);
protected delegate void DAccessD();
protected internal delegate void DAccessC();
internal delegate void DAccessB();
private delegate void DAccessA();
}
}";
TestGenerateFromSourceSymbol(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
forceLanguage: LanguageNames.CSharp);
initial = "Namespace [|N|] \n End Namespace";
expected = @"
Namespace N
Public Class C
Public Const FConst As String
Public Shared FStatic As String
Public FAccessE As String
Public FNotConst As String
Public FNotStatic As String
Protected FAccessC As String
Protected Friend FAccessD As String
Friend FAccessB As String
Private FAccessA As String
Public Sub New()
Public Sub New(a As Integer)
Public Sub New(a As Integer, b As Integer)
Protected Sub New(c As Char)
Protected Friend Sub New(s As Short)
Friend Sub New(l As Long)
Private Sub New(s As String)
Public Shared ReadOnly Property PStatic As Integer
Public ReadOnly Property PAccessE As Integer
Public ReadOnly Property PNotStatic As Integer
Default Public ReadOnly Property this[](index As Integer) As Integer
Default Public ReadOnly Property this[](index1 As Integer, index2 As Integer) As Integer
Protected ReadOnly Property PAccessD As Integer
Protected Friend ReadOnly Property PAccessC As Integer
Friend ReadOnly Property PAccessB As Integer
Private ReadOnly Property PAccessA As Integer
Public Shared Event EFStatic As Action
Public Event EFAccessE As Action
Public Event EFNotStatic As Action
Protected Event EFAccessC As Action
Protected Friend Event EFAccessD As Action
Friend Event EFAccessB As Action
Private Event EFAccessA As Action
Public Shared Sub MStatic()
Public Sub MAccessE()
Public Sub MGeneric(Of T)()
Public Sub MGeneric(Of T)(param As Integer)
Public Sub MGeneric(Of T1, T2)()
Public Sub MNotStatic()
Protected Sub MAccessD()
Protected Friend Sub MAccessC()
Friend Sub MAccessB()
Private Sub MAccessA()
Public Shared Function M2Static() As Integer
Public Function M2AccessE() As Integer
Public Function M2Generic(Of T)() As Integer
Public Function M2Generic(Of T)(param As Integer) As Integer
Public Function M2Generic(Of T1, T2)() As Integer
Public Function M2NotStatic() As Integer
Protected Function M2AccessD() As Integer
Protected Friend Function M2AccessC() As Integer
Friend Function M2AccessB() As Integer
Private Function M2AccessA() As Integer
Public Shared Operator +(c As C) As C
Public Shared Operator Not(c As C) As C
Public Enum EAccessE
End Enum
Public Enum ENameA
End Enum
Public Enum ENameB
End Enum
Protected Enum EAccessD
End Enum
Protected Friend Enum EAccessC
End Enum
Friend Enum EAccessB
End Enum
Private Enum EAccessA
End Enum
Public Interface IAccessE
End Interface
Public Interface IGeneric(Of T)
End Interface
Public Interface IGeneric(Of T1, T2)
End Interface
Protected Interface IAccessD
End Interface
Protected Friend Interface IAccessC
End Interface
Friend Interface IAccessB
End Interface
Private Interface IAccessA
End Interface
Public Structure SAccessE
End Structure
Public Structure SGeneric(Of T)
End Structure
Public Structure SGeneric(Of T1, T2)
End Structure
Public Structure SNameA
End Structure
Public Structure SNameB
End Structure
Protected Structure SAccessD
End Structure
Protected Friend Structure SAccessC
End Structure
Friend Structure SAccessB
End Structure
Private Structure SAccessA
End Structure
Public Class CAccessE
End Class
Public Class CGeneric(Of T)
End Class
Public Class CGeneric(Of T1, T2)
End Class
Public Class CNotStatic
End Class
Public Class CStatic
End Class
Protected Class CAccessD
End Class
Protected Friend Class CAccessC
End Class
Friend Class CAccessB
End Class
Private Class CAccessA
End Class
Public Delegate Sub DAccessE()
Public Delegate Sub DGeneric(Of T)(t As T, i As Integer)
Public Delegate Sub DGeneric(Of T1, T2)(a As T1, b As T2)
Protected Delegate Sub DAccessD()
Protected Friend Delegate Sub DAccessC()
Friend Delegate Sub DAccessB()
Private Delegate Sub DAccessA()
End Class
End Namespace";
TestGenerateFromSourceSymbol(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
forceLanguage: LanguageNames.VisualBasic);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public void TestSortingDefaultTypeMemberAccessibility1()
{
var generationSource = "public class [|C|] { private string B; public string C; }";
var initial = "public class [|C|] { string A; }";
var expected = @"
public class C
{
public string C;
string A;
private string B;
}";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "public struct [|S|] { string A; }";
expected = @"
public struct S
{
public string C;
string A;
private string B;
}";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Class [|C|] \n Dim A As String \n End Class";
expected = @"
Public Class C
Public C As String
Dim A As String
Private B As String
End Class";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Module [|M|] \n Dim A As String \n End Module";
expected = @"
Public Module M
Public C As String
Dim A As String
Private B As String
End Module";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Structure [|S|] \n Dim A As String \n End Structure";
expected = @"
Public Structure S
Dim A As String
Public C As String
Private B As String
End Structure";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public void TestDefaultTypeMemberAccessibility2()
{
var generationSource = "public class [|C|] { private void B(){} public void C(){} }";
var initial = "public interface [|I|] { void A(); }";
var expected = @"
public interface I
{
void A();
void B();
void C();
}";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Interface [|I|] \n Sub A() \n End Interface";
expected = @"
Public Interface I
Sub A()
Sub B()
Sub C()
End Interface";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Class [|C|] \n Sub A() \n End Sub \n End Class";
expected = @"
Public Class C
Sub A()
End Sub
Public Sub C()
End Sub
Private Sub B()
End Sub
End Class";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Module [|M|] \n Sub A() \n End Sub \n End Module";
expected = @"
Public Module M
Sub A()
End Sub
Public Sub C()
End Sub
Private Sub B()
End Sub
End Module";
TestGenerateFromSourceSymbol(generationSource, initial, expected, onlyGenerateMembers: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public void TestDefaultNamespaceMemberAccessibility1()
{
var generationSource = "internal class [|B|]{}";
var initial = "namespace [|N|] { class A{} }";
var expected = "namespace N { class A{} internal class B{} }";
TestGenerateFromSourceSymbol(generationSource, initial, expected);
initial = "Namespace [|N|] \n Class A \n End Class \n End Namespace";
expected = "Namespace N \n Class A \n End Class \n Friend Class B \n End Class \n End Namespace";
TestGenerateFromSourceSymbol(generationSource, initial, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public void TestDefaultNamespaceMemberAccessibility2()
{
var generationSource = "public class [|C|]{}";
var initial = "namespace [|N|] { class A{} }";
var expected = "namespace N { public class C{} class A{} }";
TestGenerateFromSourceSymbol(generationSource, initial, expected);
initial = "Namespace [|N|] \n Class A \n End Class \n End Namespace";
expected = "Namespace N \n Public Class C \n End Class \n Class A \n End Class \n End Namespace";
TestGenerateFromSourceSymbol(generationSource, initial, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TestDocumentationComment()
{
var generationSource = @"
public class [|C|]
{
/// <summary>When in need, a documented method is a friend, indeed.</summary>
public C() { }
}";
var initial = "public class [|C|] { }";
var expected = @"
public class C
{
/// <summary>When in need, a documented method is a friend, indeed.</summary>
public C();
}";
TestGenerateFromSourceSymbol(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false, generateDocumentationComments: true),
onlyGenerateMembers: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void TestModifiers()
{
var generationSource = @"
namespace [|N|]
{
public class A
{
public virtual string Property { get { return null; } }
public static abstract string Property1 { get; }
public virtual void Method1() {}
public static abstract void Method2() {}
}
public class C
{
public sealed override string Property { get { return null; } }
public sealed override void Method1() {}
}
}";
var initial = "namespace [|N|] { }";
var expected = @"
namespace N
{
namespace N
{
public class A
{
public static abstract string Property1 { get; }
public virtual string Property { get; }
public abstract static void Method2();
public virtual void Method1();
}
public class C
{
public sealed override string Property { get; }
public sealed override void Method1();
}
}
}
";
TestGenerateFromSourceSymbol(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
var initialVB = "Namespace [|N|] End Namespace";
var expectedVB = @"
Namespace N
Namespace N
Public Class A
Public Shared MustOverride ReadOnly Property Property1 As String
Public Overridable ReadOnly Property [Property] As String
Public MustOverride Shared Sub Method2()
Public Overridable Sub Method1()
End Class
Public Class C
Public Overrides NotOverridable ReadOnly Property [Property] As String
Public NotOverridable Overrides Sub Method1()
End Class
End Namespace
";
TestGenerateFromSourceSymbol(generationSource, initialVB, expectedVB,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
public class Device : DNABit
{
//TODO load that value from file
//TODO FIXME consumption should not be platform-hardware dependent:
// slow machines _energyPerBasePair = 0.005f;
// fast machines _energyPerBasePair = 0.002f;
private static float _energyPerBasePair = 0.002f;
private static int _idCounter;
private int _id;
//TODO factorize code with ExpressionModule's
public string displayedName { get; set; }
private string _internalName;
public override string getInternalName()
{
// Debug.Log(this.GetType() + " getInternalName()");
if (string.IsNullOrEmpty(_internalName))
{
_internalName = generateInternalName();
}
return _internalName;
}
private LinkedList<ExpressionModule> _modules;
public LinkedList<ExpressionModule> getExpressionModules() { return _modules; }
public PromoterBrick.Regulation getRegulation()
{
try
{
return ((PromoterBrick)_modules.First.Value.getBioBricks().First.Value).getRegulation();
}
catch
{
Debug.LogWarning(this.GetType() + " getRegulation error on " + this);
return PromoterBrick.Regulation.CONSTANT;
}
}
// _level
private const float _level0 = .06f;
private const float _level1 = .126f;
private const float _level2 = .23f;
private const float _level3 = .4f;
private const float _level01Threshold = (_level0 + _level1) / 2;
private const float _level12Threshold = (_level1 + _level2) / 2;
private const float _level23Threshold = (_level2 + _level3) / 2;
private int _levelIndex = -1;
public int levelIndex
{
get
{
if (-1 == _levelIndex)
{
initializeLevelIndex();
}
return _levelIndex;
}
private set
{
_levelIndex = value;
}
}
private void initializeLevelIndex()
{
float expressionLevel = getExpressionLevel();
if (expressionLevel < _level01Threshold)
{
levelIndex = 0;
}
else if (expressionLevel < _level12Threshold)
{
levelIndex = 1;
}
else if (expressionLevel < _level23Threshold)
{
levelIndex = 2;
}
else
{
levelIndex = 3;
}
}
protected int _length;
public void updateLength()
{
int sum = 0;
foreach (ExpressionModule em in _modules)
sum += em.getSize();
// Debug.Log("Size " + sum + " for " + this);
_length = sum;
}
public override int getLength()
{
if (0 == _length)
{
updateLength();
}
return _length;
}
public override string getTooltipTitleKey()
{
// Debug.Log(this.GetType() + " getTooltipTitleKey " + this);
return GameplayNames.generateRealNameFromBricks(this);
}
public override string getTooltipExplanation()
{
return TooltipManager.produceExplanation(this);
}
private void idInit()
{
_id = _idCounter;
_idCounter += 1;
}
private Device()
{
idInit();
}
//generates internal name from expression modules sequence
private string generateInternalName()
{
// Debug.Log(this.GetType() + " generateName(bricks)");
return generateInternalName(_modules);
}
private static string generateInternalName(LinkedList<ExpressionModule> modules)
{
// Debug.Log(this.GetType() + " Device generateInternalName(modules="+Logger.ToString(modules)+")");
string name = "";
//TODO extract this
string separator = "+";
if (isValid(modules))
{
LinkedList<ExpressionModule> ems = new LinkedList<ExpressionModule>(modules);
while (1 != ems.Count)
{
string toAppend = ems.First.Value.getInternalName() + separator;
name += toAppend;
ems.RemoveFirst();
}
name += ems.First.Value.getInternalName();
return name;
}
else
{
Debug.LogWarning("Device generateInternalName got invalid expression modules sequence");
return "";
}
}
private Device(string name, LinkedList<ExpressionModule> modules)
{
// Debug.Log(this.GetType() + " Device("+name+", modules="+Logger.ToString(modules)+")");
idInit();
displayedName = name;
_internalName = generateInternalName(modules);
_modules = new LinkedList<ExpressionModule>();
foreach (ExpressionModule em in modules)
{
_modules.AddLast(new ExpressionModule(em));
}
}
//returns the code name of the first - 'upstream' - protein produced by the device
public string getFirstGeneProteinName()
{
foreach (ExpressionModule module in _modules)
{
foreach (BioBrick brick in module.getBioBricks())
{
if (brick.getType() == BioBrick.Type.GENE)
{
// Debug.Log("((GeneBrick)brick).getProteinName()="+((GeneBrick)brick).getProteinName());
return ((GeneBrick)brick).getProteinName();
}
}
}
return null;
}
public string getFirstGeneBrickName()
{
foreach (ExpressionModule module in _modules)
{
foreach (BioBrick brick in module.getBioBricks())
{
if (brick.getType() == BioBrick.Type.GENE)
{
// Debug.Log("brick.getInternalName()="+brick.getInternalName());
return brick.getInternalName();
}
}
}
return null;
}
public LinkedList<BioBrick> getBioBricks()
{
LinkedList<BioBrick> result = new LinkedList<BioBrick>();
foreach (ExpressionModule module in _modules)
{
result.AppendRange(module.getBioBricks());
}
return result;
}
public float getExpressionLevel()
{
foreach (ExpressionModule module in _modules)
{
foreach (BioBrick brick in module.getBioBricks())
{
if (brick.getType() == BioBrick.Type.RBS)
{
return ((RBSBrick)brick).getRBSFactor();
}
}
}
return 0f;
}
public override string ToString()
{
return string.Format("[Device: id : {0}, name: {1}, [ExpressionModules: {2}]", _id, displayedName, Logger.ToString(_modules));
}
private LinkedList<Product> getProductsFromBiobricks(LinkedList<BioBrick> list)
{
// Debug.Log(this.GetType() + " getProductsFromBioBricks([list: "+Logger.ToString(list)+"])");
LinkedList<Product> products = new LinkedList<Product>();
Product prod;
RBSBrick rbs;
GeneBrick gene;
float RBSf = 0f;
string molName = "Unknown";
int i = 0;
foreach (BioBrick b in list)
{
// Debug.Log(this.GetType() + " getProductsFromBioBricks: starting treatment of "+b.ToString());
rbs = b as RBSBrick;
if (rbs != null)
{
// Debug.Log(this.GetType() + " getProductsFromBioBricks: rbs spotted");
RBSf = rbs.getRBSFactor();
}
else
{
// Debug.Log(this.GetType() + " getProductsFromBioBricks: not an rbs");
gene = b as GeneBrick;
if (gene != null)
{
molName = gene.getProteinName();
prod = new Product(molName, RBSf);
products.AddLast(prod);
}
else
{
if (b as TerminatorBrick == null)
Debug.LogWarning(this.GetType() + " getProductsFromBioBricks This case should never happen. Bad Biobrick in operon.");
else
{
break;
}
}
}
i++;
}
while (i > 0)
{
list.RemoveFirst();
i--;
}
return products;
}
private PromoterProperties getPromoterReaction(ExpressionModule em, int id)
{
// Debug.Log(this.GetType() + " getPromoterReaction("+em.ToString()+", "+id+")");
PromoterProperties prom = new PromoterProperties();
prom.energyCost = _energyPerBasePair * em.getSize();
//promoter only
//prom.energyCost = _energyPerBasePair*em.getBioBricks().First.Value.getSize();
LinkedList<BioBrick> bricks = em.getBioBricks();
//TODO fix this: create good properties' name
prom.name = _internalName + id;
PromoterBrick p = bricks.First.Value as PromoterBrick;
prom.formula = p.getFormula();
prom.beta = p.getBeta();
bricks.RemoveFirst();
prom.products = getProductsFromBiobricks(bricks);
TerminatorBrick tb = bricks.First.Value as TerminatorBrick;
prom.terminatorFactor = tb.getTerminatorFactor();
bricks.RemoveFirst();
if (bricks.Count != 0)
{
// Debug.Log(this.GetType() + " getPromoterReaction Warning: bricks.Count ="+bricks.Count);
}
return prom;
}
private LinkedList<PromoterProperties> getPromoterReactions()
{
// Debug.Log(this.GetType() + " getPromoterReactions() starting... device="+this);
//cf issue #224
//previously:
//LinkedList<ExpressionModule> modules = new LinkedList<ExpressionModule>(_modules);
//caused early deletion problem
LinkedList<ExpressionModule> modules = new LinkedList<ExpressionModule>();
foreach (ExpressionModule module in _modules)
{
modules.AddLast(new ExpressionModule(module));
}
LinkedList<PromoterProperties> reactions = new LinkedList<PromoterProperties>();
PromoterProperties reaction;
// Debug.Log(this.GetType() + " getPromoterReactions() built #modules="+modules.Count+" and #reactions="+reactions.Count);
foreach (ExpressionModule em in modules)
{
// Debug.Log(this.GetType() + " getPromoterReactions() analyzing em="+em);
reaction = getPromoterReaction(em, em.GetHashCode());
if (reaction != null)
reactions.AddLast(reaction);
}
if (reactions.Count == 0)
return null;
return reactions;
}
public LinkedList<Reaction> getReactions()
{
// Debug.Log(this.GetType() + " getReactions(); device="+this);
LinkedList<Reaction> reactions = new LinkedList<Reaction>();
LinkedList<PromoterProperties> props = new LinkedList<PromoterProperties>(getPromoterReactions());
foreach (PromoterProperties promoterProps in props)
{
// Debug.Log(this.GetType() + " getReactions() adding prop "+promoterProps);
reactions.AddLast(PromoterReaction.buildPromoterFromProps(promoterProps));
}
// Debug.Log(this.GetType() + " getReactions() with device="+this+" returns "+Logger.ToString<IReaction>(reactions));
return reactions;
}
public static bool isValid(Device device)
{
return (null != device && isValid(device._modules));
}
private static bool isValid(LinkedList<ExpressionModule> modules)
{
if (null == modules)
{
// Debug.Log(this.GetType() + " Device isValid null==modules");
return false;
}
if (0 == modules.Count)
{
// Debug.Log(this.GetType() + " Device isValid 0==modules.Count");
return false;
}
foreach (ExpressionModule em in modules)
if (!em.isValid())
{
Debug.LogWarning("Device isValid module " + em + " is invalid");
return false;
}
return true;
}
public static Device buildDevice(LinkedList<BioBrick> bricks)
{
// Debug.Log(this.GetType() + " Device buildDevice(bricks) with bricks="+bricks);
ExpressionModule em = new ExpressionModule(bricks);
return buildDevice(em);
}
public static Device buildDevice(ExpressionModule em)
{
// Debug.Log(this.GetType() + " Device buildDevice(em) with em="+em+")");
LinkedList<ExpressionModule> modules = new LinkedList<ExpressionModule>();
modules.AddLast(em);
return buildDevice(em.getInternalName(), modules);
}
public static Device buildDevice(LinkedList<ExpressionModule> modules)
{
// Debug.Log(this.GetType() + " Device buildDevice(modules)");
if (!isValid(modules))
{
Debug.LogWarning("Device buildDevice(modules) failed: modules==null or modules are invalid");
return null;
}
//TODO take into account all modules in device name
return buildDevice(modules.First.Value.getInternalName(), modules);
}
public static Device buildDevice(string name, LinkedList<ExpressionModule> modules)
{
// Debug.Log(this.GetType() + " Device buildDevice(name, modules) with name="+name);
if (!isValid(modules))
{
Debug.LogWarning("Device buildDevice(name, modules) failed: modules==null or modules are invalid");
return null;
}
Device device = new Device(name, modules);
// Debug.Log(this.GetType() + " Device buildDevice returns "+device);
return device;
}
//copy factory
public static Device buildDevice(Device device)
{
if (device == null)
{
Debug.LogWarning("Device buildDevice device == null");
return null;
}
return buildDevice(device.getInternalName(), device._modules);
}
//helper for simple devices
public static Device buildDevice(string name,
float beta,//promoter
string formula,//promoter
float rbsFactor,//rbs
string proteinName,//gene
float terminatorFactor,//terminator
int pSize = 0,
int rSize = 0,
int gSize = 0,
int tSize = 0
)
{
string nullName = (name == null) ? "(null)" : "";
// Debug.Log(this.GetType() + " Device buildDevice(name="+name+nullName
// +", beta="+beta
// +", formula='"+formula
// +"', rbsFactor="+rbsFactor
// +", proteinName="+proteinName
// +", terminatorFactor="+terminatorFactor
// +") starting...");
string notNullName = name;
if (notNullName == null)
{
notNullName = "device" + _idCounter;
}
BioBrick[] bioBrickArray = {
new PromoterBrick(notNullName+"_promoter", beta, formula, pSize),
new RBSBrick(notNullName+"_rbs", rbsFactor, rSize),
new GeneBrick(notNullName+"_gene", proteinName, gSize),
new TerminatorBrick(notNullName+"_terminator", terminatorFactor, tSize)
};
LinkedList<BioBrick> bricks = new LinkedList<BioBrick>(bioBrickArray);
ExpressionModule[] modulesArray = { new ExpressionModule(notNullName + "_module", bricks) };
LinkedList<ExpressionModule> modules = new LinkedList<ExpressionModule>(modulesArray);
return Device.buildDevice(notNullName, modules);
}
public bool hasSameBricks(Device device)
{
if (!Device.isValid(device)
|| (device._modules.Count != _modules.Count)
)
{
return false;
}
IEnumerator<ExpressionModule> enumerator1 = device._modules.GetEnumerator();
IEnumerator<ExpressionModule> enumerator2 = _modules.GetEnumerator();
while (enumerator1.MoveNext() && enumerator2.MoveNext())
{
if (!enumerator1.Current.hasSameBricks(enumerator2.Current))
{
return false;
}
}
return true;
}
public override bool Equals(System.Object obj)
{
if (obj == null)
{
return false;
}
Device d = obj as Device;
if ((System.Object)d == null)
{
return false;
}
// bool sameBricks = this.hasSameBricks(d);
// if(sameBricks)
// Debug.Log(this.GetType() + " equals returns " + sameBricks + " between " + this + " and " + d);
return this.hasSameBricks(d);
}
}
| |
//===============================================================================
// This file is based on the Microsoft Data Access Application Block for .NET
// For more information please go to
// http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
//===============================================================================
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace Maticsoft.DBUtility
{
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance,
/// scalable best practices for common uses of SqlClient.
/// </summary>
public abstract class SqlHelper
{
//Database connection strings
public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.AppSettings["SQLConnString1"];
public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.AppSettings["SQLConnString2"];
public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.AppSettings["SQLConnString3"];
public static readonly string ConnectionStringProfile = ConfigurationManager.AppSettings["SQLProfileConnString"];
// Hashtable to store cached parameters
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="trans">an existing sql transaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the results</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
// we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// add parameter array to the cache
/// </summary>
/// <param name="cacheKey">Key to the parameter cache</param>
/// <param name="cmdParms">an array of SqlParamters to be cached</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
/// <summary>
/// Retrieve cached parameters
/// </summary>
/// <param name="cacheKey">key used to lookup parameters</param>
/// <returns>Cached SqlParamters array</returns>
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
if (cachedParms == null)
return null;
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
/// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name="cmd">SqlCommand object</param>
/// <param name="conn">SqlConnection object</param>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
/// <param name="cmdText">Command text, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.OptionalModules.Scripting.Minimodule.Object;
using System;
using System.Security;
using PrimType = OpenSim.Region.OptionalModules.Scripting.Minimodule.Object.PrimType;
using SculptType = OpenSim.Region.OptionalModules.Scripting.Minimodule.Object.SculptType;
namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
{
internal class SOPObject : MarshalByRefObject, IObject, IObjectPhysics, IObjectShape, IObjectSound
{
private readonly uint m_localID;
private readonly Scene m_rootScene;
private readonly ISecurityCredential m_security;
[Obsolete("Replace with 'credential' constructor [security]")]
public SOPObject(Scene rootScene, uint localID)
{
m_rootScene = rootScene;
m_localID = localID;
}
public SOPObject(Scene rootScene, uint localID, ISecurityCredential credential)
{
m_rootScene = rootScene;
m_localID = localID;
m_security = credential;
}
public IObject[] Children
{
get
{
SceneObjectPart my = GetSOP();
IObject[] rets = null;
int total = my.ParentGroup.PrimCount;
rets = new IObject[total];
int i = 0;
foreach (SceneObjectPart part in my.ParentGroup.Parts)
{
rets[i++] = new SOPObject(m_rootScene, part.LocalId, m_security);
}
return rets;
}
}
public UUID CreatorId
{
get { return GetSOP().CreatorID; }
}
public string Description
{
get { return GetSOP().Description; }
set
{
if (CanEdit())
GetSOP().Description = value;
}
}
public bool Exists
{
get { return GetSOP() != null; }
}
public UUID GlobalID
{
get { return GetSOP().UUID; }
}
public IObjectInventory Inventory
{
get { return new SOPObjectInventory(m_rootScene, GetSOP().TaskInventory); }
}
public bool IsAlwaysReturned
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsFlexible
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsImmotile
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsRotationLockedX
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsRotationLockedY
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsRotationLockedZ
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsSandboxed
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsTemporary
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public uint LocalID
{
get { return m_localID; }
}
public IObjectMaterial[] Materials
{
get
{
SceneObjectPart sop = GetSOP();
IObjectMaterial[] rets = new IObjectMaterial[getNumberOfSides(sop)];
for (int i = 0; i < rets.Length; i++)
{
rets[i] = new SOPObjectMaterial(i, sop);
}
return rets;
}
}
public string Name
{
get { return GetSOP().Name; }
set
{
if (CanEdit())
GetSOP().Name = value;
}
}
public Vector3 OffsetPosition
{
get { return GetSOP().OffsetPosition; }
set
{
if (CanEdit())
{
GetSOP().OffsetPosition = value;
}
}
}
public Quaternion OffsetRotation
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public UUID OwnerId
{
get { return GetSOP().OwnerID; }
}
public IObjectPhysics Physics
{
get { return this; }
}
public PhysicsMaterial PhysicsMaterial
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public IObject Root
{
get { return new SOPObject(m_rootScene, GetSOP().ParentGroup.RootPart.LocalId, m_security); }
}
public Vector3 Scale
{
get { return GetSOP().Scale; }
set
{
if (CanEdit())
GetSOP().Scale = value;
}
}
public IObjectShape Shape
{
get { return this; }
}
public Vector3 SitTarget
{
get { return GetSOP().SitTargetPosition; }
set
{
if (CanEdit())
{
GetSOP().SitTargetPosition = value;
}
}
}
public string SitTargetText
{
get { return GetSOP().SitName; }
set
{
if (CanEdit())
{
GetSOP().SitName = value;
}
}
}
public string Text
{
get { return GetSOP().Text; }
set
{
if (CanEdit())
{
GetSOP().SetText(value, new Vector3(1.0f, 1.0f, 1.0f), 1.0f);
}
}
}
public string TouchText
{
get { return GetSOP().TouchName; }
set
{
if (CanEdit())
{
GetSOP().TouchName = value;
}
}
}
public Vector3 WorldPosition
{
get { return GetSOP().AbsolutePosition; }
set
{
if (CanEdit())
{
SceneObjectPart pos = GetSOP();
pos.UpdateOffSet(value - pos.AbsolutePosition);
}
}
}
public Quaternion WorldRotation
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
private bool CanEdit()
{
if (!m_security.CanEditObject(this))
{
throw new SecurityException("Insufficient Permission to edit object with UUID [" + GetSOP().UUID + "]");
}
return true;
}
/// <summary>
/// This needs to run very, very quickly.
/// It is utilized in nearly every property and method.
/// </summary>
/// <returns></returns>
private SceneObjectPart GetSOP()
{
return m_rootScene.GetSceneObjectPart(m_localID);
}
#region OnTouch
private bool _OnTouchActive = false;
public event OnTouchDelegate OnTouch
{
add
{
if (CanEdit())
{
if (!_OnTouchActive)
{
GetSOP().Flags |= PrimFlags.Touch;
_OnTouchActive = true;
m_rootScene.EventManager.OnObjectGrab += EventManager_OnObjectGrab;
}
_OnTouch += value;
}
}
remove
{
_OnTouch -= value;
if (_OnTouch == null)
{
GetSOP().Flags &= ~PrimFlags.Touch;
_OnTouchActive = false;
m_rootScene.EventManager.OnObjectGrab -= EventManager_OnObjectGrab;
}
}
}
private event OnTouchDelegate _OnTouch;
private void EventManager_OnObjectGrab(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs)
{
if (_OnTouchActive && m_localID == localID)
{
TouchEventArgs e = new TouchEventArgs();
e.Avatar = new SPAvatar(m_rootScene, remoteClient.AgentId, m_security);
e.TouchBiNormal = surfaceArgs.Binormal;
e.TouchMaterialIndex = surfaceArgs.FaceIndex;
e.TouchNormal = surfaceArgs.Normal;
e.TouchPosition = surfaceArgs.Position;
e.TouchST = new Vector2(surfaceArgs.STCoord.X, surfaceArgs.STCoord.Y);
e.TouchUV = new Vector2(surfaceArgs.UVCoord.X, surfaceArgs.UVCoord.Y);
IObject sender = this;
if (_OnTouch != null)
_OnTouch(sender, e);
}
}
#endregion OnTouch
#region Public Functions
public void Dialog(UUID avatar, string message, string[] buttons, int chat_channel)
{
if (!CanEdit())
return;
IDialogModule dm = m_rootScene.RequestModuleInterface<IDialogModule>();
if (dm == null)
return;
if (buttons.Length < 1)
{
Say("ERROR: No less than 1 button can be shown", 2147483647);
return;
}
if (buttons.Length > 12)
{
Say("ERROR: No more than 12 buttons can be shown", 2147483647);
return;
}
foreach (string button in buttons)
{
if (button == String.Empty)
{
Say("ERROR: button label cannot be blank", 2147483647);
return;
}
if (button.Length > 24)
{
Say("ERROR: button label cannot be longer than 24 characters", 2147483647);
return;
}
}
dm.SendDialogToUser(
avatar, GetSOP().Name, GetSOP().UUID, GetSOP().OwnerID,
message, new UUID("00000000-0000-2222-3333-100000001000"), chat_channel, buttons);
}
public void Say(string msg)
{
if (!CanEdit())
return;
SceneObjectPart sop = GetSOP();
m_rootScene.SimChat(msg, ChatTypeEnum.Say, sop.AbsolutePosition, sop.Name, sop.UUID, false);
}
public void Say(string msg, int channel)
{
if (!CanEdit())
return;
SceneObjectPart sop = GetSOP();
m_rootScene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say, channel, sop.AbsolutePosition, sop.Name, sop.UUID, false);
}
#endregion Public Functions
#region Supporting Functions
private static int getNumberOfSides(SceneObjectPart part)
{
int ret;
bool hasCut;
bool hasHollow;
bool hasDimple;
bool hasProfileCut;
int primType = getScriptPrimType(part.Shape);
hasCutHollowDimpleProfileCut(primType, part.Shape, out hasCut, out hasHollow, out hasDimple, out hasProfileCut);
switch (primType)
{
default:
case (int)PrimType.Box:
ret = 6;
if (hasCut) ret += 2;
if (hasHollow) ret += 1;
break;
case (int)PrimType.Cylinder:
ret = 3;
if (hasCut) ret += 2;
if (hasHollow) ret += 1;
break;
case (int)PrimType.Prism:
ret = 5;
if (hasCut) ret += 2;
if (hasHollow) ret += 1;
break;
case (int)PrimType.Sphere:
ret = 1;
if (hasCut) ret += 2;
if (hasDimple) ret += 2;
if (hasHollow)
ret += 1; // GOTCHA: LSL shows 2 additional sides here.
// This has been fixed, but may cause porting issues.
break;
case (int)PrimType.Torus:
ret = 1;
if (hasCut) ret += 2;
if (hasProfileCut) ret += 2;
if (hasHollow) ret += 1;
break;
case (int)PrimType.Tube:
ret = 4;
if (hasCut) ret += 2;
if (hasProfileCut) ret += 2;
if (hasHollow) ret += 1;
break;
case (int)PrimType.Ring:
ret = 3;
if (hasCut) ret += 2;
if (hasProfileCut) ret += 2;
if (hasHollow) ret += 1;
break;
case (int)PrimType.Sculpt:
ret = 1;
break;
}
return ret;
}
private static int getScriptPrimType(PrimitiveBaseShape primShape)
{
if (primShape.SculptEntry)
return (int)PrimType.Sculpt;
if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
{
if (primShape.PathCurve == (byte)Extrusion.Straight)
return (int)PrimType.Box;
if (primShape.PathCurve == (byte)Extrusion.Curve1)
return (int)PrimType.Tube;
}
else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
{
if (primShape.PathCurve == (byte)Extrusion.Straight)
return (int)PrimType.Cylinder;
if (primShape.PathCurve == (byte)Extrusion.Curve1)
return (int)PrimType.Torus;
}
else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
{
if (primShape.PathCurve == (byte)Extrusion.Curve1 || primShape.PathCurve == (byte)Extrusion.Curve2)
return (int)PrimType.Sphere;
}
else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
{
if (primShape.PathCurve == (byte)Extrusion.Straight)
return (int)PrimType.Prism;
if (primShape.PathCurve == (byte)Extrusion.Curve1)
return (int)PrimType.Ring;
}
return (int)PrimType.NotPrimitive;
}
// Helper functions to understand if object has cut, hollow, dimple, and other affecting number of faces
private static void hasCutHollowDimpleProfileCut(int primType, PrimitiveBaseShape shape, out bool hasCut, out bool hasHollow,
out bool hasDimple, out bool hasProfileCut)
{
if (primType == (int)PrimType.Box
||
primType == (int)PrimType.Cylinder
||
primType == (int)PrimType.Prism)
hasCut = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0);
else
hasCut = (shape.PathBegin > 0) || (shape.PathEnd > 0);
hasHollow = shape.ProfileHollow > 0;
hasDimple = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0); // taken from llSetPrimitiveParms
hasProfileCut = hasDimple; // is it the same thing?
}
#endregion Supporting Functions
#region IObjectPhysics
public Vector3 Acceleration
{
get
{
Vector3 tmp = GetSOP().PhysActor.Acceleration;
return tmp;
}
}
public double Buoyancy
{
get { return GetSOP().PhysActor.Buoyancy; }
set { GetSOP().PhysActor.Buoyancy = (float)value; }
}
public Vector3 CenterOfMass
{
get
{
Vector3 tmp = GetSOP().PhysActor.CenterOfMass;
return tmp;
}
}
public double Density
{
get { return (GetSOP().PhysActor.Mass / Scale.X * Scale.Y / Scale.Z); }
set { throw new NotImplementedException(); }
}
public bool Enabled
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool FloatOnWater
{
set
{
if (!CanEdit())
return;
GetSOP().PhysActor.FloatOnWater = value;
}
}
public Vector3 Force
{
get
{
Vector3 tmp = GetSOP().PhysActor.Force;
return tmp;
}
set
{
if (!CanEdit())
return;
GetSOP().PhysActor.Force = value;
}
}
public Vector3 GeometricCenter
{
get
{
Vector3 tmp = GetSOP().PhysActor.GeometricCenter;
return tmp;
}
}
public double Mass
{
get { return GetSOP().PhysActor.Mass; }
set { throw new NotImplementedException(); }
}
public bool Phantom
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool PhantomCollisions
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public Vector3 RotationalVelocity
{
get
{
Vector3 tmp = GetSOP().PhysActor.RotationalVelocity;
return tmp;
}
set
{
if (!CanEdit())
return;
GetSOP().PhysActor.RotationalVelocity = value;
}
}
public Vector3 Torque
{
get
{
Vector3 tmp = GetSOP().PhysActor.Torque;
return tmp;
}
set
{
if (!CanEdit())
return;
GetSOP().PhysActor.Torque = value;
}
}
public Vector3 Velocity
{
get
{
Vector3 tmp = GetSOP().PhysActor.Velocity;
return tmp;
}
set
{
if (!CanEdit())
return;
GetSOP().PhysActor.Velocity = value;
}
}
public void AddAngularForce(Vector3 force, bool pushforce)
{
if (!CanEdit())
return;
GetSOP().PhysActor.AddAngularForce(force, pushforce);
}
public void AddForce(Vector3 force, bool pushforce)
{
if (!CanEdit())
return;
GetSOP().PhysActor.AddForce(force, pushforce);
}
public void SetMomentum(Vector3 momentum)
{
if (!CanEdit())
return;
GetSOP().PhysActor.SetMomentum(momentum);
}
#endregion IObjectPhysics
#region Implementation of IObjectShape
private UUID m_sculptMap = UUID.Zero;
private SculptType m_sculptType = Object.SculptType.Default;
public double HoleSize
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public HoleShape HoleType
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public PrimType PrimType
{
get { return (PrimType)getScriptPrimType(GetSOP().Shape); }
set { throw new System.NotImplementedException(); }
}
public UUID SculptMap
{
get { return m_sculptMap; }
set
{
if (!CanEdit())
return;
m_sculptMap = value;
SetPrimitiveSculpted(SculptMap, (byte)SculptType);
}
}
public SculptType SculptType
{
get { return m_sculptType; }
set
{
if (!CanEdit())
return;
m_sculptType = value;
SetPrimitiveSculpted(SculptMap, (byte)SculptType);
}
}
private void SetPrimitiveSculpted(UUID map, byte type)
{
ObjectShapePacket.ObjectDataBlock shapeBlock = new ObjectShapePacket.ObjectDataBlock();
SceneObjectPart part = GetSOP();
UUID sculptId = map;
shapeBlock.ObjectLocalID = part.LocalId;
shapeBlock.PathScaleX = 100;
shapeBlock.PathScaleY = 150;
// retain pathcurve
shapeBlock.PathCurve = part.Shape.PathCurve;
part.Shape.SetSculptProperties((byte)type, sculptId);
part.Shape.SculptEntry = true;
part.UpdateShape(shapeBlock);
}
#endregion Implementation of IObjectShape
#region Implementation of IObjectSound
public IObjectSound Sound
{
get { return this; }
}
public void Play(UUID asset, double volume)
{
if (!CanEdit())
return;
ISoundModule module = m_rootScene.RequestModuleInterface<ISoundModule>();
if (module != null)
{
module.SendSound(GetSOP().UUID, asset, volume, true, 0, 0, false, false);
}
}
#endregion Implementation of IObjectSound
}
}
| |
/// Copyright (C) 2012-2014 Soomla 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.
using UnityEngine;
using System;
using System.Runtime.InteropServices;
namespace Soomla.Store
{
/// <summary>
/// This class holds the basic assets needed to operate the Store.
/// You can use it to purchase products from the mobile store.
/// This is the only class you need to initialize in order to use the SOOMLA SDK.
/// </summary>
public class SoomlaStore
{
static SoomlaStore _instance = null;
static SoomlaStore instance {
get {
if(_instance == null) {
#if UNITY_ANDROID && !UNITY_EDITOR
_instance = new SoomlaStoreAndroid();
#elif UNITY_IOS && !UNITY_EDITOR
_instance = new SoomlaStoreIOS();
#elif UNITY_WP8 && !UNITY_EDITOR
_instance = new SoomlaStoreWP();
#else
_instance = new SoomlaStore();
#endif
}
return _instance;
}
}
/// <summary>
/// Initializes the SOOMLA SDK.
/// </summary>
/// <param name="storeAssets">Your game's economy.</param>
/// <exception cref="ExitGUIException">Thrown if soomlaSecret is missing or has not been changed.</exception>
public static bool Initialize(IStoreAssets storeAssets) {
if (string.IsNullOrEmpty(CoreSettings.SoomlaSecret)) {
SoomlaUtils.LogError(TAG, "MISSING SoomlaSecret !!! Stopping here !!");
throw new ExitGUIException();
}
if (CoreSettings.SoomlaSecret==CoreSettings.ONLY_ONCE_DEFAULT) {
SoomlaUtils.LogError(TAG, "You have to change SoomlaSecret !!! Stopping here !!");
throw new ExitGUIException();
}
var storeEvents = GameObject.FindObjectOfType<StoreEvents> ();
if (storeEvents == null) {
SoomlaUtils.LogDebug(TAG, "StoreEvents Component not found in scene. We're continuing from here but you won't get many events.");
}
if (Initialized) {
StoreEvents.Instance.onUnexpectedStoreError("{\"errorCode\": 0}", true);
SoomlaUtils.LogError(TAG, "SoomlaStore is already initialized. You can't initialize it twice!");
return false;
}
SoomlaUtils.LogDebug(TAG, "SoomlaStore Initializing ...");
StoreInfo.SetStoreAssets(storeAssets);
instance._loadBillingService();
#if UNITY_IOS
// On iOS we only refresh market items
instance._refreshMarketItemsDetails();
#elif UNITY_ANDROID
// On Android we refresh market items and restore transactions
instance._refreshInventory();
#elif UNITY_WP8
instance._refreshInventory();
#endif
Initialized = true;
StoreEvents.Instance.onSoomlaStoreInitialized("", true);
return true;
}
/// <summary>
/// Starts a purchase process in the market.
/// </summary>
/// <param name="productId">product id of the item to buy. This id is the one you set up on itunesconnect or Google Play developer console.</param>
/// <param name="payload">Some text you want to get back when the purchasing process is completed.</param>
public static void BuyMarketItem(string productId, string payload) {
instance._buyMarketItem(productId, payload);
}
/// <summary>
/// This method will run RestoreTransactions followed by RefreshMarketItemsDetails
/// </summary>
public static void RefreshInventory() {
instance._refreshInventory();
}
/// <summary>
/// Creates a list of all metadata stored in the Market (the items that have been purchased).
/// The metadata includes the item's name, description, price, product id, etc...
/// Posts a <c>MarketItemsRefreshed</c> event with the list just created.
/// Upon failure, prints error message.
/// </summary>
public static void RefreshMarketItemsDetails() {
instance._refreshMarketItemsDetails();
}
/// <summary>
/// Initiates the restore transactions process.
/// </summary>
public static void RestoreTransactions() {
instance._restoreTransactions();
}
/// <summary>
/// Checks if transactions were already restored.
/// </summary>
/// <returns><c>true</c> if transactions were already restored, <c>false</c> otherwise.</returns>
public static bool TransactionsAlreadyRestored() {
return instance._transactionsAlreadyRestored();
}
/// <summary>
/// Starts in-app billing service in background.
/// </summary>
public static void StartIabServiceInBg() {
instance._startIabServiceInBg();
}
/// <summary>
/// Stops in-app billing service in background.
/// </summary>
public static void StopIabServiceInBg() {
instance._stopIabServiceInBg();
}
/** protected functions **/
/** The implementation of these functions here will be the behaviour when working in the editor **/
protected virtual void _loadBillingService() { }
protected virtual void _buyMarketItem(string productId, string payload) {
#if UNITY_EDITOR
PurchasableVirtualItem item = StoreInfo.GetPurchasableItemWithProductId(productId);
if (item == null) {
throw new VirtualItemNotFoundException("ProductId", productId);
}
// simulate onMarketPurchaseStarted event
var eventJSON = new JSONObject();
eventJSON.AddField("itemId", item.ItemId);
eventJSON.AddField("payload", payload);
StoreEvents.Instance.onMarketPurchaseStarted(eventJSON.print());
// simulate events as they happen on the device
// the order is :
// onMarketPurchase
// give item
// onItemPurchase
StoreEvents.Instance.RunLater(() => {
eventJSON = new JSONObject();
eventJSON.AddField("itemId", item.ItemId);
eventJSON.AddField("payload", payload);
var extraJSON = new JSONObject();
#if UNITY_IOS
extraJSON.AddField("receipt", "fake_receipt_abcd1234");
extraJSON.AddField("token", "fake_token_zyxw9876");
#elif UNITY_ANDROID
extraJSON.AddField("orderId", "fake_orderId_abcd1234");
extraJSON.AddField("purchaseToken", "fake_purchaseToken_zyxw9876");
#endif
eventJSON.AddField("extra", extraJSON);
StoreEvents.Instance.onMarketPurchase(eventJSON.print());
// in the editor we just give the item... no real market.
item.Give(1);
// We have to make sure the ItemPurchased event will be fired AFTER the balance/currency-changed events.
StoreEvents.Instance.RunLater(() => {
eventJSON = new JSONObject();
eventJSON.AddField("itemId", item.ItemId);
eventJSON.AddField("payload", payload);
StoreEvents.Instance.onItemPurchased(eventJSON.print());
});
});
#endif
}
protected virtual void _refreshInventory() { }
protected virtual void _restoreTransactions() { }
protected virtual void _refreshMarketItemsDetails() { }
protected virtual bool _transactionsAlreadyRestored() {
return true;
}
protected virtual void _startIabServiceInBg() { }
protected virtual void _stopIabServiceInBg() { }
/** Class Members **/
protected const string TAG = "SOOMLA SoomlaStore";
/// <summary>
/// Gets a value indicating whether <see cref="Soomla.Store.SoomlaStore"/> is initialized.
/// </summary>
/// <value><c>true</c> if initialized; otherwise, <c>false</c>.</value>
public static bool Initialized { get; private set; }
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using OpenMetaverse;
using Aurora.Framework;
using Aurora.Framework.Serialization;
using Aurora.Framework.Serialization.External;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System.Linq;
namespace Aurora.Modules.Archivers
{
/// <summary>
/// Handles an individual archive read request
/// </summary>
public class ArchiveReadRequest
{
protected static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding();
protected static UTF8Encoding m_utf8Encoding = new UTF8Encoding();
protected IScene m_scene;
protected Stream m_loadStream;
protected string m_errorMessage;
protected HashSet<AssetBase> AssetsToAdd = new HashSet<AssetBase>();
protected bool AssetSaverIsRunning = false;
protected bool m_useAsync = false;
/// <value>
/// Should the archive being loaded be merged with what is already on the region?
/// </value>
protected bool m_merge;
protected AuroraThreadPool m_threadpool;
/// <value>
/// Should we ignore any assets when reloading the archive?
/// </value>
protected bool m_skipAssets;
/// <summary>
/// Used to cache lookups for valid uuids.
/// </summary>
private readonly IDictionary<UUID, UUID> m_validUserUuids = new Dictionary<UUID, UUID>();
private int m_offsetX = 0;
private int m_offsetY = 0;
private int m_offsetZ = 0;
private bool m_flipX = false;
private bool m_flipY = false;
private bool m_useParcelOwnership = false;
private bool m_checkOwnership = false;
const string sPattern = @"(\{{0,1}([0-9a-fA-F]){8}-([0-9a-f]){4}-([0-9a-f]){4}-([0-9a-f]){4}-([0-9a-f]){12}\}{0,1})";
readonly Dictionary<UUID, AssetBase> assetNonBinaryCollection = new Dictionary<UUID, AssetBase>();
public ArchiveReadRequest(IScene scene, string loadPath, bool merge, bool skipAssets,
int offsetX, int offsetY, int offsetZ, bool flipX, bool flipY, bool useParcelOwnership, bool checkOwnership)
{
try
{
var stream = ArchiveHelpers.GetStream(loadPath);
if (stream == null)
throw new FileNotFoundException();
m_loadStream = new GZipStream(stream, CompressionMode.Decompress);
}
catch (EntryPointNotFoundException e)
{
MainConsole.Instance.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
MainConsole.Instance.Error(e);
}
Init(scene, m_loadStream, merge, skipAssets, offsetX, offsetY, offsetZ, flipX, flipY, useParcelOwnership, checkOwnership);
}
public void Init(IScene scene, Stream stream, bool merge, bool skipAssets,
int offsetX, int offsetY, int offsetZ, bool flipX, bool flipY, bool useParcelOwnership, bool checkOwnership)
{
m_loadStream = stream;
m_offsetX = offsetX;
m_offsetY = offsetY;
m_offsetZ = offsetZ;
m_flipX = flipX;
m_flipY = flipY;
m_useParcelOwnership = useParcelOwnership;
m_checkOwnership = checkOwnership;
m_scene = scene;
m_errorMessage = String.Empty;
m_merge = merge;
m_skipAssets = skipAssets;
}
public ArchiveReadRequest(IScene scene, Stream stream, bool merge, bool skipAssets,
int offsetX, int offsetY, int offsetZ, bool flipX, bool flipY, bool useParcelOwnership, bool checkOwnership)
{
Init(scene, stream, merge, skipAssets, offsetX, offsetY, offsetZ, flipX, flipY, useParcelOwnership, checkOwnership);
}
/// <summary>
/// Dearchive the region embodied in this request.
/// </summary>
public void DearchiveRegion()
{
// The same code can handle dearchiving 0.1 and 0.2 OpenSim Archive versions
DearchiveRegion0DotStar();
}
private void DearchiveRegion0DotStar()
{
int successfulAssetRestores = 0;
int failedAssetRestores = 0;
string filePath = "NONE";
DateTime start = DateTime.Now;
TarArchiveReader archive = new TarArchiveReader(m_loadStream);
if (!m_skipAssets)
m_threadpool = new Aurora.Framework.AuroraThreadPool(new Aurora.Framework.AuroraThreadPoolStartInfo()
{
Threads = 1,
priority = System.Threading.ThreadPriority.BelowNormal
});
IBackupModule backup = m_scene.RequestModuleInterface<IBackupModule>();
if (!m_merge)
{
DateTime before = DateTime.Now;
MainConsole.Instance.Info("[ARCHIVER]: Clearing all existing scene objects");
if (backup != null)
backup.DeleteAllSceneObjects();
MainConsole.Instance.Info("[ARCHIVER]: Cleared all existing scene objects in " + (DateTime.Now - before).Minutes + ":" + (DateTime.Now - before).Seconds);
}
IScriptModule[] modules = m_scene.RequestModuleInterfaces<IScriptModule>();
//Disable the script engine so that it doesn't load in the background and kill OAR loading
foreach (IScriptModule module in modules)
{
module.Disabled = true;
}
//Disable backup for now as well
if (backup != null)
backup.LoadingPrims = true;
IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>();
int sceneObjectsLoadedCount = 0;
//We save the groups so that we can back them up later
List<SceneObjectGroup> groupsToBackup = new List<SceneObjectGroup>();
List<LandData> landData = new List<LandData>();
IUserFinder UserManager = m_scene.RequestModuleInterface<IUserFinder>();
// must save off some stuff until after assets have been saved and recieved new uuids
// keeping these collection local because I am sure they will get large and garbage collection is better that way
List<byte[]> seneObjectGroups = new List<byte[]>();
Dictionary<UUID, UUID> assetBinaryChangeRecord = new Dictionary<UUID, UUID>();
Queue<UUID> assets2Save = new Queue<UUID>();
try
{
byte[] data;
TarArchiveReader.TarEntryType entryType;
while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
{
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
continue;
if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
{
seneObjectGroups.Add(data);
}
else if (!m_skipAssets && filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
{
AssetBase asset;
if (LoadAsset(filePath, data, out asset))
{
successfulAssetRestores++;
if (m_useAsync)
lock (AssetsToAdd) AssetsToAdd.Add(asset);
else
{
if (asset.IsBinaryAsset)
{
UUID aid = asset.ID;
asset.ID = m_scene.AssetService.Store(asset);
if (asset.ID != aid && asset.ID != UUID.Zero)
assetBinaryChangeRecord.Add(aid, asset.ID);
}
else
{
if (!assetNonBinaryCollection.ContainsKey(asset.ID))
{
assetNonBinaryCollection.Add(asset.ID, asset);
// I need something I can safely loop through
assets2Save.Enqueue(asset.ID);
}
}
}
}
else
failedAssetRestores++;
if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
MainConsole.Instance.Info("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
}
else if (filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
{
LoadTerrain(filePath, data);
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
{
LoadRegionSettings(filePath, data);
}
else if (filePath.StartsWith(ArchiveConstants.LANDDATA_PATH))
{
LandData parcel = LandDataSerializer.Deserialize(m_utf8Encoding.GetString(data));
parcel.OwnerID = ResolveUserUuid(parcel.OwnerID, UUID.Zero, "", Vector3.Zero, null);
landData.Add(parcel);
}
else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
{
LoadControlFile(data);
}
}
// Save Assets
int savingAssetsCount = 0;
while (assets2Save.Count > 0)
{
try
{
UUID assetid = assets2Save.Dequeue();
SaveNonBinaryAssets(assetid, assetNonBinaryCollection[assetid], assetBinaryChangeRecord);
savingAssetsCount++;
if ((savingAssetsCount) % 250 == 0)
MainConsole.Instance.Info("[ARCHIVER]: Saving " + savingAssetsCount + " assets...");
}
catch (Exception ex)
{
MainConsole.Instance.Info("[ARCHIVER]: Exception in saving an asset: " + ex.ToString());
}
}
foreach (byte[] data2 in seneObjectGroups)
{
byte[] data3 = data2;
string stringData = Utils.BytesToString(data3);
MatchCollection mc = Regex.Matches(stringData, sPattern);
bool didChange = false;
if (mc.Count >= 1)
{
foreach (Match match in mc)
{
UUID thematch = new UUID(match.Value);
UUID newvalue = thematch;
if (assetNonBinaryCollection.ContainsKey(thematch))
newvalue = assetNonBinaryCollection[thematch].ID;
else if (assetBinaryChangeRecord.ContainsKey(thematch))
newvalue = assetBinaryChangeRecord[thematch];
if (thematch == newvalue) continue;
stringData = stringData.Replace(thematch.ToString().Trim(), newvalue.ToString().Trim());
didChange = true;
}
}
if (didChange)
data3 = Utils.StringToBytes(stringData);
SceneObjectGroup sceneObject = (SceneObjectGroup)serialiser.DeserializeGroupFromXml2(data3, m_scene);
if (sceneObject == null)
{
//! big error!
MainConsole.Instance.Error("Error reading SOP XML (Please mantis this!): " + m_asciiEncoding.GetString(data3));
continue;
}
foreach (SceneObjectPart part in sceneObject.ChildrenList)
{
if (string.IsNullOrEmpty(part.CreatorData))
part.CreatorID = ResolveUserUuid(part.CreatorID, part.CreatorID, part.CreatorData, part.AbsolutePosition, landData);
if (UserManager != null)
UserManager.AddUser(part.CreatorID, part.CreatorData);
part.OwnerID = ResolveUserUuid(part.OwnerID, part.CreatorID, part.CreatorData, part.AbsolutePosition, landData);
part.LastOwnerID = ResolveUserUuid(part.LastOwnerID, part.CreatorID, part.CreatorData, part.AbsolutePosition, landData);
// And zap any troublesome sit target information
part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
part.SitTargetPosition = new Vector3(0, 0, 0);
// Fix ownership/creator of inventory items
// Not doing so results in inventory items
// being no copy/no mod for everyone
lock (part.TaskInventory)
{
TaskInventoryDictionary inv = part.TaskInventory;
foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
{
kvp.Value.OwnerID = ResolveUserUuid(kvp.Value.OwnerID, kvp.Value.CreatorID, kvp.Value.CreatorData, part.AbsolutePosition, landData);
if (string.IsNullOrEmpty(kvp.Value.CreatorData))
kvp.Value.CreatorID = ResolveUserUuid(kvp.Value.CreatorID, kvp.Value.CreatorID, kvp.Value.CreatorData, part.AbsolutePosition, landData);
if (UserManager != null)
UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
}
}
}
//Add the offsets of the region
Vector3 newPos = new Vector3(sceneObject.AbsolutePosition.X + m_offsetX,
sceneObject.AbsolutePosition.Y + m_offsetY,
sceneObject.AbsolutePosition.Z + m_offsetZ);
if (m_flipX)
newPos.X = m_scene.RegionInfo.RegionSizeX - newPos.X;
if (m_flipY)
newPos.Y = m_scene.RegionInfo.RegionSizeY - newPos.Y;
sceneObject.SetAbsolutePosition(false, newPos);
if (m_scene.SceneGraph.AddPrimToScene(sceneObject))
{
groupsToBackup.Add(sceneObject);
sceneObject.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
sceneObject.CreateScriptInstances(0, false, StateSource.RegionStart, UUID.Zero, true);
}
sceneObjectsLoadedCount++;
if (sceneObjectsLoadedCount % 250 == 0)
MainConsole.Instance.Info("[ARCHIVER]: Loaded " + sceneObjectsLoadedCount + " objects...");
}
assetNonBinaryCollection.Clear();
assetBinaryChangeRecord.Clear();
seneObjectGroups.Clear();
}
catch (Exception e)
{
MainConsole.Instance.ErrorFormat(
"[ARCHIVER]: Aborting load with error in archive file {0}. {1}", filePath, e);
m_errorMessage += e.ToString();
m_scene.EventManager.TriggerOarFileLoaded(UUID.Zero.Guid, m_errorMessage);
return;
}
finally
{
archive.Close();
m_loadStream.Close();
m_loadStream.Dispose();
//Reeanble now that we are done
foreach (IScriptModule module in modules)
{
module.Disabled = false;
}
//Reset backup too
if (backup != null)
backup.LoadingPrims = false;
}
//Now back up the prims
foreach (SceneObjectGroup grp in groupsToBackup)
{
//Backup!
grp.HasGroupChanged = true;
}
if (!m_skipAssets && m_useAsync && !AssetSaverIsRunning)
m_threadpool.QueueEvent(SaveAssets, 0);
if (!m_skipAssets)
{
MainConsole.Instance.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
if (failedAssetRestores > 0)
{
MainConsole.Instance.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
}
}
// Try to retain the original creator/owner/lastowner if their uuid is present on this grid
// otherwise, use the master avatar uuid instead
// Reload serialized parcels
MainConsole.Instance.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", landData.Count);
IParcelManagementModule parcelManagementModule = m_scene.RequestModuleInterface<IParcelManagementModule>();
if (!m_merge && parcelManagementModule != null)
parcelManagementModule.ClearAllParcels();
if (landData.Count > 0)
{
m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData, new Vector2(m_offsetX, m_offsetY));
//Update the database as well!
if (parcelManagementModule != null)
{
foreach (LandData parcel in landData)
{
parcelManagementModule.UpdateLandObject(parcelManagementModule.GetLandObject(parcel.LocalID));
}
}
}
else if (parcelManagementModule != null)
parcelManagementModule.ResetSimLandObjects();
MainConsole.Instance.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
//Clean it out
landData.Clear();
MainConsole.Instance.InfoFormat("[ARCHIVER]: Successfully loaded archive in " + (DateTime.Now - start).Minutes + ":" + (DateTime.Now - start).Seconds);
m_validUserUuids.Clear();
m_scene.EventManager.TriggerOarFileLoaded(UUID.Zero.Guid, m_errorMessage);
}
private AssetBase SaveNonBinaryAssets(UUID key, AssetBase asset, Dictionary<UUID, UUID> assetBinaryChangeRecord)
{
if (!asset.HasBeenSaved)
{
string stringData = Utils.BytesToString(asset.Data);
MatchCollection mc = Regex.Matches(stringData, sPattern);
bool didChange = false;
if (mc.Count >= 1)
{
foreach (Match match in mc)
{
UUID thematch = new UUID(match.Value);
UUID newvalue = thematch;
if ((thematch == UUID.Zero) || (thematch == key)) continue;
if (assetNonBinaryCollection.ContainsKey(thematch))
{
AssetBase subasset = assetNonBinaryCollection[thematch];
if (!subasset.HasBeenSaved)
subasset = SaveNonBinaryAssets(thematch, subasset, assetBinaryChangeRecord);
newvalue = subasset.ID;
}
else if (assetBinaryChangeRecord.ContainsKey(thematch))
newvalue = assetBinaryChangeRecord[thematch];
if (thematch == newvalue) continue;
stringData = stringData.Replace(thematch.ToString(), newvalue.ToString());
didChange = true;
}
if (didChange)
{
asset.Data = Utils.StringToBytes(stringData);
// so it doesn't try to find the old file
asset.LastHashCode = asset.HashCode;
}
}
asset.ID = m_scene.AssetService.Store(asset);
asset.HasBeenSaved = true;
}
if (assetNonBinaryCollection.ContainsKey(key))
assetNonBinaryCollection[key] = asset;
return asset;
}
/// <summary>
/// Look up the given user id to check whether it's one that is valid for this grid.
/// </summary>
/// <param name="uuid"></param>
/// <param name="creatorID"></param>
/// <param name="creatorData"></param>
/// <param name="location"></param>
/// <param name="parcels"></param>
/// <returns></returns>
private UUID ResolveUserUuid(UUID uuid, UUID creatorID, string creatorData, Vector3 location, IEnumerable<LandData> parcels)
{
UUID u;
if (!m_validUserUuids.TryGetValue(uuid, out u))
{
UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.AllScopeIDs, uuid);
if (account != null)
{
m_validUserUuids.Add(uuid, uuid);
return uuid;
}
if (uuid == creatorID)
{
UUID hid;
string first, last, url, secret;
if (HGUtil.ParseUniversalUserIdentifier(creatorData, out hid, out url, out first, out last, out secret))
{
account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.AllScopeIDs, first, last);
if (account != null)
{
m_validUserUuids.Add(uuid, account.PrincipalID);
return account.PrincipalID;//Fix the UUID
}
}
}
IUserFinder uf = m_scene.RequestModuleInterface<IUserFinder>();
if (uf != null)
if (!uf.IsLocalGridUser(uuid))//Foreign user, don't remove their info
{
m_validUserUuids.Add(uuid, uuid);
return uuid;
}
UUID id = UUID.Zero;
if (m_checkOwnership || (m_useParcelOwnership && parcels == null))//parcels == null is a parcel owner, ask for it if useparcel is on
{
tryAgain:
string ownerName = MainConsole.Instance.Prompt(string.Format("User Name to use instead of UUID '{0}'", uuid), "");
account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.AllScopeIDs, ownerName);
if (account != null)
id = account.PrincipalID;
else if (ownerName != "")
if ((ownerName = MainConsole.Instance.Prompt("User was not found, do you want to try again?", "no", new List<string>(new[] { "no", "yes" }))) == "yes")
goto tryAgain;
}
if (m_useParcelOwnership && id == UUID.Zero && location != Vector3.Zero && parcels != null)
{
foreach (LandData data in parcels)
{
if (ContainsPoint(data, (int)location.X + m_offsetX, (int)location.Y + m_offsetY))
if (uuid != data.OwnerID)
id = data.OwnerID;
}
}
if (id == UUID.Zero)
id = m_scene.RegionInfo.EstateSettings.EstateOwner;
m_validUserUuids.Add(uuid, id);
return m_validUserUuids[uuid];
}
return u;
}
private bool ContainsPoint(LandData data, int checkx, int checky)
{
int x = 0, y = 0, i = 0;
for (i = 0; i < data.Bitmap.Length; i++)
{
byte tempByte = 0;
if (i < data.Bitmap.Length)
tempByte = data.Bitmap[i];
else
break;//All the rest are false then
int bitNum = 0;
for (bitNum = 0; bitNum < 8; bitNum++)
{
if (x == checkx / 4 && y == checky / 4)
return Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & 1);
x++;
//Remove the offset so that we get a calc from the beginning of the array, not the offset array
if (x > ((m_scene.RegionInfo.RegionSizeX / 4) - 1))
{
x = 0;//Back to the beginning
y++;
}
}
}
return false;
}
/// <summary>
/// Load an asset
/// </summary>
/// <param name="assetPath"></param>
/// <param name="data"></param>
/// <param name="asset"> </param>
/// <returns>true if asset was successfully loaded, false otherwise</returns>
private bool LoadAsset(string assetPath, byte[] data, out AssetBase asset)
{
string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
if (i == -1)
{
MainConsole.Instance.ErrorFormat(
"[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
asset = null;
return false;
}
string extension = filename.Substring(i);
string uuid = filename.Remove(filename.Length - extension.Length);
if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
{
AssetType assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
if (assetType == AssetType.Unknown)
MainConsole.Instance.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
asset = new AssetBase(UUID.Parse(uuid), String.Empty, assetType, UUID.Zero) { Data = data };
return true;
}
MainConsole.Instance.ErrorFormat(
"[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
assetPath, extension);
asset = null;
return false;
}
private void SaveAssets()
{
AssetSaverIsRunning = true;
lock (AssetsToAdd)
{
foreach (AssetBase asset in AssetsToAdd)
{
asset.ID = m_scene.AssetService.Store(asset);
}
}
AssetsToAdd.Clear();
AssetSaverIsRunning = false;
}
/// <summary>
/// Load region settings data
/// </summary>
/// <param name="settingsPath"></param>
/// <param name="data"></param>
/// <returns>
/// true if settings were loaded successfully, false otherwise
/// </returns>
private void LoadRegionSettings(string settingsPath, byte[] data)
{
RegionSettings loadedRegionSettings;
try
{
loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
}
catch (Exception e)
{
MainConsole.Instance.ErrorFormat(
"[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
settingsPath, e);
return;
}
RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
currentRegionSettings.Save();
IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
if (estateModule != null)
estateModule.sendRegionHandshakeToAll();
return;
}
/// <summary>
/// Load terrain data
/// </summary>
/// <param name="terrainPath"></param>
/// <param name="data"></param>
/// <returns>
/// true if terrain was resolved successfully, false otherwise.
/// </returns>
private void LoadTerrain(string terrainPath, byte[] data)
{
ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
MemoryStream ms = new MemoryStream(data);
terrainModule.LoadFromStream(terrainPath, ms, m_offsetX, m_offsetY);
ms.Close();
MainConsole.Instance.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
}
/// <summary>
/// Load oar control file
/// </summary>
/// <param name="data"></param>
private void LoadControlFile(byte[] data)
{
//Create the XmlNamespaceManager.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
// Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader xtr
= new XmlTextReader(m_asciiEncoding.GetString(data), XmlNodeType.Document, context);
RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
// Loaded metadata will empty if no information exists in the archive
currentRegionSettings.LoadedCreationDateTime = 0;
currentRegionSettings.LoadedCreationID = "";
while (xtr.Read())
{
if (xtr.NodeType == XmlNodeType.Element)
{
if (xtr.Name == "datetime")
{
int value;
if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
currentRegionSettings.LoadedCreationDateTime = value;
}
else if (xtr.Name == "id")
{
currentRegionSettings.LoadedCreationID = xtr.ReadElementContentAsString();
}
}
}
currentRegionSettings.Save();
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace System.Data.ProviderBase
{
internal sealed class DbConnectionPool
{
private enum State
{
Initializing,
Running,
ShuttingDown,
}
private sealed class PendingGetConnection
{
public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions userOptions)
{
DueTime = dueTime;
Owner = owner;
Completion = completion;
}
public long DueTime { get; private set; }
public DbConnection Owner { get; private set; }
public TaskCompletionSource<DbConnectionInternal> Completion { get; private set; }
public DbConnectionOptions UserOptions { get; private set; }
}
private sealed class PoolWaitHandles
{
private readonly Semaphore _poolSemaphore;
private readonly ManualResetEvent _errorEvent;
// Using a Mutex requires ThreadAffinity because SQL CLR can swap
// the underlying Win32 thread associated with a managed thread in preemptive mode.
// Using an AutoResetEvent does not have that complication.
private readonly Semaphore _creationSemaphore;
private readonly WaitHandle[] _handlesWithCreate;
private readonly WaitHandle[] _handlesWithoutCreate;
internal PoolWaitHandles()
{
_poolSemaphore = new Semaphore(0, MAX_Q_SIZE);
_errorEvent = new ManualResetEvent(false);
_creationSemaphore = new Semaphore(1, 1);
_handlesWithCreate = new WaitHandle[] { _poolSemaphore, _errorEvent, _creationSemaphore };
_handlesWithoutCreate = new WaitHandle[] { _poolSemaphore, _errorEvent };
}
internal Semaphore CreationSemaphore
{
get { return _creationSemaphore; }
}
internal ManualResetEvent ErrorEvent
{
get { return _errorEvent; }
}
internal Semaphore PoolSemaphore
{
get { return _poolSemaphore; }
}
internal WaitHandle[] GetHandles(bool withCreate)
{
return withCreate ? _handlesWithCreate : _handlesWithoutCreate;
}
}
private const int MAX_Q_SIZE = (int)0x00100000;
// The order of these is important; we want the WaitAny call to be signaled
// for a free object before a creation signal. Only the index first signaled
// object is returned from the WaitAny call.
private const int SEMAPHORE_HANDLE = (int)0x0;
private const int ERROR_HANDLE = (int)0x1;
private const int CREATION_HANDLE = (int)0x2;
private const int BOGUS_HANDLE = (int)0x3;
private const int ERROR_WAIT_DEFAULT = 5 * 1000; // 5 seconds
// we do want a testable, repeatable set of generated random numbers
private static readonly Random s_random = new Random(5101977); // Value obtained from Dave Driver
private readonly int _cleanupWait;
private readonly DbConnectionPoolIdentity _identity;
private readonly DbConnectionFactory _connectionFactory;
private readonly DbConnectionPoolGroup _connectionPoolGroup;
private readonly DbConnectionPoolGroupOptions _connectionPoolGroupOptions;
private readonly DbConnectionPoolProviderInfo _connectionPoolProviderInfo;
private State _state;
private readonly ConcurrentStack<DbConnectionInternal> _stackOld = new ConcurrentStack<DbConnectionInternal>();
private readonly ConcurrentStack<DbConnectionInternal> _stackNew = new ConcurrentStack<DbConnectionInternal>();
private readonly ConcurrentQueue<PendingGetConnection> _pendingOpens = new ConcurrentQueue<PendingGetConnection>();
private int _pendingOpensWaiting = 0;
private readonly WaitCallback _poolCreateRequest;
private int _waitCount;
private readonly PoolWaitHandles _waitHandles;
private Exception _resError;
private volatile bool _errorOccurred;
private int _errorWait;
private Timer _errorTimer;
private Timer _cleanupTimer;
private readonly List<DbConnectionInternal> _objectList;
private int _totalObjects;
// only created by DbConnectionPoolGroup.GetConnectionPool
internal DbConnectionPool(
DbConnectionFactory connectionFactory,
DbConnectionPoolGroup connectionPoolGroup,
DbConnectionPoolIdentity identity,
DbConnectionPoolProviderInfo connectionPoolProviderInfo)
{
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup");
if ((null != identity) && identity.IsRestricted)
{
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken);
}
_state = State.Initializing;
lock (s_random)
{ // Random.Next is not thread-safe
_cleanupWait = s_random.Next(12, 24) * 10 * 1000; // 2-4 minutes in 10 sec intervals
}
_connectionFactory = connectionFactory;
_connectionPoolGroup = connectionPoolGroup;
_connectionPoolGroupOptions = connectionPoolGroup.PoolGroupOptions;
_connectionPoolProviderInfo = connectionPoolProviderInfo;
_identity = identity;
_waitHandles = new PoolWaitHandles();
_errorWait = ERROR_WAIT_DEFAULT;
_errorTimer = null; // No error yet.
_objectList = new List<DbConnectionInternal>(MaxPoolSize);
_poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback
_state = State.Running;
//_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls
// StartBackgroundCallbacks after pool is actually in the collection
}
private int CreationTimeout
{
get { return PoolGroupOptions.CreationTimeout; }
}
internal int Count
{
get { return _totalObjects; }
}
internal DbConnectionFactory ConnectionFactory
{
get { return _connectionFactory; }
}
internal bool ErrorOccurred
{
get { return _errorOccurred; }
}
internal TimeSpan LoadBalanceTimeout
{
get { return PoolGroupOptions.LoadBalanceTimeout; }
}
private bool NeedToReplenish
{
get
{
if (State.Running != _state) // Don't allow connection create when not running.
return false;
int totalObjects = Count;
if (totalObjects >= MaxPoolSize)
return false;
if (totalObjects < MinPoolSize)
return true;
int freeObjects = (_stackNew.Count + _stackOld.Count);
int waitingRequests = _waitCount;
bool needToReplenish = (freeObjects < waitingRequests) || ((freeObjects == waitingRequests) && (totalObjects > 1));
return needToReplenish;
}
}
internal DbConnectionPoolIdentity Identity
{
get { return _identity; }
}
internal bool IsRunning
{
get { return State.Running == _state; }
}
private int MaxPoolSize
{
get { return PoolGroupOptions.MaxPoolSize; }
}
private int MinPoolSize
{
get { return PoolGroupOptions.MinPoolSize; }
}
internal DbConnectionPoolGroup PoolGroup
{
get { return _connectionPoolGroup; }
}
internal DbConnectionPoolGroupOptions PoolGroupOptions
{
get { return _connectionPoolGroupOptions; }
}
internal DbConnectionPoolProviderInfo ProviderInfo
{
get { return _connectionPoolProviderInfo; }
}
internal bool UseLoadBalancing
{
get { return PoolGroupOptions.UseLoadBalancing; }
}
private bool UsingIntegrateSecurity
{
get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); }
}
private void CleanupCallback(object state)
{
// Called when the cleanup-timer ticks over.
// This is the automatic pruning method. Every period, we will
// perform a two-step process:
//
// First, for each free object above MinPoolSize, we will obtain a
// semaphore representing one object and destroy one from old stack.
// We will continue this until we either reach MinPoolSize, we are
// unable to obtain a free object, or we have exhausted all the
// objects on the old stack.
//
// Second we move all free objects on the new stack to the old stack.
// So, every period the objects on the old stack are destroyed and
// the objects on the new stack are pushed to the old stack. All
// objects that are currently out and in use are not on either stack.
//
// With this logic, objects are pruned from the pool if unused for
// at least one period but not more than two periods.
// Destroy free objects that put us above MinPoolSize from old stack.
while (Count > MinPoolSize)
{ // While above MinPoolSize...
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
// We obtained a objects from the semaphore.
DbConnectionInternal obj;
if (_stackOld.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
// If we obtained one from the old stack, destroy it.
DestroyObject(obj);
}
else
{
// Else we exhausted the old stack (the object the
// semaphore represents is on the new stack), so break.
_waitHandles.PoolSemaphore.Release(1);
break;
}
}
else
{
break;
}
}
// Push to the old-stack. For each free object, move object from
// new stack to old stack.
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
while (true)
{
DbConnectionInternal obj;
if (!_stackNew.TryPop(out obj))
break;
Debug.Assert(obj != null, "null connection is not expected");
Debug.Assert(!obj.IsEmancipated, "pooled object not in pool");
Debug.Assert(obj.CanBePooled, "pooled object is not poolable");
_stackOld.Push(obj);
}
_waitHandles.PoolSemaphore.Release(1);
}
// Queue up a request to bring us up to MinPoolSize
QueuePoolCreateRequest();
}
internal void Clear()
{
DbConnectionInternal obj;
// First, quickly doom everything.
lock (_objectList)
{
int count = _objectList.Count;
for (int i = 0; i < count; ++i)
{
obj = _objectList[i];
if (null != obj)
{
obj.DoNotPoolThisConnection();
}
}
}
// Second, dispose of all the free connections.
while (_stackNew.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
DestroyObject(obj);
}
while (_stackOld.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
DestroyObject(obj);
}
// Finally, reclaim everything that's emancipated (which, because
// it's been doomed, will cause it to be disposed of as well)
ReclaimEmancipatedObjects();
}
private Timer CreateCleanupTimer()
=> ADP.UnsafeCreateTimer(
new TimerCallback(CleanupCallback),
null,
_cleanupWait,
_cleanupWait);
private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
{
DbConnectionInternal newObj = null;
try
{
newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions);
if (null == newObj)
{
throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object
}
if (!newObj.CanBePooled)
{
throw ADP.InternalError(ADP.InternalErrorCode.NewObjectCannotBePooled); // CreateObject succeeded, but non-poolable object
}
newObj.PrePush(null);
lock (_objectList)
{
if ((oldConnection != null) && (oldConnection.Pool == this))
{
_objectList.Remove(oldConnection);
}
_objectList.Add(newObj);
_totalObjects = _objectList.Count;
}
// If the old connection belonged to another pool, we need to remove it from that
if (oldConnection != null)
{
var oldConnectionPool = oldConnection.Pool;
if (oldConnectionPool != null && oldConnectionPool != this)
{
Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down");
lock (oldConnectionPool._objectList)
{
oldConnectionPool._objectList.Remove(oldConnection);
oldConnectionPool._totalObjects = oldConnectionPool._objectList.Count;
}
}
}
// Reset the error wait:
_errorWait = ERROR_WAIT_DEFAULT;
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
newObj = null; // set to null, so we do not return bad new object
// Failed to create instance
_resError = e;
// Make sure the timer starts even if ThreadAbort occurs after setting the ErrorEvent.
// timer allocation has to be done out of CER block
Timer t = new Timer(new TimerCallback(this.ErrorCallback), null, Timeout.Infinite, Timeout.Infinite);
bool timerIsNotDisposed;
try { }
finally
{
_waitHandles.ErrorEvent.Set();
_errorOccurred = true;
// Enable the timer.
// Note that the timer is created to allow periodic invocation. If ThreadAbort occurs in the middle of ErrorCallback,
// the timer will restart. Otherwise, the timer callback (ErrorCallback) destroys the timer after resetting the error to avoid second callback.
_errorTimer = t;
timerIsNotDisposed = t.Change(_errorWait, _errorWait);
}
Debug.Assert(timerIsNotDisposed, "ErrorCallback timer has been disposed");
if (30000 < _errorWait)
{
_errorWait = 60000;
}
else
{
_errorWait *= 2;
}
throw;
}
return newObj;
}
private void DeactivateObject(DbConnectionInternal obj)
{
obj.DeactivateConnection();
bool returnToGeneralPool = false;
bool destroyObject = false;
if (obj.IsConnectionDoomed)
{
// the object is not fit for reuse -- just dispose of it.
destroyObject = true;
}
else
{
// NOTE: constructor should ensure that current state cannot be State.Initializing, so it can only
// be State.Running or State.ShuttingDown
Debug.Assert(_state == State.Running || _state == State.ShuttingDown);
lock (obj)
{
// A connection with a delegated transaction cannot currently
// be returned to a different customer until the transaction
// actually completes, so we send it into Stasis -- the SysTx
// transaction object will ensure that it is owned (not lost),
// and it will be certain to put it back into the pool.
if (_state == State.ShuttingDown)
{
// connection is being closed and the pool has been marked as shutting
// down, so destroy this object.
destroyObject = true;
}
else
{
if (obj.CanBePooled)
{
// We must put this connection into the transacted pool
// while inside a lock to prevent a race condition with
// the transaction asynchronously completing on a second
// thread.
// return to general pool
returnToGeneralPool = true;
}
else
{
// object is not fit for reuse -- just dispose of it
destroyObject = true;
}
}
}
}
if (returnToGeneralPool)
{
// Only push the connection into the general pool if we didn't
// already push it onto the transacted pool, put it into stasis,
// or want to destroy it.
Debug.Assert(destroyObject == false);
PutNewObject(obj);
}
else if (destroyObject)
{
DestroyObject(obj);
QueuePoolCreateRequest();
}
//-------------------------------------------------------------------------------------
// postcondition
// ensure that the connection was processed
Debug.Assert(
returnToGeneralPool == true || destroyObject == true);
}
internal void DestroyObject(DbConnectionInternal obj)
{
// A connection with a delegated transaction cannot be disposed of
// until the delegated transaction has actually completed. Instead,
// we simply leave it alone; when the transaction completes, it will
// come back through PutObjectFromTransactedPool, which will call us
// again.
bool removed = false;
lock (_objectList)
{
removed = _objectList.Remove(obj);
Debug.Assert(removed, "attempt to DestroyObject not in list");
_totalObjects = _objectList.Count;
}
if (removed)
{
}
obj.Dispose();
}
private void ErrorCallback(object state)
{
_errorOccurred = false;
_waitHandles.ErrorEvent.Reset();
// the error state is cleaned, destroy the timer to avoid periodic invocation
Timer t = _errorTimer;
_errorTimer = null;
if (t != null)
{
t.Dispose(); // Cancel timer request.
}
}
// TODO: move this to src/Common and integrate with SqlClient
// Note: Odbc connections are not passing through this code
private Exception TryCloneCachedException()
{
return _resError;
}
private void WaitForPendingOpen()
{
PendingGetConnection next;
do
{
bool started = false;
try
{
try { }
finally
{
started = Interlocked.CompareExchange(ref _pendingOpensWaiting, 1, 0) == 0;
}
if (!started)
{
return;
}
while (_pendingOpens.TryDequeue(out next))
{
if (next.Completion.Task.IsCompleted)
{
continue;
}
uint delay;
if (next.DueTime == Timeout.Infinite)
{
delay = unchecked((uint)Timeout.Infinite);
}
else
{
delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0);
}
DbConnectionInternal connection = null;
bool timeout = false;
Exception caughtException = null;
try
{
bool allowCreate = true;
bool onlyOneCheckConnection = false;
timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection);
}
catch (Exception e)
{
caughtException = e;
}
if (caughtException != null)
{
next.Completion.TrySetException(caughtException);
}
else if (timeout)
{
next.Completion.TrySetException(ADP.ExceptionWithStackTrace(ADP.PooledOpenTimeout()));
}
else
{
Debug.Assert(connection != null, "connection should never be null in success case");
if (!next.Completion.TrySetResult(connection))
{
// if the completion was cancelled, lets try and get this connection back for the next try
PutObject(connection, next.Owner);
}
}
}
}
finally
{
if (started)
{
Interlocked.Exchange(ref _pendingOpensWaiting, 0);
}
}
} while (!_pendingOpens.IsEmpty);
}
internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
{
uint waitForMultipleObjectsTimeout = 0;
bool allowCreate = false;
if (retry == null)
{
waitForMultipleObjectsTimeout = (uint)CreationTimeout;
// Set the wait timeout to INFINITE (-1) if the SQL connection timeout is 0 (== infinite)
if (waitForMultipleObjectsTimeout == 0)
waitForMultipleObjectsTimeout = unchecked((uint)Timeout.Infinite);
allowCreate = true;
}
if (_state != State.Running)
{
connection = null;
return true;
}
bool onlyOneCheckConnection = true;
if (TryGetConnection(owningObject, waitForMultipleObjectsTimeout, allowCreate, onlyOneCheckConnection, userOptions, out connection))
{
return true;
}
else if (retry == null)
{
// timed out on a sync call
return true;
}
var pendingGetConnection =
new PendingGetConnection(
CreationTimeout == 0 ? Timeout.Infinite : ADP.TimerCurrent() + ADP.TimerFromSeconds(CreationTimeout / 1000),
owningObject,
retry,
userOptions);
_pendingOpens.Enqueue(pendingGetConnection);
// it is better to StartNew too many times than not enough
if (_pendingOpensWaiting == 0)
{
Thread waitOpenThread = new Thread(WaitForPendingOpen);
waitOpenThread.IsBackground = true;
waitOpenThread.Start();
}
connection = null;
return false;
}
private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
{
DbConnectionInternal obj = null;
if (null == obj)
{
Interlocked.Increment(ref _waitCount);
do
{
int waitResult = BOGUS_HANDLE;
try
{
try
{
}
finally
{
waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(allowCreate), unchecked((int)waitForMultipleObjectsTimeout));
}
// From the WaitAny docs: "If more than one object became signaled during
// the call, this is the array index of the signaled object with the
// smallest index value of all the signaled objects." This is important
// so that the free object signal will be returned before a creation
// signal.
switch (waitResult)
{
case WaitHandle.WaitTimeout:
Interlocked.Decrement(ref _waitCount);
connection = null;
return false;
case ERROR_HANDLE:
// Throw the error that PoolCreateRequest stashed.
Interlocked.Decrement(ref _waitCount);
throw TryCloneCachedException();
case CREATION_HANDLE:
try
{
obj = UserCreateRequest(owningObject, userOptions);
}
catch
{
if (null == obj)
{
Interlocked.Decrement(ref _waitCount);
}
throw;
}
finally
{
// Ensure that we release this waiter, regardless
// of any exceptions that may be thrown.
if (null != obj)
{
Interlocked.Decrement(ref _waitCount);
}
}
if (null == obj)
{
// If we were not able to create an object, check to see if
// we reached MaxPoolSize. If so, we will no longer wait on
// the CreationHandle, but instead wait for a free object or
// the timeout.
if (Count >= MaxPoolSize && 0 != MaxPoolSize)
{
if (!ReclaimEmancipatedObjects())
{
// modify handle array not to wait on creation mutex anymore
Debug.Assert(2 == CREATION_HANDLE, "creation handle changed value");
allowCreate = false;
}
}
}
break;
case SEMAPHORE_HANDLE:
//
// guaranteed available inventory
//
Interlocked.Decrement(ref _waitCount);
obj = GetFromGeneralPool();
if ((obj != null) && (!obj.IsConnectionAlive()))
{
DestroyObject(obj);
obj = null; // Setting to null in case creating a new object fails
if (onlyOneCheckConnection)
{
if (_waitHandles.CreationSemaphore.WaitOne(unchecked((int)waitForMultipleObjectsTimeout)))
{
try
{
obj = UserCreateRequest(owningObject, userOptions);
}
finally
{
_waitHandles.CreationSemaphore.Release(1);
}
}
else
{
// Timeout waiting for creation semaphore - return null
connection = null;
return false;
}
}
}
break;
default:
Interlocked.Decrement(ref _waitCount);
throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult);
}
}
finally
{
if (CREATION_HANDLE == waitResult)
{
_waitHandles.CreationSemaphore.Release(1);
}
}
} while (null == obj);
}
if (null != obj)
{
PrepareConnection(owningObject, obj);
}
connection = obj;
return true;
}
private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj)
{
lock (obj)
{ // Protect against Clear and ReclaimEmancipatedObjects, which call IsEmancipated, which is affected by PrePush and PostPop
obj.PostPop(owningObject);
}
try
{
obj.ActivateConnection();
}
catch
{
// if Activate throws an exception
// put it back in the pool or have it properly disposed of
this.PutObject(obj, owningObject);
throw;
}
}
/// <summary>
/// Creates a new connection to replace an existing connection
/// </summary>
/// <param name="owningObject">Outer connection that currently owns <paramref name="oldConnection"/></param>
/// <param name="userOptions">Options used to create the new connection</param>
/// <param name="oldConnection">Inner connection that will be replaced</param>
/// <returns>A new inner connection that is attached to the <paramref name="owningObject"/></returns>
internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
{
DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection);
if (newConnection != null)
{
PrepareConnection(owningObject, newConnection);
oldConnection.PrepareForReplaceConnection();
oldConnection.DeactivateConnection();
oldConnection.Dispose();
}
return newConnection;
}
private DbConnectionInternal GetFromGeneralPool()
{
DbConnectionInternal obj = null;
if (!_stackNew.TryPop(out obj))
{
if (!_stackOld.TryPop(out obj))
{
obj = null;
}
else
{
Debug.Assert(obj != null, "null connection is not expected");
}
}
else
{
Debug.Assert(obj != null, "null connection is not expected");
}
// When another thread is clearing this pool,
// it will remove all connections in this pool which causes the
// following assert to fire, which really mucks up stress against
// checked bits.
if (null != obj)
{
}
return (obj);
}
private void PoolCreateRequest(object state)
{
// called by pooler to ensure pool requests are currently being satisfied -
// creation mutex has not been obtained
if (State.Running == _state)
{
// in case WaitForPendingOpen ever failed with no subsequent OpenAsync calls,
// start it back up again
if (!_pendingOpens.IsEmpty && _pendingOpensWaiting == 0)
{
Thread waitOpenThread = new Thread(WaitForPendingOpen);
waitOpenThread.IsBackground = true;
waitOpenThread.Start();
}
// Before creating any new objects, reclaim any released objects that were
// not closed.
ReclaimEmancipatedObjects();
if (!ErrorOccurred)
{
if (NeedToReplenish)
{
// Check to see if pool was created using integrated security and if so, make
// sure the identity of current user matches that of user that created pool.
// If it doesn't match, do not create any objects on the ThreadPool thread,
// since either Open will fail or we will open a object for this pool that does
// not belong in this pool. The side effect of this is that if using integrated
// security min pool size cannot be guaranteed.
if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent()))
{
return;
}
int waitResult = BOGUS_HANDLE;
try
{
try { }
finally
{
waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(withCreate: true), CreationTimeout);
}
if (CREATION_HANDLE == waitResult)
{
DbConnectionInternal newObj;
// Check ErrorOccurred again after obtaining mutex
if (!ErrorOccurred)
{
while (NeedToReplenish)
{
// Don't specify any user options because there is no outer connection associated with the new connection
newObj = CreateObject(owningObject: null, userOptions: null, oldConnection: null);
// We do not need to check error flag here, since we know if
// CreateObject returned null, we are in error case.
if (null != newObj)
{
PutNewObject(newObj);
}
else
{
break;
}
}
}
}
else if (WaitHandle.WaitTimeout == waitResult)
{
// do not wait forever and potential block this worker thread
// instead wait for a period of time and just requeue to try again
QueuePoolCreateRequest();
}
}
finally
{
if (CREATION_HANDLE == waitResult)
{
// reuse waitResult and ignore its value
_waitHandles.CreationSemaphore.Release(1);
}
}
}
}
}
}
internal void PutNewObject(DbConnectionInternal obj)
{
Debug.Assert(null != obj, "why are we adding a null object to the pool?");
// Debug.Assert(obj.CanBePooled, "non-poolable object in pool");
_stackNew.Push(obj);
_waitHandles.PoolSemaphore.Release(1);
}
internal void PutObject(DbConnectionInternal obj, object owningObject)
{
Debug.Assert(null != obj, "null obj?");
// Once a connection is closing (which is the state that we're in at
// this point in time) you cannot delegate a transaction to or enlist
// a transaction in it, so we can correctly presume that if there was
// not a delegated or enlisted transaction to start with, that there
// will not be a delegated or enlisted transaction once we leave the
// lock.
lock (obj)
{
// Calling PrePush prevents the object from being reclaimed
// once we leave the lock, because it sets _pooledCount such
// that it won't appear to be out of the pool. What that
// means, is that we're now responsible for this connection:
// it won't get reclaimed if we drop the ball somewhere.
obj.PrePush(owningObject);
}
DeactivateObject(obj);
}
private void QueuePoolCreateRequest()
{
if (State.Running == _state)
{
// Make sure we're at quota by posting a callback to the threadpool.
ThreadPool.QueueUserWorkItem(_poolCreateRequest);
}
}
private bool ReclaimEmancipatedObjects()
{
bool emancipatedObjectFound = false;
List<DbConnectionInternal> reclaimedObjects = new List<DbConnectionInternal>();
int count;
lock (_objectList)
{
count = _objectList.Count;
for (int i = 0; i < count; ++i)
{
DbConnectionInternal obj = _objectList[i];
if (null != obj)
{
bool locked = false;
try
{
Monitor.TryEnter(obj, ref locked);
if (locked)
{ // avoid race condition with PrePush/PostPop and IsEmancipated
if (obj.IsEmancipated)
{
// Inside the lock, we want to do as little
// as possible, so we simply mark the object
// as being in the pool, but hand it off to
// an out of pool list to be deactivated,
// etc.
obj.PrePush(null);
reclaimedObjects.Add(obj);
}
}
}
finally
{
if (locked)
Monitor.Exit(obj);
}
}
}
}
// NOTE: we don't want to call DeactivateObject while we're locked,
// because it can make roundtrips to the server and this will block
// object creation in the pooler. Instead, we queue things we need
// to do up, and process them outside the lock.
count = reclaimedObjects.Count;
for (int i = 0; i < count; ++i)
{
DbConnectionInternal obj = reclaimedObjects[i];
emancipatedObjectFound = true;
DeactivateObject(obj);
}
return emancipatedObjectFound;
}
internal void Startup()
{
_cleanupTimer = CreateCleanupTimer();
if (NeedToReplenish)
{
QueuePoolCreateRequest();
}
}
internal void Shutdown()
{
_state = State.ShuttingDown;
// deactivate timer callbacks
Timer t = _cleanupTimer;
_cleanupTimer = null;
if (null != t)
{
t.Dispose();
}
}
private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null)
{
// called by user when they were not able to obtain a free object but
// instead obtained creation mutex
DbConnectionInternal obj = null;
if (ErrorOccurred)
{
throw TryCloneCachedException();
}
else
{
if ((oldConnection != null) || (Count < MaxPoolSize) || (0 == MaxPoolSize))
{
// If we have an odd number of total objects, reclaim any dead objects.
// If we did not find any objects to reclaim, create a new one.
if ((oldConnection != null) || (Count & 0x1) == 0x1 || !ReclaimEmancipatedObjects())
obj = CreateObject(owningObject, userOptions, oldConnection);
}
return obj;
}
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.2.4.3. Used when the antenna pattern type in the transmitter pdu is of value 2. Specified the direction and radiation pattern from a radio transmitter's antenna. NOTE: this class must be hand-coded to clean up some implementation details.
/// </summary>
[Serializable]
[XmlRoot]
public partial class SphericalHarmonicAntennaPattern
{
private byte _order;
/// <summary>
/// Initializes a new instance of the <see cref="SphericalHarmonicAntennaPattern"/> class.
/// </summary>
public SphericalHarmonicAntennaPattern()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(SphericalHarmonicAntennaPattern left, SphericalHarmonicAntennaPattern right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(SphericalHarmonicAntennaPattern left, SphericalHarmonicAntennaPattern right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 1; // this._order
return marshalSize;
}
/// <summary>
/// Gets or sets the order
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "order")]
public byte Order
{
get
{
return this._order;
}
set
{
this._order = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteByte((byte)this._order);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._order = dis.ReadByte();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<SphericalHarmonicAntennaPattern>");
try
{
sb.AppendLine("<order type=\"byte\">" + this._order.ToString(CultureInfo.InvariantCulture) + "</order>");
sb.AppendLine("</SphericalHarmonicAntennaPattern>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as SphericalHarmonicAntennaPattern;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(SphericalHarmonicAntennaPattern obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._order != obj._order)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._order.GetHashCode();
return result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.