context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using JoinRpg.CommonUI.Models;
using JoinRpg.Data.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using JoinRpg.Helpers;
using JoinRpg.Services.Interfaces;
using JoinRpg.Web.Filter;
using JoinRpg.Web.Helpers;
using JoinRpg.Web.Models;
using JoinRpg.Web.Models.Exporters;
namespace JoinRpg.Web.Controllers
{
[Authorize]
public class FinancesController : Common.ControllerGameBase
{
private IFinanceService FinanceService { get; }
private IUriService UriService { get; }
public FinancesController(ApplicationUserManager userManager, IProjectRepository projectRepository,
IProjectService projectService, IExportDataService exportDataService, IFinanceService financeService, IUriService uriService)
: base(userManager, projectRepository, projectService, exportDataService)
{
FinanceService = financeService;
UriService = uriService;
}
[HttpGet]
public async Task<ActionResult> Setup(int projectid)
{
var project = await ProjectRepository.GetProjectForFinanceSetup(projectid);
return AsMaster(project) ?? View(new FinanceSetupViewModel(project, CurrentUserId));
}
public async Task<ActionResult> Operations(int projectid, string export)
=> await GetFinanceOperationsList(projectid, export, fo => fo.Approved);
public async Task<ActionResult> Moderation(int projectid, string export)
=> await GetFinanceOperationsList(projectid, export, fo => fo.RequireModeration);
private async Task<ActionResult> GetFinanceOperationsList(int projectid, string export, Func<FinanceOperation, bool> predicate)
{
var project = await ProjectRepository.GetProjectWithFinances(projectid);
var errorResult = AsMaster(project);
if (errorResult != null)
{
return errorResult;
}
var viewModel = new FinOperationListViewModel(project, new UrlHelper(ControllerContext.RequestContext),
project.FinanceOperations.Where(predicate).ToArray());
var exportType = GetExportTypeByName(export);
if (exportType == null)
{
return View("Operations", viewModel);
}
else
{
return await Export(viewModel.Items, "finance-export", exportType.Value);
}
}
[MasterAuthorize()]
public async Task<ActionResult> MoneySummary(int projectId, string export)
{
var project = await ProjectRepository.GetProjectWithFinances(projectId);
if (project == null)
{
return HttpNotFound();
}
var viewModel = project.PaymentTypes.Select(pt => new PaymentTypeSummaryViewModel()
{
Name = pt.GetDisplayName(),
Master = pt.User,
Total = project.FinanceOperations.Where(fo => fo.PaymentTypeId == pt.PaymentTypeId && fo.Approved).Sum(fo => fo.MoneyAmount)
}).Where(m => m.Total != 0).OrderByDescending(m => m.Total).ThenBy(m => m.Name);
var exportType = GetExportTypeByName(export);
if (exportType == null)
{
return View(viewModel);
}
else
{
return await Export(viewModel, "money-summary", exportType.Value);
}
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> TogglePaymentType(int projectid, int paymentTypeId)
{
var project = await ProjectRepository.GetProjectAsync(projectid);
var errorResult = AsMaster(project, acl => acl.CanManageMoney);
if (errorResult != null)
{
return errorResult;
}
try
{
if (paymentTypeId < 0)
{
await FinanceService.CreateCashPaymentType(projectid, -paymentTypeId);
}
else
{
await FinanceService.TogglePaymentActivness(projectid, paymentTypeId);
}
return RedirectToAction("Setup", new { projectid });
}
catch
{
//TODO: Message that comment is not added
return RedirectToAction("Setup", new { projectid });
}
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> CreatePaymentType(CreatePaymentTypeViewModel viewModel)
{
var project = await ProjectRepository.GetProjectAsync(viewModel.ProjectId);
var errorResult = AsMaster(project, acl => acl.CanManageMoney);
if (errorResult != null)
{
return errorResult;
}
try
{
await FinanceService.CreateCustomPaymentType(viewModel.ProjectId, viewModel.Name, viewModel.UserId);
return RedirectToAction("Setup", new { viewModel.ProjectId });
}
catch
{
//TODO: Message that comment is not added
return RedirectToAction("Setup", new { viewModel.ProjectId });
}
}
[HttpGet]
public async Task<ActionResult> EditPaymentType(int projectid, int paymenttypeid)
{
var project = await ProjectRepository.GetProjectAsync(projectid);
var paymentType = project.PaymentTypes.SingleOrDefault(pt => pt.PaymentTypeId == paymenttypeid);
var errorResult = AsMaster(paymentType, acl => acl.CanManageMoney);
if (errorResult != null || paymentType == null)
{
return errorResult;
}
return
View(new EditPaymentTypeViewModel()
{
IsDefault = paymentType.IsDefault,
Name = paymentType.Name,
ProjectId = projectid
});
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> EditPaymentType(EditPaymentTypeViewModel viewModel)
{
var project = await ProjectRepository.GetProjectAsync(viewModel.ProjectId);
var paymentType = project.PaymentTypes.SingleOrDefault(pt => pt.PaymentTypeId == viewModel.PaymentTypeId);
var errorResult = AsMaster(paymentType, acl => acl.CanManageMoney);
if (errorResult != null)
{
return errorResult;
}
try
{
await FinanceService.EditCustomPaymentType(viewModel.ProjectId, viewModel.PaymentTypeId, viewModel.Name, viewModel.IsDefault);
return RedirectToAction("Setup", new { viewModel.ProjectId });
}
catch (Exception exc)
{
ModelState.AddException(exc);
return View(viewModel);
}
}
public async Task<ActionResult> CreateFeeSetting(CreateProjectFeeSettingViewModel viewModel)
{
var project = await ProjectRepository.GetProjectAsync(viewModel.ProjectId);
var errorResult = AsMaster(project, acl => acl.CanManageMoney);
if (errorResult != null)
{
return errorResult;
}
try
{
await FinanceService.CreateFeeSetting(new CreateFeeSettingRequest()
{
ProjectId = viewModel.ProjectId,
Fee = viewModel.Fee,
PreferentialFee = viewModel.PreferentialFee,
StartDate = viewModel.StartDate,
});
return RedirectToAction("Setup", new { viewModel.ProjectId });
}
catch
{
//TODO: Message that comment is not added
return RedirectToAction("Setup", new { viewModel.ProjectId });
}
}
[HttpPost,ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteFeeSetting(int projectid, int projectFeeSettingId)
{
var project = await ProjectRepository.GetProjectAsync(projectid);
var errorResult = AsMaster(project, acl => acl.CanManageMoney);
if (errorResult != null)
{
return errorResult;
}
try
{
await FinanceService.DeleteFeeSetting(projectid, projectFeeSettingId);
return RedirectToAction("Setup", new { projectid });
}
catch
{
//TODO: Message that comment is not added
return RedirectToAction("Setup", new { projectid });
}
}
[HttpGet,AllowAnonymous]
public async Task<ActionResult> SummaryByMaster(string token, int projectId)
{
var project = await ProjectRepository.GetProjectWithFinances(projectId);
var guid = new Guid(token.FromHexString());
var acl = project.ProjectAcls.SingleOrDefault(a => a.Token == guid);
if (acl == null)
{
return Content("Unauthorized");
}
var summary =
project.FinanceOperations.Where(fo => fo.Approved && fo.PaymentType != null)
.GroupBy(fo => fo.PaymentType?.User)
.Select(
fg =>
new MoneySummaryByMasterListItemViewModel(fg.Sum(fo => fo.MoneyAmount), fg.Key))
.Where(fr => fr.Total != 0)
.OrderBy(fr => fr.Master.GetDisplayName());
return
await
ExportWithCustomFronend(summary, "money-summary", ExportType.Csv,
new MoneySummaryByMasterExporter(UriService),
project.ProjectName);
}
public async Task<ActionResult> ChangeSettings(FinanceGlobalSettingsViewModel viewModel)
{
var project = await ProjectRepository.GetProjectAsync(viewModel.ProjectId);
var errorResult = AsMaster(project, acl => acl.CanManageMoney);
if (errorResult != null)
{
return errorResult;
}
try
{
await FinanceService.SaveGlobalSettings(new SetFinanceSettingsRequest
{
ProjectId = viewModel.ProjectId,
WarnOnOverPayment = viewModel.WarnOnOverPayment,
PreferentialFeeEnabled = viewModel.PreferentialFeeEnabled,
PreferentialFeeConditions = viewModel.PreferentialFeeConditions
});
return RedirectToAction("Setup", new { viewModel.ProjectId });
}
catch
{
//TODO: Message that comment is not added
return RedirectToAction("Setup", new { viewModel.ProjectId });
}
}
}
}
| |
/***********************************************************************************************************************
* TorrentDotNET - A BitTorrent library based on the .NET platform *
* Copyright (C) 2004, Peter Ward *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the *
* GNU Lesser General Public License as published by the Free Software Foundation; *
* either version 2.1 of the License, or (at your option) any later version. *
* *
* 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.Collections;
using System.Collections.Generic;
using Threading = System.Threading;
using IO = System.IO;
using Net = System.Net;
using Sockets = System.Net.Sockets;
namespace BitTorrent
{
/// <summary>Delegate for torrent checking status</summary>
/// <param name="torrent">Torrent being checked</param>
/// <param name="pieceId">Piece ID which has just been checked</param>
/// <param name="good">True if the piece has been downloaded, false otherwise</param>
/// <param name="percentDone">Percentage of checking complete</param>
public delegate void TorrentCheckIntegrityCallback(Torrent torrent, int pieceId, bool good, float percentDone);
public delegate void TorrentStatusChangedCallback(Torrent torrent, TorrentStatus status);
public delegate void TorrentPeerConnectedCallback(Torrent torrent, Peer peer, bool connected);
public delegate void TorrentTrackerErrorCallback(Torrent torrent, string errorMessage);
public delegate ByteField20 CalculatePeerIdCallback(MetainfoFile infofile);
/// <summary>Status of the torrent</summary>
public enum TorrentStatus
{
/// <summary>Currently checking the file</summary>
Checking,
/// <summary>Downloading the torrent</summary>
Working,
/// <summary>Seeding the torrent</summary>
Seeding,
/// <summary>Queued for checking</summary>
QueuedForChecking,
/// <summary>Queued for downloading (file has been checked)</summary>
QueuedForWorking
}
/// <summary>
/// Represents a torrent. Torrents must be added to the Session class
/// </summary>
public class Torrent : System.IDisposable
{
private Session mSession;
private int seedCount = 0, leecherCount = 0, finishedCount = 0;
private MetainfoFile infofile;
private DownloadFile downloadFile;
private TorrentStatus status = TorrentStatus.QueuedForChecking;
private TrackerProtocol tp;
private List<Peer> mPeers = new List<Peer>(); // Arraylist of Peers
private PeerManager peerManager;
private DownloadStrategyManager mDownloadStrategy;// downloadManager;
private UploadManager uploadManager;
public TorrentCheckIntegrityCallback CheckIntegrity;
public TorrentStatusChangedCallback StatusChanged;
public TorrentPeerConnectedCallback PeerConnected;
public TorrentTrackerErrorCallback TrackerError;
private ArrayList mWaitingPeers = new ArrayList();
private int /*bytesDownloaded = 0, */bytesUploaded = 0;
/// <summary>Status of the torrent</summary>
public TorrentStatus Status
{
get { return this.status; }
}
public bool Seeding
{
get { return this.downloadFile.Bitfield.AllTrue; }
}
public int PieceCount
{
get { return this.infofile.PieceCount; }
}
public float PercentComplete
{
get { return this.downloadFile.PercentComplete; }
}
public event PercentChangedCallback PercentChanged
{
add { this.downloadFile.PercentChanged += value; }
remove { this.downloadFile.PercentChanged -= value; }
}
public int BytesDownloaded
{
get { return this.mDownloadStrategy.BytesDownloaded; }
}
public int BytesUploaded
{
get { return this.bytesUploaded; }
}
/// <summary></summary>
/// <returns>Metainfo file associated with the torrent</returns>
public MetainfoFile Metainfo
{
get { return this.infofile; }
}
/// <summary></summary>
/// <returns>Download file associated with the torrent</returns>
public DownloadFile DownloadFile
{
get { return this.downloadFile; }
}
/// <summary></summary>
/// <returns>Number of seeds on the torrent</returns>
public int SeedCount
{
get { return this.seedCount; }
}
/// <summary></summary>
/// <returns>Number of leechers (people downloading) on the torrent</returns>
public int LeecherCount
{
get { return this.leecherCount; }
}
/// <summary></summary>
/// <returns>Number of total finished downloads on this torrent. Sometimes the tracker does not support this, so it could be zero</returns>
public int FinishedCount
{
get { return this.finishedCount; }
}
public TrackerProtocol Tracker
{
get { return this.tp; }
}
public Session Session
{
get { return mSession; }
}
public List<Peer> Peers
{
get { return mPeers; }
}
/// <summary>Contructs a torrent using the metainfo filename</summary>
/// <param name="metafilename">Filename of the metainfo file</param>
internal Torrent( Session session, string metafilename )
{
this.mSession = session;
this.infofile = new MetainfoFile(metafilename);
this.downloadFile = new DownloadFile(infofile);
this.peerManager = new PeerManager();
this.mDownloadStrategy = new DownloadStrategyManager( this );
this.uploadManager = new UploadManager(infofile, downloadFile);
this.tp = new TrackerProtocol(this, infofile, downloadFile);
// this.downloadManager.PieceFinished += new PieceFinishedCallback(downloadManager_PieceFinished);
this.uploadManager.PieceSectionFinished += new PieceSectionFinishedCallback(uploadManager_PieceSectionFinished);
this.tp.TrackerUpdate += new TrackerUpdateCallback(tp_TrackerUpdate);
}
public void ProcessWaitingData()
{
lock ( this.mWaitingPeers.SyncRoot )
{
foreach ( object[] objs in mWaitingPeers )
{
AddPeerPrivate( (Sockets.Socket)objs[ 0 ], (Sockets.NetworkStream)objs[ 1 ], (PeerInformation)objs[ 2 ] );
}
mWaitingPeers.Clear();
}
this.peerManager.ProcessWaitingData();
}
private void OnIntegrityCallback(DownloadFile file, int pieceId, bool good, float percentDone)
{
if (this.CheckIntegrity != null)
this.CheckIntegrity(this, pieceId, good, percentDone);
}
/// <summary>Checks the integrity of the current file, or if it does not exists creates it. This must be called before
/// each torrent is started</summary>
/// <param name="callback">Delegate which is called every time a piece is checked</param>
public void CheckFileIntegrity( bool forced )
{
this.status = TorrentStatus.Checking;
if (this.StatusChanged != null)
this.StatusChanged(this, this.status);
this.downloadFile.CheckIntegrity( forced, new CheckIntegrityCallback( OnIntegrityCallback ) );
}
/// <summary>Starts the torrent</summary>
public void Start()
{
this.status = TorrentStatus.Working;
if (this.StatusChanged != null)
this.StatusChanged(this, this.status);
// scrape the tracker to find out info
TrackerProtocol.Scrape(this.infofile, out this.seedCount, out this.leecherCount, out this.finishedCount);
DefaultDownloadStrategy defaultStrategy = new DefaultDownloadStrategy( this.mDownloadStrategy );
this.mDownloadStrategy.AddNewStrategy( defaultStrategy );
this.mDownloadStrategy.SetActiveStrategy( defaultStrategy );
// then tell the tracker we are starting/resuming a download
this.tp.Initiate();
}
/// <summary>
/// Helper thread method to start the connection to peers
/// </summary>
/// <param name="state"></param>
private void StartPeerConnectionThread(System.IAsyncResult result)
{
object[] objs = (object[])result.AsyncState;
Sockets.Socket socket = (Sockets.Socket)objs[0];
PeerInformation peerinfo = (PeerInformation)objs[1];
ByteField20 infoDigest = new ByteField20(), peerId = new ByteField20();
Sockets.NetworkStream netStream;
try
{
socket.EndConnect(result);
netStream = new Sockets.NetworkStream(socket, true);
// send handshake info
PeerProtocol.SendHandshake(netStream, this.infofile.InfoDigest);
PeerProtocol.ReceiveHandshake(netStream, ref infoDigest);
PeerProtocol.SendPeerId(netStream, this.mSession.LocalPeerID );
if (!PeerProtocol.ReceivePeerId(netStream, ref peerId))
{ // NAT check
socket.Close();
return;
}
// check info digest matches and we are not attempting to connect to ourself
if ( infoDigest.Equals( this.infofile.InfoDigest ) && !peerId.Equals( this.mSession.LocalPeerID ) )
{
peerinfo.ID = peerId;
this.AddPeer(socket, netStream, peerinfo);
}
else // info digest doesn't match, close the connection
socket.Close();
}
catch (System.Exception e)
{
Config.LogException(e);
// die if the connection failed
if (socket != null)
socket.Close();
return;
}
}
// Called by the Session class for peers connecting through the server, adds it to a list which can then be added when
// ProcessWaitingData() is called so we keep it on one thread
internal void AddPeer( Sockets.Socket socket, Sockets.NetworkStream netStream, PeerInformation peerInformation )
{
lock ( mWaitingPeers.SyncRoot )
{
mWaitingPeers.Add( new object[] { socket, netStream, peerInformation } );
}
}
// Called by the Session class for peers connecting through the server and in StartPeerConnectionThread() method for peers
// connected to directly
private void AddPeerPrivate(Sockets.Socket socket, Sockets.NetworkStream netStream, PeerInformation peerInformation)
{
try
{
if ( Config.ActiveConfig.MaxPeersConnected < this.mPeers.Count )
{
socket.Close();
return;
}
bool connect = true;
if (Config.ActiveConfig.OnlyOneConnectionFromEachIP)
{
foreach ( Peer connectedPeer in this.mPeers )
{
if (connectedPeer.Information.IP.Equals(peerInformation.IP))
{
connect = false;
break;
}
}
}
if (!connect)
{
socket.Close();
return;
}
if (!this.downloadFile.Bitfield.AllFalse)
PeerProtocol.SendBitfieldMessage(netStream, this.downloadFile);
Peer peer = new Peer(this.infofile, this.downloadFile, socket, netStream, peerInformation);
peer.Disconnected += new PeerDisconnectedCallback(peer_Disconnected);
Config.LogDebugMessage("Connection accepted from: " + peer.ToString());
// add to download and upload manager
this.mDownloadStrategy.HookPeerEvents(peer);
this.uploadManager.AddPeer(peer);
this.peerManager.AddPeer(peer);
if (this.PeerConnected != null)
this.PeerConnected(this, peer, true);
this.mPeers.Add( peer );
}
catch ( System.Exception e )
{
Config.LogException( e );
}
}
/// <summary></summary>
/// <returns>Name of the torrent</returns>
public override string ToString()
{
return this.Metainfo.Name;
}
/// <summary>Disposes the torrent</summary>
public void Dispose()
{
// send shut down message to tracker
if (this.tp != null)
this.tp.Stop();
this.peerManager.Stop();
if (this.downloadFile != null)
this.downloadFile.Dispose();
this.downloadFile = null;
lock ( this.mPeers )
{
// disconnect each peer
foreach ( Peer peer in this.mPeers )
{
peer.Disconnected -= new PeerDisconnectedCallback(peer_Disconnected);
peer.Disconnect();
if (this.PeerConnected != null)
this.PeerConnected(this, peer, false);
}
}
this.mPeers.Clear();
if (this.tp != null)
this.tp.Dispose();
this.tp = null;
}
private void peer_Disconnected(Peer peer)
{
lock ( this.mPeers )
{
this.mPeers.Remove( peer );
}
peer.Disconnected -= new PeerDisconnectedCallback(peer_Disconnected);
if (this.PeerConnected != null)
this.PeerConnected(this, peer, false);
}
//private void downloadManager_PieceFinished(int pieceId)
//{
// // piece just finished, announce to everyone we have it
// foreach ( Peer peer in this.mPeers )
// {
// try
// {
// peer.SendHaveMessage(pieceId);
// }
// catch ( System.Exception e )
// {
// Config.LogException( e );
// peer.Disconnect();
// }
// }
// this.bytesDownloaded += this.infofile.GetPieceLength(pieceId);
//}
private void uploadManager_PieceSectionFinished(int pieceId, int begin, int length)
{
this.bytesUploaded += length;
}
private void tp_TrackerUpdate( ArrayList peers, bool success, string errorMessage )
{
Config.LogDebugMessage("Tracker update: Success: " + success + " : Num Peers : " + (peers != null ? peers.Count.ToString() : "0"));
// attempt to connect to each peer given
if (success)
{
if (peers != null)
{
foreach (PeerInformation peerinfo in peers)
{
Config.LogDebugMessage( "Peer : " + peerinfo.IP + ":" + peerinfo.Port + " ID: " + ( peerinfo.ID != null ? peerinfo.ID.ToString() : "NONE" ) );
try
{
Sockets.Socket socket = new Sockets.Socket(Sockets.AddressFamily.InterNetwork, Sockets.SocketType.Stream, Sockets.ProtocolType.Tcp);
socket.BeginConnect(new Net.IPEndPoint(Net.IPAddress.Parse(peerinfo.IP), peerinfo.Port),
new System.AsyncCallback(StartPeerConnectionThread), new object[] { socket, peerinfo});
}
catch ( System.Exception e )
{
Config.LogException( e );
}
}
}
}
else
{
if (this.TrackerError != null)
this.TrackerError(this, errorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Ocsp;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Ocsp
{
public class OcspReqGenerator
{
private IList list = Platform.CreateArrayList();
private GeneralName requestorName = null;
private X509Extensions requestExtensions = null;
private class RequestObject
{
internal CertificateID certId;
internal X509Extensions extensions;
public RequestObject(
CertificateID certId,
X509Extensions extensions)
{
this.certId = certId;
this.extensions = extensions;
}
public Request ToRequest()
{
return new Request(certId.ToAsn1Object(), extensions);
}
}
/**
* Add a request for the given CertificateID.
*
* @param certId certificate ID of interest
*/
public void AddRequest(
CertificateID certId)
{
list.Add(new RequestObject(certId, null));
}
/**
* Add a request with extensions
*
* @param certId certificate ID of interest
* @param singleRequestExtensions the extensions to attach to the request
*/
public void AddRequest(
CertificateID certId,
X509Extensions singleRequestExtensions)
{
list.Add(new RequestObject(certId, singleRequestExtensions));
}
/**
* Set the requestor name to the passed in X509Principal
*
* @param requestorName a X509Principal representing the requestor name.
*/
public void SetRequestorName(
X509Name requestorName)
{
try
{
this.requestorName = new GeneralName(GeneralName.DirectoryName, requestorName);
}
catch (Exception e)
{
throw new ArgumentException("cannot encode principal", e);
}
}
public void SetRequestorName(
GeneralName requestorName)
{
this.requestorName = requestorName;
}
public void SetRequestExtensions(
X509Extensions requestExtensions)
{
this.requestExtensions = requestExtensions;
}
private OcspReq GenerateRequest(
DerObjectIdentifier signingAlgorithm,
IAsymmetricKeyParameter privateKey,
X509Certificate[] chain,
SecureRandom random)
{
Asn1EncodableVector requests = new Asn1EncodableVector();
foreach (RequestObject reqObj in list)
{
try
{
requests.Add(reqObj.ToRequest());
}
catch (Exception e)
{
throw new OcspException("exception creating Request", e);
}
}
TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions);
ISigner sig = null;
Signature signature = null;
if (signingAlgorithm != null)
{
if (requestorName == null)
{
throw new OcspException("requestorName must be specified if request is signed.");
}
try
{
sig = SignerUtilities.GetSigner(signingAlgorithm.Id);
if (random != null)
{
sig.Init(true, new ParametersWithRandom(privateKey, random));
}
else
{
sig.Init(true, privateKey);
}
}
catch (Exception e)
{
throw new OcspException("exception creating signature: " + e, e);
}
DerBitString bitSig = null;
try
{
byte[] encoded = tbsReq.GetEncoded();
sig.BlockUpdate(encoded, 0, encoded.Length);
bitSig = new DerBitString(sig.GenerateSignature());
}
catch (Exception e)
{
throw new OcspException("exception processing TBSRequest: " + e, e);
}
AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);
if (chain != null && chain.Length > 0)
{
Asn1EncodableVector v = new Asn1EncodableVector();
try
{
for (int i = 0; i != chain.Length; i++)
{
v.Add(
X509CertificateStructure.GetInstance(
Asn1Object.FromByteArray(chain[i].GetEncoded())));
}
}
catch (IOException e)
{
throw new OcspException("error processing certs", e);
}
catch (CertificateEncodingException e)
{
throw new OcspException("error encoding certs", e);
}
signature = new Signature(sigAlgId, bitSig, new DerSequence(v));
}
else
{
signature = new Signature(sigAlgId, bitSig);
}
}
return new OcspReq(new OcspRequest(tbsReq, signature));
}
/**
* Generate an unsigned request
*
* @return the OcspReq
* @throws OcspException
*/
public OcspReq Generate()
{
return GenerateRequest(null, null, null, null);
}
public OcspReq Generate(
string signingAlgorithm,
IAsymmetricKeyParameter privateKey,
X509Certificate[] chain)
{
return Generate(signingAlgorithm, privateKey, chain, null);
}
public OcspReq Generate(
string signingAlgorithm,
IAsymmetricKeyParameter privateKey,
X509Certificate[] chain,
SecureRandom random)
{
if (signingAlgorithm == null)
throw new ArgumentException("no signing algorithm specified");
try
{
DerObjectIdentifier oid = OcspUtilities.GetAlgorithmOid(signingAlgorithm);
return GenerateRequest(oid, privateKey, chain, random);
}
catch (ArgumentException)
{
throw new ArgumentException("unknown signing algorithm specified: " + signingAlgorithm);
}
}
/**
* Return an IEnumerable of the signature names supported by the generator.
*
* @return an IEnumerable containing recognised names.
*/
public IEnumerable SignatureAlgNames
{
get { return OcspUtilities.AlgNames; }
}
}
}
| |
// 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.Linq.Expressions.Tests
{
public static class BinaryNullableAddTests
{
#region Test methods
[Fact]
public static void CheckNullableByteAddTest()
{
byte?[] array = { 0, 1, byte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableByteAdd(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableSByteAddTest()
{
sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSByteAdd(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortAddTest(bool useInterpreter)
{
ushort?[] array = { 0, 1, ushort.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortAdd(array[i], array[j], useInterpreter);
VerifyNullableUShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortAddTest(bool useInterpreter)
{
short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortAdd(array[i], array[j], useInterpreter);
VerifyNullableShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntAddTest(bool useInterpreter)
{
uint?[] array = { 0, 1, uint.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntAdd(array[i], array[j], useInterpreter);
VerifyNullableUIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntAddTest(bool useInterpreter)
{
int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntAdd(array[i], array[j], useInterpreter);
VerifyNullableIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongAddTest(bool useInterpreter)
{
ulong?[] array = { 0, 1, ulong.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongAdd(array[i], array[j], useInterpreter);
VerifyNullableULongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongAddTest(bool useInterpreter)
{
long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongAdd(array[i], array[j], useInterpreter);
VerifyNullableLongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatAddTest(bool useInterpreter)
{
float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatAdd(array[i], array[j], useInterpreter);
VerifyNullableFloatAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoubleAddTest(bool useInterpreter)
{
double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoubleAdd(array[i], array[j], useInterpreter);
VerifyNullableDoubleAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalAddTest(bool useInterpreter)
{
decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalAdd(array[i], array[j], useInterpreter);
VerifyNullableDecimalAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Fact]
public static void CheckNullableCharAddTest()
{
char?[] array = { '\0', '\b', 'A', '\uffff', null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharAdd(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableByteAdd(byte? a, byte? b)
{
Expression aExp = Expression.Constant(a, typeof(byte?));
Expression bExp = Expression.Constant(b, typeof(byte?));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.AddChecked(aExp, bExp));
}
private static void VerifyNullableSByteAdd(sbyte? a, sbyte? b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte?));
Expression bExp = Expression.Constant(b, typeof(sbyte?));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.AddChecked(aExp, bExp));
}
private static void VerifyNullableUShortAdd(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Add(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal((ushort?)(a + b), f());
}
private static void VerifyNullableUShortAddOvf(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
int? expected = a + b;
if (expected < 0 || expected > ushort.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyNullableShortAdd(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Add(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal((short?)(a + b), f());
}
private static void VerifyNullableShortAddOvf(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
int? expected = a + b;
if (expected < short.MinValue || expected > short.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyNullableUIntAdd(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Add(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableUIntAddOvf(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
long? expected = a + (long?)b;
if (expected < 0 || expected > uint.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyNullableIntAdd(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Add(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableIntAddOvf(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
long? expected = a + (long?)b;
if (expected < int.MinValue || expected > int.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyNullableULongAdd(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Add(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableULongAddOvf(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
ulong? expected;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableLongAdd(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Add(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableLongAddOvf(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
long? expected;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableFloatAdd(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Add(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableFloatAddOvf(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableDoubleAdd(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Add(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableDoubleAddOvf(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a + b, f());
}
private static void VerifyNullableDecimalAdd(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Add(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
decimal? expected;
try
{
expected = a + b;
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableDecimalAddOvf(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.AddChecked(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
decimal? expected;
try
{
expected = a + b;
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableCharAdd(char? a, char? b)
{
Expression aExp = Expression.Constant(a, typeof(char?));
Expression bExp = Expression.Constant(b, typeof(char?));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.AddChecked(aExp, bExp));
}
#endregion
}
}
| |
using System;
using System.Collections.Immutable;
using Akka.Streams.Kafka.Dsl;
using Confluent.Kafka;
namespace Akka.Streams.Kafka.Messages
{
/// <summary>
/// Type assepted by "KafkaProducer.FlexiFlow" with implementations
///
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="V"></typeparam>
/// <typeparam name="TPassThrough"></typeparam>
public interface IEnvelope<K, V, out TPassThrough>
{
TPassThrough PassThrough { get; }
IEnvelope<K, V, TPassThrough2> WithPassThrough<TPassThrough2>(TPassThrough2 value);
}
/// <summary>
/// Contains methods to generate producer messages
/// </summary>
public static class ProducerMessage
{
/// <summary>
/// Create a message containing the `record` and a `passThrough`.
/// </summary>
public static IEnvelope<K, V, TPassThrough> Single<K, V, TPassThrough>(ProducerRecord<K, V> record, TPassThrough passThrough)
=> new Message<K,V,TPassThrough>(record, passThrough);
/// <summary>
/// Create a message containing the `record`.
/// </summary>
public static IEnvelope<K, V, NotUsed> Single<K, V>(ProducerRecord<K, V> record)
=> new Message<K,V,NotUsed>(record, NotUsed.Instance);
/// <summary>
/// Create a multi-message containing several `records` and one `passThrough`.
/// </summary>
public static IEnvelope<K, V, TPassThrough> Multi<K, V, TPassThrough>(IImmutableSet<ProducerRecord<K, V>> records, TPassThrough passThrough)
=> new MultiMessage<K,V,TPassThrough>(records, passThrough);
/// <summary>
/// Create a multi-message containing several `records`
/// </summary>
public static IEnvelope<K, V, NotUsed> Multi<K, V>(IImmutableSet<ProducerRecord<K, V>> records)
=> new MultiMessage<K,V,NotUsed>(records, NotUsed.Instance);
/// <summary>
/// Create a pass-through message not containing any records.
/// </summary>
/// <remarks>
/// In some cases the type parameters need to be specified explicitly.
/// </remarks>
public static IEnvelope<K, V, TPassThrough> PassThrough<K, V, TPassThrough>(TPassThrough passThrough)
=> new PassThroughMessage<K,V,TPassThrough>(passThrough);
/// <summary>
/// Create a pass-through message not containing any records for use with `withContext` flows and sinks.
/// </summary>
/// <remarks>
/// In some cases the type parameters need to be specified explicitly.
/// </remarks>
public static IEnvelope<K, V, NotUsed> PassThrough<K, V>()
=> new PassThroughMessage<K,V,NotUsed>(NotUsed.Instance);
}
/// <summary>
/// <para>
/// <see cref="IEnvelope{K,V,TPassThrough}"/> implementation that produces a single message to a Kafka topic, flows emit
/// a <see cref="Result{K,V,TPassThrough}"/> for every element processed.
/// </para>
/// <para>
/// The `record` contains a topic name to which the record is being sent, an optional
/// partition number, and an optional key and value.
/// </para>
/// <para>
/// The `passThrough` field may hold any element that is passed through the `Producer.flow`
/// and included in the <see cref="Result{K,V,TPassThrough}"/>. That is useful when some context is needed to be passed
/// on downstream operations. That could be done with unzip/zip, but this is more convenient.
/// It can for example be a <see cref="CommittableOffset"/> or <see cref="CommittableOffsetBatch"/> that can be committed later in the flow.
/// </para>
/// </summary>
/// <typeparam name="K">The type of keys</typeparam>
/// <typeparam name="V">The type of values</typeparam>
/// <typeparam name="TPassThrough">The type of data passed through</typeparam>
public sealed class Message<K, V, TPassThrough> : IEnvelope<K, V, TPassThrough>
{
/// <summary>
/// Message
/// </summary>
public Message(ProducerRecord<K, V> record, TPassThrough passThrough)
{
Record = record;
PassThrough = passThrough;
}
/// <summary>
/// Published record
/// </summary>
public ProducerRecord<K, V> Record { get; }
/// <inheritdoc />
public TPassThrough PassThrough { get; }
/// <inheritdoc />
public IEnvelope<K, V, TPassThrough2> WithPassThrough<TPassThrough2>(TPassThrough2 value)
{
return new Message<K, V, TPassThrough2>(Record, value);
}
}
/// <summary>
/// <para>
/// <see cref="IEnvelope{K,V,TPassThrough}"/> implementation that produces multiple message to a Kafka topics, flows emit
/// a <see cref="MultiResult{K,V,TPassThrough}"/> for every element processed.
/// </para>
/// <para>
/// Every element in `records` contains a topic name to which the record is being sent, an optional
/// partition number, and an optional key and value.
/// </para>
/// <para>
/// The `passThrough` field may hold any element that is passed through the `Producer.flow`
/// and included in the <see cref="MultiResult{K,V,TPassThrough}"/>. That is useful when some context is needed to be passed
/// on downstream operations. That could be done with unzip/zip, but this is more convenient.
/// It can for example be a <see cref="CommittableOffset"/> or <see cref="CommittableOffsetBatch"/> that can be committed later in the flow.
/// </para>
/// </summary>
public sealed class MultiMessage<K, V, TPassThrough> : IEnvelope<K, V, TPassThrough>
{
/// <summary>
/// MultiMessage
/// </summary>
public MultiMessage(IImmutableSet<ProducerRecord<K, V>> records, TPassThrough passThrough)
{
Records = records;
PassThrough = passThrough;
}
/// <summary>
/// Records
/// </summary>
public IImmutableSet<ProducerRecord<K, V>> Records { get; }
/// <summary>
/// PassThrough
/// </summary>
public TPassThrough PassThrough { get; }
/// <inheritdoc />
public IEnvelope<K, V, TPassThrough2> WithPassThrough<TPassThrough2>(TPassThrough2 value)
{
return new MultiMessage<K, V, TPassThrough2>(Records, value);
}
}
/// <summary>
/// <para>
/// <see cref="IEnvelope{K,V,TPassThrough}"/> implementation that does not produce anything to Kafka, flows emit
/// a <see cref="PassThroughResult{K,V,TPassThrough}"/> for every element processed.
/// </para>
///
/// <para>
/// The `passThrough` field may hold any element that is passed through the `Producer.flow`
/// and included in the <see cref="Result{K,V,TPassThrough}"/>. That is useful when some context is needed to be passed
/// on downstream operations. That could be done with unzip/zip, but this is more convenient.
/// It can for example be a <see cref="CommittableOffset"/> or <see cref="CommittableOffsetBatch"/> that can be committed later in the flow.
/// </para>
/// </summary>
public sealed class PassThroughMessage<K, V, TPassThrough> : IEnvelope<K, V, TPassThrough>
{
/// <summary>
/// PassThroughMessage
/// </summary>
public PassThroughMessage(TPassThrough passThrough)
{
PassThrough = passThrough;
}
/// <inheritdoc />
public TPassThrough PassThrough { get; }
/// <inheritdoc />
public IEnvelope<K, V, TPassThrough2> WithPassThrough<TPassThrough2>(TPassThrough2 value)
{
return new PassThroughMessage<K, V, TPassThrough2>(value);
}
}
/// <summary>
/// Output type produced by <see cref="KafkaProducer.FlexiFlow{TKey,TValue,TPassThrough}(Akka.Streams.Kafka.Settings.ProducerSettings{TKey,TValue})"/>
/// </summary>
public interface IResults<K, V, out TPassThrough>
{
/// <summary>
/// PassThrough
/// </summary>
TPassThrough PassThrough { get; }
}
/// <summary>
/// <see cref="IResults{K,V,TPassThrough}"/> implementation emitted when a <see cref="Message"/> has been successfully published.
///
/// Includes the original message, metadata returned from <see cref="Producer{TKey,TValue}"/> and the `offset` of the produced message.
/// </summary>
public sealed class Result<K, V, TPassThrough> : IResults<K, V, TPassThrough>
{
/// <summary>
/// Message metadata
/// </summary>
public DeliveryReport<K, V> Metadata { get; }
/// <summary>
/// Message
/// </summary>
public Message<K, V, TPassThrough> Message { get; }
/// <summary>
/// Offset
/// </summary>
public Offset Offset => Metadata.Offset;
/// <inheritdoc />
public TPassThrough PassThrough => Message.PassThrough;
/// <summary>
/// Result
/// </summary>
public Result(DeliveryReport<K, V> metadata, Message<K, V, TPassThrough> message)
{
Metadata = metadata;
Message = message;
}
}
public sealed class MultiResultPart<K, V>
{
public DeliveryReport<K, V> Metadata { get; }
public ProducerRecord<K, V> Record { get; }
public MultiResultPart(DeliveryReport<K, V> metadata, ProducerRecord<K, V> record)
{
Metadata = metadata;
Record = record;
}
}
public sealed class MultiResult<K, V, TPassThrough> : IResults<K, V, TPassThrough>
{
public MultiResult(IImmutableSet<MultiResultPart<K, V>> parts, TPassThrough passThrough)
{
Parts = parts;
PassThrough = passThrough;
}
public IImmutableSet<MultiResultPart<K, V>> Parts { get; }
public TPassThrough PassThrough { get; }
}
/// <summary>
/// <see cref="IResults{K,V,TPassThrough}"/> implementation emitted when <see cref="PassThroughMessage{K,V,TPassThrough}"/>
/// has passed through the flow.
/// </summary>
public sealed class PassThroughResult<K, V, TPassThrough> : IResults<K, V, TPassThrough>
{
public PassThroughResult(TPassThrough passThrough)
{
PassThrough = passThrough;
}
public TPassThrough PassThrough { get; }
}
}
| |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
using System;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Record.CF;
using System.Collections.Generic;
using NPOI.SS;
namespace NPOI.XSSF.UserModel
{
/**
* @author Yegor Kozlov
*/
public class XSSFSheetConditionalFormatting : ISheetConditionalFormatting
{
private XSSFSheet _sheet;
/* namespace */
internal XSSFSheetConditionalFormatting(XSSFSheet sheet)
{
_sheet = sheet;
}
/**
* A factory method allowing to create a conditional formatting rule
* with a cell comparison operator<p/>
* TODO - formulas Containing cell references are currently not Parsed properly
*
* @param comparisonOperation - a constant value from
* <tt>{@link NPOI.hssf.record.CFRuleRecord.ComparisonOperator}</tt>: <p>
* <ul>
* <li>BETWEEN</li>
* <li>NOT_BETWEEN</li>
* <li>EQUAL</li>
* <li>NOT_EQUAL</li>
* <li>GT</li>
* <li>LT</li>
* <li>GE</li>
* <li>LE</li>
* </ul>
* </p>
* @param formula1 - formula for the valued, Compared with the cell
* @param formula2 - second formula (only used with
* {@link NPOI.ss.usermodel.ComparisonOperator#BETWEEN}) and
* {@link NPOI.ss.usermodel.ComparisonOperator#NOT_BETWEEN} operations)
*/
public IConditionalFormattingRule CreateConditionalFormattingRule(
ComparisonOperator comparisonOperation,
String formula1,
String formula2)
{
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
CT_CfRule cfRule = rule.GetCTCfRule();
cfRule.AddFormula(formula1);
if (formula2 != null) cfRule.AddFormula(formula2);
cfRule.type = (ST_CfType.cellIs);
ST_ConditionalFormattingOperator operator1;
switch (comparisonOperation)
{
case ComparisonOperator.Between:
operator1 = ST_ConditionalFormattingOperator.between; break;
case ComparisonOperator.NotBetween:
operator1 = ST_ConditionalFormattingOperator.notBetween; break;
case ComparisonOperator.LessThan:
operator1 = ST_ConditionalFormattingOperator.lessThan; break;
case ComparisonOperator.LessThanOrEqual:
operator1 = ST_ConditionalFormattingOperator.lessThanOrEqual; break;
case ComparisonOperator.GreaterThan:
operator1 = ST_ConditionalFormattingOperator.greaterThan; break;
case ComparisonOperator.GreaterThanOrEqual:
operator1 = ST_ConditionalFormattingOperator.greaterThanOrEqual; break;
case ComparisonOperator.Equal:
operator1 = ST_ConditionalFormattingOperator.equal; break;
case ComparisonOperator.NotEqual:
operator1 = ST_ConditionalFormattingOperator.notEqual; break;
default:
throw new ArgumentException("Unknown comparison operator: " + comparisonOperation);
}
cfRule.@operator = (operator1);
return rule;
}
public IConditionalFormattingRule CreateConditionalFormattingRule(
ComparisonOperator comparisonOperation,
String formula)
{
return CreateConditionalFormattingRule(comparisonOperation, formula, null);
}
/**
* A factory method allowing to create a conditional formatting rule with a formula.<br>
*
* @param formula - formula for the valued, Compared with the cell
*/
public IConditionalFormattingRule CreateConditionalFormattingRule(String formula)
{
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
CT_CfRule cfRule = rule.GetCTCfRule();
cfRule.AddFormula(formula);
cfRule.type = ST_CfType.expression;
return rule;
}
public int AddConditionalFormatting(CellRangeAddress[] regions, IConditionalFormattingRule[] cfRules)
{
if (regions == null)
{
throw new ArgumentException("regions must not be null");
}
foreach (CellRangeAddress range in regions) range.Validate(SpreadsheetVersion.EXCEL2007);
if (cfRules == null)
{
throw new ArgumentException("cfRules must not be null");
}
if (cfRules.Length == 0)
{
throw new ArgumentException("cfRules must not be empty");
}
if (cfRules.Length > 3)
{
throw new ArgumentException("Number of rules must not exceed 3");
}
CellRangeAddress[] mergeCellRanges = CellRangeUtil.MergeCellRanges(regions);
CT_ConditionalFormatting cf = _sheet.GetCTWorksheet().AddNewConditionalFormatting();
string refs = string.Empty;
foreach (CellRangeAddress a in mergeCellRanges)
{
if (refs.Length == 0)
refs = a.FormatAsString();
else
refs += " " +a.FormatAsString() ;
}
cf.sqref = refs;
int priority = 1;
foreach (CT_ConditionalFormatting c in _sheet.GetCTWorksheet().conditionalFormatting)
{
priority += c.sizeOfCfRuleArray();
}
foreach (IConditionalFormattingRule rule in cfRules)
{
XSSFConditionalFormattingRule xRule = (XSSFConditionalFormattingRule)rule;
xRule.GetCTCfRule().priority = (priority++);
cf.AddNewCfRule().Set(xRule.GetCTCfRule());
}
return _sheet.GetCTWorksheet().SizeOfConditionalFormattingArray() - 1;
}
public int AddConditionalFormatting(CellRangeAddress[] regions,
IConditionalFormattingRule rule1)
{
return AddConditionalFormatting(regions,
rule1 == null ? null : new XSSFConditionalFormattingRule[] {
(XSSFConditionalFormattingRule)rule1
});
}
public int AddConditionalFormatting(CellRangeAddress[] regions,
IConditionalFormattingRule rule1, IConditionalFormattingRule rule2)
{
return AddConditionalFormatting(regions,
rule1 == null ? null : new XSSFConditionalFormattingRule[] {
(XSSFConditionalFormattingRule)rule1,
(XSSFConditionalFormattingRule)rule2
});
}
/**
* Adds a copy of HSSFConditionalFormatting object to the sheet
* <p>This method could be used to copy HSSFConditionalFormatting object
* from one sheet to another. For example:
* <pre>
* HSSFConditionalFormatting cf = sheet.GetConditionalFormattingAt(index);
* newSheet.AddConditionalFormatting(cf);
* </pre>
*
* @param cf HSSFConditionalFormatting object
* @return index of the new Conditional Formatting object
*/
public int AddConditionalFormatting(IConditionalFormatting cf)
{
XSSFConditionalFormatting xcf = (XSSFConditionalFormatting)cf;
CT_Worksheet sh = _sheet.GetCTWorksheet();
sh.AddNewConditionalFormatting().Set(xcf.GetCTConditionalFormatting());//this is already copied in Set -> .Copy()); ommitted
return sh.SizeOfConditionalFormattingArray() - 1;
}
/**
* Gets Conditional Formatting object at a particular index
*
* @param index
* of the Conditional Formatting object to fetch
* @return Conditional Formatting object
*/
public IConditionalFormatting GetConditionalFormattingAt(int index)
{
CheckIndex(index);
CT_ConditionalFormatting cf = _sheet.GetCTWorksheet().GetConditionalFormattingArray(index);
return new XSSFConditionalFormatting(_sheet, cf);
}
/**
* @return number of Conditional Formatting objects of the sheet
*/
public int NumConditionalFormattings
{
get
{
return _sheet.GetCTWorksheet().SizeOfConditionalFormattingArray();
}
}
/**
* Removes a Conditional Formatting object by index
* @param index of a Conditional Formatting object to remove
*/
public void RemoveConditionalFormatting(int index)
{
CheckIndex(index);
_sheet.GetCTWorksheet().conditionalFormatting.RemoveAt(index);
}
private void CheckIndex(int index)
{
int cnt = NumConditionalFormattings;
if (index < 0 || index >= cnt)
{
throw new ArgumentException("Specified CF index " + index
+ " is outside the allowable range (0.." + (cnt - 1) + ")");
}
}
}
}
| |
namespace Viainternet.OnionArchitecture.Infrastructure.Repositories.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Init : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AreaCodes",
c => new
{
Id = c.Int(nullable: false),
Value = c.Short(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Countries", t => t.Id)
.Index(t => t.Id);
CreateTable(
"dbo.Countries",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
DisplayName = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.States",
c => new
{
Id = c.Int(nullable: false, identity: true),
CountryId = c.Int(nullable: false),
Name = c.String(),
DisplayName = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Countries", t => t.CountryId, cascadeDelete: true)
.Index(t => t.CountryId);
CreateTable(
"dbo.Municipalities",
c => new
{
Id = c.Int(nullable: false, identity: true),
StateId = c.Int(nullable: false),
Name = c.String(),
DisplayName = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.States", t => t.StateId, cascadeDelete: true)
.Index(t => t.StateId);
CreateTable(
"dbo.CompanyProfiles",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserMembershipId = c.String(),
MunicipalityId = c.Int(nullable: false),
Name = c.String(),
DisplayName = c.String(),
Website = c.String(),
Email = c.String(),
NE = c.String(),
NEQ = c.String(),
EmployeesNumber = c.Int(nullable: false),
ShortDescription = c.String(),
LongDescription = c.String(),
LastestUpdateDate = c.DateTime(nullable: false),
IsActive = c.Boolean(nullable: false),
FileName = c.String(),
DisplayFileName = c.String(),
FileDescription = c.String(),
ContentType = c.String(),
ContentLength = c.String(),
FileExtension = c.String(),
File = c.Binary(),
StreetNumber = c.Int(nullable: false),
StreetName = c.String(),
PostalCode = c.String(),
PostalBox = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Municipalities", t => t.MunicipalityId)
.Index(t => t.MunicipalityId);
CreateTable(
"dbo.PhoneNumbers",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserMembershipId = c.String(nullable: false, maxLength: 128),
CompanyProfileId = c.Int(nullable: false),
AreaCodeId = c.Int(nullable: false),
DisplayName = c.String(),
Number = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AreaCodes", t => t.AreaCodeId, cascadeDelete: true)
.ForeignKey("dbo.UserProfiles", t => t.UserMembershipId, cascadeDelete: true)
.ForeignKey("dbo.CompanyProfiles", t => t.CompanyProfileId, cascadeDelete: true)
.Index(t => t.UserMembershipId)
.Index(t => t.CompanyProfileId)
.Index(t => t.AreaCodeId);
CreateTable(
"dbo.UserProfiles",
c => new
{
UserMembershipId = c.String(nullable: false, maxLength: 128),
MunicipalityId = c.Int(nullable: false),
FirstName = c.String(),
LastName = c.String(),
StreetNumber = c.Int(nullable: false),
StreetName = c.String(),
PostalCode = c.String(),
PostalBox = c.String(),
})
.PrimaryKey(t => t.UserMembershipId)
.ForeignKey("dbo.Municipalities", t => t.MunicipalityId)
.ForeignKey("dbo.UserMembership", t => t.UserMembershipId)
.Index(t => t.UserMembershipId)
.Index(t => t.MunicipalityId);
CreateTable(
"dbo.UserMembership",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
PhoneNumber = c.String(),
UserName = c.String(nullable: false, maxLength: 256),
Email = c.String(maxLength: 256),
SecurityStamp = c.String(),
IsAccountClosed = c.Boolean(nullable: false),
CreationDate = c.DateTime(nullable: false),
LatestLogonDate = c.DateTime(nullable: false),
UnsubscribeDate = c.DateTime(nullable: false),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.MembershipClaim",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.UserMembership", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.MembershipLogin",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.UserMembership", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.UserMembershipRole",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.UserMembership", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.MembershipRole", t => t.RoleId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.UserMembershipSettings",
c => new
{
UserMembershipId = c.String(nullable: false, maxLength: 128),
UserSettingId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.UserMembershipId, t.UserSettingId })
.ForeignKey("dbo.UserMembership", t => t.UserMembershipId, cascadeDelete: true)
.ForeignKey("dbo.UserSettings", t => t.UserSettingId, cascadeDelete: true)
.Index(t => t.UserMembershipId)
.Index(t => t.UserSettingId);
CreateTable(
"dbo.UserSettings",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
DisplayName = c.String(),
ValueType = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.MembershipRole",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
CreateTable(
"dbo.SystemSettings",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
DisplayName = c.String(),
IsActivate = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.UserMembershipCompanyProfile",
c => new
{
UserMembershipId = c.String(nullable: false, maxLength: 128),
CompanyProfileId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.UserMembershipId, t.CompanyProfileId })
.ForeignKey("dbo.UserMembership", t => t.UserMembershipId, cascadeDelete: true)
.ForeignKey("dbo.CompanyProfiles", t => t.CompanyProfileId, cascadeDelete: true)
.Index(t => t.UserMembershipId)
.Index(t => t.CompanyProfileId);
}
public override void Down()
{
DropForeignKey("dbo.UserMembershipRole", "RoleId", "dbo.MembershipRole");
DropForeignKey("dbo.Municipalities", "StateId", "dbo.States");
DropForeignKey("dbo.PhoneNumbers", "CompanyProfileId", "dbo.CompanyProfiles");
DropForeignKey("dbo.UserProfiles", "UserMembershipId", "dbo.UserMembership");
DropForeignKey("dbo.UserMembershipSettings", "UserSettingId", "dbo.UserSettings");
DropForeignKey("dbo.UserMembershipSettings", "UserMembershipId", "dbo.UserMembership");
DropForeignKey("dbo.UserMembershipRole", "UserId", "dbo.UserMembership");
DropForeignKey("dbo.MembershipLogin", "UserId", "dbo.UserMembership");
DropForeignKey("dbo.UserMembershipCompanyProfile", "CompanyProfileId", "dbo.CompanyProfiles");
DropForeignKey("dbo.UserMembershipCompanyProfile", "UserMembershipId", "dbo.UserMembership");
DropForeignKey("dbo.MembershipClaim", "UserId", "dbo.UserMembership");
DropForeignKey("dbo.PhoneNumbers", "UserMembershipId", "dbo.UserProfiles");
DropForeignKey("dbo.UserProfiles", "MunicipalityId", "dbo.Municipalities");
DropForeignKey("dbo.PhoneNumbers", "AreaCodeId", "dbo.AreaCodes");
DropForeignKey("dbo.CompanyProfiles", "MunicipalityId", "dbo.Municipalities");
DropForeignKey("dbo.States", "CountryId", "dbo.Countries");
DropForeignKey("dbo.AreaCodes", "Id", "dbo.Countries");
DropIndex("dbo.UserMembershipCompanyProfile", new[] { "CompanyProfileId" });
DropIndex("dbo.UserMembershipCompanyProfile", new[] { "UserMembershipId" });
DropIndex("dbo.MembershipRole", "RoleNameIndex");
DropIndex("dbo.UserMembershipSettings", new[] { "UserSettingId" });
DropIndex("dbo.UserMembershipSettings", new[] { "UserMembershipId" });
DropIndex("dbo.UserMembershipRole", new[] { "RoleId" });
DropIndex("dbo.UserMembershipRole", new[] { "UserId" });
DropIndex("dbo.MembershipLogin", new[] { "UserId" });
DropIndex("dbo.MembershipClaim", new[] { "UserId" });
DropIndex("dbo.UserMembership", "UserNameIndex");
DropIndex("dbo.UserProfiles", new[] { "MunicipalityId" });
DropIndex("dbo.UserProfiles", new[] { "UserMembershipId" });
DropIndex("dbo.PhoneNumbers", new[] { "AreaCodeId" });
DropIndex("dbo.PhoneNumbers", new[] { "CompanyProfileId" });
DropIndex("dbo.PhoneNumbers", new[] { "UserMembershipId" });
DropIndex("dbo.CompanyProfiles", new[] { "MunicipalityId" });
DropIndex("dbo.Municipalities", new[] { "StateId" });
DropIndex("dbo.States", new[] { "CountryId" });
DropIndex("dbo.AreaCodes", new[] { "Id" });
DropTable("dbo.UserMembershipCompanyProfile");
DropTable("dbo.SystemSettings");
DropTable("dbo.MembershipRole");
DropTable("dbo.UserSettings");
DropTable("dbo.UserMembershipSettings");
DropTable("dbo.UserMembershipRole");
DropTable("dbo.MembershipLogin");
DropTable("dbo.MembershipClaim");
DropTable("dbo.UserMembership");
DropTable("dbo.UserProfiles");
DropTable("dbo.PhoneNumbers");
DropTable("dbo.CompanyProfiles");
DropTable("dbo.Municipalities");
DropTable("dbo.States");
DropTable("dbo.Countries");
DropTable("dbo.AreaCodes");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.Contracts;
using System.Diagnostics;
using System.IO;
using System.Runtime.WindowsRuntime.Internal;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.Runtime.InteropServices.WindowsRuntime
{
/// <summary>
/// Contains a extension methods that expose operations on WinRT <code>Windows.Foundation.IBuffer</code>.
/// </summary>
public static class WindowsRuntimeBufferExtensions
{
#region (Byte []).AsBuffer extensions
[CLSCompliant(false)]
public static IBuffer AsBuffer(this Byte[] source)
{
if (source == null) throw new ArgumentNullException("source");
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)source.Length));
Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)source.Length));
Contract.EndContractBlock();
return AsBuffer(source, 0, source.Length, source.Length);
}
[CLSCompliant(false)]
public static IBuffer AsBuffer(this Byte[] source, Int32 offset, Int32 length)
{
if (source == null) throw new ArgumentNullException("source");
if (offset < 0) throw new ArgumentOutOfRangeException("offset");
if (length < 0) throw new ArgumentOutOfRangeException("length");
if (source.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)length));
Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)length));
Contract.EndContractBlock();
return AsBuffer(source, offset, length, length);
}
[CLSCompliant(false)]
public static IBuffer AsBuffer(this Byte[] source, Int32 offset, Int32 length, Int32 capacity)
{
if (source == null) throw new ArgumentNullException("source");
if (offset < 0) throw new ArgumentOutOfRangeException("offset");
if (length < 0) throw new ArgumentOutOfRangeException("length");
if (length < 0) throw new ArgumentOutOfRangeException("capacity");
if (source.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (source.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((UInt32)length));
Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((UInt32)capacity));
Contract.EndContractBlock();
return new WindowsRuntimeBuffer(source, offset, length, capacity);
}
#endregion (Byte []).AsBuffer extensions
#region (Byte []).CopyTo extensions for copying to an (IBuffer)
/// <summary>
/// Copies the contents of <code>source</code> to <code>destination</code> starting at offset 0.
/// This method does <em>NOT</em> update <code>destination.Length</code>.
/// </summary>
/// <param name="source">Array to copy data from.</param>
/// <param name="destination">The buffer to copy to.</param>
[CLSCompliant(false)]
public static void CopyTo(this Byte[] source, IBuffer destination)
{
if (source == null) throw new ArgumentNullException("source");
if (destination == null) throw new ArgumentNullException("destination");
Contract.EndContractBlock();
CopyTo(source, 0, destination, 0, source.Length);
}
/// <summary>
/// Copies <code>count</code> bytes from <code>source</code> starting at offset <code>sourceIndex</code>
/// to <code>destination</code> starting at <code>destinationIndex</code>.
/// This method does <em>NOT</em> update <code>destination.Length</code>.
/// </summary>
/// <param name="source">Array to copy data from.</param>
/// <param name="sourceIndex">Position in the array from where to start copying.</param>
/// <param name="destination">The buffer to copy to.</param>
/// <param name="destinationIndex">Position in the buffer to where to start copying.</param>
/// <param name="count">The number of bytes to copy.</param>
[CLSCompliant(false)]
public static void CopyTo(this Byte[] source, Int32 sourceIndex, IBuffer destination, UInt32 destinationIndex, Int32 count)
{
if (source == null) throw new ArgumentNullException("source");
if (destination == null) throw new ArgumentNullException("destination");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex");
if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex");
if (source.Length <= sourceIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds, "sourceIndex");
if (source.Length - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
Contract.EndContractBlock();
// If destination is backed by a managed array, use the array instead of the pointer as it does not require pinning:
Byte[] destDataArr;
Int32 destDataOffs;
if (destination.TryGetUnderlyingData(out destDataArr, out destDataOffs))
{
Array.Copy(source, sourceIndex, destDataArr, (int)(destDataOffs + destinationIndex), count);
return;
}
IntPtr destPtr = destination.GetPointerAtOffset(destinationIndex);
Marshal.Copy(source, sourceIndex, destPtr, count);
}
#endregion (Byte []).CopyTo extensions for copying to an (IBuffer)
#region (IBuffer).ToArray extensions for copying to a new (Byte [])
[CLSCompliant(false)]
public static Byte[] ToArray(this IBuffer source)
{
if (source == null) throw new ArgumentNullException("source");
Contract.EndContractBlock();
return ToArray(source, 0, checked((Int32)source.Length));
}
[CLSCompliant(false)]
public static Byte[] ToArray(this IBuffer source, UInt32 sourceIndex, Int32 count)
{
if (source == null) throw new ArgumentNullException("source");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex");
if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity);
if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer);
Contract.EndContractBlock();
if (count == 0)
return Array.Empty<Byte>();
Byte[] destination = new Byte[count];
source.CopyTo(sourceIndex, destination, 0, count);
return destination;
}
#endregion (IBuffer).ToArray extensions for copying to a new (Byte [])
#region (IBuffer).CopyTo extensions for copying to a (Byte [])
[CLSCompliant(false)]
public static void CopyTo(this IBuffer source, Byte[] destination)
{
if (source == null) throw new ArgumentNullException("source");
if (destination == null) throw new ArgumentNullException("destination");
Contract.EndContractBlock();
CopyTo(source, 0, destination, 0, checked((Int32)source.Length));
}
[CLSCompliant(false)]
public static void CopyTo(this IBuffer source, UInt32 sourceIndex, Byte[] destination, Int32 destinationIndex, Int32 count)
{
if (source == null) throw new ArgumentNullException("source");
if (destination == null) throw new ArgumentNullException("destination");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex");
if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex");
if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity);
if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer);
if (destination.Length <= destinationIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds);
if (destination.Length - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
Contract.EndContractBlock();
// If source is backed by a managed array, use the array instead of the pointer as it does not require pinning:
Byte[] srcDataArr;
Int32 srcDataOffs;
if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs))
{
Array.Copy(srcDataArr, (int)(srcDataOffs + sourceIndex), destination, destinationIndex, count);
return;
}
IntPtr srcPtr = source.GetPointerAtOffset(sourceIndex);
Marshal.Copy(srcPtr, destination, destinationIndex, count);
}
#endregion (IBuffer).CopyTo extensions for copying to a (Byte [])
#region (IBuffer).CopyTo extensions for copying to an (IBuffer)
[CLSCompliant(false)]
public static void CopyTo(this IBuffer source, IBuffer destination)
{
if (source == null) throw new ArgumentNullException("source");
if (destination == null) throw new ArgumentNullException("destination");
Contract.EndContractBlock();
CopyTo(source, 0, destination, 0, source.Length);
}
[CLSCompliant(false)]
public static void CopyTo(this IBuffer source, UInt32 sourceIndex, IBuffer destination, UInt32 destinationIndex, UInt32 count)
{
if (source == null) throw new ArgumentNullException("source");
if (destination == null) throw new ArgumentNullException("destination");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex");
if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex");
if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity);
if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer);
if (destination.Capacity <= destinationIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity);
if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
Contract.EndContractBlock();
// If source are destination are backed by managed arrays, use the arrays instead of the pointers as it does not require pinning:
Byte[] srcDataArr, destDataArr;
Int32 srcDataOffs, destDataOffs;
bool srcIsManaged = source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs);
bool destIsManaged = destination.TryGetUnderlyingData(out destDataArr, out destDataOffs);
if (srcIsManaged && destIsManaged)
{
Debug.Assert(count <= Int32.MaxValue);
Debug.Assert(sourceIndex <= Int32.MaxValue);
Debug.Assert(destinationIndex <= Int32.MaxValue);
Array.Copy(srcDataArr, srcDataOffs + (Int32)sourceIndex, destDataArr, destDataOffs + (Int32)destinationIndex, (Int32)count);
return;
}
IntPtr srcPtr, destPtr;
if (srcIsManaged)
{
Debug.Assert(count <= Int32.MaxValue);
Debug.Assert(sourceIndex <= Int32.MaxValue);
destPtr = destination.GetPointerAtOffset(destinationIndex);
Marshal.Copy(srcDataArr, srcDataOffs + (Int32)sourceIndex, destPtr, (Int32)count);
return;
}
if (destIsManaged)
{
Debug.Assert(count <= Int32.MaxValue);
Debug.Assert(destinationIndex <= Int32.MaxValue);
srcPtr = source.GetPointerAtOffset(sourceIndex);
Marshal.Copy(srcPtr, destDataArr, destDataOffs + (Int32)destinationIndex, (Int32)count);
return;
}
srcPtr = source.GetPointerAtOffset(sourceIndex);
destPtr = destination.GetPointerAtOffset(destinationIndex);
MemCopy(srcPtr, destPtr, count);
}
#endregion (IBuffer).CopyTo extensions for copying to an (IBuffer)
#region Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning)
/// <summary>
/// If the specified <code>IBuffer</code> is backed by a managed array, this method will return <code>true</code> and
/// set <code>underlyingDataArray</code> to refer to that array
/// and <code>underlyingDataArrayStartOffset</code> to the value at which the buffer data begins in that array.
/// If the specified <code>IBuffer</code> is <em>not</em> backed by a managed array, this method will return <code>false</code>.
/// This method is required by managed APIs that wish to use the buffer's data with other managed APIs that use
/// arrays without a need for a memory copy.
/// </summary>
/// <param name="buffer">An <code>IBuffer</code>.</param>
/// <param name="underlyingDataArray">Will be set to the data array backing <code>buffer</code> or to <code>null</code>.</param>
/// <param name="underlyingDataArrayStartOffset">Will be set to the start offset of the buffer data in the backing array
/// or to <code>-1</code>.</param>
/// <returns>Whether the <code>IBuffer</code> is backed by a managed byte array.</returns>
internal static bool TryGetUnderlyingData(this IBuffer buffer, out Byte[] underlyingDataArray, out Int32 underlyingDataArrayStartOffset)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
Contract.EndContractBlock();
WindowsRuntimeBuffer winRtBuffer = buffer as WindowsRuntimeBuffer;
if (winRtBuffer == null)
{
underlyingDataArray = null;
underlyingDataArrayStartOffset = -1;
return false;
}
winRtBuffer.GetUnderlyingData(out underlyingDataArray, out underlyingDataArrayStartOffset);
return true;
}
/// <summary>
/// Checks if the underlying memory backing two <code>IBuffer</code> intances is actually the same memory.
/// When applied to <code>IBuffer</code> instances backed by managed arrays this method is preferable to a naive comparison
/// (such as <code>((IBufferByteAccess) buffer).Buffer == ((IBufferByteAccess) otherBuffer).Buffer</code>) because it avoids
/// pinning the backing array which would be necessary if a direct memory pointer was obtained.
/// </summary>
/// <param name="buffer">An <code>IBuffer</code> instance.</param>
/// <param name="otherBuffer">An <code>IBuffer</code> instance or <code>null</code>.</param>
/// <returns><code>true</code> if the underlying <code>Buffer</code> memory pointer is the same for both specified
/// <code>IBuffer</code> instances (i.e. if they are backed by the same memory); <code>false</code> otherwise.</returns>
[CLSCompliant(false)]
public static bool IsSameData(this IBuffer buffer, IBuffer otherBuffer)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
Contract.EndContractBlock();
if (otherBuffer == null)
return false;
if (buffer == otherBuffer)
return true;
Byte[] thisDataArr, otherDataArr;
Int32 thisDataOffs, otherDataOffs;
bool thisIsManaged = buffer.TryGetUnderlyingData(out thisDataArr, out thisDataOffs);
bool otherIsManaged = otherBuffer.TryGetUnderlyingData(out otherDataArr, out otherDataOffs);
if (thisIsManaged != otherIsManaged)
return false;
if (thisIsManaged)
return (thisDataArr == otherDataArr) && (thisDataOffs == otherDataOffs);
IBufferByteAccess thisBuff = (IBufferByteAccess)buffer;
IBufferByteAccess otherBuff = (IBufferByteAccess)otherBuffer;
unsafe
{
return (thisBuff.GetBuffer() == otherBuff.GetBuffer());
}
}
#endregion Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning)
#region Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream)
/// <summary>
/// Creates a new <code>IBuffer<code> instance backed by the same memory as is backing the specified <code>MemoryStream</code>.
/// The <code>MemoryStream</code> may re-sized in future, as a result the stream will be backed by a different memory region.
/// In such case, the buffer created by this method will remain backed by the memory behind the stream at the time the buffer was created.<br />
/// This method can throw an <code>ObjectDisposedException</code> if the specified stream is closed.<br />
/// This method can throw an <code>UnauthorizedAccessException</code> if the specified stream cannot expose its underlying memory buffer.
/// </summary>
/// <param name="underlyingStream">A memory stream to share the data memory with the buffer being created.</param>
/// <returns>A new <code>IBuffer<code> backed by the same memory as this specified stream.</returns>
// The naming inconsistency with (Byte []).AsBuffer is intentional: as this extension method will appear on
// MemoryStream, consistency with method names on MemoryStream is more important. There we already have an API
// called GetBuffer which returns the underlying array.
[CLSCompliant(false)]
public static IBuffer GetWindowsRuntimeBuffer(this MemoryStream underlyingStream)
{
if (underlyingStream == null)
throw new ArgumentNullException("underlyingStream");
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == underlyingStream.Length);
Contract.Ensures(Contract.Result<IBuffer>().Capacity == underlyingStream.Capacity);
Contract.EndContractBlock();
ArraySegment<byte> streamData;
if (!underlyingStream.TryGetBuffer(out streamData))
{
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer);
}
return new WindowsRuntimeBuffer(streamData.Array, (Int32)streamData.Offset, (Int32)underlyingStream.Length, underlyingStream.Capacity);
}
/// <summary>
/// Creates a new <code>IBuffer<code> instance backed by the same memory as is backing the specified <code>MemoryStream</code>.
/// The <code>MemoryStream</code> may re-sized in future, as a result the stream will be backed by a different memory region.
/// In such case buffer created by this method will remain backed by the memory behind the stream at the time the buffer was created.<br />
/// This method can throw an <code>ObjectDisposedException</code> if the specified stream is closed.<br />
/// This method can throw an <code>UnauthorizedAccessException</code> if the specified stream cannot expose its underlying memory buffer.
/// The created buffer begins at position <code>positionInStream</code> in the stream and extends over up to <code>length</code> bytes.
/// If the stream has less than <code>length</code> bytes after the specified starting position, the created buffer covers only as many
/// bytes as available in the stream. In either case, the <code>Length</code> and the <code>Capacity</code> properties of the created
/// buffer are set accordingly: <code>Capacity</code> - number of bytes between <code>positionInStream</code> and the stream capacity end,
/// but not more than <code>length</code>; <code>Length</code> - number of bytes between <code>positionInStream</code> and the stream
/// length end, or zero if <code>positionInStream</code> is beyond stream length end, but not more than <code>length</code>.
/// </summary>
/// <param name="underlyingStream">A memory stream to share the data memory with the buffer being created.</param>
/// <returns>A new <code>IBuffer<code> backed by the same memory as this specified stream.</returns>
// The naming inconsistency with (Byte []).AsBuffer is intentional: as this extension method will appear on
// MemoryStream, consistency with method names on MemoryStream is more important. There we already have an API
// called GetBuffer which returns the underlying array.
[CLSCompliant(false)]
public static IBuffer GetWindowsRuntimeBuffer(this MemoryStream underlyingStream, Int32 positionInStream, Int32 length)
{
if (underlyingStream == null)
throw new ArgumentNullException("underlyingStream");
if (positionInStream < 0)
throw new ArgumentOutOfRangeException("positionInStream");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (underlyingStream.Capacity <= positionInStream)
throw new ArgumentException(SR.Argument_StreamPositionBeyondEOS);
Contract.Ensures(Contract.Result<IBuffer>() != null);
Contract.Ensures(Contract.Result<IBuffer>().Length == length);
Contract.Ensures(Contract.Result<IBuffer>().Capacity == length);
Contract.EndContractBlock();
ArraySegment<byte> streamData;
if (!underlyingStream.TryGetBuffer(out streamData))
{
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer);
}
Int32 originInStream = streamData.Offset;
Debug.Assert(underlyingStream.Length <= Int32.MaxValue);
Int32 buffCapacity = Math.Min(length, underlyingStream.Capacity - positionInStream);
Int32 buffLength = Math.Max(0, Math.Min(length, ((Int32)underlyingStream.Length) - positionInStream));
return new WindowsRuntimeBuffer(streamData.Array, originInStream + positionInStream, buffLength, buffCapacity);
}
[CLSCompliant(false)]
public static Stream AsStream(this IBuffer source)
{
if (source == null)
throw new ArgumentNullException("source");
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.Ensures(Contract.Result<Stream>().Length == (UInt32)source.Capacity);
Contract.EndContractBlock();
Byte[] dataArr;
Int32 dataOffs;
if (source.TryGetUnderlyingData(out dataArr, out dataOffs))
{
Debug.Assert(source.Capacity < Int32.MaxValue);
return new MemoryStream(dataArr, dataOffs, (Int32)source.Capacity, true);
}
unsafe
{
IBufferByteAccess bufferByteAccess = (IBufferByteAccess)source;
return new WindowsRuntimeBufferUnmanagedMemoryStream(source, (byte*)bufferByteAccess.GetBuffer());
}
}
#endregion Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream)
#region Extensions for direct by-offset access to buffer data elements
[CLSCompliant(false)]
public static Byte GetByte(this IBuffer source, UInt32 byteOffset)
{
if (source == null) throw new ArgumentNullException("source");
if (byteOffset < 0) throw new ArgumentOutOfRangeException("byteOffset");
if (source.Capacity <= byteOffset) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity, "byteOffset");
Contract.EndContractBlock();
Byte[] srcDataArr;
Int32 srcDataOffs;
if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs))
{
return srcDataArr[srcDataOffs + byteOffset];
}
IntPtr srcPtr = source.GetPointerAtOffset(byteOffset);
unsafe
{
// Let's avoid an unnesecary call to Marshal.ReadByte():
Byte* ptr = (Byte*)srcPtr;
return *ptr;
}
}
#endregion Extensions for direct by-offset access to buffer data elements
#region Private plumbing
private class WindowsRuntimeBufferUnmanagedMemoryStream : UnmanagedMemoryStream
{
// We need this class because if we construct an UnmanagedMemoryStream on an IBuffer backed by native memory,
// we must keep around a reference to the IBuffer from which we got the memory pointer. Otherwise the ref count
// of the underlying COM object may drop to zero and the memory may get freed.
private IBuffer _sourceBuffer;
internal unsafe WindowsRuntimeBufferUnmanagedMemoryStream(IBuffer sourceBuffer, Byte* dataPtr)
: base(dataPtr, (Int64)sourceBuffer.Length, (Int64)sourceBuffer.Capacity, FileAccess.ReadWrite)
{
_sourceBuffer = sourceBuffer;
}
} // class WindowsRuntimeBufferUnmanagedMemoryStream
private static IntPtr GetPointerAtOffset(this IBuffer buffer, UInt32 offset)
{
Debug.Assert(0 <= offset);
Debug.Assert(offset < buffer.Capacity);
unsafe
{
IntPtr buffPtr = ((IBufferByteAccess)buffer).GetBuffer();
return new IntPtr((byte*)buffPtr + offset);
}
}
private static unsafe void MemCopy(IntPtr src, IntPtr dst, UInt32 count)
{
if (count > Int32.MaxValue)
{
MemCopy(src, dst, Int32.MaxValue);
MemCopy(src + Int32.MaxValue, dst + Int32.MaxValue, count - Int32.MaxValue);
return;
}
Debug.Assert(count <= Int32.MaxValue);
Int32 bCount = (Int32)count;
// Copy via buffer.
// Note: if becomes perf critical, we will port the routine that
// copies the data without using Marshal (and byte[])
Byte[] tmp = new Byte[bCount];
Marshal.Copy(src, tmp, 0, bCount);
Marshal.Copy(tmp, 0, dst, bCount);
return;
}
#endregion Private plumbing
} // class WindowsRuntimeBufferExtensions
} // namespace
// WindowsRuntimeBufferExtensions.cs
| |
using System;
using System.Linq;
using System.Reflection;
using FluentAssertions.Common;
using FluentAssertions.Primitives;
using FluentAssertions.Types;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
[TestClass]
public class TypeAssertionSpecs
{
#region Be
[TestMethod]
public void When_type_is_equal_to_the_same_type_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type sameType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be(sameType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_equal_to_another_type_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type differentType = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be(differentType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_equal_to_another_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type differentType = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be(differentType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected type to be FluentAssertions.Specs.ClassWithoutAttribute" +
" because we want to test the error message, but found FluentAssertions.Specs.ClassWithAttribute.");
}
[TestMethod]
public void When_asserting_equality_of_a_type_but_the_type_is_null_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type nullType = null;
Type someType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
nullType.Should().Be(someType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected type to be FluentAssertions.Specs.ClassWithAttribute" +
" because we want to test the error message, but found <null>.");
}
[TestMethod]
public void When_asserting_equality_of_a_type_with_null_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type someType = typeof (ClassWithAttribute);
Type nullType = null;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
someType.Should().Be(nullType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected type to be <null>" +
" because we want to test the error message, but found FluentAssertions.Specs.ClassWithAttribute.");
}
[TestMethod]
public void When_type_is_equal_to_same_type_from_different_assembly_it_fails_with_assembly_qualified_name
()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec
Type typeFromThisAssembly = typeof (ObjectAssertions);
#if !WINRT && !WINDOWS_PHONE_APP && !CORE_CLR
Type typeFromOtherAssembly =
typeof (TypeAssertions).Assembly.GetType("FluentAssertions.Primitives.ObjectAssertions");
#else
Type typeFromOtherAssembly =
Type.GetType("FluentAssertions.Primitives.ObjectAssertions,FluentAssertions.Core");
#endif
#pragma warning restore 436
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeFromThisAssembly.Should().Be(typeFromOtherAssembly, "because we want to test the error {0}",
"message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
const string expectedMessage =
"Expected type to be [FluentAssertions.Primitives.ObjectAssertions, FluentAssertions*]" +
" because we want to test the error message, but found " +
"[FluentAssertions.Primitives.ObjectAssertions, FluentAssertions*].";
act.ShouldThrow<AssertFailedException>().WithMessage(expectedMessage);
}
[TestMethod]
public void When_type_is_equal_to_the_same_type_using_generics_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be<ClassWithAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_equal_to_another_type_using_generics_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be<ClassWithoutAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_equal_to_another_type_using_generics_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be<ClassWithoutAttribute>("because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type to be FluentAssertions.Specs.ClassWithoutAttribute because we want to test " +
"the error message, but found FluentAssertions.Specs.ClassWithAttribute.");
}
#endregion
#region NotBe
[TestMethod]
public void When_type_is_not_equal_to_the_another_type_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type otherType = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe(otherType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type sameType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe(sameType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type sameType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe(sameType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type not to be [FluentAssertions.Specs.ClassWithAttribute*]" +
" because we want to test the error message, but it is.");
}
[TestMethod]
public void When_type_is_not_equal_to_another_type_using_generics_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe<ClassWithoutAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe<ClassWithAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe<ClassWithAttribute>("because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type not to be [FluentAssertions.Specs.ClassWithAttribute*] because we want to test " +
"the error message, but it is.");
}
#endregion
#region BeAssignableTo
[TestMethod]
public void When_its_own_type_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof (DummyImplementingClass).Should().BeAssignableTo<DummyImplementingClass>();
}
[TestMethod]
public void When_its_base_type_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof (DummyImplementingClass).Should().BeAssignableTo<DummyBaseClass>();
}
[TestMethod]
public void When_implemented_interface_type_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof (DummyImplementingClass).Should().BeAssignableTo<IDisposable>();
}
[TestMethod]
public void When_an_unrelated_type_it_fails_with_a_useful_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
Type someType = typeof (DummyImplementingClass);
Action act = () => someType.Should().BeAssignableTo<DateTime>("because we want to test the failure {0}", "message");
//-----------------------------------------------------------------------------------------------------------
// Act / Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage($"*{typeof (DummyImplementingClass)} to be assignable to {typeof (DateTime)}*failure message*");
}
[TestMethod]
public void When_its_own_type_instance_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyImplementingClass));
}
[TestMethod]
public void When_its_base_type_instance_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyBaseClass));
}
[TestMethod]
public void When_an_implemented_interface_type_instance_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(IDisposable));
}
[TestMethod]
public void When_an_unrelated_type_instance_it_fails_with_a_useful_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
Type someType = typeof(DummyImplementingClass);
Action act = () => someType.Should().BeAssignableTo(typeof(DateTime), "because we want to test the failure {0}", "message");
//-----------------------------------------------------------------------------------------------------------
// Act / Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage($"*{typeof(DummyImplementingClass)} to be assignable to {typeof(DateTime)}*failure message*");
}
#endregion
#region BeDerivedFrom
[TestMethod]
public void When_asserting_a_type_is_derived_from_its_base_class_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(DummyImplementingClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom(typeof(DummyBaseClass));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_is_derived_from_an_unrelated_class_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(DummyBaseClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom(typeof(ClassWithMembers), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.DummyBaseClass to be derived from " +
"FluentAssertions.Specs.ClassWithMembers because we want to test the error message, but it is not.");
}
[TestMethod]
public void When_asserting_a_type_is_derived_from_an_interface_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom(typeof(IDummyInterface), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<ArgumentException>()
.WithMessage("Must not be an interface Type.\r\nParameter name: baseType");
}
#endregion
#region BeDerivedFromOfT
[TestMethod]
public void When_asserting_a_type_is_DerivedFromOfT_its_base_class_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(DummyImplementingClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom<DummyBaseClass>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region BeDecoratedWith
[TestMethod]
public void When_type_is_decorated_with_expected_attribute_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithAttribute = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithAttribute.Should().BeDecoratedWith<DummyClassAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_not_decorated_with_expected_attribute_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithoutAttribute = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithoutAttribute.Should().BeDecoratedWith<DummyClassAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_not_decorated_with_expected_attribute_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithoutAttribute = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithoutAttribute.Should().BeDecoratedWith<DummyClassAttribute>(
"because we want to test the error {0}",
"message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassWithoutAttribute to be decorated with " +
"FluentAssertions.Specs.DummyClassAttribute because we want to test the error message, but the attribute " +
"was not found.");
}
[TestMethod]
public void When_type_is_decorated_with_expected_attribute_with_the_expected_properties_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithAttribute = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithAttribute.Should()
.BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Expected") && a.IsEnabled));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_decorated_with_expected_attribute_that_has_an_unexpected_property_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithAttribute = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithAttribute.Should()
.BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Unexpected") && a.IsEnabled));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassWithAttribute to be decorated with " +
"FluentAssertions.Specs.DummyClassAttribute that matches ((a.Name == \"Unexpected\")*a.IsEnabled), " +
"but no matching attribute was found.");
}
[TestMethod]
public void When_asserting_a_selection_of_decorated_types_is_decorated_with_an_attribute_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var types = new TypeSelector(new[]
{
typeof (ClassWithAttribute)
});
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
types.Should().BeDecoratedWith<DummyClassAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_selection_of_non_decorated_types_is_decorated_with_an_attribute_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var types = new TypeSelector(new[]
{
typeof (ClassWithAttribute),
typeof (ClassWithoutAttribute),
typeof (OtherClassWithoutAttribute)
});
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
types.Should().BeDecoratedWith<DummyClassAttribute>("because we do");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected all types to be decorated with FluentAssertions.Specs.DummyClassAttribute" +
" because we do, but the attribute was not found on the following types:\r\n" +
"FluentAssertions.Specs.ClassWithoutAttribute\r\n" +
"FluentAssertions.Specs.OtherClassWithoutAttribute");
}
[TestMethod]
public void When_asserting_a_selection_of_types_with_unexpected_attribute_property_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var types = new TypeSelector(new[]
{
typeof (ClassWithAttribute),
typeof (ClassWithoutAttribute),
typeof (OtherClassWithoutAttribute)
});
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
types.Should()
.BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Expected") && a.IsEnabled), "because we do");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected all types to be decorated with FluentAssertions.Specs.DummyClassAttribute" +
" that matches ((a.Name == \"Expected\")*a.IsEnabled) because we do," +
" but no matching attribute was found on the following types:\r\n" +
"FluentAssertions.Specs.ClassWithoutAttribute\r\n" +
"FluentAssertions.Specs.OtherClassWithoutAttribute");
}
#endregion
#region Implement
[TestMethod]
public void When_asserting_a_type_implements_an_interface_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement(typeof (IDummyInterface));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_then_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement(typeof (IDummyInterface), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassThatDoesNotImplementInterface to implement " +
"interface FluentAssertions.Specs.IDummyInterface because we want to test the error message, " +
"but it does not.");
}
[TestMethod]
public void When_asserting_a_type_implements_a_NonInterface_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement(typeof(DateTime), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<ArgumentException>()
.WithMessage("Must be an interface Type.\r\nParameter name: interfaceType");
}
#endregion
#region ImplementOfT
[TestMethod]
public void When_asserting_a_type_implementsOfT_an_interface_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement<IDummyInterface>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotImplement
[TestMethod]
public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_not_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement(typeof(IDummyInterface));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_implements_an_interface_which_it_does_not_then_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement(typeof(IDummyInterface), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassThatImplementsInterface to not implement interface " +
"FluentAssertions.Specs.IDummyInterface because we want to test the error message, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_implement_a_NonInterface_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement(typeof(DateTime), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<ArgumentException>()
.WithMessage("Must be an interface Type.\r\nParameter name: interfaceType");
}
#endregion
#region NotImplementOfT
[TestMethod]
public void When_asserting_a_type_does_not_implementOfT_an_interface_which_it_does_not_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement<IDummyInterface>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region HaveProperty
[TestMethod]
public void When_asserting_a_type_has_a_property_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveProperty(typeof(string), "PrivateWriteProtectedReadProperty")
.Which.Should()
.BeWritable(CSharpAccessModifier.Private)
.And.BeReadable(CSharpAccessModifier.Protected);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_property_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveProperty(typeof(string), "PublicProperty", "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithNoMembers.PublicProperty to exist because we want to " +
"test the error message, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_has_a_property_which_it_has_with_a_different_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveProperty(typeof(int), "PrivateWriteProtectedReadProperty", "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithMembers.PrivateWriteProtectedReadProperty to be of type System.Int32 because we want to test the error message, but it is not.");
}
#endregion
#region HavePropertyOfT
[TestMethod]
public void When_asserting_a_type_has_a_propertyOfT_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveProperty<string>("PrivateWriteProtectedReadProperty")
.Which.Should()
.BeWritable(CSharpAccessModifier.Private)
.And.BeReadable(CSharpAccessModifier.Protected);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotHaveProperty
[TestMethod]
public void When_asserting_a_type_does_not_have_a_property_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassWithoutMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveProperty("Property");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_a_property_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveProperty("PrivateWriteProtectedReadProperty", "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithMembers.PrivateWriteProtectedReadProperty to not exist because we want to " +
"test the error message, but it does.");
}
#endregion
#region HaveExplicitProperty
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof (IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_and_explicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "ImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ImplicitStringProperty, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_not_implement_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.NonExistantProperty, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_from_an_unimplemented_interface_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region HaveExplicitPropertyOfT
[TestMethod]
public void When_asserting_a_type_explicitlyOfT_implements_a_property_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty<IExplicitInterface>("ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotHaveExplicitProperty
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitStringProperty, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_and_explicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitImplicitStringProperty, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "ImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_not_implement_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_from_an_unimplemented_interface_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region NotHaveExplicitPropertyOfT
[TestMethod]
public void When_asserting_a_type_does_not_explicitlyOfT_implement_a_property_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty<IExplicitInterface>("ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitStringProperty, but it does.");
}
#endregion
#region HaveExplicitMethod
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_and_explicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "ImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ImplicitMethod, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_not_implement_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.NonExistantMethod, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_from_an_unimplemented_interface_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "NonExistantProperty", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region HaveExplicitMethodOfT
[TestMethod]
public void When_asserting_a_type_explicitly_implementsOfT_a_method_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod<IExplicitInterface>("ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotHaveExplicitMethod
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitMethod, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_and_explicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitImplicitMethod, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "ImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_not_implement_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_from_an_unimplemented_interface_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region NotHaveExplicitMethodOfT
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implementOfT_a_method_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod< IExplicitInterface>("ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitMethod, but it does.");
}
#endregion
#region HaveIndexer
[TestMethod]
public void When_asserting_a_type_has_an_indexer_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveIndexer(typeof(string), new[] { typeof(string) })
.Which.Should()
.BeWritable(CSharpAccessModifier.Internal)
.And.BeReadable(CSharpAccessModifier.Private);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_an_indexer_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveIndexer(typeof(string), new [] {typeof(int), typeof(Type)}, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithNoMembers[System.Int32, System.Type] to exist because we want to test the error" +
" message, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_has_an_indexer_with_different_parameters_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveIndexer(typeof(string), new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithMembers[System.Int32, System.Type] to exist because we want to test the error" +
" message, but it does not.");
}
#endregion
#region NotHaveIndexer
[TestMethod]
public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithoutMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveIndexer(new [] {typeof(string)});
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveIndexer(new [] {typeof(string)}, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected indexer FluentAssertions.Specs.ClassWithMembers[System.String] to not exist because we want to " +
"test the error message, but it does.");
}
#endregion
#region HaveConstructor
[TestMethod]
public void When_asserting_a_type_has_a_constructor_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveConstructor(new Type[] { typeof(string) })
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.Private);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_constructor_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveConstructor(new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected constructor FluentAssertions.Specs.ClassWithNoMembers(System.Int32, System.Type) to exist because " +
"we want to test the error message, but it does not.");
}
#endregion
#region HaveDefaultConstructor
[TestMethod]
public void When_asserting_a_type_has_a_default_constructor_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveDefaultConstructor()
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.ProtectedInternal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveDefaultConstructor("because the compiler generates one even if not explicitly defined.")
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region HaveMethod
[TestMethod]
public void When_asserting_a_type_has_a_method_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveMethod("VoidMethod", new Type[] { })
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.Private)
.And.ReturnVoid();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_method_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveMethod("NonExistantMethod", new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected method FluentAssertions.Specs.ClassWithNoMembers.NonExistantMethod(System.Int32, System.Type) to exist " +
"because we want to test the error message, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_has_a_method_with_different_parameter_types_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveMethod("VoidMethod", new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected method FluentAssertions.Specs.ClassWithMembers.VoidMethod(System.Int32, System.Type) to exist " +
"because we want to test the error message, but it does not.");
}
#endregion
#region NotHaveMethod
[TestMethod]
public void When_asserting_a_type_does_not_have_a_method_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithoutMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveMethod("NonExistantMethod", new Type[] {});
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_a_method_which_it_has_with_different_parameter_types_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveMethod("VoidMethod", new [] { typeof(int) });
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_that_method_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveMethod("VoidMethod", new Type[] {}, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected method Void FluentAssertions.Specs.ClassWithMembers.VoidMethod() to not exist because we want to " +
"test the error message, but it does.");
}
#endregion
#region HaveAccessModifier
[TestMethod]
public void When_asserting_a_public_type_is_public_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_public_member_is_not_public_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type
.Should()
.HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type IPublicInterface to be Internal because we want to test the error message, but it " +
"is Public.");
}
[TestMethod]
public void When_asserting_an_internal_type_is_internal_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Internal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_an_internal_type_is_not_internal_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" +
" error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type InternalClass to be ProtectedInternal because we want to test the error message, " +
"but it is Internal.");
}
[TestMethod]
public void When_asserting_a_nested_private_type_is_private_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "PrivateClass").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Private);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_private_type_is_not_private_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "PrivateClass").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type PrivateClass to be Protected because we want to test the error message, but it " +
"is Private.");
}
[TestMethod]
public void When_asserting_a_nested_protected_type_is_protected_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "ProtectedEnum").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Protected);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_protected_type_is_not_protected_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "ProtectedEnum").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type ProtectedEnum to be Public, but it is Protected.");
}
[TestMethod]
public void When_asserting_a_nested_public_type_is_public_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_public_member_is_not_public_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type
.Should()
.HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type IPublicInterface to be Internal because we want to test the error message, " +
"but it is Public.");
}
[TestMethod]
public void When_asserting_a_nested_internal_type_is_internal_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Internal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_internal_type_is_not_internal_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" +
" error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type InternalClass to be ProtectedInternal because we want to test the error message, " +
"but it is Internal.");
}
[TestMethod]
public void When_asserting_a_nested_protected_internal_member_is_protected_internal_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IProtectedInternalInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_protected_internal_member_is_not_protected_internal_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IProtectedInternalInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Private, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type IProtectedInternalInterface to be Private because we want to test the error " +
"message, but it is ProtectedInternal.");
}
#endregion
}
#region Internal classes used in unit tests
[DummyClass("Expected", true)]
public class ClassWithAttribute
{
}
public class ClassWithoutAttribute
{
}
public class OtherClassWithoutAttribute
{
}
[AttributeUsage(AttributeTargets.Class)]
public class DummyClassAttribute : Attribute
{
public string Name { get; set; }
public bool IsEnabled { get; set; }
public DummyClassAttribute(string name, bool isEnabled)
{
Name = name;
IsEnabled = isEnabled;
}
}
public interface IDummyInterface
{
}
public class ClassThatImplementsInterface : IDummyInterface
{
}
public class ClassThatDoesNotImplementInterface
{
}
public class ClassWithMembers
{
protected internal ClassWithMembers() { }
private ClassWithMembers(String overload) { }
protected string PrivateWriteProtectedReadProperty { get { return null; } private set { } }
internal string this[string str] { private get { return str; } set { } }
protected internal string this[int i] { get { return i.ToString(); } private set { } }
private void VoidMethod() { }
private void VoidMethod(string overload) { }
}
public class ClassExplicitlyImplementingInterface : IExplicitInterface
{
public string ImplicitStringProperty { get { return null; } private set { } }
string IExplicitInterface.ExplicitStringProperty { set { } }
public string ExplicitImplicitStringProperty { get; set; }
string IExplicitInterface.ExplicitImplicitStringProperty { get; set; }
public void ImplicitMethod() { }
public void ImplicitMethod(string overload) { }
void IExplicitInterface.ExplicitMethod() { }
void IExplicitInterface.ExplicitMethod(string overload) { }
public void ExplicitImplicitMethod() { }
public void ExplicitImplicitMethod(string overload) { }
void IExplicitInterface.ExplicitImplicitMethod() { }
void IExplicitInterface.ExplicitImplicitMethod(string overload) { }
}
public interface IExplicitInterface
{
string ImplicitStringProperty { get; }
string ExplicitStringProperty { set; }
string ExplicitImplicitStringProperty { get; set; }
void ImplicitMethod();
void ImplicitMethod(string overload);
void ExplicitMethod();
void ExplicitMethod(string overload);
void ExplicitImplicitMethod();
void ExplicitImplicitMethod(string overload);
}
public class ClassWithoutMembers { }
public interface IPublicInterface { }
internal class InternalClass { }
class Nested
{
class PrivateClass { }
protected enum ProtectedEnum { }
public interface IPublicInterface { }
internal class InternalClass { }
protected internal interface IProtectedInternalInterface { }
}
#endregion
}
namespace FluentAssertions.Primitives
{
#pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec
/// <summary>
/// A class that intentionally has the exact same name and namespace as the ObjectAssertions from the FluentAssertions
/// assembly. This class is used to test the behavior of comparisons on such types.
/// </summary>
internal class ObjectAssertions
{
}
#pragma warning restore 436
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A scholarly article.
/// </summary>
public class ScholarlyArticle_Core : TypeCore, IArticle
{
public ScholarlyArticle_Core()
{
this._TypeId = 233;
this._Id = "ScholarlyArticle";
this._Schema_Org_Url = "http://schema.org/ScholarlyArticle";
string label = "";
GetLabel(out label, "ScholarlyArticle", typeof(ScholarlyArticle_Core));
this._Label = label;
this._Ancestors = new int[]{266,78,20};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{20};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,15,16,235};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// The actual body of the article.
/// </summary>
private ArticleBody_Core articleBody;
public ArticleBody_Core ArticleBody
{
get
{
return articleBody;
}
set
{
articleBody = value;
SetPropertyInstance(articleBody);
}
}
/// <summary>
/// Articles may belong to one or more 'sections' in a magazine or newspaper, such as Sports, Lifestyle, etc.
/// </summary>
private ArticleSection_Core articleSection;
public ArticleSection_Core ArticleSection
{
get
{
return articleSection;
}
set
{
articleSection = value;
SetPropertyInstance(articleSection);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
/// <summary>
/// The number of words in the text of the Article.
/// </summary>
private WordCount_Core wordCount;
public WordCount_Core WordCount
{
get
{
return wordCount;
}
set
{
wordCount = value;
SetPropertyInstance(wordCount);
}
}
}
}
| |
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//#ifndef AGG_RASTERIZER_SL_CLIP_INCLUDED
//#define AGG_RASTERIZER_SL_CLIP_INCLUDED
//#include "agg_clip_liang_barsky.h"
using PixelFarm.CpuBlit.VertexProcessing;
using PixelFarm.CpuBlit.PrimitiveProcessing;
namespace PixelFarm.CpuBlit.Rasterization
{
partial class ScanlineRasterizer
{
/// <summary>
/// rect-clipper
/// </summary>
class VectorClipper
{
Q1Rect _clipBox;
int _x1;
int _y1;
int _f1;
bool _clipping;
readonly CellAARasterizer _ras;
public VectorClipper(CellAARasterizer ras)
{
_ras = ras;
_clipBox = new Q1Rect(0, 0, 0, 0);
_x1 = _y1 = _f1 = 0;
_clipping = false;
}
public Q1Rect GetVectorClipBox() => _clipBox;
public void SetClipBox(int x1, int y1, int x2, int y2)
{
_clipBox = new Q1Rect(x1, y1, x2, y2, true);
_clipping = true;
}
/// <summary>
/// clip box width is extened 3 times for lcd-effect subpixel rendering
/// </summary>
bool _clipBoxWidthX3ForSubPixelLcdEffect = false; //default
/// <summary>
/// when we render in subpixel rendering, we extend a row length 3 times (expand RGB)
/// </summary>
/// <param name="value"></param>
public void SetClipBoxWidthX3ForSubPixelLcdEffect(bool value)
{
//-----------------------------------------------------------------------------
//if we don't want to expand our img buffer 3 times (larger than normal)
//we should use this method to extend only a cliper box's width x3
//-----------------------------------------------------------------------------
//special method for our need
if (value != _clipBoxWidthX3ForSubPixelLcdEffect)
{
//changed
if (value)
{
_clipBox = new Q1Rect(_clipBox.Left, _clipBox.Bottom, _clipBox.Left + (_clipBox.Width * 3), _clipBox.Height);
}
else
{
//set back
_clipBox = new Q1Rect(_clipBox.Left, _clipBox.Bottom, _clipBox.Left + (_clipBox.Width / 3), _clipBox.Height);
}
_clipBoxWidthX3ForSubPixelLcdEffect = value;
}
}
public void ResetClipping()
{
_clipping = false;
}
public void MoveTo(int x1, int y1)
{
_x1 = x1;
_y1 = y1;
if (_clipping)
{
_f1 = ClipLiangBarsky.Flags(x1, y1, _clipBox);
}
}
//------------------------------------------------------------------------
void LineClipY(int x1, int y1,
int x2, int y2,
int f1, int f2)
{
f1 &= 10;
f2 &= 10;
if ((f1 | f2) == 0)
{
// Fully visible
_ras.DrawLine(x1, y1, x2, y2);
}
else
{
if (f1 == f2)
{
// Invisible by Y
return;
}
int tx1 = x1;
int ty1 = y1;
int tx2 = x2;
int ty2 = y2;
if ((f1 & 8) != 0) // y1 < clip.y1
{
tx1 = x1 + MulDiv(_clipBox.Bottom - y1, x2 - x1, y2 - y1);
ty1 = _clipBox.Bottom;
}
if ((f1 & 2) != 0) // y1 > clip.y2
{
tx1 = x1 + MulDiv(_clipBox.Top - y1, x2 - x1, y2 - y1);
ty1 = _clipBox.Top;
}
if ((f2 & 8) != 0) // y2 < clip.y1
{
tx2 = x1 + MulDiv(_clipBox.Bottom - y1, x2 - x1, y2 - y1);
ty2 = _clipBox.Bottom;
}
if ((f2 & 2) != 0) // y2 > clip.y2
{
tx2 = x1 + MulDiv(_clipBox.Top - y1, x2 - x1, y2 - y1);
ty2 = _clipBox.Top;
}
_ras.DrawLine(tx1, ty1, tx2, ty2);
}
}
//--------------------------------------------------------------------
public void LineTo(int x2, int y2)
{
if (_clipping)
{
int f2 = ClipLiangBarsky.Flags(x2, y2, _clipBox);
if ((_f1 & 10) == (f2 & 10) && (_f1 & 10) != 0)
{
// Invisible by Y
_x1 = x2;
_y1 = y2;
_f1 = f2;
return;
}
int x1 = _x1;
int y1 = _y1;
int f1 = _f1;
int y3, y4;
int f3, f4;
switch (((f1 & 5) << 1) | (f2 & 5))
{
case 0: // Visible by X
LineClipY(x1, y1, x2, y2, f1, f2);
break;
case 1: // x2 > clip.x2
y3 = y1 + MulDiv(_clipBox.Right - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.GetFlagsY(y3, _clipBox);
LineClipY(x1, y1, _clipBox.Right, y3, f1, f3);
LineClipY(_clipBox.Right, y3, _clipBox.Right, y2, f3, f2);
break;
case 2: // x1 > clip.x2
y3 = y1 + MulDiv(_clipBox.Right - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.GetFlagsY(y3, _clipBox);
LineClipY(_clipBox.Right, y1, _clipBox.Right, y3, f1, f3);
LineClipY(_clipBox.Right, y3, x2, y2, f3, f2);
break;
case 3: // x1 > clip.x2 && x2 > clip.x2
LineClipY(_clipBox.Right, y1, _clipBox.Right, y2, f1, f2);
break;
case 4: // x2 < clip.x1
y3 = y1 + MulDiv(_clipBox.Left - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.GetFlagsY(y3, _clipBox);
LineClipY(x1, y1, _clipBox.Left, y3, f1, f3);
LineClipY(_clipBox.Left, y3, _clipBox.Left, y2, f3, f2);
break;
case 6: // x1 > clip.x2 && x2 < clip.x1
y3 = y1 + MulDiv(_clipBox.Right - x1, y2 - y1, x2 - x1);
y4 = y1 + MulDiv(_clipBox.Left - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.GetFlagsY(y3, _clipBox);
f4 = ClipLiangBarsky.GetFlagsY(y4, _clipBox);
LineClipY(_clipBox.Right, y1, _clipBox.Right, y3, f1, f3);
LineClipY(_clipBox.Right, y3, _clipBox.Left, y4, f3, f4);
LineClipY(_clipBox.Left, y4, _clipBox.Left, y2, f4, f2);
break;
case 8: // x1 < clip.x1
y3 = y1 + MulDiv(_clipBox.Left - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.GetFlagsY(y3, _clipBox);
LineClipY(_clipBox.Left, y1, _clipBox.Left, y3, f1, f3);
LineClipY(_clipBox.Left, y3, x2, y2, f3, f2);
break;
case 9: // x1 < clip.x1 && x2 > clip.x2
y3 = y1 + MulDiv(_clipBox.Left - x1, y2 - y1, x2 - x1);
y4 = y1 + MulDiv(_clipBox.Right - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.GetFlagsY(y3, _clipBox);
f4 = ClipLiangBarsky.GetFlagsY(y4, _clipBox);
LineClipY(_clipBox.Left, y1, _clipBox.Left, y3, f1, f3);
LineClipY(_clipBox.Left, y3, _clipBox.Right, y4, f3, f4);
LineClipY(_clipBox.Right, y4, _clipBox.Right, y2, f4, f2);
break;
case 12: // x1 < clip.x1 && x2 < clip.x1
LineClipY(_clipBox.Left, y1, _clipBox.Left, y2, f1, f2);
break;
}
_f1 = f2;
}
else
{
_ras.DrawLine(_x1, _y1, x2, y2);
}
_x1 = x2;
_y1 = y2;
}
static int MulDiv(int a, int b, int c)
{
return AggMathRound.iround_f((float)a * (float)b / (float)c);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace SwarmNLP
{
public class Win32
{
public const uint DIB_RGB_COLORS = 0;
public const uint SRCCOPY = 0x00CC0020;
public const uint BI_RGB = 0;
public const int COLORONCOLOR = 3;
public enum Bool
{
False = 0,
True
};
public enum TernaryRasterOperations
{
SRCCOPY = 0x00CC0020, /* dest = source */
SRCPAINT = 0x00EE0086, /* dest = source OR dest */
SRCAND = 0x008800C6, /* dest = source AND dest */
SRCINVERT = 0x00660046, /* dest = source XOR dest */
SRCERASE = 0x00440328, /* dest = source AND (NOT dest ) */
NOTSRCCOPY = 0x00330008, /* dest = (NOT source) */
NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */
MERGECOPY = 0x00C000CA, /* dest = (source AND pattern) */
MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest */
PATCOPY = 0x00F00021, /* dest = pattern */
PATPAINT = 0x00FB0A09, /* dest = DPSnoo */
PATINVERT = 0x005A0049, /* dest = pattern XOR dest */
DSTINVERT = 0x00550009, /* dest = (NOT dest) */
BLACKNESS = 0x00000042, /* dest = BLACK */
WHITENESS = 0x00FF0062, /* dest = WHITE */
};
public enum PenStyles
{
PS_SOLID = 0,
PS_DASH = 1,
PS_DOT = 2,
PS_DASHDOT = 3,
PS_DASHDOTDOT = 4,
PS_NULL = 5,
PS_INSIDEFRAME = 6,
PS_USERSTYLE = 7,
PS_ALTERNATE = 8,
PS_STYLE_MASK = 0x0000000F,
PS_ENDCAP_ROUND = 0x00000000,
PS_ENDCAP_SQUARE = 0x00000100,
PS_ENDCAP_FLAT = 0x00000200,
PS_ENDCAP_MASK = 0x00000F00,
PS_JOIN_ROUND = 0x00000000,
PS_JOIN_BEVEL = 0x00001000,
PS_JOIN_MITER = 0x00002000,
PS_JOIN_MASK = 0x0000F000,
PS_COSMETIC = 0x00000000,
PS_GEOMETRIC = 0x00010000,
PS_TYPE_MASK = 0x000F0000
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFOHEADER
{
public UInt32 biSize;
public Int32 biWidth;
public Int32 biHeight;
public Int16 biPlanes;
public Int16 biBitCount;
public UInt32 biCompression;
public UInt32 biSizeImage;
public Int32 biXPelsPerMeter;
public Int32 biYPelsPerMeter;
public UInt32 biClrUsed;
public UInt32 biClrImportant;
}
[StructLayout(LayoutKind.Sequential)]
public struct RGBQUAD
{
public byte Blue;
public byte Green;
public byte Red;
public byte Reserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFO
{
public BITMAPINFOHEADER Header;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 256)]
public uint[] Colors;
}
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern Bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll", ExactSpelling = true)]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern Bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hObject, int width, int height);
[DllImport("gdi32.dll")]
public static extern bool LineTo(
IntPtr hdc, // device context handle
int nXEnd, // x-coordinate of line's ending point
int nYEnd // y-coordinate of line's ending point
);
[DllImport("user32.dll")]
public static extern int FillRect(
IntPtr hDC, // handle to DC
ref RECT lprc, // rectangle
IntPtr hbr // handle to brush
);
[DllImport("gdi32.dll")]
public static extern IntPtr CreatePen(
PenStyles fnPenStyle, // pen style
int nWidth, // pen width
int crColor // pen color
);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateSolidBrush(
int crColor // brush color value
);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern Bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjSource, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern int SetDIBitsToDevice(
IntPtr hdc, // handle to DC
int XDest, // x-coord of destination upper-left corner
int YDest, // y-coord of destination upper-left corner
uint dwWidth, // source rectangle width
uint dwHeight, // source rectangle height
int XSrc, // x-coord of source lower-left corner
int YSrc, // y-coord of source lower-left corner
uint uStartScan, // first scan line in array
uint cScanLines, // number of scan lines
IntPtr lpvBits, // array of DIB bits CONST VOID *lpvBits
IntPtr lpbmi, // bitmap information CONST BITMAPINFO *lpbmi
uint fuColorUse // RGB or palette indexes
);
[DllImportAttribute("gdi32.dll")]
public static extern bool MoveToEx(
IntPtr hdc, // handle to device context
int X, // x-coordinate of new current position
int Y, // y-coordinate of new current position
int oldp// pointer to old current position
);
static public uint MAKERGB(int r, int g, int b)
{
return ((uint)(b & 255)) | ((uint)((r & 255) << 8)) | ((uint)((g & 255) << 16));
}
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern int StretchDIBits(
IntPtr hdc, // handle to DC
int XDest, // x-coord of destination upper-left corner
int YDest, // y-coord of destination upper-left corner
int nDestWidth, // width of destination rectangle
int nDestHeight, // height of destination rectangle
int XSrc, // x-coord of source upper-left corner
int YSrc, // y-coord of source upper-left corner
int nSrcWidth, // width of source rectangle
int nSrcHeight, // height of source rectangle
IntPtr lpBits, // bitmap bits CONST VOID *lpBits
ref BITMAPINFO lpBitsInfo, // bitmap data CONST BITMAPINFO *lpBitsInfo
uint iUsage, // usage options
uint dwRop // raster operation code
);
[DllImport("gdi32.dll")]
public static extern bool StretchBlt(IntPtr hdcDest, int nXOriginDest, int nYOriginDest,
int nWidthDest, int nHeightDest,
IntPtr hdcSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc,
Int32 dwRop);
[DllImport("gdi32.dll")]
public static extern int SetStretchBltMode(
IntPtr hdc, // handle to DC
int iStretchMode // bitmap stretching mode
);
[DllImport("gdi32.dll")]
public static extern bool Arc(
IntPtr hdc, // handle to device context
int nLeftRect, // x-coord of rectangle's upper-left corner
int nTopRect, // y-coord of rectangle's upper-left corner
int nRightRect, // x-coord of rectangle's lower-right corner
int nBottomRect, // y-coord of rectangle's lower-right corner
int nXStartArc, // x-coord of first radial ending point
int nYStartArc, // y-coord of first radial ending point
int nXEndArc, // x-coord of second radial ending point
int nYEndArc // y-coord of second radial ending point
);
[DllImport("gdi32.dll")]
public static extern bool Ellipse(
IntPtr hdc, // handle to DC
int nLeftRect, // x-coord of upper-left corner of rectangle
int nTopRect, // y-coord of upper-left corner of rectangle
int nRightRect, // x-coord of lower-right corner of rectangle
int nBottomRect // y-coord of lower-right corner of rectangle
);
}
}
| |
using System.Drawing;
using Sce.Atf.Dom;
using Sce.Atf.Controls.Timelines;
using Sce.Atf.Controls.PropertyEditing;
using Sce.Atf.Adaptation;
using pico.Controls.PropertyEditing;
using System.ComponentModel;
using pico.Anim;
using pico.Timeline;
namespace picoTimelineEditor.DomNodeAdapters
{
class IntervalSoundLister : DynamicEnumUITypeEditorLister
{
public string[] GetNames( object instance )
{
IntervalSound interval = instance.As<IntervalSound>();
if ( interval == null )
// returning an non-empty string is necessary to avaid LongEnumEditorCrash
//
return new string[] { "#objectIsNotIntervalSound" };
string[] soundNames = pico.ScreamInterop.GetBankSounds( interval.SoundBank );
if ( soundNames == null || soundNames.Length == 0 )
return new string[] { "#noSoundsFound" };
return soundNames;
}
}
class IntervalAnimSkelLister : DynamicEnumUITypeEditorLister
{
public string[] GetNames( object instance )
{
IntervalSound interval = instance.As<IntervalSound>();
if ( interval == null )
// returning an non-empty string is necessary to avaid LongEnumEditorCrash
//
return new string[] { "#objectIsNotIntervalSound" };
// return joints based on where this interval is rooted at
//
// root is GroupAnimController
//
foreach ( DomNode pp in interval.DomNode.Lineage )
{
GroupAnimController group = pp.As<GroupAnimController>();
if ( group != null )
{
SkelFileInfo sfi = AnimCache.GetSkelInfo( group.SkelFilename );
if ( sfi != null )
return sfi.JointNames;
}
}
// root is GroupCharacterController
//
foreach ( DomNode pp in interval.DomNode.Lineage )
{
GroupCharacterController group = pp.As<GroupCharacterController>();
if ( group != null )
{
SkelFileInfo sfi = AnimCache.GetSkelInfo( group.SkelFilename );
if ( sfi != null )
return sfi.JointNames;
}
}
return new string[] { "#noJointsFound" };
}
}
class IntervalAnimPositionalEnabledCallback : ICustomEnableAttributePropertyDescriptorCallback
{
public bool IsReadOnly( DomNode domNode, CustomEnableAttributePropertyDescriptor descriptor )
{
IntervalSound interval = domNode.As<IntervalSound>();
if ( interval == null )
return true;
if ( interval.GroupAC != null )
return false;
if ( interval.GroupCC != null )
return false;
return true;
}
};
class IntervalAnimPositionEnabledCallback : ICustomEnableAttributePropertyDescriptorCallback
{
public bool IsReadOnly( DomNode domNode, CustomEnableAttributePropertyDescriptor descriptor )
{
IntervalSound interval = domNode.As<IntervalSound>();
if ( interval == null )
return true;
if ( !interval.Positional )
return true;
if ( interval.GroupAC != null )
return false;
if ( interval.GroupCC != null )
return false;
return true;
}
};
/// <summary>
/// Adapts DomNode to a IntervalSound</summary>
public class IntervalSound : Interval, ITimelineValidationCallback, ITimelineObjectCreator
{
#region IEvent Members
///// <summary>
///// Gets and sets the event's color</summary>
//public override Color Color
//{
// get { return Color.Aqua; }
// set { }
//}
/// <summary>
/// Gets and sets the event's color</summary>
public override Color Color
{
get { return Color.FromArgb( (int) DomNode.GetAttribute( Schema.intervalSoundType.colorAttribute ) ); }
set { DomNode.SetAttribute( Schema.intervalSoundType.colorAttribute, value.ToArgb() ); }
}
#endregion
#region ITimelineObjectCreator Members
ITimelineObject ITimelineObjectCreator.Create()
{
DomNodeType type = Schema.intervalSoundType.Type;
DomNode dn = new DomNode( type );
IntervalSound i = dn.As<IntervalSound>();
NodeTypePaletteItem paletteItem = type.GetTag<NodeTypePaletteItem>();
AttributeInfo idAttribute = type.IdAttribute;
if (paletteItem != null &&
idAttribute != null)
{
i.DomNode.SetAttribute( idAttribute, paletteItem.Name );
}
return i;
}
#endregion
/// <summary>
/// Performs initialization when the adapter is connected to the DomNode.
/// Raises the DomNodeAdapter NodeSet event. Creates read only data for animdata
/// </summary>
protected override void OnNodeSet()
{
base.OnNodeSet();
if ( string.IsNullOrEmpty( SoundBank ) )
{
SoundBank = TimelineEditor.LastSoundBankFilename;
}
DomNode.AttributeChanged += DomNode_AttributeChanged;
}
private void DomNode_AttributeChanged( object sender, AttributeEventArgs e )
{
if ( e.AttributeInfo.Equivalent( Schema.intervalSoundType.soundBankAttribute ) )
{
TimelineEditor.LastSoundBankFilename = SoundBank;
}
}
/// <summary>
/// Gets and sets the sound bank</summary>
public string SoundBank
{
get { return (string) DomNode.GetAttribute( Schema.intervalSoundType.soundBankAttribute ); }
set { DomNode.SetAttribute( Schema.intervalSoundType.soundBankAttribute, value ); }
}
/// <summary>
/// Gets and sets the sound name</summary>
public string Sound
{
get { return (string) DomNode.GetAttribute( Schema.intervalSoundType.soundAttribute ); }
set { DomNode.SetAttribute( Schema.intervalSoundType.soundAttribute, value ); }
}
/// <summary>
/// Gets and sets whether sound is positional or not</summary>
public bool Positional
{
get { return (bool) DomNode.GetAttribute( Schema.intervalSoundType.positionalAttribute ); }
set { DomNode.SetAttribute( Schema.intervalSoundType.positionalAttribute, value ); }
}
/// <summary>
/// Gets and sets the local position on character</summary>
public string Position
{
get { return (string) DomNode.GetAttribute( Schema.intervalSoundType.positionAttribute ); }
set { DomNode.SetAttribute( Schema.intervalSoundType.positionAttribute, value ); }
}
public GroupAnimController GroupAC
{
get
{
foreach ( DomNode pp in DomNode.Lineage )
{
GroupAnimController group = pp.As<GroupAnimController>();
if ( group != null )
{
return group;
}
}
return null;
}
}
public GroupCharacterController GroupCC
{
get
{
foreach ( DomNode pp in DomNode.Lineage )
{
GroupCharacterController group = pp.As<GroupCharacterController>();
if ( group != null )
{
return group;
}
}
return null;
}
}
public bool CanParentTo( DomNode parent )
{
return ValidateImpl( parent, 0 );
}
public bool Validate( DomNode parent )
{
return ValidateImpl( parent, 1 );
}
private bool ValidateImpl( DomNode parent, int validating )
{
foreach ( DomNode pp in parent.Lineage )
{
if ( pp.Type == Schema.groupCharacterControllerType.Type
|| pp.Type == Schema.groupAnimControllerType.Type
|| pp.Type == Schema.groupType.Type
)
{
return true;
}
}
return false;
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A job schedule that allows recurring jobs by specifying when to run jobs and a specification used to create each
/// job.
/// </summary>
public partial class CloudJobSchedule : ITransportObjectProvider<Models.JobScheduleAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<JobScheduleExecutionInformation> ExecutionInformationProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<JobSpecification> JobSpecificationProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<Common.JobScheduleState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<Schedule> ScheduleProperty;
public readonly PropertyAccessor<Common.JobScheduleState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<JobScheduleStatistics> StatisticsProperty;
public readonly PropertyAccessor<string> UrlProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None);
this.ExecutionInformationProperty = this.CreatePropertyAccessor<JobScheduleExecutionInformation>(nameof(ExecutionInformation), BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.JobSpecificationProperty = this.CreatePropertyAccessor<JobSpecification>(nameof(JobSpecification), BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.JobScheduleState?>(nameof(PreviousState), BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None);
this.ScheduleProperty = this.CreatePropertyAccessor<Schedule>(nameof(Schedule), BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.JobScheduleState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<JobScheduleStatistics>(nameof(Statistics), BindingAccess.None);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
}
public PropertyContainer(Models.CloudJobSchedule protocolObject) : base(BindingState.Bound)
{
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
nameof(CreationTime),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
nameof(ETag),
BindingAccess.Read);
this.ExecutionInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new JobScheduleExecutionInformation(o).Freeze()),
nameof(ExecutionInformation),
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.JobSpecificationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobSpecification, o => new JobSpecification(o)),
nameof(JobSpecification),
BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
nameof(LastModified),
BindingAccess.Read);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
nameof(Metadata),
BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.JobScheduleState, Common.JobScheduleState>(protocolObject.PreviousState),
nameof(PreviousState),
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
nameof(PreviousStateTransitionTime),
BindingAccess.Read);
this.ScheduleProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Schedule, o => new Schedule(o)),
nameof(Schedule),
BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.JobScheduleState, Common.JobScheduleState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new JobScheduleStatistics(o).Freeze()),
nameof(Statistics),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudJobSchedule"/> class.
/// </summary>
/// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param>
/// <param name='baseBehaviors'>The base behaviors to use.</param>
internal CloudJobSchedule(
BatchClient parentBatchClient,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.propertyContainer = new PropertyContainer();
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
}
/// <summary>
/// Default constructor to support mocking the <see cref="CloudJobSchedule"/> class.
/// </summary>
protected CloudJobSchedule()
{
this.propertyContainer = new PropertyContainer();
}
internal CloudJobSchedule(
BatchClient parentBatchClient,
Models.CloudJobSchedule protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudJobSchedule"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudJobSchedule
/// <summary>
/// Gets the creation time of the job schedule.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the display name of the job schedule.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets the ETag of the job schedule.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets the execution information for the job schedule.
/// </summary>
public JobScheduleExecutionInformation ExecutionInformation
{
get { return this.propertyContainer.ExecutionInformationProperty.Value; }
}
/// <summary>
/// Gets or sets the id of the job schedule.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets a <see cref="JobSpecification" /> containing details of the jobs to be created according to the
/// <see cref="Schedule"/>.
/// </summary>
public JobSpecification JobSpecification
{
get { return this.propertyContainer.JobSpecificationProperty.Value; }
set { this.propertyContainer.JobSpecificationProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the job schedule.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the schedule as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the previous state of the job schedule.
/// </summary>
/// <remarks>
/// If the schedule is in its initial <see cref="Common.JobScheduleState.Active"/> state, the PreviousState property
/// is not defined.
/// </remarks>
public Common.JobScheduleState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the job schedule entered its previous state.
/// </summary>
/// <remarks>
/// If the schedule is in its initial <see cref="Common.JobScheduleState.Active"/> state, the PreviousStateTransitionTime
/// property is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the schedule that determines when jobs will be created.
/// </summary>
public Schedule Schedule
{
get { return this.propertyContainer.ScheduleProperty.Value; }
set { this.propertyContainer.ScheduleProperty.Value = value; }
}
/// <summary>
/// Gets the current state of the job schedule.
/// </summary>
public Common.JobScheduleState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the <see cref="CloudJobSchedule"/> entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets a <see cref="JobScheduleStatistics" /> containing resource usage statistics for the entire lifetime of the
/// job schedule.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudJobSchedule"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch
/// service performs periodic roll-up of statistics. The typical delay is about 30 minutes.
/// </remarks>
public JobScheduleStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets the URL of the job schedule.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
#endregion // CloudJobSchedule
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobScheduleAddParameter ITransportObjectProvider<Models.JobScheduleAddParameter>.GetTransportObject()
{
Models.JobScheduleAddParameter result = new Models.JobScheduleAddParameter()
{
DisplayName = this.DisplayName,
Id = this.Id,
JobSpecification = UtilitiesInternal.CreateObjectWithNullCheck(this.JobSpecification, (o) => o.GetTransportObject()),
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
Schedule = UtilitiesInternal.CreateObjectWithNullCheck(this.Schedule, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
using System.Diagnostics.Contracts;
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// SymmetricAlgorithm.cs
//
namespace System.Security.Cryptography {
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class SymmetricAlgorithm : IDisposable {
protected int BlockSizeValue;
protected int FeedbackSizeValue;
protected byte[] IVValue;
protected byte[] KeyValue;
protected KeySizes[] LegalBlockSizesValue;
protected KeySizes[] LegalKeySizesValue;
protected int KeySizeValue;
protected CipherMode ModeValue;
protected PaddingMode PaddingValue;
//
// protected constructors
//
protected SymmetricAlgorithm() {
// Default to cipher block chaining (CipherMode.CBC) and
// PKCS-style padding (pad n bytes with value n)
ModeValue = CipherMode.CBC;
PaddingValue = PaddingMode.PKCS7;
}
// SymmetricAlgorithm implements IDisposable
// To keep mscorlib compatibility with Orcas, CoreCLR's SymmetricAlgorithm has an explicit IDisposable
// implementation. Post-Orcas the desktop has an implicit IDispoable implementation.
#if FEATURE_CORECLR
void IDisposable.Dispose()
{
Dispose();
}
#endif // FEATURE_CORECLR
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear() {
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
// Note: we always want to zeroize the sensitive key material
if (KeyValue != null) {
Array.Clear(KeyValue, 0, KeyValue.Length);
KeyValue = null;
}
if (IVValue != null) {
Array.Clear(IVValue, 0, IVValue.Length);
IVValue = null;
}
}
}
//
// public properties
//
public virtual int BlockSize {
get { return BlockSizeValue; }
set {
int i;
int j;
for (i=0; i<LegalBlockSizesValue.Length; i++) {
// If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0
if (LegalBlockSizesValue[i].SkipSize == 0) {
if (LegalBlockSizesValue[i].MinSize == value) { // assume MinSize = MaxSize
BlockSizeValue = value;
IVValue = null;
return;
}
} else {
for (j = LegalBlockSizesValue[i].MinSize; j<=LegalBlockSizesValue[i].MaxSize;
j += LegalBlockSizesValue[i].SkipSize) {
if (j == value) {
if (BlockSizeValue != value) {
BlockSizeValue = value;
IVValue = null; // Wrong length now
}
return;
}
}
}
}
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidBlockSize"));
}
}
public virtual int FeedbackSize {
get { return FeedbackSizeValue; }
set {
if (value <= 0 || value > BlockSizeValue || (value % 8) != 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFeedbackSize"));
FeedbackSizeValue = value;
}
}
public virtual byte[] IV {
get {
if (IVValue == null) GenerateIV();
return (byte[]) IVValue.Clone();
}
set {
if (value == null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
if (value.Length != BlockSizeValue / 8)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize"));
IVValue = (byte[]) value.Clone();
}
}
public virtual byte[] Key {
get {
if (KeyValue == null) GenerateKey();
return (byte[]) KeyValue.Clone();
}
set {
if (value == null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
if (!ValidKeySize(value.Length * 8))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
// must convert bytes to bits
KeyValue = (byte[]) value.Clone();
KeySizeValue = value.Length * 8;
}
}
public virtual KeySizes[] LegalBlockSizes {
get { return (KeySizes[]) LegalBlockSizesValue.Clone(); }
}
public virtual KeySizes[] LegalKeySizes {
get { return (KeySizes[]) LegalKeySizesValue.Clone(); }
}
public virtual int KeySize {
get { return KeySizeValue; }
set {
if (!ValidKeySize(value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
KeySizeValue = value;
KeyValue = null;
}
}
public virtual CipherMode Mode {
get { return ModeValue; }
set {
if ((value < CipherMode.CBC) || (CipherMode.CFB < value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidCipherMode"));
ModeValue = value;
}
}
public virtual PaddingMode Padding {
get { return PaddingValue; }
set {
if ((value < PaddingMode.None) || (PaddingMode.ISO10126 < value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode"));
PaddingValue = value;
}
}
//
// public methods
//
// The following method takes a bit length input and returns whether that length is a valid size
// according to LegalKeySizes
public bool ValidKeySize(int bitLength) {
KeySizes[] validSizes = this.LegalKeySizes;
int i,j;
if (validSizes == null) return false;
for (i=0; i< validSizes.Length; i++) {
if (validSizes[i].SkipSize == 0) {
if (validSizes[i].MinSize == bitLength) { // assume MinSize = MaxSize
return true;
}
} else {
for (j = validSizes[i].MinSize; j<= validSizes[i].MaxSize;
j += validSizes[i].SkipSize) {
if (j == bitLength) {
return true;
}
}
}
}
return false;
}
static public SymmetricAlgorithm Create() {
// use the crypto config system to return an instance of
// the default SymmetricAlgorithm on this machine
return Create("System.Security.Cryptography.SymmetricAlgorithm");
}
static public SymmetricAlgorithm Create(String algName) {
return (SymmetricAlgorithm) CryptoConfig.CreateFromName(algName);
}
public virtual ICryptoTransform CreateEncryptor() {
return CreateEncryptor(Key, IV);
}
public abstract ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV);
public virtual ICryptoTransform CreateDecryptor() {
return CreateDecryptor(Key, IV);
}
public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV);
public abstract void GenerateKey();
public abstract void GenerateIV();
}
}
| |
/*
* 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.Collections;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
namespace Aurora.Modules.Scripting
{
public class UrlData
{
public UUID hostID;
public UUID itemID;
public IScriptModule engine;
public string url;
public UUID urlcode;
public Dictionary<UUID, RequestData> requests;
}
public class RequestData
{
public UUID requestID;
public Dictionary<string, string> headers;
public string body;
public int responseCode;
public string responseBody;
public string contentType;
//public ManualResetEvent ev;
public bool requestDone;
public int startTime;
public string uri;
}
public class UrlModule : ISharedRegionModule, IUrlModule
{
private readonly Dictionary<UUID, UrlData> m_RequestMap =
new Dictionary<UUID, UrlData>();
private readonly Dictionary<string, UrlData> m_UrlMap =
new Dictionary<string, UrlData>();
private const int m_TotalUrls = 100;
private IHttpServer m_HttpServer = null;
public string ExternalHostNameForLSL
{
get { return MainServer.Instance.HostName; }
}
public Type ReplaceableInterface
{
get { return null; }
}
private Hashtable HandleHttpPoll(Hashtable request)
{
return new Hashtable();
}
public string Name
{
get { return "UrlModule"; }
}
public void Initialise(IConfigSource config)
{
}
public void PostInitialise()
{
}
public void AddRegion (IScene scene)
{
if (m_HttpServer == null)
{
// There can only be one
//
m_HttpServer = MainServer.Instance;
}
scene.RegisterModuleInterface<IUrlModule>(this);
}
public void RegionLoaded (IScene scene)
{
}
public void RemoveRegion (IScene scene)
{
}
public void Close()
{
}
public UUID RequestURL (IScriptModule engine, ISceneChildEntity host, UUID itemID)
{
UUID urlcode = UUID.Random();
lock (m_UrlMap)
{
if (m_UrlMap.Count >= m_TotalUrls)
{
engine.PostScriptEvent(itemID, host.UUID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
return urlcode;
}
string url = m_HttpServer.ServerURI + "/lslhttp/" + urlcode.ToString() + "/";
UrlData urlData = new UrlData
{
hostID = host.UUID,
itemID = itemID,
engine = engine,
url = url,
urlcode = urlcode,
requests = new Dictionary<UUID, RequestData>()
};
m_UrlMap[url] = urlData;
string uri = "/lslhttp/" + urlcode.ToString() + "/";
m_HttpServer.AddPollServiceHTTPHandler(uri, HandleHttpPoll,
new PollServiceEventArgs(HttpRequestHandler,HasEvents, GetEvents, NoEvents, Valid,
urlcode));
engine.PostScriptEvent(itemID, host.UUID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url });
}
return urlcode;
}
private bool Valid()
{
return true;
}
public UUID RequestSecureURL (IScriptModule engine, ISceneChildEntity host, UUID itemID)
{
UUID urlcode = UUID.Random();
engine.PostScriptEvent(itemID, host.UUID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
return urlcode;
}
public void ReleaseURL(string url)
{
lock (m_UrlMap)
{
UrlData data;
if (!m_UrlMap.TryGetValue(url, out data))
{
return;
}
foreach (UUID req in data.requests.Keys)
m_RequestMap.Remove(req);
RemoveUrl(data);
m_UrlMap.Remove(url);
}
}
public void SetContentType (UUID request, string content_type)
{
if(m_RequestMap.ContainsKey(request))
{
UrlData urlData = m_RequestMap[request];
urlData.requests[request].contentType = content_type;
}
}
public void HttpResponse(UUID request, int status, string body)
{
if (m_RequestMap.ContainsKey(request))
{
UrlData urlData = m_RequestMap[request];
urlData.requests[request].responseCode = status;
urlData.requests[request].responseBody = body;
//urlData.requests[request].ev.Set();
urlData.requests[request].requestDone =true;
}
else
{
MainConsole.Instance.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString());
}
}
public string GetHttpHeader(UUID requestId, string header)
{
if (m_RequestMap.ContainsKey(requestId))
{
UrlData urlData=m_RequestMap[requestId];
string value;
if (urlData.requests[requestId].headers.TryGetValue(header,out value))
return value;
}
else
{
MainConsole.Instance.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId);
}
return String.Empty;
}
public int GetFreeUrls()
{
return m_TotalUrls - m_UrlMap.Count;
}
public void ScriptRemoved(UUID itemID)
{
lock (m_UrlMap)
{
List<string> removeURLs = new List<string>();
foreach (KeyValuePair<string, UrlData> url in m_UrlMap)
{
if (url.Value.itemID == itemID)
{
RemoveUrl(url.Value);
removeURLs.Add(url.Key);
foreach (UUID req in url.Value.requests.Keys)
m_RequestMap.Remove(req);
}
}
foreach (string urlname in removeURLs)
m_UrlMap.Remove(urlname);
}
}
public void ObjectRemoved(UUID objectID)
{
lock (m_UrlMap)
{
List<string> removeURLs = new List<string>();
foreach (KeyValuePair<string, UrlData> url in m_UrlMap)
{
if (url.Value.hostID == objectID)
{
RemoveUrl(url.Value);
removeURLs.Add(url.Key);
foreach (UUID req in url.Value.requests.Keys)
m_RequestMap.Remove(req);
}
}
foreach (string urlname in removeURLs)
m_UrlMap.Remove(urlname);
}
}
private void RemoveUrl(UrlData data)
{
m_HttpServer.RemovePollServiceHTTPHandler("", "/lslhttp/"+data.urlcode.ToString()+"/");
}
private Hashtable NoEvents(UUID requestID, UUID sessionID)
{
Hashtable response = new Hashtable();
UrlData url;
lock (m_RequestMap)
{
if (!m_RequestMap.ContainsKey(requestID))
return response;
url = m_RequestMap[requestID];
}
if (Environment.TickCount - url.requests[requestID].startTime > 25000)
{
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
//remove from map
lock (url)
{
url.requests.Remove(requestID);
m_RequestMap.Remove(requestID);
}
return response;
}
return response;
}
private bool HasEvents(UUID requestID, UUID sessionID)
{
UrlData url=null;
lock (m_RequestMap)
{
if (!m_RequestMap.ContainsKey(requestID))
{
return false;
}
url = m_RequestMap[requestID];
if (!url.requests.ContainsKey(requestID))
{
return false;
}
}
if (Environment.TickCount-url.requests[requestID].startTime>25000)
{
return true;
}
if (url.requests[requestID].requestDone)
return true;
return false;
}
private Hashtable GetEvents(UUID requestID, UUID sessionID, string request)
{
UrlData url = null;
RequestData requestData = null;
lock (m_RequestMap)
{
if (!m_RequestMap.ContainsKey(requestID))
return NoEvents(requestID,sessionID);
url = m_RequestMap[requestID];
requestData = url.requests[requestID];
}
if (!requestData.requestDone)
return NoEvents(requestID,sessionID);
Hashtable response = new Hashtable();
if (Environment.TickCount - requestData.startTime > 25000)
{
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
return response;
}
//put response
response["int_response_code"] = requestData.responseCode;
response["str_response_string"] = requestData.responseBody;
response["content_type"] = requestData.contentType;
response["keepalive"] = false;
response["reusecontext"] = false;
//remove from map
lock (url)
{
url.requests.Remove(requestID);
m_RequestMap.Remove(requestID);
}
return response;
}
public void HttpRequestHandler(UUID requestID, Hashtable request)
{
lock (request)
{
string uri = request["uri"].ToString();
try
{
Hashtable headers = (Hashtable)request["headers"];
int pos1 = uri.IndexOf("/");// /lslhttp
int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/
int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/
string uri_tmp = uri.Substring(0, pos3 + 1);
//HTTP server code doesn't provide us with QueryStrings
string queryString = "";
string pathInfo = uri.Substring(pos3);
UrlData url = m_UrlMap[m_HttpServer.ServerURI + uri_tmp];
//for llGetHttpHeader support we need to store original URI here
//to make x-path-info / x-query-string / x-script-url / x-remote-ip headers
//as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader
RequestData requestData = new RequestData
{
requestID = requestID,
requestDone = false,
startTime = Environment.TickCount,
uri = uri
};
if (requestData.headers == null)
requestData.headers = new Dictionary<string, string>();
foreach (DictionaryEntry header in headers)
{
string key = (string)header.Key;
string value = (string)header.Value;
requestData.headers.Add(key, value);
}
foreach (DictionaryEntry de in request)
{
if (de.Key.ToString() == "querystringkeys")
{
String[] keys = (String[])de.Value;
foreach (String key in keys)
{
if (request.ContainsKey(key))
{
string val = (String)request[key];
queryString = queryString + key + "=" + val + "&";
}
}
if (queryString.Length > 1)
queryString = queryString.Substring(0, queryString.Length - 1);
}
}
//if this machine is behind DNAT/port forwarding, currently this is being
//set to address of port forwarding router
requestData.headers["x-remote-ip"] = requestData.headers["remote_addr"];
requestData.headers["x-path-info"] = pathInfo;
requestData.headers["x-query-string"] = queryString;
requestData.headers["x-script-url"] = url.url;
//requestData.ev = new ManualResetEvent(false);
lock (url.requests)
{
url.requests.Add(requestID, requestData);
}
lock (m_RequestMap)
{
//add to request map
m_RequestMap.Add(requestID, url);
}
url.engine.PostScriptEvent(url.itemID, url.hostID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() });
//send initial response?
// Hashtable response = new Hashtable();
return;
}
catch (Exception we)
{
//Hashtable response = new Hashtable();
MainConsole.Instance.Warn("[HttpRequestHandler]: http-in request failed");
MainConsole.Instance.Warn(we.Message);
MainConsole.Instance.Warn(we.StackTrace);
}
}
}
private void OnScriptReset(uint localID, UUID itemID)
{
ScriptRemoved(itemID);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#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;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json.Utilities;
using System.Linq;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal interface IWrappedCollection : IList
{
object UnderlyingCollection { get; }
}
internal class CollectionWrapper<T> : ICollection<T>, IWrappedCollection
{
private readonly IList _list;
private readonly ICollection<T> _genericCollection;
private object _syncRoot;
public CollectionWrapper(IList list)
{
ValidationUtils.ArgumentNotNull(list, "list");
if (list is ICollection<T>)
_genericCollection = (ICollection<T>)list;
else
_list = list;
}
public CollectionWrapper(ICollection<T> list)
{
ValidationUtils.ArgumentNotNull(list, "list");
_genericCollection = list;
}
public virtual void Add(T item)
{
if (_genericCollection != null)
_genericCollection.Add(item);
else
_list.Add(item);
}
public virtual void Clear()
{
if (_genericCollection != null)
_genericCollection.Clear();
else
_list.Clear();
}
public virtual bool Contains(T item)
{
if (_genericCollection != null)
return _genericCollection.Contains(item);
else
return _list.Contains(item);
}
public virtual void CopyTo(T[] array, int arrayIndex)
{
if (_genericCollection != null)
_genericCollection.CopyTo(array, arrayIndex);
else
_list.CopyTo(array, arrayIndex);
}
public virtual int Count
{
get
{
if (_genericCollection != null)
return _genericCollection.Count;
else
return _list.Count;
}
}
public virtual bool IsReadOnly
{
get
{
if (_genericCollection != null)
return _genericCollection.IsReadOnly;
else
return _list.IsReadOnly;
}
}
public virtual bool Remove(T item)
{
if (_genericCollection != null)
{
return _genericCollection.Remove(item);
}
else
{
bool contains = _list.Contains(item);
if (contains)
_list.Remove(item);
return contains;
}
}
public virtual IEnumerator<T> GetEnumerator()
{
if (_genericCollection != null)
return _genericCollection.GetEnumerator();
return _list.Cast<T>().GetEnumerator();
}
public bool IsGenericCollection()
{
return _genericCollection != null;
}
IEnumerator IEnumerable.GetEnumerator()
{
#if (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE)
IEnumerator result;
result = _genericCollection != null ? ((IEnumerable)_genericCollection).GetEnumerator() : ((IEnumerable)_list).GetEnumerator();
return result;
#else
if (_genericCollection != null)
return _genericCollection.GetEnumerator();
else
return _list.GetEnumerator();
#endif
}
int IList.Add(object value)
{
VerifyValueType(value);
Add((T)value);
return (Count - 1);
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
return Contains((T)value);
return false;
}
int IList.IndexOf(object value)
{
if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support IndexOf.");
if (IsCompatibleObject(value))
return _list.IndexOf((T)value);
return -1;
}
void IList.RemoveAt(int index)
{
if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support RemoveAt.");
_list.RemoveAt(index);
}
void IList.Insert(int index, object value)
{
if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support Insert.");
VerifyValueType(value);
_list.Insert(index, (T)value);
}
bool IList.IsFixedSize
{
get
{
if (_genericCollection != null)
// ICollection<T> only has IsReadOnly
return _genericCollection.IsReadOnly;
else
return _list.IsFixedSize;
}
}
void IList.Remove(object value)
{
if (IsCompatibleObject(value))
Remove((T)value);
}
object IList.this[int index]
{
get
{
if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support indexer.");
return _list[index];
}
set
{
if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support indexer.");
VerifyValueType(value);
_list[index] = (T)value;
}
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
CopyTo((T[])array, arrayIndex);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
private static void VerifyValueType(object value)
{
if (!IsCompatibleObject(value))
throw new ArgumentException("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.".FormatWith(CultureInfo.InvariantCulture, value, typeof(T)), "value");
}
private static bool IsCompatibleObject(object value)
{
if (!(value is T) && (value != null || (typeof(T).IsValueType && !ReflectionUtils.IsNullableType(typeof(T)))))
return false;
return true;
}
public object UnderlyingCollection
{
get
{
if (_genericCollection != null)
return _genericCollection;
else
return _list;
}
}
}
}
#endif
| |
/*
* 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 swf-2012-01-25.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.SimpleWorkflow.Model
{
/// <summary>
/// Provides details of the <code>ActivityTaskScheduled</code> event.
/// </summary>
public partial class ActivityTaskScheduledEventAttributes
{
private string _activityId;
private ActivityType _activityType;
private string _control;
private long? _decisionTaskCompletedEventId;
private string _heartbeatTimeout;
private string _input;
private string _scheduleToCloseTimeout;
private string _scheduleToStartTimeout;
private string _startToCloseTimeout;
private TaskList _taskList;
private string _taskPriority;
/// <summary>
/// Gets and sets the property ActivityId.
/// <para>
/// The unique ID of the activity task.
/// </para>
/// </summary>
public string ActivityId
{
get { return this._activityId; }
set { this._activityId = value; }
}
// Check to see if ActivityId property is set
internal bool IsSetActivityId()
{
return this._activityId != null;
}
/// <summary>
/// Gets and sets the property ActivityType.
/// <para>
/// The type of the activity task.
/// </para>
/// </summary>
public ActivityType ActivityType
{
get { return this._activityType; }
set { this._activityType = value; }
}
// Check to see if ActivityType property is set
internal bool IsSetActivityType()
{
return this._activityType != null;
}
/// <summary>
/// Gets and sets the property Control.
/// <para>
/// <i>Optional.</i> Data attached to the event that can be used by the decider in subsequent
/// workflow tasks. This data is not sent to the activity.
/// </para>
/// </summary>
public string Control
{
get { return this._control; }
set { this._control = value; }
}
// Check to see if Control property is set
internal bool IsSetControl()
{
return this._control != null;
}
/// <summary>
/// Gets and sets the property DecisionTaskCompletedEventId.
/// <para>
/// The ID of the <code>DecisionTaskCompleted</code> event corresponding to the decision
/// that resulted in the scheduling of this activity task. This information can be useful
/// for diagnosing problems by tracing back the chain of events leading up to this event.
/// </para>
/// </summary>
public long DecisionTaskCompletedEventId
{
get { return this._decisionTaskCompletedEventId.GetValueOrDefault(); }
set { this._decisionTaskCompletedEventId = value; }
}
// Check to see if DecisionTaskCompletedEventId property is set
internal bool IsSetDecisionTaskCompletedEventId()
{
return this._decisionTaskCompletedEventId.HasValue;
}
/// <summary>
/// Gets and sets the property HeartbeatTimeout.
/// <para>
/// The maximum time before which the worker processing this task must report progress
/// by calling <a>RecordActivityTaskHeartbeat</a>. If the timeout is exceeded, the activity
/// task is automatically timed out. If the worker subsequently attempts to record a heartbeat
/// or return a result, it will be ignored.
/// </para>
/// </summary>
public string HeartbeatTimeout
{
get { return this._heartbeatTimeout; }
set { this._heartbeatTimeout = value; }
}
// Check to see if HeartbeatTimeout property is set
internal bool IsSetHeartbeatTimeout()
{
return this._heartbeatTimeout != null;
}
/// <summary>
/// Gets and sets the property Input.
/// <para>
/// The input provided to the activity task.
/// </para>
/// </summary>
public string Input
{
get { return this._input; }
set { this._input = value; }
}
// Check to see if Input property is set
internal bool IsSetInput()
{
return this._input != null;
}
/// <summary>
/// Gets and sets the property ScheduleToCloseTimeout.
/// <para>
/// The maximum amount of time for this activity task.
/// </para>
/// </summary>
public string ScheduleToCloseTimeout
{
get { return this._scheduleToCloseTimeout; }
set { this._scheduleToCloseTimeout = value; }
}
// Check to see if ScheduleToCloseTimeout property is set
internal bool IsSetScheduleToCloseTimeout()
{
return this._scheduleToCloseTimeout != null;
}
/// <summary>
/// Gets and sets the property ScheduleToStartTimeout.
/// <para>
/// The maximum amount of time the activity task can wait to be assigned to a worker.
/// </para>
/// </summary>
public string ScheduleToStartTimeout
{
get { return this._scheduleToStartTimeout; }
set { this._scheduleToStartTimeout = value; }
}
// Check to see if ScheduleToStartTimeout property is set
internal bool IsSetScheduleToStartTimeout()
{
return this._scheduleToStartTimeout != null;
}
/// <summary>
/// Gets and sets the property StartToCloseTimeout.
/// <para>
/// The maximum amount of time a worker may take to process the activity task.
/// </para>
/// </summary>
public string StartToCloseTimeout
{
get { return this._startToCloseTimeout; }
set { this._startToCloseTimeout = value; }
}
// Check to see if StartToCloseTimeout property is set
internal bool IsSetStartToCloseTimeout()
{
return this._startToCloseTimeout != null;
}
/// <summary>
/// Gets and sets the property TaskList.
/// <para>
/// The task list in which the activity task has been scheduled.
/// </para>
/// </summary>
public TaskList TaskList
{
get { return this._taskList; }
set { this._taskList = value; }
}
// Check to see if TaskList property is set
internal bool IsSetTaskList()
{
return this._taskList != null;
}
/// <summary>
/// Gets and sets the property TaskPriority.
/// <para>
/// <i>Optional.</i> The priority to assign to the scheduled activity task. If set, this
/// will override any default priority value that was assigned when the activity type
/// was registered.
/// </para>
///
/// <para>
/// Valid values are integers that range from Java's <code>Integer.MIN_VALUE</code> (-2147483648)
/// to <code>Integer.MAX_VALUE</code> (2147483647). Higher numbers indicate higher priority.
/// </para>
///
/// <para>
/// For more information about setting task priority, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html">Setting
/// Task Priority</a> in the <i>Amazon Simple Workflow Developer Guide</i>.
/// </para>
/// </summary>
public string TaskPriority
{
get { return this._taskPriority; }
set { this._taskPriority = value; }
}
// Check to see if TaskPriority property is set
internal bool IsSetTaskPriority()
{
return this._taskPriority != null;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmResourcesInfo.
/// </summary>
public partial class frmProcsAll: System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (Session["UserLevel"].ToString() == "0")
{
btnAddProcs.Visible = false;
}
lblProfilesName.Text = "Business Profile for: " + Session["ProfilesName"].ToString();
lblServiceName.Text = "Service Delivered: " + Session["ServiceName"].ToString();
lblDeliverableName.Text = "Deliverable: " + Session["EventsName"].ToString();
loadProcs();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void loadProcs()
{
if (!IsPostBack)
{
//lblOrg.Text=Session["OrgName"].ToString();
lblContent.Text="The processes below are normally associated with the above service."
+ " Check all processes that are normally associated with generating the above deliverable."
+ " Note that"
+ " it is possible that processes that are normally associated with generating other kinds of services"
+ " may also be involved in generating the above deliverable. To review and appropriately include"
+ " such processes, click on 'More Processes...'. Finally, if you are unable to locate an"
+ " existing process description to match your requirements, you may identify and describe a new process. To create a new process, click on"
+ " 'Add Process'";
loadData();
}
}
private void loadData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText = "wms_RetrieveProcs";
cmd.Connection = this.epsDbConn;
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
cmd.Parameters.Add("@OrgIdP", SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value = Session["OrgIdP"].ToString();
cmd.Parameters.Add("@LicenseId", SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value = Session["LicenseId"].ToString();
cmd.Parameters.Add("@DomainId", SqlDbType.Int);
cmd.Parameters["@DomainId"].Value = Session["DomainId"].ToString();
cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int);
//cmd.Parameters["@ServiceTypesId"].Value=lstService.SelectedItem.Value;
cmd.Parameters["@ServiceTypesId"].Value = Session["ServicesId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"ProcsAll");
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
//refreshGrid();
}
protected void btnOK_Click(object sender, System.EventArgs e)
{
if (Session["CProcsAll"].ToString() == "frmProfileSEProcs")
{
updateGridPSEP();
}
else
{
updateGrid();
}
Exit();
}
private void updateGridPSEP()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[2].FindControl("cbxSel"));
if ((cb.Checked) == true)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "wms_AddProfileSEProcs";//eps_UpdateProfileSEProcs
cmd.Connection = this.epsDbConn;
if (Session["ProfileType"].ToString() == "Producer")
{
cmd.Parameters.Add("@ProfileSEventsId", SqlDbType.Int);
cmd.Parameters["@ProfileSEventsId"].Value = Session["ProfileSEventsId"].ToString();
cmd.Parameters.Add("@Name", SqlDbType.NVarChar);
cmd.Parameters["@Name"].Value = i.Cells[1].Text;
/*cmd.Parameters.Add ("@ProcType",SqlDbType.NVarChar);
cmd.Parameters["@ProcType"].Value=Session["ProcType"].ToString();*/
}
else
{
cmd.Parameters.Add("@ProfileServiceLocsId", SqlDbType.Int);
cmd.Parameters["@ProfileServiceLocsId"].Value = Session["ProfileServiceLocsId"].ToString();
}
cmd.Parameters.Add("@ProcsId", SqlDbType.Int);
cmd.Parameters["@ProcsId"].Value = i.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void updateGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[2].FindControl("cbxSel"));
if ((cb.Checked) & (cb.Enabled == true))
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_UpdateProfileSP";//eps_UpdateServiceProcs
cmd.Connection=this.epsDbConn;
if (Session["ProfileType"].ToString() == "Producer")
{
cmd.Parameters.Add ("@ProfileServicesId",SqlDbType.Int);
cmd.Parameters["@ProfileServicesId"].Value=Session["ProfileServicesId"].ToString();
/*cmd.Parameters.Add ("@ProcType",SqlDbType.NVarChar);
cmd.Parameters["@ProcType"].Value=Session["ProcType"].ToString();*/
}
else
{
cmd.Parameters.Add ("@ProfileServiceLocsId",SqlDbType.Int);
cmd.Parameters["@ProfileServiceLocsId"].Value=Session["ProfileServiceLocsId"].ToString();
}
cmd.Parameters.Add("@ProcessId", SqlDbType.Int);
cmd.Parameters ["@ProcessId"].Value=i.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[2].FindControl("cbxSel"));
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.Text;
if (Session["ProfileType"].ToString() == "Producer")
{
cmd.CommandText="Select Id from ProfileServiceProcs"
+ " Where ProfileServicesId="
+ "'" + Session["ProfileServicesId"].ToString() + "'"
+ " and ProcessId = "
+ "'" + i.Cells[0].Text + "'"
+ " and ProfileServiceProcs.Type="
+ "'" + Session["ProcType"].ToString() + "'";
}
else
{
cmd.CommandText="Select Id from ProfileServiceProcs"
+ " Where ProfileServiceLocsId="
+ "'" + Session["ProfileServiceLocsId"].ToString() + "'"
+ " and ProcessId = "
+ "'" + i.Cells[0].Text + "'";
}
cmd.Connection.Open();
if (cmd.ExecuteScalar() != null)
{
cb.Checked=true;
cb.Enabled=false;
}
cmd.Connection.Close();
}
}
private void Exit()
{
Response.Redirect (strURL + Session["CProcsAll"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Exit();
}
protected void btnAddProcs_Click(object sender, System.EventArgs e)
{
Session["CServiceTypes"] = "frmProfileSEProcs";
Response.Redirect(strURL + "frmServiceTypes.aspx?");
}
protected void btnMoreProcs_Click(object sender, System.EventArgs e)
{
Session["btnAction"] = "Add";
Session["CUPSEP"] = "frmProfileSEProcs";
Response.Redirect(strURL + "frmUpdProfileSEProcs.aspx?"
+ "&btnAction=" + "Add");
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
#endregion
using System;
using System.Runtime.InteropServices;
using Grpc.Core;
namespace Grpc.Core.Internal
{
/// <summary>
/// grpcsharp_batch_context
/// </summary>
internal class BatchContextSafeHandle : SafeHandleZeroIsInvalid
{
[DllImport("grpc_csharp_ext.dll")]
static extern BatchContextSafeHandle grpcsharp_batch_context_create();
[DllImport("grpc_csharp_ext.dll")]
static extern IntPtr grpcsharp_batch_context_recv_initial_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern IntPtr grpcsharp_batch_context_recv_message_length(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern void grpcsharp_batch_context_recv_message_to_buffer(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
[DllImport("grpc_csharp_ext.dll")]
static extern StatusCode grpcsharp_batch_context_recv_status_on_client_status(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern IntPtr grpcsharp_batch_context_recv_status_on_client_details(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
static extern IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern CallSafeHandle grpcsharp_batch_context_server_rpc_new_call(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern IntPtr grpcsharp_batch_context_server_rpc_new_method(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
static extern IntPtr grpcsharp_batch_context_server_rpc_new_host(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
static extern Timespec grpcsharp_batch_context_server_rpc_new_deadline(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern int grpcsharp_batch_context_recv_close_on_server_cancelled(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern void grpcsharp_batch_context_destroy(IntPtr ctx);
private BatchContextSafeHandle()
{
}
public static BatchContextSafeHandle Create()
{
return grpcsharp_batch_context_create();
}
public IntPtr Handle
{
get
{
return handle;
}
}
// Gets data of recv_initial_metadata completion.
public Metadata GetReceivedInitialMetadata()
{
IntPtr metadataArrayPtr = grpcsharp_batch_context_recv_initial_metadata(this);
return MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr);
}
// Gets data of recv_status_on_client completion.
public ClientSideStatus GetReceivedStatusOnClient()
{
string details = Marshal.PtrToStringAnsi(grpcsharp_batch_context_recv_status_on_client_details(this));
var status = new Status(grpcsharp_batch_context_recv_status_on_client_status(this), details);
IntPtr metadataArrayPtr = grpcsharp_batch_context_recv_status_on_client_trailing_metadata(this);
var metadata = MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr);
return new ClientSideStatus(status, metadata);
}
// Gets data of recv_message completion.
public byte[] GetReceivedMessage()
{
IntPtr len = grpcsharp_batch_context_recv_message_length(this);
if (len == new IntPtr(-1))
{
return null;
}
byte[] data = new byte[(int)len];
grpcsharp_batch_context_recv_message_to_buffer(this, data, new UIntPtr((ulong)data.Length));
return data;
}
// Gets data of server_rpc_new completion.
public ServerRpcNew GetServerRpcNew(Server server)
{
var call = grpcsharp_batch_context_server_rpc_new_call(this);
var method = Marshal.PtrToStringAnsi(grpcsharp_batch_context_server_rpc_new_method(this));
var host = Marshal.PtrToStringAnsi(grpcsharp_batch_context_server_rpc_new_host(this));
var deadline = grpcsharp_batch_context_server_rpc_new_deadline(this);
IntPtr metadataArrayPtr = grpcsharp_batch_context_server_rpc_new_request_metadata(this);
var metadata = MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr);
return new ServerRpcNew(server, call, method, host, deadline, metadata);
}
// Gets data of receive_close_on_server completion.
public bool GetReceivedCloseOnServerCancelled()
{
return grpcsharp_batch_context_recv_close_on_server_cancelled(this) != 0;
}
protected override bool ReleaseHandle()
{
grpcsharp_batch_context_destroy(handle);
return true;
}
}
/// <summary>
/// Status + metadata received on client side when call finishes.
/// (when receive_status_on_client operation finishes).
/// </summary>
internal struct ClientSideStatus
{
readonly Status status;
readonly Metadata trailers;
public ClientSideStatus(Status status, Metadata trailers)
{
this.status = status;
this.trailers = trailers;
}
public Status Status
{
get
{
return this.status;
}
}
public Metadata Trailers
{
get
{
return this.trailers;
}
}
}
/// <summary>
/// Details of a newly received RPC.
/// </summary>
internal struct ServerRpcNew
{
readonly Server server;
readonly CallSafeHandle call;
readonly string method;
readonly string host;
readonly Timespec deadline;
readonly Metadata requestMetadata;
public ServerRpcNew(Server server, CallSafeHandle call, string method, string host, Timespec deadline, Metadata requestMetadata)
{
this.server = server;
this.call = call;
this.method = method;
this.host = host;
this.deadline = deadline;
this.requestMetadata = requestMetadata;
}
public Server Server
{
get
{
return this.server;
}
}
public CallSafeHandle Call
{
get
{
return this.call;
}
}
public string Method
{
get
{
return this.method;
}
}
public string Host
{
get
{
return this.host;
}
}
public Timespec Deadline
{
get
{
return this.deadline;
}
}
public Metadata RequestMetadata
{
get
{
return this.requestMetadata;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="CampaignCriterionServiceClient"/> instances.</summary>
public sealed partial class CampaignCriterionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CampaignCriterionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CampaignCriterionServiceSettings"/>.</returns>
public static CampaignCriterionServiceSettings GetDefault() => new CampaignCriterionServiceSettings();
/// <summary>
/// Constructs a new <see cref="CampaignCriterionServiceSettings"/> object with default settings.
/// </summary>
public CampaignCriterionServiceSettings()
{
}
private CampaignCriterionServiceSettings(CampaignCriterionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateCampaignCriteriaSettings = existing.MutateCampaignCriteriaSettings;
OnCopy(existing);
}
partial void OnCopy(CampaignCriterionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignCriterionServiceClient.MutateCampaignCriteria</c> and
/// <c>CampaignCriterionServiceClient.MutateCampaignCriteriaAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCampaignCriteriaSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CampaignCriterionServiceSettings"/> object.</returns>
public CampaignCriterionServiceSettings Clone() => new CampaignCriterionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CampaignCriterionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CampaignCriterionServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignCriterionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CampaignCriterionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CampaignCriterionServiceClientBuilder()
{
UseJwtAccessWithScopes = CampaignCriterionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CampaignCriterionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignCriterionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CampaignCriterionServiceClient Build()
{
CampaignCriterionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CampaignCriterionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CampaignCriterionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CampaignCriterionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CampaignCriterionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CampaignCriterionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CampaignCriterionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CampaignCriterionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignCriterionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignCriterionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CampaignCriterionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign criteria.
/// </remarks>
public abstract partial class CampaignCriterionServiceClient
{
/// <summary>
/// The default endpoint for the CampaignCriterionService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CampaignCriterionService scopes.</summary>
/// <remarks>
/// The default CampaignCriterionService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CampaignCriterionServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignCriterionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CampaignCriterionServiceClient"/>.</returns>
public static stt::Task<CampaignCriterionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CampaignCriterionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CampaignCriterionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignCriterionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CampaignCriterionServiceClient"/>.</returns>
public static CampaignCriterionServiceClient Create() => new CampaignCriterionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CampaignCriterionServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CampaignCriterionServiceSettings"/>.</param>
/// <returns>The created <see cref="CampaignCriterionServiceClient"/>.</returns>
internal static CampaignCriterionServiceClient Create(grpccore::CallInvoker callInvoker, CampaignCriterionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CampaignCriterionService.CampaignCriterionServiceClient grpcClient = new CampaignCriterionService.CampaignCriterionServiceClient(callInvoker);
return new CampaignCriterionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> 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 stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CampaignCriterionService client</summary>
public virtual CampaignCriterionService.CampaignCriterionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 MutateCampaignCriteriaResponse MutateCampaignCriteria(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 stt::Task<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(MutateCampaignCriteriaRequest request, st::CancellationToken cancellationToken) =>
MutateCampaignCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignCriteriaResponse MutateCampaignCriteria(string customerId, scg::IEnumerable<CampaignCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignCriteria(new MutateCampaignCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(string customerId, scg::IEnumerable<CampaignCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignCriteriaAsync(new MutateCampaignCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(string customerId, scg::IEnumerable<CampaignCriterionOperation> operations, st::CancellationToken cancellationToken) =>
MutateCampaignCriteriaAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CampaignCriterionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign criteria.
/// </remarks>
public sealed partial class CampaignCriterionServiceClientImpl : CampaignCriterionServiceClient
{
private readonly gaxgrpc::ApiCall<MutateCampaignCriteriaRequest, MutateCampaignCriteriaResponse> _callMutateCampaignCriteria;
/// <summary>
/// Constructs a client wrapper for the CampaignCriterionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CampaignCriterionServiceSettings"/> used within this client.
/// </param>
public CampaignCriterionServiceClientImpl(CampaignCriterionService.CampaignCriterionServiceClient grpcClient, CampaignCriterionServiceSettings settings)
{
GrpcClient = grpcClient;
CampaignCriterionServiceSettings effectiveSettings = settings ?? CampaignCriterionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateCampaignCriteria = clientHelper.BuildApiCall<MutateCampaignCriteriaRequest, MutateCampaignCriteriaResponse>(grpcClient.MutateCampaignCriteriaAsync, grpcClient.MutateCampaignCriteria, effectiveSettings.MutateCampaignCriteriaSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCampaignCriteria);
Modify_MutateCampaignCriteriaApiCall(ref _callMutateCampaignCriteria);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_MutateCampaignCriteriaApiCall(ref gaxgrpc::ApiCall<MutateCampaignCriteriaRequest, MutateCampaignCriteriaResponse> call);
partial void OnConstruction(CampaignCriterionService.CampaignCriterionServiceClient grpcClient, CampaignCriterionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CampaignCriterionService client</summary>
public override CampaignCriterionService.CampaignCriterionServiceClient GrpcClient { get; }
partial void Modify_MutateCampaignCriteriaRequest(ref MutateCampaignCriteriaRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 MutateCampaignCriteriaResponse MutateCampaignCriteria(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignCriteriaRequest(ref request, ref callSettings);
return _callMutateCampaignCriteria.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 stt::Task<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignCriteriaRequest(ref request, ref callSettings);
return _callMutateCampaignCriteria.Async(request, callSettings);
}
}
}
| |
// <copyright file="FilterableObservableMasterSlaveCollection{TItem,TFilter}.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using IX.Observable.DebugAide;
using IX.StandardExtensions.Contracts;
using JetBrains.Annotations;
namespace IX.Observable;
/// <summary>
/// An observable collection created from a master collection (to which updates go) and many slave, read-only
/// collections, whose items can also be filtered.
/// </summary>
/// <typeparam name="TItem">The type of the item.</typeparam>
/// <typeparam name="TFilter">The type of the filter.</typeparam>
/// <seealso cref="IX.Observable.ObservableMasterSlaveCollection{T}" />
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[PublicAPI]
public class FilterableObservableMasterSlaveCollection<TItem, TFilter> : ObservableMasterSlaveCollection<TItem>
{
#region Internal state
private TFilter? filter;
private IList<TItem>? filteredElements;
#endregion
#region Constructors and destructors
/// <summary>
/// Initializes a new instance of the <see cref="FilterableObservableMasterSlaveCollection{TItem, TFilter}" /> class.
/// </summary>
/// <param name="filteringPredicate">The filtering predicate.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="filteringPredicate" /> is <see langword="null" /> (
/// <see langword="Nothing" />) in Visual Basic.
/// </exception>
public FilterableObservableMasterSlaveCollection(Func<TItem, TFilter, bool> filteringPredicate)
{
this.FilteringPredicate = Requires.NotNull(filteringPredicate);
}
/// <summary>
/// Initializes a new instance of the <see cref="FilterableObservableMasterSlaveCollection{TItem, TFilter}" /> class.
/// </summary>
/// <param name="filteringPredicate">The filtering predicate.</param>
/// <param name="context">The synchronization context to use, if any.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="filteringPredicate" /> is <see langword="null" /> (
/// <see langword="Nothing" />) in Visual Basic.
/// </exception>
public FilterableObservableMasterSlaveCollection(
Func<TItem, TFilter, bool> filteringPredicate,
SynchronizationContext context)
: base(context)
{
this.FilteringPredicate = Requires.NotNull(filteringPredicate);
}
#endregion
#region Properties and indexers
/// <summary>
/// Gets the number of items in the collection.
/// </summary>
/// <value>
/// The item count.
/// </value>
public override int Count
{
get
{
if (!this.IsFilter())
{
return base.Count;
}
if (this.filteredElements == null)
{
this.FillCachedList();
}
return this.filteredElements!.Count;
}
}
/// <summary>
/// Gets the filtering predicate.
/// </summary>
/// <value>
/// The filtering predicate.
/// </value>
public Func<TItem, TFilter, bool> FilteringPredicate { get; }
/// <summary>
/// Gets or sets the filter value.
/// </summary>
/// <value>
/// The filter value.
/// </value>
public TFilter? Filter
{
get => this.filter;
set
{
this.filter = value;
this.ClearCachedContents();
this.RaiseCollectionReset();
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
}
}
#endregion
#region Methods
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
[SuppressMessage(
"Performance",
"HAA0401:Possible allocation of reference type enumerator",
Justification = "This cannot be avoidable.")]
public override IEnumerator<TItem> GetEnumerator()
{
if (!this.IsFilter())
{
return base.GetEnumerator();
}
if (this.filteredElements != null)
{
return this.filteredElements.GetEnumerator();
}
this.FillCachedList();
return base.GetEnumerator();
}
/// <summary>
/// Called when an item is added to a collection.
/// </summary>
/// <param name="addedItem">The added item.</param>
/// <param name="index">The index.</param>
protected override void RaiseCollectionChangedAdd(
TItem addedItem,
int index)
{
if (this.IsFilter())
{
this.RaiseCollectionReset();
}
else
{
base.RaiseCollectionChangedAdd(
addedItem,
index);
}
}
/// <summary>
/// Called when an item in a collection is changed.
/// </summary>
/// <param name="oldItem">The old item.</param>
/// <param name="newItem">The new item.</param>
/// <param name="index">The index.</param>
protected override void RaiseCollectionChangedChanged(
TItem oldItem,
TItem newItem,
int index)
{
if (this.IsFilter())
{
this.RaiseCollectionReset();
}
else
{
base.RaiseCollectionChangedChanged(
oldItem,
newItem,
index);
}
}
/// <summary>
/// Called when an item is removed from a collection.
/// </summary>
/// <param name="removedItem">The removed item.</param>
/// <param name="index">The index.</param>
protected override void RaiseCollectionChangedRemove(
TItem removedItem,
int index)
{
if (this.IsFilter())
{
this.RaiseCollectionReset();
}
else
{
base.RaiseCollectionChangedRemove(
removedItem,
index);
}
}
[SuppressMessage(
"Performance",
"HAA0401:Possible allocation of reference type enumerator",
Justification = "This cannot be avoidable.")]
private IEnumerator<TItem> EnumerateFiltered()
{
TFilter? localFilter = this.Filter;
using IEnumerator<TItem> enumerator = base.GetEnumerator();
if (localFilter is null)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
else
{
while (enumerator.MoveNext())
{
TItem current = enumerator.Current;
if (this.FilteringPredicate(
current,
localFilter))
{
yield return current;
}
}
}
}
[SuppressMessage(
"Performance",
"HAA0401:Possible allocation of reference type enumerator",
Justification = "This cannot be avoidable.")]
private void FillCachedList()
{
this.filteredElements = new List<TItem>(base.Count);
using IEnumerator<TItem> enumerator = this.EnumerateFiltered();
while (enumerator.MoveNext())
{
TItem current = enumerator.Current;
this.filteredElements.Add(current);
}
}
private void ClearCachedContents()
{
if (this.filteredElements == null)
{
return;
}
IList<TItem> coll = this.filteredElements;
this.filteredElements = null;
coll.Clear();
}
private bool IsFilter()
{
if (this.filter == null)
{
return true;
}
return !EqualityComparer<TFilter>.Default.Equals(
this.filter,
default!);
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.ProviderBase
{
internal abstract class DbConnectionFactory
{
private Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> _connectionPoolGroups;
private readonly List<DbConnectionPool> _poolsToRelease;
private readonly List<DbConnectionPoolGroup> _poolGroupsToRelease;
private readonly Timer _pruningTimer;
private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes
private const int PruningPeriod = 30 * 1000; // thirty seconds
// s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to
// a maximum of Environment.ProcessorCount at a time.
private static uint s_pendingOpenNonPooledNext = 0;
private static Task<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount];
private static Task<DbConnectionInternal> s_completedTask;
protected DbConnectionFactory()
{
_connectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>();
_poolsToRelease = new List<DbConnectionPool>();
_poolGroupsToRelease = new List<DbConnectionPoolGroup>();
_pruningTimer = CreatePruningTimer();
}
abstract public DbProviderFactory ProviderFactory
{
get;
}
public void ClearAllPools()
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
DbConnectionPoolGroup poolGroup = entry.Value;
if (null != poolGroup)
{
poolGroup.Clear();
}
}
}
public void ClearPool(DbConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection);
if (null != poolGroup)
{
poolGroup.Clear();
}
}
public void ClearPool(DbConnectionPoolKey key)
{
Debug.Assert(key != null, "key cannot be null");
ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString));
DbConnectionPoolGroup poolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out poolGroup))
{
poolGroup.Clear();
}
}
internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
{
Debug.Assert(null != owningConnection, "null owningConnection?");
Debug.Assert(null != poolGroup, "null poolGroup?");
DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions;
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo;
DbConnectionPoolKey poolKey = poolGroup.PoolKey;
DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions);
if (null != newConnection)
{
newConnection.MakeNonPooledObject(owningConnection);
}
return newConnection;
}
internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
{
Debug.Assert(null != pool, "null pool?");
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo;
DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions);
if (null != newConnection)
{
newConnection.MakePooledConnection(pool);
}
return newConnection;
}
virtual internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
private Timer CreatePruningTimer()
{
TimerCallback callback = new TimerCallback(PruneConnectionPoolGroups);
return new Timer(callback, null, PruningDueTime, PruningPeriod);
}
protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key)
{
Debug.Assert(key != null, "key cannot be null");
if (!string.IsNullOrEmpty(key.ConnectionString))
{
DbConnectionPoolGroup connectionPoolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
return connectionPoolGroup.ConnectionOptions;
}
}
return null;
}
private static Task<DbConnectionInternal> GetCompletedTask()
{
Debug.Assert(Monitor.IsEntered(s_pendingOpenNonPooled), $"Expected {nameof(s_pendingOpenNonPooled)} lock to be held.");
return s_completedTask ?? (s_completedTask = Task.FromResult<DbConnectionInternal>(null));
}
internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
{
Debug.Assert(null != owningConnection, "null owningConnection?");
DbConnectionPoolGroup poolGroup;
DbConnectionPool connectionPool;
connection = null;
// Work around race condition with clearing the pool between GetConnectionPool obtaining pool
// and GetConnection on the pool checking the pool state. Clearing the pool in this window
// will switch the pool into the ShuttingDown state, and GetConnection will return null.
// There is probably a better solution involving locking the pool/group, but that entails a major
// re-design of the connection pooling synchronization, so is postponed for now.
// Use retriesLeft to prevent CPU spikes with incremental sleep
// start with one msec, double the time every retry
// max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries)
int retriesLeft = 10;
int timeBetweenRetriesMilliseconds = 1;
do
{
poolGroup = GetConnectionPoolGroup(owningConnection);
// Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread.
connectionPool = GetConnectionPool(owningConnection, poolGroup);
if (null == connectionPool)
{
// If GetConnectionPool returns null, we can be certain that
// this connection should not be pooled via DbConnectionPool
// or have a disabled pool entry.
poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled
if (retry != null)
{
Task<DbConnectionInternal> newTask;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
lock (s_pendingOpenNonPooled)
{
// look for an available task slot (completed or empty)
int idx;
for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++)
{
Task task = s_pendingOpenNonPooled[idx];
if (task == null)
{
s_pendingOpenNonPooled[idx] = GetCompletedTask();
break;
}
else if (task.IsCompleted)
{
break;
}
}
// if didn't find one, pick the next one in round-robin fashion
if (idx == s_pendingOpenNonPooled.Length)
{
idx = (int)(s_pendingOpenNonPooledNext % s_pendingOpenNonPooled.Length);
unchecked
{
s_pendingOpenNonPooledNext++;
}
}
// now that we have an antecedent task, schedule our work when it is completed.
// If it is a new slot or a completed task, this continuation will start right away.
newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) =>
{
var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
{
oldConnection.PrepareForReplaceConnection();
oldConnection.Dispose();
}
return newConnection;
}, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
// Place this new task in the slot so any future work will be queued behind it
s_pendingOpenNonPooled[idx] = newTask;
}
// Set up the timeout (if needed)
if (owningConnection.ConnectionTimeout > 0)
{
int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000;
cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds);
}
// once the task is done, propagate the final results to the original caller
newTask.ContinueWith((task) =>
{
cancellationTokenSource.Dispose();
if (task.IsCanceled)
{
retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout()));
}
else if (task.IsFaulted)
{
retry.TrySetException(task.Exception.InnerException);
}
else
{
if (!retry.TrySetResult(task.Result))
{
// The outer TaskCompletionSource was already completed
// Which means that we don't know if someone has messed with the outer connection in the middle of creation
// So the best thing to do now is to destroy the newly created connection
task.Result.DoomThisConnection();
task.Result.Dispose();
}
}
}, TaskScheduler.Default);
return false;
}
connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
}
else
{
if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection)
{
Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection");
connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection);
}
else
{
if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection))
{
return false;
}
}
if (connection == null)
{
// connection creation failed on semaphore waiting or if max pool reached
if (connectionPool.IsRunning)
{
// If GetConnection failed while the pool is running, the pool timeout occurred.
throw ADP.PooledOpenTimeout();
}
else
{
// We've hit the race condition, where the pool was shut down after we got it from the group.
// Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated
// before retrying.
Threading.Thread.Sleep(timeBetweenRetriesMilliseconds);
timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration
}
}
}
} while (connection == null && retriesLeft-- > 0);
if (connection == null)
{
// exhausted all retries or timed out - give up
throw ADP.PooledOpenTimeout();
}
return true;
}
private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup)
{
// if poolgroup is disabled, it will be replaced with a new entry
Debug.Assert(null != owningObject, "null owningObject?");
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
// It is possible that while the outer connection object has
// been sitting around in a closed and unused state in some long
// running app, the pruner may have come along and remove this
// the pool entry from the master list. If we were to use a
// pool entry in this state, we would create "unmanaged" pools,
// which would be bad. To avoid this problem, we automagically
// re-create the pool entry whenever it's disabled.
// however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work
if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions;
// get the string to hash on again
DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions;
Debug.Assert(null != connectionOptions, "prevent expansion of connectionString");
connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions);
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
SetConnectionPoolGroup(owningObject, connectionPoolGroup);
}
DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this);
return connectionPool;
}
internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions)
{
if (string.IsNullOrEmpty(key.ConnectionString))
{
return (DbConnectionPoolGroup)null;
}
DbConnectionPoolGroup connectionPoolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)))
{
// If we can't find an entry for the connection string in
// our collection of pool entries, then we need to create a
// new pool entry and add it to our collection.
DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions);
if (null == connectionOptions)
{
throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing);
}
if (null == userConnectionOptions)
{ // we only allow one expansion on the connection string
userConnectionOptions = connectionOptions;
}
// We don't support connection pooling on Win9x
if (null == poolOptions)
{
if (null != connectionPoolGroup)
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
poolOptions = connectionPoolGroup.PoolGroupOptions;
}
else
{
// Note: may return null for non-pooled connections
poolOptions = CreateConnectionPoolGroupOptions(connectionOptions);
}
}
DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions);
newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions);
lock (this)
{
connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
// build new dictionary with space for new connection string
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(1 + connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
// lock prevents race condition with PruneConnectionPoolGroups
newConnectionPoolGroups.Add(key, newConnectionPoolGroup);
connectionPoolGroup = newConnectionPoolGroup;
_connectionPoolGroups = newConnectionPoolGroups;
}
else
{
Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered");
}
}
Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?");
Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?");
}
else if (null == userConnectionOptions)
{
userConnectionOptions = connectionPoolGroup.ConnectionOptions;
}
return connectionPoolGroup;
}
private void PruneConnectionPoolGroups(object state)
{
// First, walk the pool release list and attempt to clear each
// pool, when the pool is finally empty, we dispose of it. If the
// pool isn't empty, it's because there are active connections or
// distributed transactions that need it.
lock (_poolsToRelease)
{
if (0 != _poolsToRelease.Count)
{
DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray();
foreach (DbConnectionPool pool in poolsToRelease)
{
if (null != pool)
{
pool.Clear();
if (0 == pool.Count)
{
_poolsToRelease.Remove(pool);
}
}
}
}
}
// Next, walk the pool entry release list and dispose of each
// pool entry when it is finally empty. If the pool entry isn't
// empty, it's because there are active pools that need it.
lock (_poolGroupsToRelease)
{
if (0 != _poolGroupsToRelease.Count)
{
DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray();
foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease)
{
if (null != poolGroup)
{
int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease
if (0 == poolsLeft)
{
_poolGroupsToRelease.Remove(poolGroup);
}
}
}
}
}
// Finally, we walk through the collection of connection pool entries
// and prune each one. This will cause any empty pools to be put
// into the release list.
lock (this)
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
if (null != entry.Value)
{
Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered");
// entries start active and go idle during prune if all pools are gone
// move idle entries from last prune pass to a queue for pending release
// otherwise process entry which may move it from active to idle
if (entry.Value.Prune())
{ // may add entries to _poolsToRelease
QueuePoolGroupForRelease(entry.Value);
}
else
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
}
}
_connectionPoolGroups = newConnectionPoolGroups;
}
}
internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing)
{
// Queue the pool up for release -- we'll clear it out and dispose
// of it as the last part of the pruning timer callback so we don't
// do it with the pool entry or the pool collection locked.
Debug.Assert(null != pool, "null pool?");
// set the pool to the shutdown state to force all active
// connections to be automatically disposed when they
// are returned to the pool
pool.Shutdown();
lock (_poolsToRelease)
{
if (clearing)
{
pool.Clear();
}
_poolsToRelease.Add(pool);
}
}
internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup)
{
Debug.Assert(null != poolGroup, "null poolGroup?");
lock (_poolGroupsToRelease)
{
_poolGroupsToRelease.Add(poolGroup);
}
}
virtual protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
{
return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection);
}
abstract protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection);
abstract protected DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous);
abstract protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options);
abstract internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection);
abstract internal DbConnectionInternal GetInnerConnection(DbConnection connection);
abstract internal void PermissionDemand(DbConnection outerConnection);
abstract internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup);
abstract internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to);
abstract internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from);
abstract internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to);
}
}
| |
// 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 Internal.NativeCrypto;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography
{
/// <summary>
/// Safehandle representing HCRYPTPROV
/// </summary>
internal sealed class SafeProvHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private string _containerName;
private string _providerName;
private int _type;
private uint _flags;
private bool _fPersistKeyInCsp;
private SafeProvHandle() : base(true)
{
SetHandle(IntPtr.Zero);
_containerName = null;
_providerName = null;
_type = 0;
_flags = 0;
_fPersistKeyInCsp = true;
}
internal string ContainerName
{
get
{
return _containerName;
}
set
{
_containerName = value;
}
}
internal string ProviderName
{
get
{
return _providerName;
}
set
{
_providerName = value;
}
}
internal int Types
{
get
{
return _type;
}
set
{
_type = value;
}
}
internal uint Flags
{
get
{
return _flags;
}
set
{
_flags = value;
}
}
internal bool PersistKeyInCsp
{
get
{
return _fPersistKeyInCsp;
}
set
{
_fPersistKeyInCsp = value;
}
}
internal static SafeProvHandle InvalidHandle
{
get { return SafeHandleCache<SafeProvHandle>.GetInvalidHandle(() => new SafeProvHandle()); }
}
protected override void Dispose(bool disposing)
{
if (!SafeHandleCache<SafeProvHandle>.IsCachedInvalidHandle(this))
{
base.Dispose(disposing);
}
}
protected override bool ReleaseHandle()
{
// Make sure not to delete a key that we want to keep in the key container or an ephemeral key
if (!_fPersistKeyInCsp && 0 == (_flags & (uint)CapiHelper.CryptAcquireContextFlags.CRYPT_VERIFYCONTEXT))
{
// Delete the key container.
uint flags = (_flags & (uint)CapiHelper.CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) | (uint)CapiHelper.CryptAcquireContextFlags.CRYPT_DELETEKEYSET;
SafeProvHandle hIgnoredProv;
bool ignoredSuccess = CapiHelper.CryptAcquireContext(out hIgnoredProv, _containerName, _providerName, _type, flags);
hIgnoredProv.Dispose();
// Ignoring success result code as CryptAcquireContext is being called to delete a key container rather than acquire a context.
// If it fails, we can't do anything about it anyway as we're in a dispose method.
}
bool successfullyFreed = CapiHelper.CryptReleaseContext(handle, 0);
Debug.Assert(successfullyFreed);
SetHandle(IntPtr.Zero);
return successfullyFreed;
}
}
/// <summary>
/// Safe handle representing a HCRYPTKEY
/// </summary>
/// <summary>
/// Since we need to delete the key handle before the provider is released we need to actually hold a
/// pointer to a CRYPT_KEY_CTX unmanaged structure whose destructor decrements a refCount. Only when
/// the provider refCount is 0 it is deleted. This way, we loose a race in the critical finalization
/// of the key handle and provider handle. This also applies to hash handles, which point to a
/// CRYPT_HASH_CTX. Those structures are defined in COMCryptography.h
/// </summary>
internal sealed class SafeKeyHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private int _keySpec;
private bool _fPublicOnly;
private SafeProvHandle _parent;
private SafeKeyHandle() : base(true)
{
SetHandle(IntPtr.Zero);
_keySpec = 0;
_fPublicOnly = false;
}
internal int KeySpec
{
get
{
return _keySpec;
}
set
{
_keySpec = value;
}
}
internal bool PublicOnly
{
get
{
return _fPublicOnly;
}
set
{
_fPublicOnly = value;
}
}
internal void SetParent(SafeProvHandle parent)
{
if (IsInvalid || IsClosed)
{
return;
}
Debug.Assert(_parent == null);
Debug.Assert(!parent.IsClosed);
Debug.Assert(!parent.IsInvalid);
_parent = parent;
bool ignored = false;
_parent.DangerousAddRef(ref ignored);
}
internal static SafeKeyHandle InvalidHandle
{
get { return SafeHandleCache<SafeKeyHandle>.GetInvalidHandle(() => new SafeKeyHandle()); }
}
protected override void Dispose(bool disposing)
{
if (!SafeHandleCache<SafeKeyHandle>.IsCachedInvalidHandle(this))
{
base.Dispose(disposing);
}
}
protected override bool ReleaseHandle()
{
bool successfullyFreed = CapiHelper.CryptDestroyKey(handle);
Debug.Assert(successfullyFreed);
SafeProvHandle parent = _parent;
_parent = null;
parent?.DangerousRelease();
return successfullyFreed;
}
}
/// <summary>
/// SafeHandle representing HCRYPTHASH handle
/// </summary>
internal sealed class SafeHashHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeProvHandle _parent;
private SafeHashHandle() : base(true)
{
SetHandle(IntPtr.Zero);
}
internal void SetParent(SafeProvHandle parent)
{
if (IsInvalid || IsClosed)
{
return;
}
Debug.Assert(_parent == null);
Debug.Assert(!parent.IsClosed);
Debug.Assert(!parent.IsInvalid);
_parent = parent;
bool ignored = false;
_parent.DangerousAddRef(ref ignored);
}
internal static SafeHashHandle InvalidHandle
{
get { return SafeHandleCache<SafeHashHandle>.GetInvalidHandle(() => new SafeHashHandle()); }
}
protected override void Dispose(bool disposing)
{
if (!SafeHandleCache<SafeHashHandle>.IsCachedInvalidHandle(this))
{
base.Dispose(disposing);
}
}
protected override bool ReleaseHandle()
{
bool successfullyFreed = CapiHelper.CryptDestroyHash(handle);
Debug.Assert(successfullyFreed);
SafeProvHandle parent = _parent;
_parent = null;
parent?.DangerousRelease();
return successfullyFreed;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Nop.Core.Data;
using Nop.Core.Domain.Customers;
using Nop.Plugin.Api.DTOs.Customers;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text.RegularExpressions;
using Nop.Core;
using Nop.Core.Domain.Common;
using Nop.Plugin.Api.Constants;
using Nop.Plugin.Api.DataStructures;
using Nop.Plugin.Api.Helpers;
using Nop.Plugin.Api.MappingExtensions;
using Nop.Services.Localization;
using Nop.Services.Stores;
using Nop.Core.Domain.Messages;
using Nop.Core.Caching;
namespace Nop.Plugin.Api.Services
{
public class CustomerApiService : ICustomerApiService
{
private const string FirstName = "firstname";
private const string LastName = "lastname";
private const string LanguageId = "languageid";
private const string DateOfBirth = "dateofbirth";
private const string Gender = "gender";
private const string KeyGroup = "customer";
private readonly IStoreContext _storeContext;
private readonly ILanguageService _languageService;
private readonly IStoreMappingService _storeMappingService;
private readonly IRepository<Customer> _customerRepository;
private readonly IRepository<GenericAttribute> _genericAttributeRepository;
private readonly IRepository<NewsLetterSubscription> _subscriptionRepository;
private readonly IStaticCacheManager _cacheManager;
public CustomerApiService(IRepository<Customer> customerRepository,
IRepository<GenericAttribute> genericAttributeRepository,
IRepository<NewsLetterSubscription> subscriptionRepository,
IStoreContext storeContext,
ILanguageService languageService,
IStoreMappingService storeMappingService,
IStaticCacheManager staticCacheManager)
{
_customerRepository = customerRepository;
_genericAttributeRepository = genericAttributeRepository;
_subscriptionRepository = subscriptionRepository;
_storeContext = storeContext;
_languageService = languageService;
_storeMappingService = storeMappingService;
_cacheManager = staticCacheManager;
}
public IList<CustomerDto> GetCustomersDtos(DateTime? createdAtMin = null, DateTime? createdAtMax = null, int limit = Configurations.DefaultLimit,
int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId)
{
var query = GetCustomersQuery(createdAtMin, createdAtMax, sinceId);
var result = HandleCustomerGenericAttributes(null, query, limit, page);
SetNewsletterSubscribtionStatus(result);
return result;
}
public int GetCustomersCount()
{
return _customerRepository.Table.Count(customer => !customer.Deleted
&& (customer.RegisteredInStoreId == 0 || customer.RegisteredInStoreId == _storeContext.CurrentStore.Id));
}
// Need to work with dto object so we can map the first and last name from generic attributes table.
public IList<CustomerDto> Search(string queryParams = "", string order = Configurations.DefaultOrder,
int page = Configurations.DefaultPageValue, int limit = Configurations.DefaultLimit)
{
IList<CustomerDto> result = new List<CustomerDto>();
var searchParams = EnsureSearchQueryIsValid(queryParams, ParseSearchQuery);
if (searchParams != null)
{
var query = _customerRepository.Table.Where(customer => !customer.Deleted);
foreach (var searchParam in searchParams)
{
// Skip non existing properties.
if (ReflectionHelper.HasProperty(searchParam.Key, typeof(Customer)))
{
// @0 is a placeholder used by dynamic linq and it is used to prevent possible sql injections.
query = query.Where(string.Format("{0} = @0 || {0}.Contains(@0)", searchParam.Key), searchParam.Value);
}
// The code bellow will search in customer addresses as well.
//else if (HasProperty(searchParam.Key, typeof(Address)))
//{
// query = query.Where(string.Format("Addresses.Where({0} == @0).Any()", searchParam.Key), searchParam.Value);
//}
}
result = HandleCustomerGenericAttributes(searchParams, query, limit, page, order);
}
return result;
}
public Dictionary<string, string> GetFirstAndLastNameByCustomerId(int customerId)
{
return _genericAttributeRepository.Table.Where(
x =>
x.KeyGroup == KeyGroup && x.EntityId == customerId &&
(x.Key == FirstName || x.Key == LastName)).ToDictionary(x => x.Key.ToLowerInvariant(), y => y.Value);
}
public Customer GetCustomerEntityById(int id)
{
var customer = _customerRepository.Table.FirstOrDefault(c => c.Id == id && !c.Deleted);
return customer;
}
public CustomerDto GetCustomerById(int id, bool showDeleted = false)
{
if (id == 0)
return null;
// Here we expect to get two records, one for the first name and one for the last name.
var customerAttributeMappings = (from customer in _customerRepository.Table //NoTracking
join attribute in _genericAttributeRepository.Table//NoTracking
on customer.Id equals attribute.EntityId
where customer.Id == id &&
attribute.KeyGroup == "Customer"
select new CustomerAttributeMappingDto
{
Attribute = attribute,
Customer = customer
}).ToList();
CustomerDto customerDto = null;
// This is in case we have first and last names set for the customer.
if (customerAttributeMappings.Count > 0)
{
var customer = customerAttributeMappings.First().Customer;
// The customer object is the same in all mappings.
customerDto = customer.ToDto();
var defaultStoreLanguageId = GetDefaultStoreLangaugeId();
// If there is no Language Id generic attribute create one with the default language id.
if (!customerAttributeMappings.Any(cam => cam?.Attribute != null && cam.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)))
{
var languageId = new GenericAttribute
{
Key = LanguageId,
Value = defaultStoreLanguageId.ToString()
};
var customerAttributeMappingDto = new CustomerAttributeMappingDto
{
Customer = customer,
Attribute = languageId
};
customerAttributeMappings.Add(customerAttributeMappingDto);
}
foreach (var mapping in customerAttributeMappings)
{
if (!showDeleted && mapping.Customer.Deleted)
{
continue;
}
if (mapping.Attribute != null)
{
if (mapping.Attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.FirstName = mapping.Attribute.Value;
}
else if (mapping.Attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.LastName = mapping.Attribute.Value;
}
else if (mapping.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.LanguageId = mapping.Attribute.Value;
}
else if (mapping.Attribute.Key.Equals(DateOfBirth, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.DateOfBirth = string.IsNullOrEmpty(mapping.Attribute.Value) ? (DateTime?)null : DateTime.Parse(mapping.Attribute.Value);
}
else if (mapping.Attribute.Key.Equals(Gender, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.Gender = mapping.Attribute.Value;
}
}
}
}
else
{
// This is when we do not have first and last name set.
var currentCustomer = _customerRepository.Table.FirstOrDefault(customer => customer.Id == id);
if (currentCustomer != null)
{
if (showDeleted || !currentCustomer.Deleted)
{
customerDto = currentCustomer.ToDto();
}
}
}
SetNewsletterSubscribtionStatus(customerDto);
return customerDto;
}
private Dictionary<string, string> EnsureSearchQueryIsValid(string query, Func<string, Dictionary<string, string>> parseSearchQuery)
{
if (!string.IsNullOrEmpty(query))
{
return parseSearchQuery(query);
}
return null;
}
private Dictionary<string, string> ParseSearchQuery(string query)
{
var parsedQuery = new Dictionary<string, string>();
var splitPattern = @"(\w+):";
var fieldValueList = Regex.Split(query, splitPattern).Where(s => s != String.Empty).ToList();
if (fieldValueList.Count < 2)
{
return parsedQuery;
}
for (var i = 0; i < fieldValueList.Count; i += 2)
{
var field = fieldValueList[i];
var value = fieldValueList[i + 1];
if (!string.IsNullOrEmpty(field) && !string.IsNullOrEmpty(value))
{
field = field.Replace("_", string.Empty);
parsedQuery.Add(field.Trim(), value.Trim());
}
}
return parsedQuery;
}
/// <summary>
/// The idea of this method is to get the first and last name from the GenericAttribute table and to set them in the CustomerDto object.
/// </summary>
/// <param name="searchParams">Search parameters is used to shrinc the range of results from the GenericAttibutes table
/// to be only those with specific search parameter (i.e. currently we focus only on first and last name).</param>
/// <param name="query">Query parameter represents the current customer records which we will join with GenericAttributes table.</param>
/// <param name="limit"></param>
/// <param name="page"></param>
/// <param name="order"></param>
/// <returns></returns>
private IList<CustomerDto> HandleCustomerGenericAttributes(IReadOnlyDictionary<string, string> searchParams, IQueryable<Customer> query,
int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, string order = Configurations.DefaultOrder)
{
// Here we join the GenericAttribute records with the customers and making sure that we are working only with the attributes
// that are in the customers keyGroup and their keys are either first or last name.
// We are returning a collection with customer record and attribute record.
// It will look something like:
// customer data for customer 1
// attribute that contains the first name of customer 1
// attribute that contains the last name of customer 1
// customer data for customer 2,
// attribute that contains the first name of customer 2
// attribute that contains the last name of customer 2
// etc.
var allRecordsGroupedByCustomerId =
(from customer in query
from attribute in _genericAttributeRepository.Table
.Where(attr => attr.EntityId == customer.Id &&
attr.KeyGroup == "Customer").DefaultIfEmpty()
select new CustomerAttributeMappingDto
{
Attribute = attribute,
Customer = customer
}).GroupBy(x => x.Customer.Id);
if (searchParams != null && searchParams.Count > 0)
{
if (searchParams.ContainsKey(FirstName))
{
allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, FirstName, searchParams[FirstName]);
}
if (searchParams.ContainsKey(LastName))
{
allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, LastName, searchParams[LastName]);
}
if (searchParams.ContainsKey(LanguageId))
{
allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, LanguageId, searchParams[LanguageId]);
}
if (searchParams.ContainsKey(DateOfBirth))
{
allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, DateOfBirth, searchParams[DateOfBirth]);
}
if (searchParams.ContainsKey(Gender))
{
allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, Gender, searchParams[Gender]);
}
}
var result = GetFullCustomerDtos(allRecordsGroupedByCustomerId, page, limit, order);
return result;
}
/// <summary>
/// This method is responsible for getting customer dto records with first and last names set from the attribute mappings.
/// </summary>
private IList<CustomerDto> GetFullCustomerDtos(IQueryable<IGrouping<int, CustomerAttributeMappingDto>> customerAttributesMappings,
int page = Configurations.DefaultPageValue, int limit = Configurations.DefaultLimit, string order = Configurations.DefaultOrder)
{
var customerDtos = new List<CustomerDto>();
customerAttributesMappings = customerAttributesMappings.OrderBy(x => x.Key);
IList<IGrouping<int, CustomerAttributeMappingDto>> customerAttributeGroupsList = new ApiList<IGrouping<int, CustomerAttributeMappingDto>>(customerAttributesMappings, page - 1, limit);
// Get the default language id for the current store.
var defaultLanguageId = GetDefaultStoreLangaugeId();
foreach (var group in customerAttributeGroupsList)
{
IList<CustomerAttributeMappingDto> mappingsForMerge = group.Select(x => x).ToList();
var customerDto = Merge(mappingsForMerge, defaultLanguageId);
customerDtos.Add(customerDto);
}
// Needed so we can apply the order parameter
return customerDtos.AsQueryable().OrderBy(order).ToList();
}
private static CustomerDto Merge(IList<CustomerAttributeMappingDto> mappingsForMerge, int defaultLanguageId)
{
// We expect the customer to be always set.
var customerDto = mappingsForMerge.First().Customer.ToDto();
var attributes = mappingsForMerge.Select(x => x.Attribute).ToList();
// If there is no Language Id generic attribute create one with the default language id.
if (!attributes.Any(atr => atr != null && atr.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)))
{
var languageId = new GenericAttribute
{
Key = LanguageId,
Value = defaultLanguageId.ToString()
};
attributes.Add(languageId);
}
foreach (var attribute in attributes)
{
if (attribute != null)
{
if (attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.FirstName = attribute.Value;
}
else if (attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.LastName = attribute.Value;
}
else if (attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.LanguageId = attribute.Value;
}
else if (attribute.Key.Equals(DateOfBirth, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.DateOfBirth = string.IsNullOrEmpty(attribute.Value) ? (DateTime?)null : DateTime.Parse(attribute.Value);
}
else if (attribute.Key.Equals(Gender, StringComparison.InvariantCultureIgnoreCase))
{
customerDto.Gender = attribute.Value;
}
}
}
return customerDto;
}
private IQueryable<IGrouping<int, CustomerAttributeMappingDto>> GetCustomerAttributesMappingsByKey(
IQueryable<IGrouping<int, CustomerAttributeMappingDto>> customerAttributesGroups, string key, string value)
{
// Here we filter the customerAttributesGroups to be only the ones that have the passed key parameter as a key.
var customerAttributesMappingByKey = from @group in customerAttributesGroups
where @group.Select(x => x.Attribute)
.Any(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase) &&
x.Value.Equals(value, StringComparison.InvariantCultureIgnoreCase))
select @group;
return customerAttributesMappingByKey;
}
private IQueryable<Customer> GetCustomersQuery(DateTime? createdAtMin = null, DateTime? createdAtMax = null, int sinceId = 0)
{
var query = _customerRepository.Table //NoTracking
.Where(customer => !customer.Deleted && !customer.IsSystemAccount && customer.Active);
query = query.Where(customer => !customer.CustomerCustomerRoleMappings.Any(ccrm => ccrm.CustomerRole.Active && ccrm.CustomerRole.SystemName == NopCustomerDefaults.GuestsRoleName)
&& (customer.RegisteredInStoreId == 0 || customer.RegisteredInStoreId == _storeContext.CurrentStore.Id));
if (createdAtMin != null)
{
query = query.Where(c => c.CreatedOnUtc > createdAtMin.Value);
}
if (createdAtMax != null)
{
query = query.Where(c => c.CreatedOnUtc < createdAtMax.Value);
}
query = query.OrderBy(customer => customer.Id);
if (sinceId > 0)
{
query = query.Where(customer => customer.Id > sinceId);
}
return query;
}
private int GetDefaultStoreLangaugeId()
{
// Get the default language id for the current store.
var defaultLanguageId = _storeContext.CurrentStore.DefaultLanguageId;
if (defaultLanguageId == 0)
{
var allLanguages = _languageService.GetAllLanguages();
var storeLanguages = allLanguages.Where(l =>
_storeMappingService.Authorize(l, _storeContext.CurrentStore.Id)).ToList();
// If there is no language mapped to the current store, get all of the languages,
// and use the one with the first display order. This is a default nopCommerce workflow.
if (storeLanguages.Count == 0)
{
storeLanguages = allLanguages.ToList();
}
var defaultLanguage = storeLanguages.OrderBy(l => l.DisplayOrder).First();
defaultLanguageId = defaultLanguage.Id;
}
return defaultLanguageId;
}
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
private void SetNewsletterSubscribtionStatus(IList<CustomerDto> customerDtos)
{
if (customerDtos == null)
{
return;
}
var allNewsletterCustomerEmail = GetAllNewsletterCustomersEmails();
foreach (var customerDto in customerDtos)
{
SetNewsletterSubscribtionStatus(customerDto, allNewsletterCustomerEmail);
}
}
private void SetNewsletterSubscribtionStatus(BaseCustomerDto customerDto, IEnumerable<String> allNewsletterCustomerEmail = null)
{
if (customerDto == null || String.IsNullOrEmpty(customerDto.Email))
{
return;
}
if (allNewsletterCustomerEmail == null)
{
allNewsletterCustomerEmail = GetAllNewsletterCustomersEmails();
}
if (allNewsletterCustomerEmail != null && allNewsletterCustomerEmail.Contains(customerDto.Email.ToLowerInvariant()))
{
customerDto.SubscribedToNewsletter = true;
}
}
private IEnumerable<String> GetAllNewsletterCustomersEmails()
{
return _cacheManager.Get(Configurations.NEWSLETTER_SUBSCRIBERS_KEY, () =>
{
IEnumerable<String> subscriberEmails = (from nls in _subscriptionRepository.Table
where nls.StoreId == _storeContext.CurrentStore.Id
&& nls.Active
select nls.Email).ToList();
subscriberEmails = subscriberEmails.Where(e => !String.IsNullOrEmpty(e)).Select(e => e.ToLowerInvariant());
return subscriberEmails.Where(e => !String.IsNullOrEmpty(e)).Select(e => e.ToLowerInvariant());
});
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent
{
internal abstract partial class AbstractIndentationService
{
internal abstract class AbstractIndenter
{
protected readonly OptionSet OptionSet;
protected readonly TextLine LineToBeIndented;
protected readonly int TabSize;
protected readonly CancellationToken CancellationToken;
protected readonly SyntaxTree Tree;
protected readonly IEnumerable<IFormattingRule> Rules;
protected readonly BottomUpBaseIndentationFinder Finder;
private static readonly Func<SyntaxToken, bool> s_tokenHasDirective = tk => tk.ContainsDirectives &&
(tk.LeadingTrivia.Any(tr => tr.IsDirective) || tk.TrailingTrivia.Any(tr => tr.IsDirective));
private readonly ISyntaxFactsService _syntaxFacts;
public AbstractIndenter(
ISyntaxFactsService syntaxFacts,
SyntaxTree syntaxTree,
IEnumerable<IFormattingRule> rules,
OptionSet optionSet,
TextLine lineToBeIndented,
CancellationToken cancellationToken)
{
var syntaxRoot = syntaxTree.GetRoot(cancellationToken);
this._syntaxFacts = syntaxFacts;
this.OptionSet = optionSet;
this.Tree = syntaxTree;
this.LineToBeIndented = lineToBeIndented;
this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, syntaxRoot.Language);
this.CancellationToken = cancellationToken;
this.Rules = rules;
this.Finder = new BottomUpBaseIndentationFinder(
new ChainedFormattingRules(this.Rules, OptionSet),
this.TabSize,
this.OptionSet.GetOption(FormattingOptions.IndentationSize, syntaxRoot.Language),
tokenStream: null,
lastToken: default(SyntaxToken));
}
public IndentationResult? GetDesiredIndentation(Document document)
{
var indentStyle = OptionSet.GetOption(FormattingOptions.SmartIndent, document.Project.Language);
if (indentStyle == FormattingOptions.IndentStyle.None)
{
// If there is no indent style, then do nothing.
return null;
}
// find previous line that is not blank. this will skip over things like preprocessor
// regions and inactive code.
var previousLineOpt = GetPreviousNonBlankOrPreprocessorLine();
// it is beginning of the file, there is no previous line exists.
// in that case, indentation 0 is our base indentation.
if (previousLineOpt == null)
{
return IndentFromStartOfLine(0);
}
var previousNonWhitespaceOrPreprocessorLine = previousLineOpt.Value;
// If the user wants block indentation, then we just return the indentation
// of the last piece of real code.
//
// TODO(cyrusn): It's not clear to me that this is correct. Block indentation
// should probably follow the indentation of hte last non-blank line *regardless
// if it is inactive/preprocessor region. By skipping over thse, we are essentially
// being 'smart', and that seems to be overriding the user desire to have Block
// indentation.
if (indentStyle == FormattingOptions.IndentStyle.Block)
{
// If it's block indentation, then just base
return GetIndentationOfLine(previousNonWhitespaceOrPreprocessorLine);
}
Debug.Assert(indentStyle == FormattingOptions.IndentStyle.Smart);
// Because we know that previousLine is not-whitespace, we know that we should be
// able to get the last non-whitespace position.
var lastNonWhitespacePosition = previousNonWhitespaceOrPreprocessorLine.GetLastNonWhitespacePosition().Value;
var token = Tree.GetRoot(CancellationToken).FindToken(lastNonWhitespacePosition);
Debug.Assert(token.RawKind != 0, "FindToken should always return a valid token");
return GetDesiredIndentationWorker(
token, previousNonWhitespaceOrPreprocessorLine, lastNonWhitespacePosition);
}
protected abstract IndentationResult? GetDesiredIndentationWorker(
SyntaxToken token, TextLine previousLine, int lastNonWhitespacePosition);
protected IndentationResult IndentFromStartOfLine(int addedSpaces)
=> new IndentationResult(this.LineToBeIndented.Start, addedSpaces);
protected IndentationResult GetIndentationOfToken(SyntaxToken token)
=> GetIndentationOfToken(token, addedSpaces: 0);
protected IndentationResult GetIndentationOfToken(SyntaxToken token, int addedSpaces)
=> GetIndentationOfPosition(token.SpanStart, addedSpaces);
protected IndentationResult GetIndentationOfLine(TextLine lineToMatch)
=> GetIndentationOfLine(lineToMatch, addedSpaces: 0);
protected IndentationResult GetIndentationOfLine(TextLine lineToMatch, int addedSpaces)
{
var firstNonWhitespace = lineToMatch.GetFirstNonWhitespacePosition();
firstNonWhitespace = firstNonWhitespace ?? lineToMatch.End;
return GetIndentationOfPosition(firstNonWhitespace.Value, addedSpaces);
}
protected IndentationResult GetIndentationOfPosition(int position, int addedSpaces)
{
if (this.Tree.OverlapsHiddenPosition(GetNormalizedSpan(position), CancellationToken))
{
// Oops, the line we want to line up to is either hidden, or is in a different
// visible region.
var root = this.Tree.GetRoot(CancellationToken.None);
var token = root.FindTokenFromEnd(LineToBeIndented.Start);
var indentation = Finder.GetIndentationOfCurrentPosition(this.Tree, token, LineToBeIndented.Start, CancellationToken.None);
return new IndentationResult(LineToBeIndented.Start, indentation);
}
return new IndentationResult(position, addedSpaces);
}
private TextSpan GetNormalizedSpan(int position)
{
if (LineToBeIndented.Start < position)
{
return TextSpan.FromBounds(LineToBeIndented.Start, position);
}
return TextSpan.FromBounds(position, LineToBeIndented.Start);
}
protected TextLine? GetPreviousNonBlankOrPreprocessorLine()
{
if (LineToBeIndented.LineNumber <= 0)
{
return null;
}
var sourceText = this.LineToBeIndented.Text;
var lineNumber = this.LineToBeIndented.LineNumber - 1;
while (lineNumber >= 0)
{
var actualLine = sourceText.Lines[lineNumber];
// Empty line, no indentation to match.
if (string.IsNullOrWhiteSpace(actualLine.ToString()))
{
lineNumber--;
continue;
}
// No preprocessors in the entire tree, so this
// line definitely doesn't have one
var root = Tree.GetRoot(CancellationToken);
if (!root.ContainsDirectives)
{
return sourceText.Lines[lineNumber];
}
// This line is inside an inactive region. Examine the
// first preceding line not in an inactive region.
var disabledSpan = _syntaxFacts.GetInactiveRegionSpanAroundPosition(this.Tree, actualLine.Span.Start, CancellationToken);
if (disabledSpan != default(TextSpan))
{
var targetLine = sourceText.Lines.GetLineFromPosition(disabledSpan.Start).LineNumber;
lineNumber = targetLine - 1;
continue;
}
// A preprocessor directive starts on this line.
if (HasPreprocessorCharacter(actualLine) &&
root.DescendantTokens(actualLine.Span, tk => tk.FullWidth() > 0).Any(s_tokenHasDirective))
{
lineNumber--;
continue;
}
return sourceText.Lines[lineNumber];
}
return null;
}
protected int GetCurrentPositionNotBelongToEndOfFileToken(int position)
{
var compilationUnit = Tree.GetRoot(CancellationToken) as ICompilationUnitSyntax;
if (compilationUnit == null)
{
return position;
}
return Math.Min(compilationUnit.EndOfFileToken.FullSpan.Start, position);
}
protected bool HasPreprocessorCharacter(TextLine currentLine)
{
var text = currentLine.ToString();
Contract.Requires(!string.IsNullOrWhiteSpace(text));
var trimmedText = text.Trim();
return trimmedText[0] == '#';
}
}
}
}
| |
// Copyright 2014, Google Inc. 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.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.v201411;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201411 {
/// <summary>
/// UnitTests for <see cref="LineItemCreativeAssociationServiceTests"/> class.
/// </summary>
[TestFixture]
public class LineItemCreativeAssociationServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="LineItemCreativeAssociationService"/> class.
/// </summary>
private LineItemCreativeAssociationService licaService;
/// <summary>
/// Advertiser company id for running tests.
/// </summary>
private long advertiserId;
/// <summary>
/// Salesperson user id for running tests.
/// </summary>
private long salespersonId;
/// <summary>
/// Trafficker user id for running tests.
/// </summary>
private long traffickerId;
/// <summary>
/// Order id for running tests.
/// </summary>
private long orderId;
/// <summary>
/// Ad unit id for running tests.
/// </summary>
private string adUnitId;
/// <summary>
/// Creative id 1 for running tests.
/// </summary>
private long creativeId1;
/// <summary>
/// Creative id 2 for running tests.
/// </summary>
private long creativeId2;
/// <summary>
/// Creative id 3 for running tests.
/// </summary>
private long creativeId3;
/// <summary>
/// Creative id 4 for running tests.
/// </summary>
private long creativeId4;
/// <summary>
/// Line item id 1 for running tests.
/// </summary>
private long lineItemId1;
/// <summary>
/// Line item id 2 for running tests.
/// </summary>
private long lineItemId2;
/// <summary>
/// Line item id 3 for running tests.
/// </summary>
private long lineItemId3;
/// <summary>
/// Line item id 4 for running tests.
/// </summary>
private long lineItemId4;
/// <summary>
/// Line item creative association 1 for running tests.
/// </summary>
private LineItemCreativeAssociation lica1;
/// <summary>
/// Line item creative association 2 for running tests.
/// </summary>
private LineItemCreativeAssociation lica2;
/// <summary>
/// Default public constructor.
/// </summary>
public LineItemCreativeAssociationServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
licaService = (LineItemCreativeAssociationService) user.GetService(
DfpService.v201411.LineItemCreativeAssociationService);
advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id;
salespersonId = utils.GetSalesperson(user).id;
traffickerId = utils.GetTrafficker(user).id;
orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id;
adUnitId = utils.CreateAdUnit(user).id;
lineItemId1 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId2 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId3 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId4 = utils.CreateLineItem(user, orderId, adUnitId).id;
creativeId1 = utils.CreateCreative(user, advertiserId).id;
creativeId2 = utils.CreateCreative(user, advertiserId).id;
creativeId3 = utils.CreateCreative(user, advertiserId).id;
creativeId4 = utils.CreateCreative(user, advertiserId).id;
lica1 = utils.CreateLica(user, lineItemId3, creativeId3);
lica2 = utils.CreateLica(user, lineItemId4, creativeId4);
}
/// <summary>
/// Test whether we can create a list of line item creative associations.
/// </summary>
[Test]
public void TestCreateLineItemCreativeAssociations() {
LineItemCreativeAssociation localLica1 = new LineItemCreativeAssociation();
localLica1.creativeId = creativeId1;
localLica1.lineItemId = lineItemId1;
LineItemCreativeAssociation localLica2 = new LineItemCreativeAssociation();
localLica2.creativeId = creativeId2;
localLica2.lineItemId = lineItemId2;
LineItemCreativeAssociation[] newLicas = null;
Assert.DoesNotThrow(delegate() {
newLicas = licaService.createLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {localLica1, localLica2});
});
Assert.NotNull(newLicas);
Assert.AreEqual(newLicas.Length, 2);
Assert.NotNull(newLicas[0]);
Assert.AreEqual(newLicas[0].creativeId, localLica1.creativeId);
Assert.AreEqual(newLicas[0].lineItemId, localLica1.lineItemId);
Assert.NotNull(newLicas[1]);
Assert.AreEqual(newLicas[1].creativeId, localLica2.creativeId);
Assert.AreEqual(newLicas[1].lineItemId, localLica2.lineItemId);
}
/// <summary>
/// Test whether we can fetch a list of existing line item creative
/// associations that match given statement.
/// </summary>
[Test]
public void TestGetLineItemCreativeAssociationsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 500", lineItemId3);
LineItemCreativeAssociationPage page = null;
Assert.DoesNotThrow(delegate() {
page = licaService.getLineItemCreativeAssociationsByStatement(statement);
});
Assert.NotNull(page);
Assert.NotNull(page.results);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results[0]);
Assert.AreEqual(page.results[0].creativeId, lica1.creativeId);
Assert.AreEqual(page.results[0].lineItemId, lica1.lineItemId);
}
/// <summary>
/// Test whether we can deactivate a line item create association.
/// </summary>
[Test]
public void TestPerformLineItemCreativeAssociationAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 1", lineItemId3);
DeactivateLineItemCreativeAssociations action = new DeactivateLineItemCreativeAssociations();
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = licaService.performLineItemCreativeAssociationAction(action, statement);
});
Assert.NotNull(result);
Assert.AreEqual(result.numChanges, 1);
}
/// <summary>
/// Test whether we can update a list of line item creative associations.
/// </summary>
[Test]
public void TestUpdateLineItemCreativeAssociations() {
lica1.destinationUrl = "http://news.google.com";
lica2.destinationUrl = "http://news.google.com";
LineItemCreativeAssociation[] newLicas = null;
Assert.DoesNotThrow(delegate() {
newLicas = licaService.updateLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {lica1, lica2});
});
Assert.NotNull(newLicas);
Assert.AreEqual(newLicas.Length, 2);
Assert.NotNull(newLicas[0]);
Assert.AreEqual(newLicas[0].creativeId, lica1.creativeId);
Assert.AreEqual(newLicas[0].lineItemId, lica1.lineItemId);
Assert.NotNull(newLicas[1]);
Assert.AreEqual(newLicas[1].creativeId, lica2.creativeId);
Assert.AreEqual(newLicas[1].lineItemId, lica2.lineItemId);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace YAF.Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext;
using IBits = YAF.Lucene.Net.Util.IBits;
using IndexReader = YAF.Lucene.Net.Index.IndexReader;
using Term = YAF.Lucene.Net.Index.Term;
using ToStringUtils = YAF.Lucene.Net.Util.ToStringUtils;
/// <summary>
/// A query that applies a filter to the results of another query.
///
/// <para/>Note: the bits are retrieved from the filter each time this
/// query is used in a search - use a <see cref="CachingWrapperFilter"/> to avoid
/// regenerating the bits every time.
/// <para/>
/// @since 1.4 </summary>
/// <seealso cref="CachingWrapperFilter"/>
public class FilteredQuery : Query
{
private readonly Query query;
private readonly Filter filter;
private readonly FilterStrategy strategy;
/// <summary>
/// Constructs a new query which applies a filter to the results of the original query.
/// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary>
/// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param>
/// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param>
public FilteredQuery(Query query, Filter filter)
: this(query, filter, RANDOM_ACCESS_FILTER_STRATEGY)
{
}
/// <summary>
/// Expert: Constructs a new query which applies a filter to the results of the original query.
/// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary>
/// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param>
/// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param>
/// <param name="strategy"> A filter strategy used to create a filtered scorer.
/// </param>
/// <seealso cref="FilterStrategy"/>
public FilteredQuery(Query query, Filter filter, FilterStrategy strategy)
{
if (query == null || filter == null)
{
throw new System.ArgumentException("Query and filter cannot be null.");
}
if (strategy == null)
{
throw new System.ArgumentException("FilterStrategy can not be null");
}
this.strategy = strategy;
this.query = query;
this.filter = filter;
}
/// <summary>
/// Returns a <see cref="Weight"/> that applies the filter to the enclosed query's <see cref="Weight"/>.
/// this is accomplished by overriding the <see cref="Scorer"/> returned by the <see cref="Weight"/>.
/// </summary>
public override Weight CreateWeight(IndexSearcher searcher)
{
Weight weight = query.CreateWeight(searcher);
return new WeightAnonymousInnerClassHelper(this, weight);
}
private class WeightAnonymousInnerClassHelper : Weight
{
private readonly FilteredQuery outerInstance;
private Lucene.Net.Search.Weight weight;
public WeightAnonymousInnerClassHelper(FilteredQuery outerInstance, Lucene.Net.Search.Weight weight)
{
this.outerInstance = outerInstance;
this.weight = weight;
}
public override bool ScoresDocsOutOfOrder
{
get { return true; }
}
public override float GetValueForNormalization()
{
return weight.GetValueForNormalization() * outerInstance.Boost * outerInstance.Boost; // boost sub-weight
}
public override void Normalize(float norm, float topLevelBoost)
{
weight.Normalize(norm, topLevelBoost * outerInstance.Boost); // incorporate boost
}
public override Explanation Explain(AtomicReaderContext ir, int i)
{
Explanation inner = weight.Explain(ir, i);
Filter f = outerInstance.filter;
DocIdSet docIdSet = f.GetDocIdSet(ir, ir.AtomicReader.LiveDocs);
DocIdSetIterator docIdSetIterator = docIdSet == null ? DocIdSetIterator.GetEmpty() : docIdSet.GetIterator();
if (docIdSetIterator == null)
{
docIdSetIterator = DocIdSetIterator.GetEmpty();
}
if (docIdSetIterator.Advance(i) == i)
{
return inner;
}
else
{
Explanation result = new Explanation(0.0f, "failure to match filter: " + f.ToString());
result.AddDetail(inner);
return result;
}
}
// return this query
public override Query Query
{
get
{
return outerInstance;
}
}
// return a filtering scorer
public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
{
Debug.Assert(outerInstance.filter != null);
DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs);
if (filterDocIdSet == null)
{
// this means the filter does not accept any documents.
return null;
}
return outerInstance.strategy.FilteredScorer(context, weight, filterDocIdSet);
}
// return a filtering top scorer
public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs)
{
Debug.Assert(outerInstance.filter != null);
DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs);
if (filterDocIdSet == null)
{
// this means the filter does not accept any documents.
return null;
}
return outerInstance.strategy.FilteredBulkScorer(context, weight, scoreDocsInOrder, filterDocIdSet);
}
}
/// <summary>
/// A scorer that consults the filter if a document was matched by the
/// delegate scorer. This is useful if the filter computation is more expensive
/// than document scoring or if the filter has a linear running time to compute
/// the next matching doc like exact geo distances.
/// </summary>
private sealed class QueryFirstScorer : Scorer
{
private readonly Scorer scorer;
private int scorerDoc = -1;
private readonly IBits filterBits;
internal QueryFirstScorer(Weight weight, IBits filterBits, Scorer other)
: base(weight)
{
this.scorer = other;
this.filterBits = filterBits;
}
public override int NextDoc()
{
int doc;
for (; ; )
{
doc = scorer.NextDoc();
if (doc == Scorer.NO_MORE_DOCS || filterBits.Get(doc))
{
return scorerDoc = doc;
}
}
}
public override int Advance(int target)
{
int doc = scorer.Advance(target);
if (doc != Scorer.NO_MORE_DOCS && !filterBits.Get(doc))
{
return scorerDoc = NextDoc();
}
else
{
return scorerDoc = doc;
}
}
public override int DocID
{
get { return scorerDoc; }
}
public override float GetScore()
{
return scorer.GetScore();
}
public override int Freq
{
get { return scorer.Freq; }
}
public override ICollection<ChildScorer> GetChildren()
{
return new[] { new ChildScorer(scorer, "FILTERED") };
}
public override long GetCost()
{
return scorer.GetCost();
}
}
private class QueryFirstBulkScorer : BulkScorer
{
private readonly Scorer scorer;
private readonly IBits filterBits;
public QueryFirstBulkScorer(Scorer scorer, IBits filterBits)
{
this.scorer = scorer;
this.filterBits = filterBits;
}
public override bool Score(ICollector collector, int maxDoc)
{
// the normalization trick already applies the boost of this query,
// so we can use the wrapped scorer directly:
collector.SetScorer(scorer);
if (scorer.DocID == -1)
{
scorer.NextDoc();
}
while (true)
{
int scorerDoc = scorer.DocID;
if (scorerDoc < maxDoc)
{
if (filterBits.Get(scorerDoc))
{
collector.Collect(scorerDoc);
}
scorer.NextDoc();
}
else
{
break;
}
}
return scorer.DocID != Scorer.NO_MORE_DOCS;
}
}
/// <summary>
/// A <see cref="Scorer"/> that uses a "leap-frog" approach (also called "zig-zag join"). The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// </summary>
private class LeapFrogScorer : Scorer
{
private readonly DocIdSetIterator secondary;
private readonly DocIdSetIterator primary;
private readonly Scorer scorer;
protected int m_primaryDoc = -1;
protected int m_secondaryDoc = -1;
protected internal LeapFrogScorer(Weight weight, DocIdSetIterator primary, DocIdSetIterator secondary, Scorer scorer)
: base(weight)
{
this.primary = primary;
this.secondary = secondary;
this.scorer = scorer;
}
private int AdvanceToNextCommonDoc()
{
for (; ; )
{
if (m_secondaryDoc < m_primaryDoc)
{
m_secondaryDoc = secondary.Advance(m_primaryDoc);
}
else if (m_secondaryDoc == m_primaryDoc)
{
return m_primaryDoc;
}
else
{
m_primaryDoc = primary.Advance(m_secondaryDoc);
}
}
}
public override sealed int NextDoc()
{
m_primaryDoc = PrimaryNext();
return AdvanceToNextCommonDoc();
}
protected virtual int PrimaryNext()
{
return primary.NextDoc();
}
public override sealed int Advance(int target)
{
if (target > m_primaryDoc)
{
m_primaryDoc = primary.Advance(target);
}
return AdvanceToNextCommonDoc();
}
public override sealed int DocID
{
get { return m_secondaryDoc; }
}
public override sealed float GetScore()
{
return scorer.GetScore();
}
public override sealed int Freq
{
get { return scorer.Freq; }
}
public override sealed ICollection<ChildScorer> GetChildren()
{
return new[] { new ChildScorer(scorer, "FILTERED") };
}
public override long GetCost()
{
return Math.Min(primary.GetCost(), secondary.GetCost());
}
}
// TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
private sealed class PrimaryAdvancedLeapFrogScorer : LeapFrogScorer
{
private readonly int firstFilteredDoc;
internal PrimaryAdvancedLeapFrogScorer(Weight weight, int firstFilteredDoc, DocIdSetIterator filterIter, Scorer other)
: base(weight, filterIter, other, other)
{
this.firstFilteredDoc = firstFilteredDoc;
this.m_primaryDoc = firstFilteredDoc; // initialize to prevent and advance call to move it further
}
protected override int PrimaryNext()
{
if (m_secondaryDoc != -1)
{
return base.PrimaryNext();
}
else
{
return firstFilteredDoc;
}
}
}
/// <summary>
/// Rewrites the query. If the wrapped is an instance of
/// <see cref="MatchAllDocsQuery"/> it returns a <see cref="ConstantScoreQuery"/>. Otherwise
/// it returns a new <see cref="FilteredQuery"/> wrapping the rewritten query.
/// </summary>
public override Query Rewrite(IndexReader reader)
{
Query queryRewritten = query.Rewrite(reader);
if (queryRewritten != query)
{
// rewrite to a new FilteredQuery wrapping the rewritten query
Query rewritten = new FilteredQuery(queryRewritten, filter, strategy);
rewritten.Boost = this.Boost;
return rewritten;
}
else
{
// nothing to rewrite, we are done!
return this;
}
}
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s (unfiltered) <see cref="Query"/> </summary>
public Query Query
{
get
{
return query;
}
}
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s filter </summary>
public Filter Filter
{
get
{
return filter;
}
}
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s <seealso cref="FilterStrategy"/> </summary>
public virtual FilterStrategy Strategy
{
get
{
return this.strategy;
}
}
/// <summary>
/// Expert: adds all terms occurring in this query to the terms set. Only
/// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form.
/// </summary>
/// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception>
public override void ExtractTerms(ISet<Term> terms)
{
Query.ExtractTerms(terms);
}
/// <summary>
/// Prints a user-readable version of this query. </summary>
public override string ToString(string s)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("filtered(");
buffer.Append(query.ToString(s));
buffer.Append(")->");
buffer.Append(filter);
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
/// <summary>
/// Returns true if <paramref name="o"/> is equal to this. </summary>
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (!base.Equals(o))
{
return false;
}
Debug.Assert(o is FilteredQuery);
FilteredQuery fq = (FilteredQuery)o;
return fq.query.Equals(this.query) && fq.filter.Equals(this.filter) && fq.strategy.Equals(this.strategy);
}
/// <summary>
/// Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
int hash = base.GetHashCode();
hash = hash * 31 + strategy.GetHashCode();
hash = hash * 31 + query.GetHashCode();
hash = hash * 31 + filter.GetHashCode();
return hash;
}
/// <summary>
/// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if
/// the given <see cref="DocIdSet"/> supports random access (returns a non-null value
/// from <see cref="DocIdSet.Bits"/>) and
/// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns
/// <c>true</c>. Otherwise this strategy falls back to a "zig-zag join" (
/// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy.
///
/// <para>
/// Note: this strategy is the default strategy in <see cref="FilteredQuery"/>
/// </para>
/// </summary>
public static readonly FilterStrategy RANDOM_ACCESS_FILTER_STRATEGY = new RandomAccessFilterStrategy();
/// <summary>
/// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
/// The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// <para>
/// Note: this strategy uses the filter to lead the iteration.
/// </para>
/// </summary>
public static readonly FilterStrategy LEAP_FROG_FILTER_FIRST_STRATEGY = new LeapFrogFilterStrategy(false);
/// <summary>
/// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
/// The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// <para>
/// Note: this strategy uses the query to lead the iteration.
/// </para>
/// </summary>
public static readonly FilterStrategy LEAP_FROG_QUERY_FIRST_STRATEGY = new LeapFrogFilterStrategy(true);
/// <summary>
/// A filter strategy that advances the <see cref="Search.Query"/> or rather its <see cref="Scorer"/> first and consults the
/// filter <see cref="DocIdSet"/> for each matched document.
/// <para>
/// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise
/// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/>
/// </para>
/// <para>
/// Use this strategy if the filter computation is more expensive than document
/// scoring or if the filter has a linear running time to compute the next
/// matching doc like exact geo distances.
/// </para>
/// </summary>
public static readonly FilterStrategy QUERY_FIRST_FILTER_STRATEGY = new QueryFirstFilterStrategy();
/// <summary>
/// Abstract class that defines how the filter (<see cref="DocIdSet"/>) applied during document collection. </summary>
public abstract class FilterStrategy
{
/// <summary>
/// Returns a filtered <see cref="Scorer"/> based on this strategy.
/// </summary>
/// <param name="context">
/// the <see cref="AtomicReaderContext"/> for which to return the <see cref="Scorer"/>. </param>
/// <param name="weight"> the <see cref="FilteredQuery"/> <see cref="Weight"/> to create the filtered scorer. </param>
/// <param name="docIdSet"> the filter <see cref="DocIdSet"/> to apply </param>
/// <returns> a filtered scorer
/// </returns>
/// <exception cref="System.IO.IOException"> if an <see cref="System.IO.IOException"/> occurs </exception>
public abstract Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet);
/// <summary>
/// Returns a filtered <see cref="BulkScorer"/> based on this
/// strategy. this is an optional method: the default
/// implementation just calls <see cref="FilteredScorer(AtomicReaderContext, Weight, DocIdSet)"/> and
/// wraps that into a <see cref="BulkScorer"/>.
/// </summary>
/// <param name="context">
/// the <seealso cref="AtomicReaderContext"/> for which to return the <seealso cref="Scorer"/>. </param>
/// <param name="weight"> the <seealso cref="FilteredQuery"/> <seealso cref="Weight"/> to create the filtered scorer. </param>
/// <param name="scoreDocsInOrder"> <c>true</c> to score docs in order </param>
/// <param name="docIdSet"> the filter <seealso cref="DocIdSet"/> to apply </param>
/// <returns> a filtered top scorer </returns>
public virtual BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet)
{
Scorer scorer = FilteredScorer(context, weight, docIdSet);
if (scorer == null)
{
return null;
}
// this impl always scores docs in order, so we can
// ignore scoreDocsInOrder:
return new Weight.DefaultBulkScorer(scorer);
}
}
/// <summary>
/// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if
/// the given <see cref="DocIdSet"/> supports random access (returns a non-null value
/// from <see cref="DocIdSet.Bits"/>) and
/// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns
/// <code>true</code>. Otherwise this strategy falls back to a "zig-zag join" (
/// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy .
/// </summary>
public class RandomAccessFilterStrategy : FilterStrategy
{
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
DocIdSetIterator filterIter = docIdSet.GetIterator();
if (filterIter == null)
{
// this means the filter does not accept any documents.
return null;
}
int firstFilterDoc = filterIter.NextDoc();
if (firstFilterDoc == DocIdSetIterator.NO_MORE_DOCS)
{
return null;
}
IBits filterAcceptDocs = docIdSet.Bits;
// force if RA is requested
bool useRandomAccess = filterAcceptDocs != null && UseRandomAccess(filterAcceptDocs, firstFilterDoc);
if (useRandomAccess)
{
// if we are using random access, we return the inner scorer, just with other acceptDocs
return weight.GetScorer(context, filterAcceptDocs);
}
else
{
Debug.Assert(firstFilterDoc > -1);
// we are gonna advance() this scorer, so we set inorder=true/toplevel=false
// we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
Scorer scorer = weight.GetScorer(context, null);
// TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
return (scorer == null) ? null : new PrimaryAdvancedLeapFrogScorer(weight, firstFilterDoc, filterIter, scorer);
}
}
/// <summary>
/// Expert: decides if a filter should be executed as "random-access" or not.
/// Random-access means the filter "filters" in a similar way as deleted docs are filtered
/// in Lucene. This is faster when the filter accepts many documents.
/// However, when the filter is very sparse, it can be faster to execute the query+filter
/// as a conjunction in some cases.
/// <para/>
/// The default implementation returns <c>true</c> if the first document accepted by the
/// filter is < 100.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual bool UseRandomAccess(IBits bits, int firstFilterDoc)
{
//TODO once we have a cost API on filters and scorers we should rethink this heuristic
return firstFilterDoc < 100;
}
}
private sealed class LeapFrogFilterStrategy : FilterStrategy
{
private readonly bool scorerFirst;
internal LeapFrogFilterStrategy(bool scorerFirst)
{
this.scorerFirst = scorerFirst;
}
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
DocIdSetIterator filterIter = docIdSet.GetIterator();
if (filterIter == null)
{
// this means the filter does not accept any documents.
return null;
}
// we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
Scorer scorer = weight.GetScorer(context, null);
if (scorer == null)
{
return null;
}
if (scorerFirst)
{
return new LeapFrogScorer(weight, scorer, filterIter, scorer);
}
else
{
return new LeapFrogScorer(weight, filterIter, scorer, scorer);
}
}
}
/// <summary>
/// A filter strategy that advances the <see cref="Scorer"/> first and consults the
/// <see cref="DocIdSet"/> for each matched document.
/// <para>
/// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise
/// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/>
/// </para>
/// <para>
/// Use this strategy if the filter computation is more expensive than document
/// scoring or if the filter has a linear running time to compute the next
/// matching doc like exact geo distances.
/// </para>
/// </summary>
private sealed class QueryFirstFilterStrategy : FilterStrategy
{
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
IBits filterAcceptDocs = docIdSet.Bits;
if (filterAcceptDocs == null)
{
// Filter does not provide random-access Bits; we
// must fallback to leapfrog:
return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredScorer(context, weight, docIdSet);
}
Scorer scorer = weight.GetScorer(context, null);
return scorer == null ? null : new QueryFirstScorer(weight, filterAcceptDocs, scorer);
}
public override BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet) // ignored (we always top-score in order)
{
IBits filterAcceptDocs = docIdSet.Bits;
if (filterAcceptDocs == null)
{
// Filter does not provide random-access Bits; we
// must fallback to leapfrog:
return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredBulkScorer(context, weight, scoreDocsInOrder, docIdSet);
}
Scorer scorer = weight.GetScorer(context, null);
return scorer == null ? null : new QueryFirstBulkScorer(scorer, filterAcceptDocs);
}
}
}
}
| |
// 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.Threading;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
// This class allows you to create an opaque, GC handle to any
// COM+ object. A GC handle is used when an object reference must be
// reachable from unmanaged memory. There are 3 kinds of roots:
// Normal - keeps the object from being collected.
// Weak - allows object to be collected and handle contents will be zeroed.
// Weak references are zeroed before the finalizer runs, so if the
// object is resurrected in the finalizer the weak reference is
// still zeroed.
// WeakTrackResurrection - Same as weak, but stays until after object is
// really gone.
// Pinned - same as normal, but allows the address of the actual object
// to be taken.
//
[StructLayout(LayoutKind.Sequential)]
public struct GCHandle
{
// IMPORTANT: This must be kept in sync with the GCHandleType enum.
private const GCHandleType MaxHandleType = GCHandleType.Pinned;
// Allocate a handle storing the object and the type.
internal GCHandle(Object value, GCHandleType type)
{
// Make sure the type parameter is within the valid range for the enum.
if ((uint)type > (uint)MaxHandleType)
{
throw new ArgumentOutOfRangeException(); // "type", SR.ArgumentOutOfRange_Enum;
}
if (type == GCHandleType.Pinned)
GCHandleValidatePinnedObject(value);
_handle = RuntimeImports.RhHandleAlloc(value, type);
// Record if the handle is pinned.
if (type == GCHandleType.Pinned)
SetIsPinned();
}
// Used in the conversion functions below.
internal GCHandle(IntPtr handle)
{
_handle = handle;
}
// Creates a new GC handle for an object.
//
// value - The object that the GC handle is created for.
// type - The type of GC handle to create.
//
// returns a new GC handle that protects the object.
public static GCHandle Alloc(Object value)
{
return new GCHandle(value, GCHandleType.Normal);
}
public static GCHandle Alloc(Object value, GCHandleType type)
{
return new GCHandle(value, type);
}
// Frees a GC handle.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public void Free()
{
// Copy the handle instance member to a local variable. This is required to prevent
// race conditions releasing the handle.
IntPtr handle = _handle;
// Free the handle if it hasn't already been freed.
if (handle != default(IntPtr) && Interlocked.CompareExchange(ref _handle, default(IntPtr), handle) == handle)
{
#if BIT64
RuntimeImports.RhHandleFree((IntPtr)(((long)handle) & ~1L));
#else
RuntimeImports.RhHandleFree((IntPtr)(((int)handle) & ~1));
#endif
}
else
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
}
// Target property - allows getting / updating of the handle's referent.
public Object Target
{
get
{
// Check if the handle was never initialized or was freed.
if (_handle == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
return RuntimeImports.RhHandleGet(GetHandleValue());
}
set
{
// Check if the handle was never initialized or was freed.
if (_handle == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
RuntimeImports.RhHandleSet(GetHandleValue(), value);
}
}
// Retrieve the address of an object in a Pinned handle. This throws
// an exception if the handle is any type other than Pinned.
public IntPtr AddrOfPinnedObject()
{
// Check if the handle was not a pinned handle.
if (!IsPinned())
{
// Check if the handle was never initialized for was freed.
if (_handle == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
// You can only get the address of pinned handles.
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotPinned);
}
unsafe
{
// Get the address of the pinned object.
// The layout of String and Array is different from Object
Object target = this.Target;
if (target == null)
return default(IntPtr);
String targetAsString = target as String;
if (targetAsString != null)
{
fixed (char* ptr = targetAsString)
{
return (IntPtr)ptr;
}
}
Array targetAsArray = target as Array;
if (targetAsArray != null)
{
fixed (IntPtr* pTargetEEType = &targetAsArray.m_pEEType)
{
return (IntPtr)Array.GetAddrOfPinnedArrayFromEETypeField(pTargetEEType);
}
}
else
{
fixed (IntPtr* pTargetEEType = &target.m_pEEType)
{
return (IntPtr)Object.GetAddrOfPinnedObjectFromEETypeField(pTargetEEType);
}
}
}
}
// Determine whether this handle has been allocated or not.
public bool IsAllocated
{
get
{
return _handle != default(IntPtr);
}
}
// Used to create a GCHandle from an int. This is intended to
// be used with the reverse conversion.
public static explicit operator GCHandle(IntPtr value)
{
return FromIntPtr(value);
}
public static GCHandle FromIntPtr(IntPtr value)
{
if (value == default(IntPtr))
{
throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized);
}
return new GCHandle(value);
}
// Used to get the internal integer representation of the handle out.
public static explicit operator IntPtr(GCHandle value)
{
return ToIntPtr(value);
}
public static IntPtr ToIntPtr(GCHandle value)
{
return value._handle;
}
public override int GetHashCode()
{
return _handle.GetHashCode();
}
public override bool Equals(Object o)
{
GCHandle hnd;
// Check that o is a GCHandle first
if (o == null || !(o is GCHandle))
return false;
else
hnd = (GCHandle)o;
return _handle == hnd._handle;
}
public static bool operator ==(GCHandle a, GCHandle b)
{
return a._handle == b._handle;
}
public static bool operator !=(GCHandle a, GCHandle b)
{
return a._handle != b._handle;
}
internal IntPtr GetHandleValue()
{
#if BIT64
return new IntPtr(((long)_handle) & ~1L);
#else
return new IntPtr(((int)_handle) & ~1);
#endif
}
internal bool IsPinned()
{
#if BIT64
return (((long)_handle) & 1) != 0;
#else
return (((int)_handle) & 1) != 0;
#endif
}
internal void SetIsPinned()
{
#if BIT64
_handle = new IntPtr(((long)_handle) | 1L);
#else
_handle = new IntPtr(((int)_handle) | 1);
#endif
}
//
// C# port of GCHandleValidatePinnedObject(OBJECTREF) in MarshalNative.cpp.
//
private static void GCHandleValidatePinnedObject(Object obj)
{
if (obj == null)
return;
if (obj is String)
return;
EETypePtr eeType = obj.EETypePtr;
if (eeType.IsArray)
{
EETypePtr elementEEType = eeType.ArrayElementType;
if (elementEEType.IsPrimitive)
return;
if (elementEEType.IsValueType && elementEEType.MightBeBlittable())
return;
}
else if (eeType.MightBeBlittable())
{
return;
}
throw new ArgumentException(SR.Argument_NotIsomorphic);
}
// The actual integer handle value that the EE uses internally.
private IntPtr _handle;
}
}
| |
//
// 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 System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Compute Management API includes operations for managing the dns
/// servers for your subscription.
/// </summary>
internal partial class DNSServerOperations : IServiceOperations<ComputeManagementClient>, IDNSServerOperations
{
/// <summary>
/// Initializes a new instance of the DNSServerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DNSServerOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> AddDNSServerAsync(string serviceName, string deploymentName, DNSAddParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "AddDNSServerAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.DnsServer.BeginAddingDNSServerAsync(serviceName, deploymentName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginAddingDNSServerAsync(string serviceName, string deploymentName, DNSAddParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginAddingDNSServerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/dnsservers";
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement dnsServerElement = new XElement(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(dnsServerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
dnsServerElement.Add(nameElement);
}
if (parameters.Address != null)
{
XElement addressElement = new XElement(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
addressElement.Value = parameters.Address;
dnsServerElement.Add(addressElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// 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.Accepted)
{
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
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
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>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginDeletingDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (dnsServerName == null)
{
throw new ArgumentNullException("dnsServerName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingDNSServerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/dnsservers/";
url = url + Uri.EscapeDataString(dnsServerName);
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.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-03-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.Accepted)
{
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
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
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 a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginUpdatingDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (dnsServerName == null)
{
throw new ArgumentNullException("dnsServerName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdatingDNSServerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/dnsservers/";
url = url + Uri.EscapeDataString(dnsServerName);
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("x-ms-version", "2016-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement dnsServerElement = new XElement(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(dnsServerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
dnsServerElement.Add(nameElement);
}
if (parameters.Address != null)
{
XElement addressElement = new XElement(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
addressElement.Value = parameters.Address;
dnsServerElement.Add(addressElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// 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.Accepted)
{
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
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
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>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> DeleteDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
TracingAdapter.Enter(invocationId, this, "DeleteDNSServerAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.DnsServer.BeginDeletingDNSServerAsync(serviceName, deploymentName, dnsServerName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Updates a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> UpdateDNSServerAsync(string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("dnsServerName", dnsServerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateDNSServerAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.DnsServer.BeginUpdatingDNSServerAsync(serviceName, deploymentName, dnsServerName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
public partial struct ImmutableArray<T>
{
/// <summary>
/// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/>
/// instance without allocating memory.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))]
public sealed class Builder : IList<T>, IReadOnlyList<T>
{
/// <summary>
/// The backing array for the builder.
/// </summary>
private T[] _elements;
/// <summary>
/// The number of initialized elements in the array.
/// </summary>
private int _count;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of the internal array.</param>
internal Builder(int capacity)
{
Requires.Range(capacity >= 0, "capacity");
_elements = new T[capacity];
_count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
internal Builder()
: this(8)
{
}
/// <summary>
/// Get and sets the length of the internal array. When set the internal array is
/// reallocated to the given capacity if it is not already the specified length.
/// </summary>
public int Capacity
{
get { return _elements.Length; }
set
{
if (value < _count)
{
throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, paramName: "value");
}
if (value != _elements.Length)
{
if (value > 0)
{
var temp = new T[value];
if (_count > 0)
{
Array.Copy(_elements, 0, temp, 0, _count);
}
_elements = temp;
}
else
{
_elements = ImmutableArray<T>.Empty.array;
}
}
}
}
/// <summary>
/// Gets or sets the length of the builder.
/// </summary>
/// <remarks>
/// If the value is decreased, the array contents are truncated.
/// If the value is increased, the added elements are initialized to the default value of type <typeparamref name="T"/>.
/// </remarks>
public int Count
{
get
{
return _count;
}
set
{
Requires.Range(value >= 0, "value");
if (value < _count)
{
// truncation mode
// Clear the elements of the elements that are effectively removed.
// PERF: Array.Clear works well for big arrays,
// but may have too much overhead with small ones (which is the common case here)
if (_count - value > 64)
{
Array.Clear(_elements, value, _count - value);
}
else
{
for (int i = value; i < this.Count; i++)
{
_elements[i] = default(T);
}
}
}
else if (value > _count)
{
// expansion
this.EnsureCapacity(value);
}
_count = value;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public T this[int index]
{
get
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
return _elements[index];
}
set
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
_elements[index] = value;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Returns an immutable copy of the current contents of this collection.
/// </summary>
/// <returns>An immutable array.</returns>
public ImmutableArray<T> ToImmutable()
{
if (Count == 0)
{
return Empty;
}
return new ImmutableArray<T>(this.ToArray());
}
/// <summary>
/// Extracts the internal array as an <see cref="ImmutableArray{T}"/> and replaces it
/// with a zero length array.
/// </summary>
/// <exception cref="InvalidOperationException">When <see cref="ImmutableArray{T}.Builder.Count"/> doesn't
/// equal <see cref="ImmutableArray{T}.Builder.Capacity"/>.</exception>
public ImmutableArray<T> MoveToImmutable()
{
if (Capacity != Count)
{
throw new InvalidOperationException(SR.CapacityMustEqualCountOnMove);
}
T[] temp = _elements;
_elements = ImmutableArray<T>.Empty.array;
_count = 0;
return new ImmutableArray<T>(temp);
}
/// <summary>
/// Removes all items from the <see cref="ICollection{T}"/>.
/// </summary>
public void Clear()
{
this.Count = 0;
}
/// <summary>
/// Inserts an item to the <see cref="IList{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param>
public void Insert(int index, T item)
{
Requires.Range(index >= 0 && index <= this.Count, "index");
this.EnsureCapacity(this.Count + 1);
if (index < this.Count)
{
Array.Copy(_elements, index, _elements, index + 1, this.Count - index);
}
_count++;
_elements[index] = item;
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param>
public void Add(T item)
{
this.EnsureCapacity(this.Count + 1);
_elements[_count++] = item;
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<T> items)
{
Requires.NotNull(items, "items");
int count;
if (items.TryGetCount(out count))
{
this.EnsureCapacity(this.Count + count);
}
foreach (var item in items)
{
this.Add(item);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(params T[] items)
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(TDerived[] items) where TDerived : T
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(T[] items, int length)
{
Requires.NotNull(items, "items");
Requires.Range(length >= 0 && length <= items.Length, "length");
var offset = this.Count;
this.Count += length;
Array.Copy(items, 0, _elements, offset, length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(ImmutableArray<T> items)
{
this.AddRange(items, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(ImmutableArray<T> items, int length)
{
Requires.Range(length >= 0, "length");
if (items.array != null)
{
this.AddRange(items.array, length);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T
{
if (items.array != null)
{
this.AddRange(items.array);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(Builder items)
{
Requires.NotNull(items, "items");
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T
{
Requires.NotNull(items, "items");
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Removes the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>A value indicating whether the specified element was found and removed from the collection.</returns>
public bool Remove(T element)
{
int index = this.IndexOf(element);
if (index >= 0)
{
this.RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Removes the <see cref="IList{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, "index");
if (index < this.Count - 1)
{
Array.Copy(_elements, index + 1, _elements, index, this.Count - index - 1);
}
this.Count--;
}
/// <summary>
/// Determines whether the <see cref="ICollection{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false.
/// </returns>
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
/// <summary>
/// Creates a new array with the current contents of this Builder.
/// </summary>
public T[] ToArray()
{
T[] result = new T[this.Count];
Array.Copy(_elements, 0, result, 0, this.Count);
return result;
}
/// <summary>
/// Copies the current contents to the specified array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="index">The starting index of the target array.</param>
public void CopyTo(T[] array, int index)
{
Requires.NotNull(array, "array");
Requires.Range(index >= 0 && index + this.Count <= array.Length, "start");
Array.Copy(_elements, 0, array, index, this.Count);
}
/// <summary>
/// Resizes the array to accommodate the specified capacity requirement.
/// </summary>
/// <param name="capacity">The required capacity.</param>
private void EnsureCapacity(int capacity)
{
if (_elements.Length < capacity)
{
int newCapacity = Math.Max(_elements.Length * 2, capacity);
Array.Resize(ref _elements, newCapacity);
}
}
/// <summary>
/// Determines the index of a specific item in the <see cref="IList{T}"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="IList{T}"/>.</param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
[Pure]
public int IndexOf(T item)
{
return this.IndexOf(item, 0, _count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex)
{
return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count)
{
return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(equalityComparer, "equalityComparer");
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex + count <= this.Count, "count");
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.IndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i < startIndex + count; i++)
{
if (equalityComparer.Equals(_elements[i], item))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item)
{
if (this.Count == 0)
{
return -1;
}
return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex)
{
if (this.Count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count)
{
return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(equalityComparer, "equalityComparer");
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count");
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.LastIndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i >= startIndex - count + 1; i--)
{
if (equalityComparer.Equals(item, _elements[i]))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Reverses the order of elements in the collection.
/// </summary>
public void Reverse()
{
// The non-generic Array.Reverse is not used because it does not perform
// well for non-primitive value types.
// If/when a generic Array.Reverse<T> becomes available, the below code
// can be deleted and replaced with a call to Array.Reverse<T>.
int i = 0;
int j = _count - 1;
T[] array = _elements;
while (i < j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
/// <summary>
/// Sorts the array.
/// </summary>
public void Sort()
{
if (Count > 1)
{
Array.Sort(_elements, 0, this.Count, Comparer<T>.Default);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(IComparer<T> comparer)
{
if (Count > 1)
{
Array.Sort(_elements, 0, _count, comparer);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="index">The index of the first element to consider in the sort.</param>
/// <param name="count">The number of elements to include in the sort.</param>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(int index, int count, IComparer<T> comparer)
{
// Don't rely on Array.Sort's argument validation since our internal array may exceed
// the bounds of the publicly addressable region.
Requires.Range(index >= 0, "index");
Requires.Range(count >= 0 && index + count <= this.Count, "count");
if (count > 1)
{
Array.Sort(_elements, index, count, comparer);
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < this.Count; i++)
{
yield return this[i];
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Adds items to this collection.
/// </summary>
/// <typeparam name="TDerived">The type of source elements.</typeparam>
/// <param name="items">The source array.</param>
/// <param name="length">The number of elements to add to this array.</param>
private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T
{
this.EnsureCapacity(this.Count + length);
var offset = this.Count;
this.Count += length;
var nodes = _elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i] = items[i];
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal sealed class ImmutableArrayBuilderDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableArray<T>.Builder _builder;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy{T}"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder)
{
_builder = builder;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
return _builder.ToArray();
}
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. 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.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Returns a projection of tuples, where each tuple contains the N-th
/// element from each of the argument sequences.
/// </summary>
/// <typeparam name="TFirst">Type of elements in first sequence.</typeparam>
/// <typeparam name="TSecond">Type of elements in second sequence.</typeparam>
/// <typeparam name="TResult">Type of elements in result sequence.</typeparam>
/// <param name="first">The first sequence.</param>
/// <param name="second">The second sequence.</param>
/// <param name="resultSelector">
/// Function to apply to each pair of elements.</param>
/// <returns>
/// A sequence that contains elements of the two input sequences,
/// combined by <paramref name="resultSelector"/>.
/// </returns>
/// <example>
/// <code><![CDATA[
/// var numbers = new[] { 1, 2, 3, 4 };
/// var letters = new[] { "A", "B", "C", "D" };
/// var zipped = numbers.EquiZip(letters, (n, l) => n + l);
/// ]]></code>
/// The <c>zipped</c> variable, when iterated over, will yield "1A",
/// "2B", "3C", "4D" in turn.
/// </example>
/// <remarks>
/// <para>
/// If the two input sequences are of different lengths then
/// <see cref="InvalidOperationException"/> is thrown.</para>
/// <para>
/// This operator uses deferred execution and streams its results.</para>
/// </remarks>
public static IEnumerable<TResult> EquiZip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
return EquiZipImpl<TFirst, TSecond, object, object, TResult>(first, second, null, null, (a, b, c, d) => resultSelector(a, b));
}
/// <summary>
/// Returns a projection of tuples, where each tuple contains the N-th
/// element from each of the argument sequences.
/// </summary>
/// <typeparam name="T1">Type of elements in first sequence.</typeparam>
/// <typeparam name="T2">Type of elements in second sequence.</typeparam>
/// <typeparam name="T3">Type of elements in third sequence.</typeparam>
/// <typeparam name="TResult">Type of elements in result sequence.</typeparam>
/// <param name="first">The first sequence.</param>
/// <param name="second">The second sequence.</param>
/// <param name="third">The third sequence.</param>
/// <param name="resultSelector">
/// Function to apply to each triplet of elements.</param>
/// <returns>
/// A sequence that contains elements of the three input sequences,
/// combined by <paramref name="resultSelector"/>.
/// </returns>
/// <example>
/// <code><![CDATA[
/// var numbers = new[] { 1, 2, 3, 4 };
/// var letters = new[] { "A", "B", "C", "D" };
/// var chars = new[] { 'a', 'b', 'c', 'd' };
/// var zipped = numbers.EquiZip(letters, chars, (n, l, c) => n + l + c);
/// ]]></code>
/// The <c>zipped</c> variable, when iterated over, will yield "1Aa",
/// "2Bb", "3Cc", "4Dd" in turn.
/// </example>
/// <remarks>
/// <para>If the three input sequences are of different lengths then
/// <see cref="InvalidOperationException"/> is thrown.</para>
/// <para>
/// This operator uses deferred execution and streams its results.</para>
/// </remarks>
public static IEnumerable<TResult> EquiZip<T1, T2, T3, TResult>(
this IEnumerable<T1> first,
IEnumerable<T2> second, IEnumerable<T3> third,
Func<T1, T2, T3, TResult> resultSelector)
{
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
if (third == null) throw new ArgumentNullException(nameof(third));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
return EquiZipImpl<T1, T2, T3, object, TResult>(first, second, third, null, (a, b, c, _) => resultSelector(a, b, c));
}
/// <summary>
/// Returns a projection of tuples, where each tuple contains the N-th
/// element from each of the argument sequences.
/// </summary>
/// <typeparam name="T1">Type of elements in first sequence</typeparam>
/// <typeparam name="T2">Type of elements in second sequence</typeparam>
/// <typeparam name="T3">Type of elements in third sequence</typeparam>
/// <typeparam name="T4">Type of elements in fourth sequence</typeparam>
/// <typeparam name="TResult">Type of elements in result sequence</typeparam>
/// <param name="first">The first sequence.</param>
/// <param name="second">The second sequence.</param>
/// <param name="third">The third sequence.</param>
/// <param name="fourth">The fourth sequence.</param>
/// <param name="resultSelector">
/// Function to apply to each quadruplet of elements.</param>
/// <returns>
/// A sequence that contains elements of the four input sequences,
/// combined by <paramref name="resultSelector"/>.
/// </returns>
/// <example>
/// <code><![CDATA[
/// var numbers = new[] { 1, 2, 3, 4 };
/// var letters = new[] { "A", "B", "C", "D" };
/// var chars = new[] { 'a', 'b', 'c', 'd' };
/// var flags = new[] { true, false, true, false };
/// var zipped = numbers.EquiZip(letters, chars, flags, (n, l, c, f) => n + l + c + f);
/// ]]></code>
/// The <c>zipped</c> variable, when iterated over, will yield "1AaTrue",
/// "2BbFalse", "3CcTrue", "4DdFalse" in turn.
/// </example>
/// <remarks>
/// <para>
/// If the four input sequences are of different lengths then
/// <see cref="InvalidOperationException"/> is thrown.</para>
/// <para>
/// This operator uses deferred execution and streams its results.</para>
/// </remarks>
public static IEnumerable<TResult> EquiZip<T1, T2, T3, T4, TResult>(
this IEnumerable<T1> first,
IEnumerable<T2> second, IEnumerable<T3> third, IEnumerable<T4> fourth,
Func<T1, T2, T3, T4, TResult> resultSelector)
{
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
if (third == null) throw new ArgumentNullException(nameof(third));
if (fourth == null) throw new ArgumentNullException(nameof(fourth));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
return EquiZipImpl(first, second, third, fourth, resultSelector);
}
static IEnumerable<TResult> EquiZipImpl<T1, T2, T3, T4, TResult>(
IEnumerable<T1> s1,
IEnumerable<T2> s2,
IEnumerable<T3> s3,
IEnumerable<T4> s4,
Func<T1, T2, T3, T4, TResult> resultSelector)
{
Debug.Assert(s1 != null);
Debug.Assert(s2 != null);
const int zero = 0, one = 1;
var limit = 1 + (s3 != null ? one : zero)
+ (s4 != null ? one : zero);
return ZipImpl(s1, s2, s3, s4, resultSelector, limit, enumerators =>
{
var i = enumerators.Index().First(x => x.Value == null).Key;
return new InvalidOperationException(OrdinalNumbers[i] + " sequence too short.");
});
}
static readonly string[] OrdinalNumbers =
{
"First",
"Second",
"Third",
"Fourth",
// "Fifth",
// "Sixth",
// "Seventh",
// "Eighth",
// "Ninth",
// "Tenth",
// "Eleventh",
// "Twelfth",
// "Thirteenth",
// "Fourteenth",
// "Fifteenth",
// "Sixteenth",
};
}
}
| |
using Microsoft.Toolkit.Mvvm.Messaging;
using MvvmScarletToolkit.Observables;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Input;
namespace MvvmScarletToolkit
{
// manages
// https://github.com/tom-englert/DataGridExtensions
// http://dotnetpattern.com/wpf-datagrid-grouping
public sealed class GroupingViewModel : BusinessViewModelListBase<GroupsViewModel>
{
public static GroupingViewModel Create<T>(IEnumerable<T> collection)
where T : class, INotifyPropertyChanged
{
return Create(ScarletCommandBuilder.Default, collection);
}
public static GroupingViewModel Create<T>(IScarletCommandBuilder commandBuilder, IEnumerable<T> collection)
where T : class, INotifyPropertyChanged
{
return new GroupingViewModel(commandBuilder, () => (ListCollectionView)CollectionViewSource.GetDefaultView(collection), typeof(T));
}
public static GroupingViewModel Create<T>(IScarletCommandBuilder commandBuilder, Func<ListCollectionView> collectionViewFactory)
where T : class, INotifyPropertyChanged
{
return new GroupingViewModel(commandBuilder, collectionViewFactory, typeof(T));
}
private readonly ConcurrentDictionary<string, GroupViewModel> _filterCollection;
private readonly Func<ListCollectionView> _collectionViewFactory;
private readonly Type _type;
private int _maxGroupings;
private ListCollectionView? _view;
private bool _isLiveGroupingEnabled;
public bool IsLiveGroupingEnabled
{
get { return _isLiveGroupingEnabled; }
set
{
if (SetProperty(ref _isLiveGroupingEnabled, value))
{
if (_view is null)
{
return;
}
_view.IsLiveGrouping = value;
}
}
}
private bool _isLiveSortingEnabled;
public bool IsLiveSortingEnabled
{
get { return _isLiveSortingEnabled; }
set
{
if (SetProperty(ref _isLiveSortingEnabled, value))
{
if (_view is null)
{
return;
}
using (_view.DeferRefresh())
{
//var descriptions = _view.SortDescriptions.Cast<SortDescription>().DistinctBy(p => p.PropertyName).ToArray();
//_view.SortDescriptions.Clear();
_view.IsLiveSorting = value;
//_view.SortDescriptions.AddRange(descriptions);
}
}
}
}
public ICommand AddCommand { get; }
public override ICommand RemoveCommand { get; }
private GroupingViewModel(IScarletCommandBuilder commandBuilder, Func<ListCollectionView> collectionViewFactory, Type type)
: base(commandBuilder)
{
_type = type ?? throw new ArgumentNullException(nameof(type));
_filterCollection = new ConcurrentDictionary<string, GroupViewModel>();
_collectionViewFactory = collectionViewFactory ?? throw new ArgumentNullException(nameof(collectionViewFactory));
AddCommand = commandBuilder.Create(Add, CanAdd)
.WithBusyNotification(BusyStack)
.WithSingleExecution()
.WithCancellation()
.Build();
RemoveCommand = commandBuilder
.Create<GroupsViewModel>((p, t) => Remove(p, t), (p) => CanRemove(p))
.WithSingleExecution()
.WithBusyNotification(BusyStack)
.WithCancellation()
.Build();
Messenger.Register<GroupingViewModel, ViewModelListBaseSelectionChanging<GroupViewModel>>(this, (r, m) =>
{
if (m.Value is null)
{
return;
}
r._filterCollection.TryAdd(m.Value.Name, m.Value);
});
Messenger.Register<GroupingViewModel, ViewModelListBaseSelectionChanged<GroupViewModel>>(this, (r, m) =>
{
if (m.Value is null)
{
return;
}
r._filterCollection.TryRemove(m.Value.Name, out var _);
});
}
private ListCollectionView GetCollectionView()
{
_view ??= _collectionViewFactory.Invoke();
using (_view.DeferRefresh())
{
_view.IsLiveGrouping = _isLiveGroupingEnabled;
_view.IsLiveSorting = _isLiveSortingEnabled;
}
return _view;
}
public override async Task Remove(GroupsViewModel item, CancellationToken token)
{
await base.Remove(item, token).ConfigureAwait(false);
Messenger.Send(new GroupsViewModelRemoved(item));
var description = item.SelectedItem?.GroupDescription;
if (!(description is null))
{
await Dispatcher.Invoke(() => _view?.GroupDescriptions.Remove(description)).ConfigureAwait(false);
}
if (!(item.SelectedItem is null))
{
_filterCollection.TryAdd(item.SelectedItem.Name, item.SelectedItem);
}
}
protected override Task RefreshInternal(CancellationToken token)
{
_filterCollection.Clear();
return Task.Run(() =>
{
_type
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead && p.GetGetMethod(true)?.IsPublic == true)
.Select(p => new GroupViewModel(CommandBuilder, p))
.Select(p => new KeyValuePair<string, GroupViewModel>(p.Name, p))
.ForEach(p => _filterCollection.TryAdd(p.Key, p.Value));
_maxGroupings = _filterCollection.Count;
});
}
private async Task Add(CancellationToken token)
{
var result = new GroupsViewModel(CommandBuilder, GetCollectionView);
await result.AddRange(_filterCollection.Values).ConfigureAwait(false);
await Add(result).ConfigureAwait(false);
}
private bool CanAdd()
{
return !IsDisposed
&& !IsBusy
&& _filterCollection?.Count > 0
&& _maxGroupings > Count;
}
public override async Task Clear(CancellationToken token)
{
for (var i = 0; i < _items.Count; i++)
{
var item = _items[i];
item.Dispose();
}
await base.Clear(token).ConfigureAwait(false);
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractInt16()
{
var test = new SimpleBinaryOpTest__SubtractInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractInt16 testClass)
{
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__SubtractInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Subtract(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Subtract(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Subtract(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractInt16();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Subtract(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(left[0] - right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(left[i] - right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
/// <summary>
/// String.Join(String, String[], Int32, Int32)
/// Concatenates a specified separator String between each
/// element of a specified String array, yielding a single concatenated string.
/// Parameters specify the first array element and number of elements to use.
/// </summary>
class StringJoin2
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
private const int c_MIN_STR_ARRAY_LEN = 4;
private const int c_MAX_STR_ARRAY_LEN = 127;
private const int c_SUPER_MAX_INTEGER = 1 << 17;
public static int Main()
{
StringJoin2 si = new StringJoin2();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.Join(String, String[], Int32, Int32)");
if (si.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
//retVal = NegTest5() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Random separator and random string array, positive count";
const string c_TEST_ID = "P001";
string separator, joinedStr;
int startIndex, count;
bool condition1 = false; //Used to verify the element of the string array
bool condition2 = false; //used to verify the separator
bool expectedValue, actualValue;
int i, j, startIndex1, startIndex2;
string[] strs;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
//strs = new string[] { "AAAA", "BBBBB", "CCCCCC", "ddd", "EEEE"};
separator = TestLibrary.Generator.GetString(-55, false, 1, c_MAX_STRING_LEN);
//separator = "&&";
startIndex = GetInt32(0, strs.GetLength(0) - 1);
//startIndex = 1;
count = GetInt32(1, strs.GetLength(0) - startIndex);
//count = 1;
try
{
joinedStr = string.Join(separator, strs, startIndex, count);
string[] strsUsed = new string[count];
for (int m = 0; m < count; m++)
{
strsUsed[m] = strs[startIndex + m];
}
i = GetInt32(0, strsUsed.GetLength(0) - 1);
//i = 1;
//Get source array element's start position of the joined string
startIndex1 = 0;
for (int m = i; m > 0;)
{
startIndex1 += separator.Length + strsUsed[--m].Length;
}
condition1 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex1, strsUsed[i].Length), strsUsed[i]));
if (strsUsed.GetLength(0) > 1)
{
//Index of separator
j = GetInt32(0, strsUsed.GetLength(0) - 2);
startIndex2 = 0;
while(j>0)
{
startIndex2 += strsUsed[j--].Length + separator.Length;
}
startIndex2 += strsUsed[0].Length;
condition2 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex2, separator.Length), separator));
}
else
{
condition2 = true;
}
expectedValue = true;
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strs, separator, startIndex, count);
TestLibrary.TestFramework.LogError("001" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strs, separator, startIndex, count));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Random separator and random string array, count is zero";
const string c_TEST_ID = "P002";
string separator, joinedStr;
int startIndex, count;
bool expectedValue, actualValue;
string[] strs;
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
separator = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = GetInt32(0, strs.GetLength(0) - 1);
count = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
joinedStr = string.Join(separator, strs, startIndex, count);
expectedValue = true;
actualValue = (joinedStr == String.Empty);
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("003" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Separator is null, random string array, positive count";
const string c_TEST_ID = "P003";
string separator, joinedStr;
int startIndex, count;
bool condition1 = false; //Used to verify the element of the string array
bool condition2 = false; //used to verify the separator
bool expectedValue, actualValue;
int i, j, startIndex1, startIndex2;
string[] strs;
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
separator = null;
startIndex = GetInt32(0, strs.GetLength(0) - 1);
count = GetInt32(1, strs.GetLength(0) - startIndex);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
joinedStr = string.Join(separator, strs, startIndex, count);
separator = string.Empty;
string[] strsUsed = new string[count];
for (int m = 0; m < count; m++)
{
strsUsed[m] = strs[startIndex + m];
}
i = GetInt32(0, strsUsed.GetLength(0) - 1);
//Get source array element's start position of the joined string
startIndex1 = 0;
for (int m = i; m > 0; )
{
startIndex1 += separator.Length + strsUsed[--m].Length;
}
condition1 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex1, strsUsed[i].Length), strsUsed[i]));
if (strsUsed.GetLength(0) > 1)
{
//Index of separator
j = GetInt32(0, strsUsed.GetLength(0) - 2);
startIndex2 = 0;
while (j > 0)
{
startIndex2 += strsUsed[j--].Length + separator.Length;
}
startIndex2 += strsUsed[0].Length;
condition2 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex2, separator.Length), separator));
}
else
{
condition2 = true;
}
expectedValue = true;
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("005" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Start element is the last element of array, count of joined is 1";
const string c_TEST_ID = "P004";
string separator, joinedStr;
int startIndex, count;
bool condition1 = false; //Used to verify the element of the string array
bool condition2 = false; //used to verify the separator
bool expectedValue, actualValue;
int i, j, startIndex1, startIndex2;
string[] strs;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
//strs = new string[] { "AAAA", "BBBBB", "CCCCCC", "ddd", "EEEE"};
separator = TestLibrary.Generator.GetString(-55, false, 1, c_MAX_STRING_LEN);
//separator = "&&";
startIndex = strs.GetLength(0) - 1;
count = GetInt32(1, strs.GetLength(0) - startIndex);
count = 1;
try
{
joinedStr = string.Join(separator, strs, startIndex, count);
string[] strsUsed = new string[count];
for (int m = 0; m < count; m++)
{
strsUsed[m] = strs[startIndex + m];
}
i = GetInt32(0, strsUsed.GetLength(0) - 1);
//i = 1;
//Get source array element's start position of the joined string
startIndex1 = 0;
for (int m = i; m > 0; )
{
startIndex1 += separator.Length + strsUsed[--m].Length;
}
condition1 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex1, strsUsed[i].Length), strsUsed[i]));
if (strsUsed.GetLength(0) > 1)
{
//Index of separator
j = GetInt32(0, strsUsed.GetLength(0) - 2);
startIndex2 = 0;
while (j > 0)
{
startIndex2 += strsUsed[j--].Length + separator.Length;
}
startIndex2 += strsUsed[0].Length;
condition2 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex2, separator.Length), separator));
}
else
{
condition2 = true;
}
expectedValue = true;
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strs, separator, startIndex, count);
TestLibrary.TestFramework.LogError("007" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strs, separator, startIndex, count));
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5: Start element is the first element of array, join all elements of array";
const string c_TEST_ID = "P005";
string separator, joinedStr;
int startIndex, count;
bool condition1 = false; //Used to verify the element of the string array
bool condition2 = false; //used to verify the separator
bool expectedValue, actualValue;
int i, j, startIndex1, startIndex2;
string[] strs;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
separator = TestLibrary.Generator.GetString(-55, false, 1, c_MAX_STRING_LEN);
startIndex =0;
count =strs.GetLength(0);
try
{
joinedStr = string.Join(separator, strs, startIndex, count);
string[] strsUsed = new string[count];
for (int m = 0; m < count; m++)
{
strsUsed[m] = strs[startIndex + m];
}
i = GetInt32(0, strsUsed.GetLength(0) - 1);
//i = 1;
//Get source array element's start position of the joined string
startIndex1 = 0;
for (int m = i; m > 0; )
{
startIndex1 += separator.Length + strsUsed[--m].Length;
}
condition1 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex1, strsUsed[i].Length), strsUsed[i]));
if (strsUsed.GetLength(0) > 1)
{
//Index of separator
j = GetInt32(0, strsUsed.GetLength(0) - 2);
startIndex2 = 0;
while (j > 0)
{
startIndex2 += strsUsed[j--].Length + separator.Length;
}
startIndex2 += strsUsed[0].Length;
condition2 = (0 == String.CompareOrdinal(joinedStr.Substring(startIndex2, separator.Length), separator));
}
else
{
condition2 = true;
}
expectedValue = true;
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strs, separator, startIndex, count);
TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strs, separator, startIndex, count));
retVal = false;
}
return retVal;
}
#endregion
#region Negative test scenairos
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: The string array is a null reference";
const string c_TEST_ID = "N001";
string separator;
string[] strs;
int startIndex, count;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
separator = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strs = null;
startIndex = 0;
count = 0;
String.Join(separator, strs, startIndex, count);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "ArgumentNullException is not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: The start index of array is a negative value";
const string c_TEST_ID = "N002";
string separator;
string[] strs;
int startIndex, count;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
separator = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
startIndex = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
count = 0;
String.Join(separator, strs, startIndex, count);
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: The count of array elements to join is a negative value";
const string c_TEST_ID = "N003";
string separator;
string[] strs;
int startIndex, count;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
separator = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
startIndex = 0;
count = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
String.Join(separator, strs, startIndex, count);
TestLibrary.TestFramework.LogError("015" + "TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: The start index plus joined count is greater than numbers of elements in string array";
const string c_TEST_ID = "N004";
string separator;
string[] strs;
int startIndex, count;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
separator = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strs = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STR_ARRAY_LEN, c_MAX_STR_ARRAY_LEN);
startIndex = TestLibrary.Generator.GetInt32(-55);
count = strs.GetLength(0) - startIndex + GetInt32(1, Int32.MaxValue - strs.GetLength(0));
String.Join(separator, strs, startIndex, count);
TestLibrary.TestFramework.LogError("017" + "TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest5() //bug
{
bool retVal = true;
const string c_TEST_DESC = "NegTest5: Out of memory";
const string c_TEST_ID = "N005";
string separator;
string[] strs;
int startIndex, count;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
separator = new string(TestLibrary.Generator.GetChar(-55), c_SUPER_MAX_INTEGER);
strs = new string[c_SUPER_MAX_INTEGER];
//for (int i = 0; i < strs.GetLength(0); i++)
//{
// strs[i] = new string(TestLibrary.Generator.GetChar(-55), 1);
//}
startIndex = 0;
count = strs.GetLength(0);
string joinedStr = String.Join(separator, strs, startIndex, count);
TestLibrary.TestFramework.LogError("019" + "TestId-" + c_TEST_ID, "OutOfMemoryException is not thrown as expected");
retVal = false;
}
catch (OutOfMemoryException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
private string GetDataString(string[] strs, string separator, int startIndex, int count)
{
string str1, str2, str;
int len1, len2;
str2 = string.Empty;
if (null == separator)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = separator;
len1 = separator.Length;
}
if (null == strs)
{
str2 = "null";
len2 = 0;
}
else
{
len2 = strs.GetLength(0);
for (int i = 0; i < len2; i++)
{
str2 += "\n" + strs[i];
}
}
str = string.Format("\n[String array value]\n \"{0}\"", str2);
str += string.Format("\n[Separator string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of string array]\n \"{0}\"", len2);
str += string.Format("\n[Length of separator string]\n \"{0}\"", len1);
str += string.Format("\n[Joined elements start index]: {0}", startIndex);
str += string.Format("\n[Joined elements count]: {0}", count);
return str;
}
}
| |
// 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.Diagnostics;
using System.Reflection.Metadata;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RuntimeMembers
{
/// <summary>
/// Helper class to match signatures in format of
/// MemberDescriptor.Signature to members.
/// </summary>
internal abstract class SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol>
where MethodSymbol : class
where FieldSymbol : class
where PropertySymbol : class
where TypeSymbol : class
where ParameterSymbol : class
{
/// <summary>
/// Returns true if signature matches signature of the field.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchFieldSignature(FieldSymbol field, ImmutableArray<byte> signature)
{
int position = 0;
// get the type
bool result = MatchType(GetFieldType(field), signature, ref position);
Debug.Assert(!result || position == signature.Length);
return result;
}
/// <summary>
/// Returns true if signature matches signature of the property.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchPropertySignature(PropertySymbol property, ImmutableArray<byte> signature)
{
int position = 0;
// Get the parameter count
int paramCount = signature[position++];
// Get all of the parameters.
ImmutableArray<ParameterSymbol> parameters = GetParameters(property);
if (paramCount != parameters.Length)
{
return false;
}
// get the property type
if (!MatchType(GetPropertyType(property), signature, ref position))
{
return false;
}
// Match parameters
foreach (ParameterSymbol parameter in parameters)
{
if (!MatchParameter(parameter, signature, ref position))
{
return false;
}
}
Debug.Assert(position == signature.Length);
return true;
}
/// <summary>
/// Returns true if signature matches signature of the method.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchMethodSignature(MethodSymbol method, ImmutableArray<byte> signature)
{
int position = 0;
// Get the parameter count
int paramCount = signature[position++];
// Get all of the parameters.
ImmutableArray<ParameterSymbol> parameters = GetParameters(method);
if (paramCount != parameters.Length)
{
return false;
}
// get the return type
if (!MatchType(GetReturnType(method), signature, ref position))
{
return false;
}
// Match parameters
foreach (ParameterSymbol parameter in parameters)
{
if (!MatchParameter(parameter, signature, ref position))
{
return false;
}
}
Debug.Assert(position == signature.Length);
return true;
}
private bool MatchParameter(ParameterSymbol parameter, ImmutableArray<byte> signature, ref int position)
{
SignatureTypeCode typeCode = (SignatureTypeCode)signature[position];
bool isByRef;
if (typeCode == SignatureTypeCode.ByReference)
{
isByRef = true;
position++;
}
else
{
isByRef = false;
}
if (IsByRefParam(parameter) != isByRef)
{
return false;
}
return MatchType(GetParamType(parameter), signature, ref position);
}
/// <summary>
/// Does pretty much the same thing as MetadataDecoder.DecodeType only instead of
/// producing a type symbol it compares encoded type to the target.
///
/// Signature should be in format described in MemberDescriptor.
/// </summary>
private bool MatchType(TypeSymbol type, ImmutableArray<byte> signature, ref int position)
{
if (type == null)
{
return false;
}
int paramPosition;
// Get the type.
SignatureTypeCode typeCode = (SignatureTypeCode)signature[position++];
// Switch on the type.
switch (typeCode)
{
case SignatureTypeCode.TypeHandle:
// Ecma-335 spec:
// 23.1.16 Element types used in signatures
// ...
// ELEMENT_TYPE_VALUETYPE 0x11 Followed by TypeDef or TypeRef token
// ELEMENT_TYPE_CLASS 0x12 Followed by TypeDef or TypeRef token
short expectedType = ReadTypeId(signature, ref position);
return MatchTypeToTypeId(type, expectedType);
case SignatureTypeCode.Array:
if (!MatchType(GetMDArrayElementType(type), signature, ref position))
{
return false;
}
int countOfDimensions = signature[position++];
return MatchArrayRank(type, countOfDimensions);
case SignatureTypeCode.SZArray:
return MatchType(GetSZArrayElementType(type), signature, ref position);
case SignatureTypeCode.Pointer:
return MatchType(GetPointedToType(type), signature, ref position);
case SignatureTypeCode.GenericTypeParameter:
paramPosition = signature[position++];
return IsGenericTypeParam(type, paramPosition);
case SignatureTypeCode.GenericMethodParameter:
paramPosition = signature[position++];
return IsGenericMethodTypeParam(type, paramPosition);
case SignatureTypeCode.GenericTypeInstance:
if (!MatchType(GetGenericTypeDefinition(type), signature, ref position))
{
return false;
}
int argumentCount = signature[position++];
for (int argumentIndex = 0; argumentIndex < argumentCount; argumentIndex++)
{
if (!MatchType(GetGenericTypeArgument(type, argumentIndex), signature, ref position))
{
return false;
}
}
return true;
default:
throw ExceptionUtilities.UnexpectedValue(typeCode);
}
}
/// <summary>
/// Read a type Id from the signature.
/// This may consume one or two bytes, and therefore increment the position correspondingly.
/// </summary>
private static short ReadTypeId(ImmutableArray<byte> signature, ref int position)
{
var firstByte = signature[position++];
if (firstByte == (byte)WellKnownType.ExtSentinel)
{
return (short)(signature[position++] + WellKnownType.ExtSentinel);
}
else
{
return firstByte;
}
}
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol GetGenericTypeArgument(TypeSymbol type, int argumentIndex);
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol GetGenericTypeDefinition(TypeSymbol type);
protected abstract bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition);
protected abstract bool IsGenericTypeParam(TypeSymbol type, int paramPosition);
/// <summary>
/// Should only accept Pointer types.
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol GetPointedToType(TypeSymbol type);
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol GetSZArrayElementType(TypeSymbol type);
/// <summary>
/// Should only accept multi-dimensional arrays.
/// </summary>
protected abstract bool MatchArrayRank(TypeSymbol type, int countOfDimensions);
/// <summary>
/// Should only accept multi-dimensional arrays.
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol GetMDArrayElementType(TypeSymbol type);
protected abstract bool MatchTypeToTypeId(TypeSymbol type, int typeId);
protected abstract TypeSymbol GetReturnType(MethodSymbol method);
protected abstract ImmutableArray<ParameterSymbol> GetParameters(MethodSymbol method);
protected abstract TypeSymbol GetPropertyType(PropertySymbol property);
protected abstract ImmutableArray<ParameterSymbol> GetParameters(PropertySymbol property);
protected abstract TypeSymbol GetParamType(ParameterSymbol parameter);
protected abstract bool IsByRefParam(ParameterSymbol parameter);
protected abstract TypeSymbol GetFieldType(FieldSymbol field);
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using Frapid.Configuration;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.DbPolicy;
using Frapid.Framework.Extensions;
using Npgsql;
using Frapid.NPoco;
using Serilog;
namespace Frapid.Account.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "account.installed_domains".
/// </summary>
public class InstalledDomain : DbAccess, IInstalledDomainRepository
{
/// <summary>
/// The schema of this table. Returns literal "account".
/// </summary>
public override string _ObjectNamespace => "account";
/// <summary>
/// The schema unqualified name of this table. Returns literal "installed_domains".
/// </summary>
public override string _ObjectName => "installed_domains";
/// <summary>
/// Login id of application user accessing this table.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Performs SQL count on the table "account.installed_domains".
/// </summary>
/// <returns>Returns the number of rows of the table "account.installed_domains".</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long Count()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM account.installed_domains;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.installed_domains" to return all instances of the "InstalledDomain" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "InstalledDomain" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.InstalledDomain> GetAll()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains ORDER BY domain_id;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.installed_domains" to return all instances of the "InstalledDomain" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "InstalledDomain" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<dynamic> Export()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains ORDER BY domain_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.installed_domains" with a where filter on the column "domain_id" to return a single instance of the "InstalledDomain" class.
/// </summary>
/// <param name="domainId">The column "domain_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "InstalledDomain" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.InstalledDomain Get(int domainId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get entity \"InstalledDomain\" filtered by \"DomainId\" with value {DomainId} was denied to the user with Login ID {_LoginId}", domainId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains WHERE domain_id=@0;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql, domainId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "account.installed_domains".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "InstalledDomain" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.InstalledDomain GetFirst()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the first record of entity \"InstalledDomain\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains ORDER BY domain_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "account.installed_domains" sorted by domainId.
/// </summary>
/// <param name="domainId">The column "domain_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "InstalledDomain" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.InstalledDomain GetPrevious(int domainId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the previous entity of \"InstalledDomain\" by \"DomainId\" with value {DomainId} was denied to the user with Login ID {_LoginId}", domainId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains WHERE domain_id < @0 ORDER BY domain_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql, domainId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "account.installed_domains" sorted by domainId.
/// </summary>
/// <param name="domainId">The column "domain_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "InstalledDomain" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.InstalledDomain GetNext(int domainId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the next entity of \"InstalledDomain\" by \"DomainId\" with value {DomainId} was denied to the user with Login ID {_LoginId}", domainId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains WHERE domain_id > @0 ORDER BY domain_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql, domainId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "account.installed_domains".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "InstalledDomain" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Account.Entities.InstalledDomain GetLast()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the last record of entity \"InstalledDomain\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains ORDER BY domain_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "account.installed_domains" with a where filter on the column "domain_id" to return a multiple instances of the "InstalledDomain" class.
/// </summary>
/// <param name="domainIds">Array of column "domain_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "InstalledDomain" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.InstalledDomain> Get(int[] domainIds)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}. domainIds: {domainIds}.", this._LoginId, domainIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains WHERE domain_id IN (@0);";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql, domainIds);
}
/// <summary>
/// Custom fields are user defined form elements for account.installed_domains.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table account.installed_domains</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get custom fields for entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
string sql;
if (string.IsNullOrWhiteSpace(resourceId))
{
sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='account.installed_domains' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('account.installed_domains'::text, @0::text) ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId);
}
/// <summary>
/// Displayfields provide a minimal name/value context for data binding the row collection of account.installed_domains.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table account.installed_domains</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>();
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return displayFields;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get display field for entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT domain_id AS key, domain_name as value FROM account.installed_domains;";
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
using (DataTable table = DbOperation.GetDataTable(this._Catalog, command))
{
if (table?.Rows == null || table.Rows.Count == 0)
{
return displayFields;
}
foreach (DataRow row in table.Rows)
{
if (row != null)
{
DisplayField displayField = new DisplayField
{
Key = row["key"].ToString(),
Value = row["value"].ToString()
};
displayFields.Add(displayField);
}
}
}
}
return displayFields;
}
/// <summary>
/// Inserts or updates the instance of InstalledDomain class on the database table "account.installed_domains".
/// </summary>
/// <param name="installedDomain">The instance of "InstalledDomain" class to insert or update.</param>
/// <param name="customFields">The custom field collection.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object AddOrEdit(dynamic installedDomain, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
object primaryKeyValue = installedDomain.domain_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
this.Update(installedDomain, Cast.To<int>(primaryKeyValue));
}
else
{
primaryKeyValue = this.Add(installedDomain);
}
string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" +
"SELECT custom_field_setup_id " +
"FROM config.custom_field_setup " +
"WHERE form_name=config.get_custom_field_form_name('account.installed_domains')" +
");";
Factory.NonQuery(this._Catalog, sql);
if (customFields == null)
{
return primaryKeyValue;
}
foreach (var field in customFields)
{
sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " +
"SELECT config.get_custom_field_setup_id_by_table_name('account.installed_domains', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of InstalledDomain class on the database table "account.installed_domains".
/// </summary>
/// <param name="installedDomain">The instance of "InstalledDomain" class to insert.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object Add(dynamic installedDomain)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to add entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}. {InstalledDomain}", this._LoginId, installedDomain);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, installedDomain, "account.installed_domains", "domain_id");
}
/// <summary>
/// Inserts or updates multiple instances of InstalledDomain class on the database table "account.installed_domains";
/// </summary>
/// <param name="installedDomains">List of "InstalledDomain" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> installedDomains)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}. {installedDomains}", this._LoginId, installedDomains);
throw new UnauthorizedException("Access is denied.");
}
}
var result = new List<object>();
int line = 0;
try
{
using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName))
{
using (ITransaction transaction = db.GetTransaction())
{
foreach (dynamic installedDomain in installedDomains)
{
line++;
object primaryKeyValue = installedDomain.domain_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
result.Add(installedDomain.domain_id);
db.Update("account.installed_domains", "domain_id", installedDomain, installedDomain.domain_id);
}
else
{
result.Add(db.Insert("account.installed_domains", "domain_id", installedDomain));
}
}
transaction.Complete();
}
return result;
}
}
catch (NpgsqlException ex)
{
string errorMessage = $"Error on line {line} ";
if (ex.Code.StartsWith("P"))
{
errorMessage += Factory.GetDbErrorResource(ex);
throw new DataAccessException(errorMessage, ex);
}
errorMessage += ex.Message;
throw new DataAccessException(errorMessage, ex);
}
catch (System.Exception ex)
{
string errorMessage = $"Error on line {line} ";
throw new DataAccessException(errorMessage, ex);
}
}
/// <summary>
/// Updates the row of the table "account.installed_domains" with an instance of "InstalledDomain" class against the primary key value.
/// </summary>
/// <param name="installedDomain">The instance of "InstalledDomain" class to update.</param>
/// <param name="domainId">The value of the column "domain_id" which will be updated.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Update(dynamic installedDomain, int domainId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to edit entity \"InstalledDomain\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {InstalledDomain}", domainId, this._LoginId, installedDomain);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, installedDomain, domainId, "account.installed_domains", "domain_id");
}
/// <summary>
/// Deletes the row of the table "account.installed_domains" against the primary key value.
/// </summary>
/// <param name="domainId">The value of the column "domain_id" which will be deleted.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Delete(int domainId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to delete entity \"InstalledDomain\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", domainId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM account.installed_domains WHERE domain_id=@0;";
Factory.NonQuery(this._Catalog, sql, domainId);
}
/// <summary>
/// Performs a select statement on table "account.installed_domains" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "InstalledDomain" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.InstalledDomain> GetPaginatedResult()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the first page of the entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.installed_domains ORDER BY domain_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "account.installed_domains" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "InstalledDomain" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.InstalledDomain> GetPaginatedResult(long pageNumber)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
const string sql = "SELECT * FROM account.installed_domains ORDER BY domain_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql, offset);
}
public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName)
{
const string sql = "SELECT * FROM config.filters WHERE object_name='account.installed_domains' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "account.installed_domains".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "InstalledDomain" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.installed_domains WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.InstalledDomain(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.installed_domains" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of "InstalledDomain" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.InstalledDomain> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM account.installed_domains WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.InstalledDomain(), filters);
sql.OrderBy("domain_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "account.installed_domains".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "InstalledDomain" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountFiltered(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.installed_domains WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.InstalledDomain(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.installed_domains" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of "InstalledDomain" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.InstalledDomain> GetFiltered(long pageNumber, string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"InstalledDomain\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM account.installed_domains WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.InstalledDomain(), filters);
sql.OrderBy("domain_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.InstalledDomain>(this._Catalog, sql);
}
}
}
| |
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Graphics;
using osu.Game.Rulesets;
using osu.Game.Screens.Menu;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament.Components
{
public class SongBar : CompositeDrawable
{
private BeatmapInfo beatmap;
[Resolved]
private IBindable<RulesetInfo> ruleset { get; set; }
public BeatmapInfo Beatmap
{
get => beatmap;
set
{
if (beatmap == value)
return;
beatmap = value;
update();
}
}
private LegacyMods mods;
public LegacyMods Mods
{
get => mods;
set
{
mods = value;
update();
}
}
private Container panelContents;
private Container innerPanel;
private Container outerPanel;
private TournamentBeatmapPanel panel;
private float panelWidth => expanded ? 0.6f : 1;
private const float main_width = 0.97f;
private const float inner_panel_width = 0.7f;
private bool expanded;
public bool Expanded
{
get => expanded;
set
{
expanded = value;
panel?.ResizeWidthTo(panelWidth, 800, Easing.OutQuint);
if (expanded)
{
innerPanel.ResizeWidthTo(inner_panel_width, 800, Easing.OutQuint);
outerPanel.ResizeWidthTo(main_width, 800, Easing.OutQuint);
}
else
{
innerPanel.ResizeWidthTo(1, 800, Easing.OutQuint);
outerPanel.ResizeWidthTo(0.25f, 800, Easing.OutQuint);
}
}
}
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.Both;
InternalChildren = new Drawable[]
{
outerPanel = new Container
{
Masking = true,
EdgeEffect = new EdgeEffectParameters
{
Colour = Color4.Black.Opacity(0.2f),
Type = EdgeEffectType.Shadow,
Radius = 5,
},
RelativeSizeAxes = Axes.X,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
RelativePositionAxes = Axes.X,
X = -(1 - main_width) / 2,
Y = -10,
Width = main_width,
Height = TournamentBeatmapPanel.HEIGHT,
CornerRadius = TournamentBeatmapPanel.HEIGHT / 2,
CornerExponent = 2,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.Gray(0.93f),
},
new OsuLogo
{
Triangles = false,
Colour = OsuColour.Gray(0.33f),
Scale = new Vector2(0.08f),
Margin = new MarginPadding(50),
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
},
innerPanel = new Container
{
Masking = true,
CornerRadius = TournamentBeatmapPanel.HEIGHT / 2,
CornerExponent = 2,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Width = inner_panel_width,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.Gray(0.86f),
},
panelContents = new Container
{
RelativeSizeAxes = Axes.Both,
}
}
}
}
}
};
Expanded = true;
}
private void update()
{
if (beatmap == null)
{
panelContents.Clear();
return;
}
var bpm = beatmap.BeatmapSet.OnlineInfo.BPM;
var length = beatmap.Length;
string hardRockExtra = "";
string srExtra = "";
var ar = beatmap.BaseDifficulty.ApproachRate;
if ((mods & LegacyMods.HardRock) > 0)
{
hardRockExtra = "*";
srExtra = "*";
}
if ((mods & LegacyMods.DoubleTime) > 0)
{
// temporary local calculation (taken from OsuDifficultyCalculator)
double preempt = (int)BeatmapDifficulty.DifficultyRange(ar, 1800, 1200, 450) / 1.5;
ar = (float)(preempt > 1200 ? (1800 - preempt) / 120 : (1200 - preempt) / 150 + 5);
bpm *= 1.5f;
length /= 1.5f;
srExtra = "*";
}
(string heading, string content)[] stats;
switch (ruleset.Value.ID)
{
default:
stats = new (string heading, string content)[]
{
("CS", $"{beatmap.BaseDifficulty.CircleSize:0.#}{hardRockExtra}"),
("AR", $"{ar:0.#}{hardRockExtra}"),
("OD", $"{beatmap.BaseDifficulty.OverallDifficulty:0.#}{hardRockExtra}"),
};
break;
case 1:
case 3:
stats = new (string heading, string content)[]
{
("OD", $"{beatmap.BaseDifficulty.OverallDifficulty:0.#}{hardRockExtra}"),
("HP", $"{beatmap.BaseDifficulty.DrainRate:0.#}{hardRockExtra}")
};
break;
case 2:
stats = new (string heading, string content)[]
{
("CS", $"{beatmap.BaseDifficulty.CircleSize:0.#}{hardRockExtra}"),
("AR", $"{ar:0.#}"),
};
break;
}
panelContents.Children = new Drawable[]
{
new DiffPiece(("Length", TimeSpan.FromMilliseconds(length).ToString(@"mm\:ss")))
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.BottomLeft,
},
new DiffPiece(("BPM", $"{bpm:0.#}"))
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.TopLeft
},
new DiffPiece(stats)
{
Anchor = Anchor.CentreRight,
Origin = Anchor.BottomRight
},
new DiffPiece(("Star Rating", $"{beatmap.StarDifficulty:0.#}{srExtra}"))
{
Anchor = Anchor.CentreRight,
Origin = Anchor.TopRight
},
panel = new TournamentBeatmapPanel(beatmap)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(panelWidth, 1)
}
};
}
public class DiffPiece : TextFlowContainer
{
public DiffPiece(params (string heading, string content)[] tuples)
{
Margin = new MarginPadding { Horizontal = 15, Vertical = 1 };
AutoSizeAxes = Axes.Both;
static void cp(SpriteText s, Color4 colour)
{
s.Colour = colour;
s.Font = OsuFont.Torus.With(weight: FontWeight.Bold, size: 15);
}
for (var i = 0; i < tuples.Length; i++)
{
var (heading, content) = tuples[i];
if (i > 0)
{
AddText(" / ", s =>
{
cp(s, OsuColour.Gray(0.33f));
s.Spacing = new Vector2(-2, 0);
});
}
AddText(new TournamentSpriteText { Text = heading }, s => cp(s, OsuColour.Gray(0.33f)));
AddText(" ", s => cp(s, OsuColour.Gray(0.33f)));
AddText(new TournamentSpriteText { Text = content }, s => cp(s, OsuColour.Gray(0.5f)));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Google.GData.Client;
using Google.GData.Extensions.Apps;
namespace Google.GData.Apps
{
/// <summary>
/// Service class for managing organization units and users within Google Apps.
///
/// An OrgUnit path is the URL-encoding (e.g., using HttpUtility.UrlPathEncode) of an OrgUnit's lineage,
/// concatenated together with the slash ('/') character.
/// </summary>
public class OrganizationService : AppsPropertyService
{
public enum OrgUnitProperty
{
Name,
Description,
ParentOrgUnitPath,
BlockInheritance,
UsersToMove
}
public OrganizationService(string domain, string applicationName)
: base(domain, applicationName)
{
}
/// <summary>
/// Retrieves the customer Id that will be used for all other operations.
/// </summary>
/// <param name="domain">the customer domain</param>
/// <returns></returns>
public AppsExtendedEntry RetrieveCustomerId(string domain)
{
string customerIdUri = string.Format("{0}/{1}",
AppsOrganizationNameTable.AppsCustomerBaseFeedUri, AppsOrganizationNameTable.CustomerId);
return Get(customerIdUri) as AppsExtendedEntry;
}
/// <summary>
/// Create a new organization unit under the given parent.
/// </summary>
/// <param name="customerId">The unique Id of the customer retrieved through customer feed.</param>
/// <param name="orgUnitName">The new organization name.</param>
/// <param name="parentOrgUnitPath">The path of the parent organization unit where
/// '/' denotes the root of the organization hierarchy.
/// For any OrgUnits to be created directly under root, specify '/' as parent path.</param>
/// <param name="description">A description for the organization unit created.</param>
/// <param name="blockInheritance">If true, blocks inheritance of policies from
/// parent units.</param>
/// <returns></returns>
public AppsExtendedEntry CreateOrganizationUnit(string customerId, string orgUnitName,
string parentOrgUnitPath, string description, bool blockInheritance)
{
Uri orgUnitUri = new Uri(string.Format("{0}/{1}",
AppsOrganizationNameTable.AppsOrgUnitBaseFeedUri, customerId));
AppsExtendedEntry entry = new AppsExtendedEntry();
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.ParentOrgUnitPath, parentOrgUnitPath));
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.Description, description));
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.OrgUnitName, orgUnitName));
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.BlockInheritance,
blockInheritance.ToString()));
return Insert(orgUnitUri, entry);
;
}
/// <summary>
/// Retrieves an organization unit from the customer's domain.
/// </summary>
/// <param name="orgUnitPath">The path of the unit to be retrieved for e.g /corp</param>
/// <returns></returns>
public AppsExtendedEntry RetrieveOrganizationUnit(string customerId, string orgUnitPath)
{
string uri = string.Format("{0}/{1}/{2}",
AppsOrganizationNameTable.AppsOrgUnitBaseFeedUri,
customerId, HttpUtility.UrlEncode(orgUnitPath));
return Get(uri) as AppsExtendedEntry;
}
/// <summary>
/// Retrieves all organization units for the given customer account.
/// </summary>
/// <param name="customerId">The unique Id of the customer retrieved through customer feed.</param>
/// <returns></returns>
public AppsExtendedFeed RetrieveAllOrganizationUnits(string customerId)
{
string uri = string.Format("{0}/{1}?get=all", AppsOrganizationNameTable.AppsOrgUnitBaseFeedUri, customerId);
return QueryExtendedFeed(new Uri(uri), true);
}
/// <summary>
/// Retrieves all the child units of the given organization unit.
/// </summary>
/// <param name="customerId">The unique Id of the customer retrieved through customer feed.</param>
/// <param name="orgUnitPath">The path of the unit to be retrieved for e.g /corp</param>
/// <returns></returns>
public AppsExtendedFeed RetrieveChildOrganizationUnits(string customerId, string orgUnitPath)
{
string uri = string.Format("{0}/{1}?get=children&orgUnitPath={2}",
AppsOrganizationNameTable.AppsOrgUnitBaseFeedUri, customerId,
HttpUtility.UrlEncode(orgUnitPath));
return QueryExtendedFeed(new Uri(uri), true);
}
/// <summary>
/// Deletes the given organization unit. The unit must not have any OrgUsers or any
/// child OrgUnits for it to be deleted
/// </summary>
/// <param name="customerId">The unique Id of the customer retrieved through customer feed.</param>
/// <param name="orgUnitPath">The path of the unit to be retrieved for e.g /corp</param>
public void DeleteOrganizationUnit(string customerId, string orgUnitPath)
{
string uri = string.Format("{0}/{1}/{2}", AppsOrganizationNameTable.AppsOrgUnitBaseFeedUri, customerId,
HttpUtility.UrlEncode(orgUnitPath));
Delete(new Uri(uri));
}
/// <summary>
/// Updates the given organization attributes.
/// attributes.USERS_TO_MOVE is a comma separated list of email addresses that are to be moved across orgUnits.
/// </summary>
/// <param name="customerId">The unique Id of the customer retrieved through customer feed.</param>
/// <param name="orgUnitPath">The path of the unit to be retrieved for e.g /corp</param>
/// <param name="attributes">A dictionary of <code>OrgUnitProperty</code> and values to be updated.</param>
/// <returns></returns>
public AppsExtendedEntry UpdateOrganizationUnit(string customerId, string orgUnitPath,
IDictionary<OrgUnitProperty, string> attributes)
{
AppsExtendedEntry entry = new AppsExtendedEntry();
string uri = string.Format("{0}/{1}/{2}",
AppsOrganizationNameTable.AppsOrgUnitBaseFeedUri, customerId,
HttpUtility.UrlEncode(orgUnitPath));
entry.EditUri = new AtomUri(uri);
foreach (KeyValuePair<OrgUnitProperty, string> mapEntry in attributes)
{
string value = mapEntry.Value;
if (string.IsNullOrEmpty(value))
{
continue;
}
switch (mapEntry.Key)
{
case OrgUnitProperty.Name:
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.OrgUnitName, value));
break;
case OrgUnitProperty.ParentOrgUnitPath:
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.ParentOrgUnitPath, value));
break;
case OrgUnitProperty.Description:
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.Description, value));
break;
case OrgUnitProperty.BlockInheritance:
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.BlockInheritance, value));
break;
case OrgUnitProperty.UsersToMove:
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.UsersToMove, value));
break;
default:
break;
}
}
return Update(entry);
}
/// <summary>
/// Updates the orgunit of an organization user.
/// </summary>
///
/// <param name="customerId"></param>
/// <param name="orgUserEmail">The email address of the user</param>
/// <param name="oldOrgUnitPath">The old organization unit path.
/// If specified, validates the OrgUser's current path.</param>
/// <param name="newOrgUnitPath"></param>
/// <returns></returns>
public AppsExtendedEntry UpdateOrganizationUser(string customerId, string orgUserEmail,
string newOrgUnitPath, string oldOrgUnitPath)
{
string uri = string.Format("{0}/{1}/{2}",
AppsOrganizationNameTable.AppsOrgUserBaseFeedUri, customerId,
orgUserEmail);
AppsExtendedEntry entry = new AppsExtendedEntry();
entry.EditUri = new Uri(uri);
if (!string.IsNullOrEmpty(oldOrgUnitPath))
{
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.OldOrgUnitPath, oldOrgUnitPath));
}
entry.Properties.Add(new PropertyElement(AppsOrganizationNameTable.NewOrgUnitPath, newOrgUnitPath));
return Update(entry);
}
/// <summary>
/// Updates the orgunit of an organization user.
/// </summary>
/// <param name="customerId"></param>
/// <param name="orgUserEmail">The email address of the user.</param>
/// <param name="newOrgUnitPath">The new organization unit path.</param>
/// <returns></returns>
public AppsExtendedEntry UpdateOrganizationUser(string customerId, string orgUserEmail,
string newOrgUnitPath)
{
return UpdateOrganizationUser(customerId, orgUserEmail, newOrgUnitPath, null);
}
/// <summary>
/// Retrieves the details of a given organization user.
/// </summary>
/// <param name="customerId"></param>
/// <param name="orgUserEmail">The email address of the user</param>
/// <returns>AppsExtendedEntry</returns>
public AppsExtendedEntry RetrieveOrganizationUser(string customerId, string orgUserEmail)
{
string uri = string.Format("{0}/{1}/{2}",
AppsOrganizationNameTable.AppsOrgUserBaseFeedUri, customerId,
orgUserEmail);
return Get(uri) as AppsExtendedEntry;
}
/// <summary>
/// Retrieves the next page of a paginated feed using resumeKey from the previous feed.
/// i.e. <code>atom:next</code> link
/// </summary>
/// <param name="resumeKey"></param>
/// <returns></returns>
public AppsExtendedFeed RetrieveNextPageFromResumeKey(string resumeKey)
{
return QueryExtendedFeed(new Uri(resumeKey), false);
}
/// <summary>
/// Retrieves all users belongging to all org units. This may take a long time to execute for
/// domains with large number of users. Instead use pagination i.e.
/// <code>RetrieveFirstPageOrganizationUsers</code>
/// followed by <code>RetrieveNextPageFromResumeKey</code>
/// </summary>
/// <param name="customerId"></param>
/// <returns></returns>
public AppsExtendedFeed RetrieveAllOrganizationUsers(string customerId)
{
string uri = string.Format("{0}/{1}?get=all",
AppsOrganizationNameTable.AppsOrgUserBaseFeedUri, customerId);
return QueryExtendedFeed(new Uri(uri), true);
}
/// <summary>
/// Retrieves first page of results for all org users query. For subsequent pages,
/// follow up with <code>RetrieveNextPageFromResumeKey</code>
/// </summary>
/// <param name="customerId"></param>
/// <returns></returns>
public AppsExtendedFeed RetrieveFirstPageOrganizationUsers(string customerId)
{
string uri = string.Format("{0}/{1}?get=all",
AppsOrganizationNameTable.AppsOrgUserBaseFeedUri, customerId);
return QueryExtendedFeed(new Uri(uri), false);
}
/// <summary>
/// Retrieves all users by org unit. This may take a long time to execute for domains with
/// large number of users. Instead use pagination i.e.
/// <code>RetrieveFirstPageOfOrganizationUsersByOrgUnit</code>
/// followed by <code>RetrieveNextPageFromResumeKey</code>
/// </summary>
/// <param name="customerId">The unique Id of the customer retrieved through customer feed.</param>
/// <param name="orgUnitPath">The path of the unit to be retrieved for e.g /corp</param>
/// <returns></returns>
public AppsExtendedFeed RetrieveAllOrganizationUsersByOrgUnit(string customerId, string orgUnitPath)
{
string uri = string.Format("{0}/{1}?get=children&orgUnitPath={2}",
AppsOrganizationNameTable.AppsOrgUserBaseFeedUri, customerId,
HttpUtility.UrlEncode(orgUnitPath));
return QueryExtendedFeed(new Uri(uri), true);
}
/// <summary>
/// Retrieves first page of results for all org users by orgunit query. For subsequent pages,
/// follow up with <code>RetrieveNextPageFromResumeKey</code>
/// </summary>
/// <param name="customerId">The unique Id of the customer retrieved through customer feed.</param>
/// <param name="orgUnitPath">The path of the unit to be retrieved for e.g /corp</param>
/// <returns></returns>
public AppsExtendedFeed RetrieveFirstPageOfOrganizationUsersByOrgUnit(string customerId, string orgUnitPath)
{
string uri = string.Format("{0}/{1}?get=children&orgUnitPath={2}",
AppsOrganizationNameTable.AppsOrgUserBaseFeedUri, customerId,
HttpUtility.UrlEncode(orgUnitPath));
return QueryExtendedFeed(new Uri(uri), false);
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using LSCollections;
namespace DequeTest
{
class Tester
{
private const int ElementCount = 100;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
TestDeque(new Deque());
TestDeque(Deque.Synchronized(new Deque()));
}
private static void TestDeque(Deque deque)
{
deque.Clear();
Debug.Assert(deque.Count == 0);
PopulateDequePushFront(deque);
PopulateDequePushBack(deque);
TestPopFront(deque);
TestPopBack(deque);
TestContains(deque);
TestCopyTo(deque);
TestToArray(deque);
TestClone(deque);
TestEnumerator(deque);
}
private static void PopulateDequePushFront(Deque deque)
{
deque.Clear();
for(int i = 0; i < ElementCount; i++)
{
deque.PushFront(i);
}
Debug.Assert(deque.Count == ElementCount);
int j = ElementCount - 1;
foreach(int i in deque)
{
Debug.Assert(i == j);
j--;
}
}
private static void PopulateDequePushBack(Deque deque)
{
deque.Clear();
for(int i = 0; i < ElementCount; i++)
{
deque.PushBack(i);
}
Debug.Assert(deque.Count == ElementCount);
int j = 0;
foreach(int i in deque)
{
Debug.Assert(i == j);
j++;
}
}
private static void TestPopFront(Deque deque)
{
deque.Clear();
PopulateDequePushBack(deque);
int j;
for(int i = 0; i < ElementCount; i++)
{
j = (int)deque.PopFront();
Debug.Assert(j == i);
}
Debug.Assert(deque.Count == 0);
}
private static void TestPopBack(Deque deque)
{
deque.Clear();
PopulateDequePushBack(deque);
int j;
for(int i = 0; i < ElementCount; i++)
{
j = (int)deque.PopBack();
Debug.Assert(j == ElementCount - 1 - i);
}
Debug.Assert(deque.Count == 0);
}
private static void TestContains(Deque deque)
{
deque.Clear();
PopulateDequePushBack(deque);
for(int i = 0; i < deque.Count; i++)
{
Debug.Assert(deque.Contains(i));
}
Debug.Assert(!deque.Contains(ElementCount));
}
private static void TestCopyTo(Deque deque)
{
deque.Clear();
PopulateDequePushBack(deque);
int[] array = new int[deque.Count];
deque.CopyTo(array, 0);
foreach(int i in deque)
{
Debug.Assert(array[i] == i);
}
array = new int[deque.Count * 2];
deque.CopyTo(array, deque.Count);
foreach(int i in deque)
{
Debug.Assert(array[i + deque.Count] == i);
}
array = new int[deque.Count];
try
{
deque.CopyTo(null, deque.Count);
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
deque.CopyTo(array, -1);
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
deque.CopyTo(array, deque.Count / 2);
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
deque.CopyTo(array, deque.Count);
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
deque.CopyTo(new int[10, 10], deque.Count);
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void TestToArray(Deque deque)
{
deque.Clear();
PopulateDequePushBack(deque);
object[] array = deque.ToArray();
int i = 0;
foreach(object obj in deque)
{
Debug.Assert(obj.Equals(array[i]));
i++;
}
}
private static void TestClone(Deque deque)
{
deque.Clear();
PopulateDequePushBack(deque);
Deque deque2 = (Deque)deque.Clone();
Debug.Assert(deque.Count == deque2.Count);
IEnumerator d2 = deque2.GetEnumerator();
d2.MoveNext();
foreach(object obj in deque)
{
Debug.Assert(obj.Equals(d2.Current));
d2.MoveNext();
}
}
private static void TestEnumerator(Deque deque)
{
deque.Clear();
PopulateDequePushBack(deque);
IEnumerator e = deque.GetEnumerator();
try
{
object obj = e.Current;
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
foreach(object obj in deque)
{
Debug.Assert(e.MoveNext());
}
Debug.Assert(!e.MoveNext());
object o = e.Current;
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
e.Reset();
foreach(object obj in deque)
{
Debug.Assert(e.MoveNext());
}
Debug.Assert(!e.MoveNext());
object o = e.Current;
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
deque.PushBack(deque.Count);
e.Reset();
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
e.MoveNext();
Debug.Fail("Exception failed");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| |
using System;
using Microsoft.Data.Entity.Migrations;
using Microsoft.Data.Entity.Metadata;
namespace AllReady.Migrations
{
public partial class RenamingActivityToEvent : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Activity_ActivityId", table: "AllReadyTask");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropColumn(name: "ActivityId", table: "AllReadyTask");
migrationBuilder.DropTable("ActivitySignup");
migrationBuilder.DropTable("ActivitySkill");
migrationBuilder.DropTable("Activity");
migrationBuilder.CreateTable(
name: "Event",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CampaignId = table.Column<int>(nullable: false),
Description = table.Column<string>(nullable: true),
EndDateTime = table.Column<DateTimeOffset>(nullable: false),
EventType = table.Column<int>(nullable: false),
ImageUrl = table.Column<string>(nullable: true),
IsAllowWaitList = table.Column<bool>(nullable: false),
IsLimitVolunteers = table.Column<bool>(nullable: false),
LocationId = table.Column<int>(nullable: true),
Name = table.Column<string>(nullable: false),
NumberOfVolunteersRequired = table.Column<int>(nullable: false),
OrganizerId = table.Column<string>(nullable: true),
StartDateTime = table.Column<DateTimeOffset>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Event", x => x.Id);
table.ForeignKey(
name: "FK_Event_Campaign_CampaignId",
column: x => x.CampaignId,
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Event_Location_LocationId",
column: x => x.LocationId,
principalTable: "Location",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Event_ApplicationUser_OrganizerId",
column: x => x.OrganizerId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "EventSignup",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
AdditionalInfo = table.Column<string>(nullable: true),
CheckinDateTime = table.Column<DateTime>(nullable: true),
EventId = table.Column<int>(nullable: true),
PreferredEmail = table.Column<string>(nullable: true),
PreferredPhoneNumber = table.Column<string>(nullable: true),
SignupDateTime = table.Column<DateTime>(nullable: false),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_EventSignup", x => x.Id);
table.ForeignKey(
name: "FK_EventSignup_Event_EventId",
column: x => x.EventId,
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_EventSignup_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "EventSkill",
columns: table => new
{
EventId = table.Column<int>(nullable: false),
SkillId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_EventSkill", x => new { x.EventId, x.SkillId });
table.ForeignKey(
name: "FK_EventSkill_Event_EventId",
column: x => x.EventId,
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_EventSkill_Skill_SkillId",
column: x => x.SkillId,
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.AddColumn<int>(
name: "EventId",
table: "AllReadyTask",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_AllReadyTask_Event_EventId",
table: "AllReadyTask",
column: "EventId",
principalTable: "Event",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropColumn(name: "EventId", table: "AllReadyTask");
migrationBuilder.DropTable("EventSignup");
migrationBuilder.DropTable("EventSkill");
migrationBuilder.DropTable("Event");
migrationBuilder.CreateTable(
name: "Activity",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CampaignId = table.Column<int>(nullable: false),
Description = table.Column<string>(nullable: true),
EndDateTime = table.Column<DateTimeOffset>(nullable: false),
EventType = table.Column<int>(nullable: false),
ImageUrl = table.Column<string>(nullable: true),
IsAllowWaitList = table.Column<bool>(nullable: false),
IsLimitVolunteers = table.Column<bool>(nullable: false),
LocationId = table.Column<int>(nullable: true),
Name = table.Column<string>(nullable: false),
NumberOfVolunteersRequired = table.Column<int>(nullable: false),
OrganizerId = table.Column<string>(nullable: true),
StartDateTime = table.Column<DateTimeOffset>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Activity", x => x.Id);
table.ForeignKey(
name: "FK_Activity_Campaign_CampaignId",
column: x => x.CampaignId,
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Activity_Location_LocationId",
column: x => x.LocationId,
principalTable: "Location",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Activity_ApplicationUser_OrganizerId",
column: x => x.OrganizerId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "ActivitySignup",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ActivityId = table.Column<int>(nullable: true),
AdditionalInfo = table.Column<string>(nullable: true),
CheckinDateTime = table.Column<DateTime>(nullable: true),
PreferredEmail = table.Column<string>(nullable: true),
PreferredPhoneNumber = table.Column<string>(nullable: true),
SignupDateTime = table.Column<DateTime>(nullable: false),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ActivitySignup", x => x.Id);
table.ForeignKey(
name: "FK_ActivitySignup_Activity_ActivityId",
column: x => x.ActivityId,
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ActivitySignup_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "ActivitySkill",
columns: table => new
{
ActivityId = table.Column<int>(nullable: false),
SkillId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ActivitySkill", x => new { x.ActivityId, x.SkillId });
table.ForeignKey(
name: "FK_ActivitySkill_Activity_ActivityId",
column: x => x.ActivityId,
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ActivitySkill_Skill_SkillId",
column: x => x.SkillId,
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.AddColumn<int>(
name: "ActivityId",
table: "AllReadyTask",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_AllReadyTask_Activity_ActivityId",
table: "AllReadyTask",
column: "ActivityId",
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| |
/***************************************************************************
* FileNamePattern.cs
*
* Copyright (C) 2005-2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.IO;
#if !win32
using Mono.Unix;
#else
using Banshee.Winforms;
#endif
using Banshee.Configuration.Schema;
namespace Banshee.Base
{
public static class FileNamePattern
{
public delegate string ExpandTokenHandler(TrackInfo track, object replace);
public delegate string FilterHandler(string path);
private static string invalid_path_characters = "'~`!@#$%^&*_-+|?/><[]";//\"\\:
private static Regex invalid_path_regex;
public static FilterHandler Filter;
public struct Conversion
{
private string token;
private string name;
private ExpandTokenHandler handler;
public Conversion(string token, string name, ExpandTokenHandler handler)
{
this.token = token;
this.name = name;
this.handler = handler;
}
public string Token {
get { return token; }
}
public string Name {
get { return name; }
}
public ExpandTokenHandler Handler {
get { return handler; }
}
}
private static SortedList<string, Conversion> conversion_table;
public static void AddConversion(string token, string name, ExpandTokenHandler handler)
{
conversion_table.Add(token, new Conversion(token, name, handler));
}
static FileNamePattern()
{
conversion_table = new SortedList<string, Conversion>();
AddConversion("artist", Catalog.GetString("Artist"),
delegate(TrackInfo t, object r) {
return Escape(t == null ? (string)r : t.DisplayArtist);
});
AddConversion("album", Catalog.GetString("Album"),
delegate(TrackInfo t, object r) {
return Escape(t == null ? (string)r : t.DisplayAlbum);
});
AddConversion("title", Catalog.GetString("Title"),
delegate(TrackInfo t, object r) {
return Escape(t == null ? (string)r : t.DisplayTitle);
});
AddConversion("track_count", Catalog.GetString("Count"),
delegate(TrackInfo t, object r) {
return String.Format("{0:00}", t == null ? (uint)r : t.TrackCount);
});
AddConversion("track_number", Catalog.GetString("Number"),
delegate(TrackInfo t, object r) {
return String.Format("{0:00}", t == null ? (uint)r : t.TrackNumber);
});
AddConversion("track_count_nz", Catalog.GetString("Count (unsorted)"),
delegate(TrackInfo t, object r) {
return String.Format("{0}", t == null ? (uint)r : t.TrackCount);
});
AddConversion("track_number_nz", Catalog.GetString("Number (unsorted)"),
delegate(TrackInfo t, object r) {
return String.Format("{0}", t == null ? (uint)r : t.TrackNumber);
});
AddConversion("path_sep", Path.DirectorySeparatorChar.ToString(),
delegate(TrackInfo t, object r) {
return Path.DirectorySeparatorChar.ToString();
});
}
public static IEnumerable<Conversion> PatternConversions {
get { return conversion_table.Values; }
}
public static string DefaultFolder {
get { return "%artist%%path_sep%%album%"; }
}
public static string DefaultFile {
get { return "%track_number%. %title%"; }
}
public static string DefaultPattern {
get { return CreateFolderFilePattern(DefaultFolder, DefaultFile); }
}
private static string [] suggested_folders = new string [] {
DefaultFolder,
"%artist%%path_sep%%artist% - %album%",
"%artist% - %album%",
"%album%",
"%artist%"
};
public static string [] SuggestedFolders {
get { return suggested_folders; }
}
private static string [] suggested_files = new string [] {
DefaultFile,
"%track_number%. %artist% - %title%",
"%artist% - %title%",
"%artist% - %track_number% - %title%",
"%artist% (%album%) - %track_number% - %title%",
"%title%"
};
public static string [] SuggestedFiles {
get { return suggested_files; }
}
private static string OnFilter(string input)
{
string repl_pattern = input;
FilterHandler filter_handler = Filter;
if(filter_handler != null) {
repl_pattern = filter_handler(repl_pattern);
}
return repl_pattern;
}
public static string CreateFolderFilePattern(string folder, string file)
{
if (String.IsNullOrEmpty(folder))
folder = "%album%";
if(string.IsNullOrEmpty(file))
file = "%artist%-%title%";
return String.Format("{0}%path_sep%{1}", folder, file);
}
public static string CreatePatternDescription(string pattern)
{
string repl_pattern = pattern;
foreach(Conversion conversion in PatternConversions) {
repl_pattern = repl_pattern.Replace("%" + conversion.Token + "%", conversion.Name);
}
return OnFilter(repl_pattern);
}
public static string CreateFromTrackInfo(TrackInfo track)
{
string pattern = null;
try {
pattern = CreateFolderFilePattern(
LibrarySchema.FolderPattern.Get(),
LibrarySchema.FilePattern.Get()
);
} catch {
}
return CreateFromTrackInfo(pattern, track);
}
public static string CreateFromTrackInfo(string pattern, TrackInfo track)
{
string repl_pattern;
if(pattern == null || pattern.Trim() == String.Empty) {
repl_pattern = DefaultPattern;
} else {
repl_pattern = pattern;
}
foreach(Conversion conversion in PatternConversions) {
repl_pattern = repl_pattern.Replace("%" + conversion.Token + "%",
conversion.Handler(track, null));
}
return OnFilter(repl_pattern);
}
public static string BuildFull(TrackInfo track, string ext)
{
if(ext == null || ext.Length < 1) {
ext = String.Empty;
} else if(ext[0] != '.') {
ext = String.Format(".{0}", ext);
}
string songpath = CreateFromTrackInfo(track) + ext;
string dir = Path.GetFullPath(Globals.Library.Location +
Path.DirectorySeparatorChar +
Path.GetDirectoryName(songpath));
string filename = dir + Path.DirectorySeparatorChar +
Path.GetFileName(songpath);
if(!Banshee.IO.IOProxy.Directory.Exists(dir)) {
Banshee.IO.IOProxy.Directory.Create(dir);
}
return filename;
}
public static string Escape(string input)
{
if(invalid_path_regex == null) {
string regex_str = "[";
/*for(int i = 0; i < invalid_path_characters.Length; i++) {
regex_str += @"" + invalid_path_characters[i];
}*/
char[] invalidchars = Path.GetInvalidPathChars();
for (int i = 0; i < invalidchars.Length; i++)
{
regex_str += @"\"+invalidchars[i].ToString();
}
regex_str += "]+";
//string test = Regex.Escape(regex_str);
invalid_path_regex = new Regex(regex_str);
}
return invalid_path_regex.Replace(input, String.Empty);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Tools;
using Xunit;
namespace System.Numerics.Tests
{
public class powTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunPowPositive()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Pow Method - 0^(1)
VerifyPowString(BigInteger.One.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
// Pow Method - 0^(0)
VerifyPowString(BigInteger.Zero.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
// Pow Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
}
// Pow Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
}
// Pow Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyPowString(Print(tempByteArray2) + Print(tempByteArray1) + "bPow");
}
// Pow Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
VerifyPowString(Print(tempByteArray2) + Print(tempByteArray1) + "bPow");
}
}
[Fact]
public static void RunPowAxiomXPow1()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X^1 = X
VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " bPow", Int32.MaxValue.ToString());
VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " bPow", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(BigInteger.One + " " + randBigInt + "bPow", randBigInt.Substring(0, randBigInt.Length - 1));
}
}
[Fact]
public static void RunPowAxiomXPow0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X^0 = 1
VerifyIdentityString(BigInteger.Zero + " " + Int32.MaxValue + " bPow", BigInteger.One.ToString());
VerifyIdentityString(BigInteger.Zero + " " + Int64.MaxValue + " bPow", BigInteger.One.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(BigInteger.Zero + " " + randBigInt + "bPow", BigInteger.One.ToString());
}
}
[Fact]
public static void RunPowAxiom0PowX()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: 0^X = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bPow", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomPosByteArray(s_random, 4));
VerifyIdentityString(randBigInt + BigInteger.Zero + " bPow", BigInteger.Zero.ToString());
}
}
[Fact]
public static void RunPowAxiom1PowX()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: 1^X = 1
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " bPow", BigInteger.One.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomPosByteArray(s_random, 4));
VerifyIdentityString(randBigInt + BigInteger.One + " bPow", BigInteger.One.ToString());
}
}
[Fact]
public static void RunPowBoundary()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyPowString("2 " + Math.Pow(2, 32) + " bPow");
// 32 bit boundary n1=0 n2=1
VerifyPowString("2 " + Math.Pow(2, 33) + " bPow");
}
[Fact]
public static void RunPowNegative()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Pow Method - 1^(-1)
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(BigInteger.MinusOne.ToString() + " " + BigInteger.One.ToString() + " bPow");
});
// Pow Method - 0^(-1)
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(BigInteger.MinusOne.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
});
// Pow Method - Negative Exponent
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomNegByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
});
}
}
private static void VerifyPowString(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(0, 10));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(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);
}
}
}
| |
namespace GRTR.Client.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Initialy : DbMigration
{
public override void Up()
{
CreateTable(
"grtr_stat.ChargingDurations",
c => new
{
CHARGINGDURATIONID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
CHARGINGDURATIONNAME = c.String(),
CHARGINGDURATIONMINUTE = c.Double(nullable: false),
CHARGINGDURATIONHOUR = c.Double(nullable: false),
CHARGINGDURATIONDAY = c.Double(nullable: false),
CHARGINGDURATIONWEEK = c.Double(nullable: false),
CHARGINGDURATIONMONTH = c.Double(nullable: false),
})
.PrimaryKey(t => t.CHARGINGDURATIONID);
CreateTable(
"grtr_stat.ChargingPolicies",
c => new
{
CHARGINGPOLICYID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
CHARGINGPOLICYNAME = c.String(),
CHARGINGPOLICYCAPACITY = c.Int(nullable: false),
CHARGINGPOLICYMINIMUMBOOKINGAMOUNT = c.Int(nullable: false),
CHARGINGPOLICYDAYOVERLAP = c.Boolean(nullable: false),
CHARGINGPOLICYROOMBASED = c.Boolean(nullable: false),
CHARGINGDURATIONNAME = c.String(),
CHARGINGPOLICYMILEAGEBASED = c.Boolean(nullable: false),
CHARGINGPOLICYINSURANCEBASED = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.CHARGINGPOLICYID);
CreateTable(
"grtr_stat.Countries",
c => new
{
COUNTRYID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
COUNTRYNAME = c.String(),
COUNTRYTELEPHONECODE = c.String(),
COUNTRYDESCRIPTION = c.String(),
COUNTRYNATIONALITY = c.String(),
LANGUAGENAME = c.String(),
})
.PrimaryKey(t => t.COUNTRYID);
CreateTable(
"grtr_stat.Currencies",
c => new
{
CURRENCYID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
CURRENCYNAME = c.String(),
CURRENCYISOCODE = c.String(),
CURRENCYSYMBOL = c.String(),
CURRENCYROUNDINGVALUE = c.Double(nullable: false),
})
.PrimaryKey(t => t.CURRENCYID);
CreateTable(
"grtr_stat.Languages",
c => new
{
LANGUAGEID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
LANGUAGENAME = c.String(),
LANGUAGECODE = c.String(),
})
.PrimaryKey(t => t.LANGUAGEID);
CreateTable(
"grtr_stat.MealPlans",
c => new
{
MEALPLANID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
MEALPLANNAME = c.String(),
MEALPLANBREAKFAST = c.Boolean(nullable: false),
MEALPLANLUNCH = c.Boolean(nullable: false),
MEALPLANDINNER = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.MEALPLANID);
CreateTable(
"grtr_stat.ServiceQueue",
c => new
{
ID = c.Int(nullable: false),
Processed = c.Boolean(nullable: false),
ProcessedDate = c.DateTime(),
Error = c.String(),
})
.PrimaryKey(t => t.ID);
CreateTable(
"grtr_stat.Ratings",
c => new
{
RATINGID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
RATINGNAME = c.String(),
RATINGTYPEID = c.Int(nullable: false),
RATINGTYPENAME = c.String(),
})
.PrimaryKey(t => t.RATINGID);
CreateTable(
"grtr_stat.Regions",
c => new
{
REGIONID = c.Int(nullable: false),
PARENTREGIONID = c.Int(),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
REGIONNAME = c.String(),
REGIONSHORTNAME = c.String(),
REGIONDESCRIPTION = c.String(),
REGIONTYPEID = c.Int(nullable: false),
PARENTREGIONNAME = c.String(),
REGIONTYPE = c.String(),
})
.PrimaryKey(t => t.REGIONID);
CreateTable(
"grtr_stat.ServiceDropOffDetails",
c => new
{
ID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
Time = c.String(),
Terms = c.String(),
})
.PrimaryKey(t => t.ID);
CreateTable(
"grtr_stat.ServiceErrors",
c => new
{
ErrorNo = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
ErrorType = c.Int(nullable: false),
ErrorMessage = c.String(),
Description = c.String(),
ErrDate = c.DateTime(nullable: false),
Source = c.String(),
})
.PrimaryKey(t => t.ErrorNo);
CreateTable(
"grtr_stat.ServiceExtras",
c => new
{
ExtraID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
ExtraName = c.String(),
})
.PrimaryKey(t => t.ExtraID);
CreateTable(
"grtr_stat.ServiceFacilities",
c => new
{
ServiceFacilityID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
FacilityID = c.Int(nullable: false),
ServiceTypeFacilityName = c.String(),
ServiceTypeFacilityDescription = c.String(),
FacilityTypeID = c.Int(nullable: false),
FacilityTypeName = c.String(),
})
.PrimaryKey(t => t.ServiceFacilityID);
CreateTable(
"grtr_stat.ServiceFacilityTypes",
c => new
{
SERVICETYPEFACILITYID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
SERVICETYPEFACILITYNAME = c.String(),
SERVICETYPEFACILITYDESCRIPTION = c.String(),
SERVICETYPEID = c.Int(nullable: false),
FACILITYTYPENAME = c.String(),
})
.PrimaryKey(t => t.SERVICETYPEFACILITYID);
CreateTable(
"grtr_stat.ServiceImages",
c => new
{
AssignedImageID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
MD5 = c.String(),
ImageName = c.String(),
ImageStatusID = c.Int(nullable: false),
ImageURL = c.String(),
IsURL = c.Boolean(nullable: false),
ImageCategoryTypeName = c.String(),
srvcimg_stream_id = c.Guid(),
})
.PrimaryKey(t => t.AssignedImageID);
CreateTable(
"grtr_stat.ServiceInformations",
c => new
{
ServiceID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceName = c.String(),
ServiceDescription = c.String(),
AddressLine1 = c.String(),
AddressLine2 = c.String(),
AddressLine3 = c.String(),
AddressLine4 = c.String(),
AddressPostCode = c.String(),
AddressCity = c.String(),
AddressTelephoneNumber = c.String(),
AddressFaxNumber = c.String(),
AddressEmailAddress = c.String(),
AddressWebSiteURL = c.String(),
CountryID = c.Int(nullable: false),
StateID = c.Int(nullable: false),
ServiceMaximumOccupancy = c.String(),
CancellationPeriod = c.Int(nullable: false),
NearestAirport = c.String(),
LastInspectedDate = c.String(),
Longitude = c.String(),
Latitude = c.String(),
ServiceTermsInclusions = c.String(),
ServiceTermsExclusions = c.String(),
ServiceRegionID = c.Int(nullable: false),
ServiceRegionName = c.String(),
PickupOptionId = c.Int(nullable: false),
DropOffOptionId = c.Int(nullable: false),
IsRecommendedProduct = c.Boolean(nullable: false),
SearchPriority = c.Int(nullable: false),
CurrencyID = c.Int(nullable: false),
ServiceTypeID = c.Int(nullable: false),
GLAccount_CostGLAccountName = c.String(),
GLAccount_CostGLAccountID = c.String(),
GLAccount_RevenueGLAccountName = c.String(),
GLAccount_RevenueGLAccountID = c.String(),
BestSeller = c.Boolean(nullable: false),
ServiceTermDuration = c.String(),
ServiceTime = c.String(),
ServiceDuration = c.String(),
XMLResponse = c.String(),
XMLRequest = c.String(),
})
.PrimaryKey(t => t.ServiceID);
CreateTable(
"grtr_stat.ServiceLists",
c => new
{
SERVICEID = c.Int(nullable: false),
CountryFK = c.Int(nullable: false),
ServiceTypeFK = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
SERVICELONGNAME = c.String(),
SERVICESHORTNAME = c.String(),
REGIONNAME = c.String(),
REGIONID = c.Int(nullable: false),
})
.PrimaryKey(t => t.SERVICEID);
CreateTable(
"grtr_stat.ServiceNotes",
c => new
{
ID = c.Int(nullable: false, identity: true),
ServiceID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
Subject = c.String(),
Text = c.String(),
NoteStatus = c.String(),
NoteType = c.String(),
NoteTypeID = c.Int(nullable: false),
NoteStatusID = c.Int(nullable: false),
NoteEventDate = c.DateTime(nullable: false),
NoteEndDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.ID);
CreateTable(
"grtr_stat.ServiceOptionFacilities",
c => new
{
ServiceOptionInServiceID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
ServiceFacilityID = c.Int(nullable: false),
ServiceTypeOptionName = c.String(),
FacilityID = c.Int(nullable: false),
ServiceTypeFacilityName = c.String(),
ServiceTypeFacilityDescription = c.String(),
FacilityTypeID = c.Int(nullable: false),
FacilityTypeName = c.String(),
})
.PrimaryKey(t => t.ServiceOptionInServiceID);
CreateTable(
"grtr_stat.ServiceOptions",
c => new
{
OptionID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
OptionName = c.String(),
LuggageCapacityLarge = c.String(),
LuggageCapacitySmall = c.String(),
OptionDescription = c.String(),
})
.PrimaryKey(t => t.OptionID);
CreateTable(
"grtr_stat.ServiceOptionStatuses",
c => new
{
SERVICEOPTIONSTATUSID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
SERVICEOPTIONSTATUSNAME = c.String(),
SERVICEOPTIONSTATUSSERVICEREQUIREMENTS = c.Boolean(nullable: false),
SERVICEOPTIONSTATUSDEFAULT = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.SERVICEOPTIONSTATUSID);
CreateTable(
"grtr_stat.ServicePickUpDetails",
c => new
{
ID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
Time = c.String(),
Terms = c.String(),
})
.PrimaryKey(t => t.ID);
CreateTable(
"grtr_stat.ServiceRatings",
c => new
{
RatingID = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
HashValues = c.Int(nullable: false),
ServiceID = c.Int(nullable: false),
DefaultFlag = c.Int(nullable: false),
RatingName = c.String(),
RatingSequence = c.Int(nullable: false),
})
.PrimaryKey(t => t.RatingID);
CreateTable(
"grtr_stat.ServiceStatuses",
c => new
{
SERVICESTATUSID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
SERVICESTATUSNAME = c.String(),
SERVICESTATUSCODE = c.String(),
SERVICESTATUSBOOKINGSEARCH = c.Boolean(nullable: false),
SERVICESTATUSMAINTENANCESEARCH = c.Boolean(nullable: false),
SERVICESTATUSINTERNETSEARCH = c.Boolean(nullable: false),
SERVICESTATUSNOBOOKINGS = c.Boolean(nullable: false),
SERVICESTATUSDEFAULT = c.Boolean(nullable: false),
SERVICESTATUSCANDELETE = c.Boolean(nullable: false),
SERVICESTATUSFASTBUILD = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.SERVICESTATUSID);
CreateTable(
"grtr_stat.ServiceTypes",
c => new
{
SERVICETYPEID = c.Int(nullable: false),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
SERVICETYPENAME = c.String(),
SERVICETYPEMARKUP = c.Double(nullable: false),
SERVICETYPECOMMISSION = c.Double(nullable: false),
SERVICETYPEQUOTE = c.Boolean(nullable: false),
SERVICETYPEPACKAGE = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.SERVICETYPEID);
CreateTable(
"grtr_stat.States",
c => new
{
STATEID = c.Int(nullable: false),
CountryFK = c.Int(),
HashValues = c.Int(nullable: false),
UpdateDate = c.DateTime(nullable: false),
STATENAME = c.String(),
STATEDESCRIPTION = c.String(),
STATETELEPHONECODE = c.String(),
COUNTRYNAME = c.String(),
COUNTRYID = c.String(),
})
.PrimaryKey(t => t.STATEID);
}
public override void Down()
{
DropTable("grtr_stat.States");
DropTable("grtr_stat.ServiceTypes");
DropTable("grtr_stat.ServiceStatuses");
DropTable("grtr_stat.ServiceRatings");
DropTable("grtr_stat.ServicePickUpDetails");
DropTable("grtr_stat.ServiceOptionStatuses");
DropTable("grtr_stat.ServiceOptions");
DropTable("grtr_stat.ServiceOptionFacilities");
DropTable("grtr_stat.ServiceNotes");
DropTable("grtr_stat.ServiceLists");
DropTable("grtr_stat.ServiceInformations");
DropTable("grtr_stat.ServiceImages");
DropTable("grtr_stat.ServiceFacilityTypes");
DropTable("grtr_stat.ServiceFacilities");
DropTable("grtr_stat.ServiceExtras");
DropTable("grtr_stat.ServiceErrors");
DropTable("grtr_stat.ServiceDropOffDetails");
DropTable("grtr_stat.Regions");
DropTable("grtr_stat.Ratings");
DropTable("grtr_stat.ServiceQueue");
DropTable("grtr_stat.MealPlans");
DropTable("grtr_stat.Languages");
DropTable("grtr_stat.Currencies");
DropTable("grtr_stat.Countries");
DropTable("grtr_stat.ChargingPolicies");
DropTable("grtr_stat.ChargingDurations");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using Ink.Runtime;
using Newtonsoft.Json;
using Cysharp.Threading.Tasks;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class DialogueOverlay : SingletonMonoBehavior<DialogueOverlay>
{
public static Badge CurrentBadge;
[GetComponent] public Canvas canvas;
[GetComponent] public CanvasGroup canvasGroup;
public Image backdropImage;
public InteractableMonoBehavior detectionArea;
public GameObject parent;
public DialogueBox topDialogueBox;
public DialogueBox bottomDialogueBox;
public DialogueBox bottomFullDialogueBox;
public RectTransform choicesRoot;
public SoftButton choiceButtonPrefab;
public DialogueImage image;
public bool IsActive { get; private set; }
private void Start()
{
canvas.enabled = false;
canvasGroup.enabled = false;
canvas.overrideSorting = true;
canvas.sortingOrder = NavigationSortingOrder.DialogueOverlay;
canvasGroup.alpha = 0;
canvasGroup.blocksRaycasts = false;
canvasGroup.interactable = false;
parent.SetActive(false);
topDialogueBox.SetDisplayed(false);
bottomDialogueBox.SetDisplayed(false);
bottomFullDialogueBox.SetDisplayed(false);
backdropImage.SetAlpha(0.7f);
}
private async UniTask Enter()
{
backdropImage.DOKill();
backdropImage.SetAlpha(0.7f);
IsActive = true;
canvas.enabled = true;
canvas.overrideSorting = true;
canvas.sortingOrder = NavigationSortingOrder.DialogueOverlay;
canvasGroup.enabled = true;
canvasGroup.blocksRaycasts = true;
canvasGroup.interactable = true;
canvasGroup.DOKill();
canvasGroup.DOFade(1, 0.4f).SetEase(Ease.OutCubic);
parent.SetActive(true);
Context.SetMajorCanvasBlockRaycasts(false);
await UniTask.Delay(TimeSpan.FromSeconds(0.4f));
}
private async UniTask Leave()
{
canvasGroup.blocksRaycasts = false;
canvasGroup.interactable = false;
canvasGroup.DOKill();
canvasGroup.DOFade(0, 0.4f).SetEase(Ease.OutCubic);
Context.SetMajorCanvasBlockRaycasts(true);
await UniTask.Delay(TimeSpan.FromSeconds(0.4f));
canvas.enabled = false;
topDialogueBox.SetDisplayed(false);
bottomDialogueBox.SetDisplayed(false);
bottomFullDialogueBox.SetDisplayed(false);
canvasGroup.enabled = false;
parent.SetActive(false);
IsActive = false;
}
public static bool IsShown() => Instance.IsActive;
public static bool TerminateCurrentStory;
public static async UniTask Show(Story story)
{
var instance = Instance;
if (instance.IsActive)
{
await UniTask.WaitUntil(() => !instance.IsActive);
}
await instance.Enter();
var spriteSets = new Dictionary<string, DialogueSpriteSet>();
var animationSets = new Dictionary<string, DialogueAnimationSet>();
if (story.globalTags != null)
{
story.globalTags.FindAll(it => it.Trim().StartsWith("SpriteSet:"))
.Select(it => it.Substring(it.IndexOf(':') + 1).Trim())
.Select(DialogueSpriteSet.Parse)
.ForEach(it => spriteSets[it.Id] = it);
story.globalTags.FindAll(it => it.Trim().StartsWith("AnimationSet:"))
.Select(it => it.Substring(it.IndexOf(':') + 1).Trim())
.Select(DialogueAnimationSet.Parse)
.ForEach(it => animationSets[it.Id] = it);
}
await spriteSets.Values.Select(it => it.Initialize());
await animationSets.Values.Select(it => it.Initialize());
Sprite currentImageSprite = null;
string currentImageSpritePath = null;
Sprite currentSprite = null;
string currentAnimation = null;
var currentSpeaker = "";
var currentPosition = DialogueBoxPosition.Bottom;
var shouldSetImageSprite = false;
Dialogue lastDialogue = null;
DialogueBox lastDialogueBox = null;
DialogueHighlightTarget lastHighlightTarget = null;
while (story.canContinue && !TerminateCurrentStory)
{
var message = ReplacePlaceholders(story.Continue());
var duration = 0f;
var tags = story.currentTags;
var doAction = TagValue(tags, "Action");
if (doAction != null)
{
switch (doAction)
{
case "GamePreparation/ShowGameplayTab":
var tabs = Context.ScreenManager.GetScreen<GamePreparationScreen>().actionTabs;
tabs.OnAction(tabs.Actions.Find(it => it.index == 2));
break;
}
}
var setDuration = TagValue(tags, "Duration");
if (setDuration != null)
{
duration = float.Parse(setDuration);
}
var setOverlayOpacity = TagValue(tags, "OverlayOpacity");
if (setOverlayOpacity != null)
{
setOverlayOpacity.Split('/', out var targetOpacity, out var fadeDuration, out var fadeDelay);
SetOverlayOpacity().Forget();
async UniTaskVoid SetOverlayOpacity()
{
await UniTask.Delay(TimeSpan.FromSeconds(float.Parse(fadeDelay)));
instance.backdropImage.DOFade(float.Parse(targetOpacity), float.Parse(fadeDuration));
}
}
var setHighlight = TagValue(tags, "Highlight");
if (setHighlight != null)
{
lastHighlightTarget = await DialogueHighlightTarget.Find(setHighlight);
if (lastHighlightTarget != null)
{
lastHighlightTarget.Highlighted = true;
}
}
var waitForHighlightOnClick = FlagValue(tags, "WaitForHighlightOnClick");
if (waitForHighlightOnClick && lastHighlightTarget == null)
{
waitForHighlightOnClick = false;
}
var setImage = TagValue(tags, "Image");
string imageWidth = null, imageHeight = null, imageRadius = null;
if (setImage != null)
{
if (setImage == "null")
{
currentImageSprite = null;
}
else
{
setImage.Split('/', out imageWidth, out imageHeight, out imageRadius, out var imageUrl);
imageUrl = ReplacePlaceholders(imageUrl);
SpinnerOverlay.Show();
currentImageSprite = await Context.AssetMemory.LoadAsset<Sprite>(imageUrl, AssetTag.DialogueImage);
currentImageSpritePath = imageUrl;
SpinnerOverlay.Hide();
shouldSetImageSprite = true;
}
}
var setSprite = TagValue(tags, "Sprite");
if (setSprite != null)
{
if (setSprite == "null")
{
currentSprite = null;
DisposeImageSprite();
}
else
{
setSprite.Split('/', out var id, out var state);
if (!spriteSets.ContainsKey(id)) throw new ArgumentOutOfRangeException();
currentSprite = spriteSets[id].States[state].Sprite;
currentAnimation = null;
}
}
var setAnimation = TagValue(tags, "Animation");
if (setAnimation != null)
{
if (setAnimation == "null")
{
currentAnimation = null;
}
else
{
currentAnimation = setAnimation;
currentSprite = null;
}
}
var setSpeaker = TagValue(tags, "Speaker");
if (setSpeaker != null)
{
currentSpeaker = setSpeaker == "null" ? null : setSpeaker;
}
var setPosition = TagValue(tags, "Position");
if (setPosition != null)
{
currentPosition = (DialogueBoxPosition) Enum.Parse(typeof(DialogueBoxPosition), setPosition);
}
var dialogue = new Dialogue
{
Message = message,
SpeakerName = currentSpeaker,
Sprite = currentSprite,
Position = currentPosition,
HasChoices = story.currentChoices.Count > 0,
IsBlocked = waitForHighlightOnClick || duration > 0
};
// Lookup animation
if (currentAnimation != null)
{
currentAnimation.Split('/', out var id, out var animationName);
if (!animationSets.ContainsKey(id)) throw new ArgumentOutOfRangeException();
dialogue.AnimatorController = animationSets[id].Controller;
dialogue.AnimationName = animationName;
}
DialogueBox dialogueBox;
if (dialogue.Position == DialogueBoxPosition.Top) dialogueBox = instance.topDialogueBox;
else if (dialogue.Sprite != null || dialogue.AnimatorController != null) dialogueBox = instance.bottomFullDialogueBox;
else dialogueBox = instance.bottomDialogueBox;
if (lastDialogue != null && (lastDialogueBox != dialogueBox || lastDialogue.SpeakerName != dialogue.SpeakerName))
{
await lastDialogueBox.SetDisplayed(false);
dialogueBox.messageBox.SetLocalScale(1f);
}
// Display image
if (currentImageSprite != null)
{
if (shouldSetImageSprite)
{
instance.image.SetData(currentImageSprite, int.Parse(imageWidth), int.Parse(imageHeight), int.Parse(imageRadius));
await UniTask.Delay(TimeSpan.FromSeconds(1.5f));
shouldSetImageSprite = false;
}
}
else
{
instance.image.Clear();
}
if (message.IsNullOrEmptyTrimmed())
{
await dialogueBox.SetDisplayed(false);
}
else
{
await dialogueBox.SetDisplayed(true);
lastDialogue = dialogue;
lastDialogueBox = dialogueBox;
instance.detectionArea.onPointerDown.SetListener(_ => { dialogueBox.messageBox.DOScale(0.97f, 0.2f); });
instance.detectionArea.onPointerUp.SetListener(_ => { dialogueBox.messageBox.DOScale(1f, 0.2f); });
instance.detectionArea.onPointerClick.SetListener(_ => { dialogueBox.WillFastForwardDialogue = true; });
await dialogueBox.ShowDialogue(dialogue);
}
if (waitForHighlightOnClick)
{
instance.detectionArea.onPointerDown.RemoveAllListeners();
instance.detectionArea.onPointerUp.RemoveAllListeners();
await lastHighlightTarget.WaitForOnClick();
}
else if (story.currentChoices.Count > 0)
{
var proceed = false;
var buttons = new List<SoftButton>();
for (var index = 0; index < story.currentChoices.Count; index++)
{
var choice = story.currentChoices[index];
var choiceButton = Instantiate(instance.choiceButtonPrefab, instance.choicesRoot);
var closureIndex = index;
choiceButton.onPointerClick.SetListener(_ =>
{
if (proceed) return;
story.ChooseChoiceIndex(closureIndex);
proceed = true;
});
choiceButton.Label = choice.text.Get();
buttons.Add(choiceButton);
}
LayoutFixer.Fix(instance.choicesRoot);
await UniTask.DelayFrame(5);
foreach (var button in buttons)
{
button.transitionElement.UseCurrentStateAsDefault();
button.transitionElement.Enter();
await UniTask.Delay(TimeSpan.FromSeconds(0.2f));
}
await UniTask.WaitUntil(() => proceed);
buttons.ForEach(it => Destroy(it.gameObject));
}
else
{
var proceed = false;
instance.detectionArea.onPointerDown.SetListener(_ => { dialogueBox.messageBox.DOScale(0.95f, 0.2f); });
instance.detectionArea.onPointerUp.SetListener(_ =>
{
dialogueBox.messageBox.DOScale(1f, 0.2f);
proceed = true;
});
if (duration > 0)
{
await UniTask.WhenAny(UniTask.WaitUntil(() => proceed),
UniTask.Delay(TimeSpan.FromSeconds(duration)));
}
else
{
await UniTask.WaitUntil(() => proceed);
}
instance.detectionArea.onPointerDown.RemoveAllListeners();
instance.detectionArea.onPointerUp.RemoveAllListeners();
}
if (lastHighlightTarget != null)
{
lastHighlightTarget.Highlighted = false;
lastHighlightTarget = null;
}
}
TerminateCurrentStory = false;
if (lastDialogueBox != null) lastDialogueBox.SetDisplayed(false);
instance.image.Clear();
await instance.Leave();
DisposeImageSprite();
spriteSets.Values.ForEach(it => it.Dispose());
animationSets.Values.ForEach(it => it.Dispose());
string TagValue(List<string> tags, string tag)
{
return tags.Find(it => it.Trim().StartsWith(tag + ":"))?.Let(it => it.Substring(it.IndexOf(':') + 1).Trim());
}
bool FlagValue(List<string> tags, string tag)
{
return tags.Any(it => it.Trim() == tag);
}
void DisposeImageSprite()
{
if (currentImageSprite != null)
{
Context.AssetMemory.DisposeAsset(currentImageSpritePath, AssetTag.DialogueImage);
currentImageSprite = null;
currentImageSpritePath = null;
}
}
string ReplacePlaceholders(string str)
{
str = str.Replace("[N/A]", "");
str = str.Trim();
if (str.StartsWith("[STORY_"))
{
str = str.Substring(1, str.Length - 2).Get();
}
foreach (var (placeholder, function) in PlaceholderFunctions)
{
if (str.Contains(placeholder))
{
str = str.Replace(placeholder, function());
}
}
return str;
}
}
private static readonly Dictionary<string, Func<string>> PlaceholderFunctions = new Dictionary<string, Func<string>>
{
{"[BADGE_TITLE]", () => CurrentBadge.title},
{"[BADGE_DATE]", () => CurrentBadge.date.ToString("yyyy.MM.dd")},
{"[BADGE_DESCRIPTION]", () => CurrentBadge.description},
{"[BADGE_IMAGE_URL]", () => CurrentBadge.GetImageUrl()},
{"[RATING]", () => Context.OnlinePlayer?.LastProfile?.Rating.ToString("N2") ?? "N/A"}
};
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ExternalNoCookieLogin.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryNotEqualTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolNotEqualTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteNotEqualTest(bool useInterpreter)
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharNotEqualTest(bool useInterpreter)
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalNotEqualTest(bool useInterpreter)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleNotEqualTest(bool useInterpreter)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatNotEqualTest(bool useInterpreter)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntNotEqualTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongNotEqualTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteNotEqualTest(bool useInterpreter)
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortNotEqualTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntNotEqualTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongNotEqualTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortNotEqualTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortNotEqual(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyBoolNotEqual(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyByteNotEqual(byte a, byte b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(byte))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyCharNotEqual(char a, char b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(char)),
Expression.Constant(b, typeof(char))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyDecimalNotEqual(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyDoubleNotEqual(double a, double b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyFloatNotEqual(float a, float b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyIntNotEqual(int a, int b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyLongNotEqual(long a, long b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifySByteNotEqual(sbyte a, sbyte b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(sbyte))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyShortNotEqual(short a, short b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyUIntNotEqual(uint a, uint b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyULongNotEqual(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyUShortNotEqual(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.NotEqual(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.NotEqual(null, Expression.Constant(0)));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.NotEqual(Expression.Constant(0), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.NotEqual(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.NotEqual(Expression.Constant(1), value));
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections;
using System.Drawing;
using System.Runtime.CompilerServices;
namespace Encog.App.Quant.Loader.OpenQuant.Data
{
/// <summary>
/// This holds the various data used by Openquant
/// Bars, and various custom series.
/// </summary>
public class Data
{
/// <summary>
/// Different data , a bar holds
/// </summary>
public enum BarData
{
Close,
Open,
High,
Low,
Median,
Typical,
Weighted,
Volume,
OpenInt
}
/// <summary>
/// Different possible prices on a bar.
/// </summary>
public enum BarPrice
{
High,
Low,
Open,
Close,
Median,
Typical,
Weighted
}
public enum BarSlycing
{
Normal,
Equally
}
/// <summary>
/// The different bar types
/// </summary>
public enum BarType : byte
{
/// <summary>
/// Dynamic types.
/// </summary>
Dynamic = 5,
/// <summary>
/// Range bars
/// </summary>
Range = 4,
/// <summary>
/// Tick bars
/// </summary>
Tick = 2,
/// <summary>
/// Time bars (open, high, low, close)
/// </summary>
Time = 1,
Volume = 3
}
/// <summary>
/// Adds two numbers.
/// </summary>
private Func<int, int, int> Add = (x, y) => x + y;
[Serializable]
public class Bar : ICloneable
{
/// <summary>
/// Initializes a new instance of the <see cref="Bar" /> class.
/// </summary>
/// <param name="barType">Type of the bar.</param>
/// <param name="size">The size.</param>
/// <param name="beginTime">The begin time.</param>
/// <param name="endTime">The end time.</param>
/// <param name="open">The open.</param>
/// <param name="high">The high.</param>
/// <param name="low">The low.</param>
/// <param name="close">The close.</param>
/// <param name="volume">The volume.</param>
/// <param name="openInt">The open int.</param>
public Bar(BarType barType, long size, DateTime beginTime, DateTime endTime, double open, double high,
double low, double close, long volume, long openInt)
{
this.barType = barType;
Size = size;
BeginTime = beginTime;
EndTime = endTime;
Open = open;
High = high;
Low = low;
Close = close;
Volume = volume;
OpenInt = openInt;
ProviderId = 0;
color = Color.Empty;
IsComplete = false;
DateKind = beginTime.Kind;
DateTimeKind kind = beginTime.Kind;
DateTimeKind kind2 = endTime.Kind;
}
/// <summary>
/// Initializes a new instance of the <see cref="Bar" /> class.
/// </summary>
/// <param name="size">The size.</param>
/// <param name="open">The open.</param>
/// <param name="high">The high.</param>
/// <param name="low">The low.</param>
/// <param name="close">The close.</param>
public Bar(long size, double open, double high, double low, double close)
{
barType = barType;
Size = size;
BeginTime = beginTime;
Open = open;
High = high;
Low = low;
Close = close;
ProviderId = 0;
color = Color.Empty;
IsComplete = false;
}
#region ICloneable Members
public object Clone()
{
return MemberwiseClone();
}
#endregion
public DateTime DateTime { get; set; }
public double Close { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public DateTime BeginTime { get; set; }
protected DateTime EndTime { get; set; } //end time for this bar.
public TimeSpan Duration { get; set; }
// Fields
protected BarType barType { get; set; }
protected DateTime beginTime { get; set; } //Begin time for this bar
protected Color color { get; set; } //Color the bar should be drawed
protected bool IsComplete { get; set; } // is the bar complete.
protected long OpenInt { get; set; } // open interests on othis bar.
protected byte ProviderId { get; set; } // provider for this bar (a byte , e.g Simulated executions 1.
protected long Size { get; set; } // the size : Lenght in seconds of this bar.
protected long Volume { get; set; } // the volume of this bar.
protected DateTimeKind DateKind { get; set; } //Bar kind.
protected double Weighted { get; set; }
protected double Median { get; set; }
protected double Typical { get; set; }
/// <summary>
/// Gets the last price for a bar price option
/// </summary>
/// <param name="option">The option.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public double GetPrice(BarPrice option)
{
switch (option)
{
case BarPrice.High:
return High;
case BarPrice.Low:
return Low;
case BarPrice.Open:
return Open;
case BarPrice.Close:
return Close;
case BarPrice.Median:
return Median;
case BarPrice.Typical:
return Typical;
case BarPrice.Weighted:
return Weighted;
}
return 0.0;
}
}
/// <summary>
/// holds arrays of bars
/// </summary>
public class BarArray : IEnumerable
{
// Methods
public DataArray BarSeries;
[MethodImpl(MethodImplOptions.NoInlining)]
public BarArray()
{
BarSeries = new DataArray();
}
// Properties
/// <summary>
/// Gets the <see cref="Bar" /> at the specified index.
/// </summary>
public Bar this[int index]
{
[MethodImpl(MethodImplOptions.NoInlining)] get { return this[index]; }
}
public IEnumerator GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Adds the specified bar.
/// </summary>
/// <param name="bar">The bar.</param>
public void Add(Bar bar)
{
BarSeries.Add(bar);
}
}
public interface IDataObject
{
// Properties
DateTime DateTime { get; set; }
byte ProviderId { get; set; }
}
}
}
| |
// Use using to declare namespaces and functions we wish to use
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AnimalNS;
/*
Multiline Comment
*/
// Delegates are used to pass methods as arguments to other methods
// A delegate can represent a method with a similar return type and attribute list
delegate double GetSum(double num1, double num2);
// ---------- ENUMS ----------
// Enums are unique types with symbolic names and associated values
public enum Temperature
{
Freeze,
Low,
Warm,
Boil
}
// ---------- STRUCT ----------
// A struct is a custom type that holds data made up from different data types
struct Customers
{
private string name;
private double balance;
private int id;
public void createCust(string n, double b, int i)
{
name = n;
balance = b;
id = i;
}
public void showCust()
{
Console.WriteLine("Name : " + name);
Console.WriteLine("Balance : " + balance);
Console.WriteLine("ID : " + id);
}
}
// Give our code a custom namespace
namespace ConsoleApplication1
{
class Program
{
// Code in the main function is executed
static void Main(string[] args)
{
// Prints string out to the console with a line break (Write = No Line Break)
Console.WriteLine("What is your name : ");
// Accept input from the user
string name = Console.ReadLine();
// You can combine Strings with +
Console.WriteLine("Hello " + name);
// ---------- DATA TYPES ----------
// Booleans are true or false
bool canVote = true;
// Characters are single 16 bit unicode characters
char grade = 'A';
// Integer with a max number of 2,147,483,647
int maxInt = int.MaxValue;
// Long with a max number of 9,223,372,036,854,775,807
long maxLong = long.MaxValue;
// Decimal has a maximum value of 79,228,162,514,264,337,593,543,950,335
// If you need something bigger look up BigInteger
decimal maxDec = decimal.MaxValue;
// A float is a 32 bit number with a maxValue of 3.402823E+38 with 7 decimals of precision
float maxFloat = float.MaxValue;
// A float is a 32 bit number with a maxValue of 1.797693134E+308 with 15 decimals of precision
double maxDouble = double.MaxValue;
// You can combine strings with other values with +
Console.WriteLine("Max Int : " + maxDouble);
// The dynamic data type is defined at run time
dynamic otherName = "Paul";
otherName = 1;
// The var data type is defined when compiled and then can't change
var anotherName = "Tom";
// ERROR : anotherName = 2;
Console.WriteLine("Hello " + anotherName);
// How to get the type and how to format strings
Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode());
// ---------- MATH ----------
Console.WriteLine("5 + 3 = " + (5 + 3));
Console.WriteLine("5 - 3 = " + (5 - 3));
Console.WriteLine("5 * 3 = " + (5 * 3));
Console.WriteLine("5 / 3 = " + (5 / 3));
Console.WriteLine("5.2 % 3 = " + (5.2 % 3));
int i = 0;
Console.WriteLine("i++ = " + (i++));
Console.WriteLine("++i = " + (++i));
Console.WriteLine("i-- = " + (i--));
Console.WriteLine("--i = " + (--i));
Console.WriteLine("i += 3 " + (i += 3));
Console.WriteLine("i -= 2 " + (i -= 2));
Console.WriteLine("i *= 2 " + (i *= 2));
Console.WriteLine("i /= 2 " + (i /= 2));
Console.WriteLine("i %= 2 " + (i %= 2));
// Casting : If no magnitude is lost casting happens automatically, but otherwise it must be done
// like this
double pi = 3.14;
int intPi = (int)pi; // put the data type to convert to between braces
// Math Functions
// Acos, Asin, Atan, Atan2, Cos, Cosh, Exp, Log, Sin, Sinh, Tan, Tanh
double number1 = 10.5;
double number2 = 15;
Console.WriteLine("Math.Abs(number1) " + (Math.Abs(number1)));
Console.WriteLine("Math.Ceiling(number1) " + (Math.Ceiling(number1)));
Console.WriteLine("Math.Floor(number1) " + (Math.Floor(number1)));
Console.WriteLine("Math.Max(number1, number2) " + (Math.Max(number1, number2)));
Console.WriteLine("Math.Min(number1, number2) " + (Math.Min(number1, number2)));
Console.WriteLine("Math.Pow(number1, 2) " + (Math.Pow(number1, 2)));
Console.WriteLine("Math.Round(number1) " + (Math.Round(number1)));
Console.WriteLine("Math.Sqrt(number1) " + (Math.Sqrt(number1)));
// Random Numbers
Random rand = new Random();
Console.WriteLine("Random Number Between 1 and 10 " + (rand.Next(1,11)));
// ---------- CONDITIONALS ----------
// Relational Operators : > < >= <= == !=
// Logical Operators : && || ^ !
// If Statement
int age = 17;
if ((age >= 5) && (age <= 7)) {
Console.WriteLine("Go to elementary school");
}
else if ((age > 7) && (age < 13)) {
Console.WriteLine("Go to middle school");
}
else {
Console.WriteLine("Go to high school");
}
if ((age < 14) || (age > 67)) {
Console.WriteLine("You shouldn't work");
}
Console.WriteLine("! true = " + (! true));
// Ternary Operator
bool canDrive = age >= 16 ? true : false;
// Switch is used when you have limited options
// Fall through isn't allowed with C# unless there are no statements between cases
// You can't check multiple values at once
switch (age)
{
case 0:
Console.WriteLine("Infant");
break;
case 1:
case 2:
Console.WriteLine("Toddler");
// Goto can be used to jump to a label elsewhere in the code
goto Cute;
default:
Console.WriteLine("Child");
break;
}
// Lable we can jump to with Goto
Cute:
Console.WriteLine("Toddlers are cute");
// ---------- LOOPING ----------
int i = 0;
while (i < 10)
{
// If i = 7 then skip the rest of the code and start with i = 8
if (i == 7)
{
i++;
continue;
}
// Jump completely out of the loop if i = 9
if (i == 9)
{
break;
}
// You can't convert an int into a bool : Print out only odds
if ((i % 2) > 0)
{
Console.WriteLine(i);
}
i++;
}
// The do while loop will go through the loop at least once
string guess;
do
{
Console.WriteLine("Guess a Number ");
guess = Console.ReadLine();
} while (! guess.Equals("15")); // How to check String equality
// Puts all changes to the iterator in one place
for(int j = 0; j < 10; j++)
{
if ((j % 2) > 0)
{
Console.WriteLine(j);
}
}
// foreach cycles through every item in an array or collection
string randStr = "Here are some random characters";
foreach( char c in randStr)
{
Console.WriteLine(c);
}
// ---------- STRINGS ----------
// Escape Sequences : \' \" \\ \b \n \t
string sampString = "A bunch of random words";
// Check if empty
Console.WriteLine("Is empty " + String.IsNullOrEmpty(sampString));
Console.WriteLine("Is empty " + String.IsNullOrWhiteSpace(sampString));
Console.WriteLine("String Length " + sampString.Length);
// Find a string index (Starts with 0)
Console.WriteLine("Index of bunch " + sampString.IndexOf("bunch"));
// Get a substring
Console.WriteLine("2nd Word " + sampString.Substring(2, 6));
string sampString2 = "More random words";
// Are strings equal
Console.WriteLine("Strings equal " + sampString.Equals(sampString2));
// Compare strings
Console.WriteLine("Starts with A bunch " + sampString.StartsWith("A bunch"));
Console.WriteLine("Ends with words " + sampString.EndsWith("words"));
// Trim white space at beginning and end or (TrimEnd / TrimStart)
sampString = sampString.Trim();
// Replace words or characters
sampString = sampString.Replace("words", "characters");
Console.WriteLine(sampString);
// Remove starting at a defined index up to the second index
sampString = sampString.Remove(0,2);
Console.WriteLine(sampString);
// Join values in array and save to string
string[] names = new string[3] { "Matt", "Joe", "Paul" };
Console.WriteLine("Name List " + String.Join(", ", names));
// Formatting : Currency, Decimal Places, Before Decimals, Thousands Separator
string fmtStr = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 1.56, 15.567, .56, 1000);
Console.WriteLine(fmtStr.ToString());
// ---------- STRINGBUILDER ----------
// Each time you create a string you actually create another string in memory
// StringBuilders are used when you want to be able to edit a string without creating new ones
StringBuilder sb = new StringBuilder();
// Append a string to the StringBuilder (AppendLine also adds a newline at the end)
sb.Append("This is the first sentence.");
// Append a formatted string
sb.AppendFormat("My name is {0} and I live in {1}", "Derek", "Pennsylvania");
// Clear the StringBuilder
// sb.Clear();
// Replaces every instance of the first with the second
sb.Replace("a", "e");
// Remove characters starting at the index and then up to the defined index
sb.Remove(5, 7);
// Out put everything
Console.WriteLine(sb.ToString());
// ---------- ARRAYS ----------
// Declare an array
int[] randNumArray;
// Declare the number of items an array can contain
int[] randArray = new int[5];
// Declare and initialize an array
int[] randArray2 = { 1, 2, 3, 4, 5 };
// Get array length
Console.WriteLine("Array Length " + randArray2.Length);
// Get item at index
Console.WriteLine("Item 0 " + randArray2[0]);
// Cycle through array
for (int i = 0; i < randArray2.Length; i++)
{
Console.WriteLine("{0} : {1}", i, randArray2[i]);
}
// Cycle with foreach
foreach (int num in randArray2)
{
Console.WriteLine(num);
}
// Get the index of an item or -1
Console.WriteLine("Where is 1 " + Array.IndexOf(randArray2, 1));
string[] names = { "Tom", "Paul", "Sally" };
// Join an array into a string
string nameStr = string.Join(", ", names);
Console.WriteLine(nameStr);
// Split a string into an array
string[] nameArray = nameStr.Split(',');
// Create a multidimensional array
int[,] multArray = new int[5, 3];
// Create and initialize a multidimensional array
int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
// Cycle through multidimensional array
foreach(int num in multArray2)
{
Console.WriteLine(num);
}
// Cycle and have access to indexes
for (int x = 0; x < multArray2.GetLength(0); x += 1)
{
for (int y = 0; y < multArray2.GetLength(1); y += 1)
{
Console.WriteLine("{0} | {1} : {2}", x, y, multArray2[x, y]);
}
}
// ---------- LISTS ----------
// A list unlike an array automatically resizes
// Create a list and add values
List<int> numList = new List<int>();
numList.Add(5);
numList.Add(15);
numList.Add(25);
// Add an array to a list
int[] randArray = { 1, 2, 3, 4, 5 };
numList.AddRange(randArray);
// Clear a list
// numList.Clear();
// Copy an array into a List
List<int> numList2 = new List<int>(randArray);
// Create a List with array
List<int> numList3 = new List<int>(new int[] { 1, 2, 3, 4 });
// Insert in a specific index
numList.Insert(1, 10);
// Remove a specific value
numList.Remove(5);
// Remove at an index
numList.RemoveAt(2);
// Cycle through a List with foreach or
for (int i = 0; i < numList.Count; i++)
{
Console.WriteLine(numList[i]);
}
// Return the index for a value or -1
Console.WriteLine("4 is in index " + numList3.IndexOf(4));
// Does the List contain a value
Console.WriteLine("5 in list " + numList3.Contains(5));
// Search for a value in a string List
List<string> strList = new List<string>(new string[] { "Tom","Paul" });
Console.WriteLine("Tom in list " + strList.Contains("tom", StringComparer.OrdinalIgnoreCase));
// Sort the List
strList.Sort();
// ---------- EXCEPTION HANDLING ----------
// All the exceptions
// msdn.microsoft.com/en-us/library/system.systemexception.aspx#inheritanceContinued
try
{
Console.Write("Divide 10 by ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine("10 / {0} = {1}", num, (10/num));
}
// Specifically catches the divide by zero exception
catch (DivideByZeroException ex)
{
Console.WriteLine("Can't divide by zero");
// Get additonal info on the exception
Console.WriteLine(ex.GetType().Name);
Console.WriteLine(ex.Message);
// Throw the exception to the next inline
// throw ex;
// Throw a specific exception
throw new InvalidOperationException("Operation Failed", ex);
}
// Catches any other exception
catch (Exception ex)
{
Console.WriteLine("An error occurred");
Console.WriteLine(ex.GetType().Name);
Console.WriteLine(ex.Message);
}
// ---------- CLASSES & OBJECTS ----------
Animal bulldog = new Animal(13, 50, "Spot", "Woof");
Console.WriteLine("{0} says {1}", bulldog.name, bulldog.sound);
// Console.WriteLine("No. of Animals " + Animal.getNumOfAnimals());
// ---------- ENUMS ----------
Temperature micTemp = Temperature.Low;
Console.Write("What Temp : ");
Console.ReadLine();
switch (micTemp)
{
case Temperature.Freeze:
Console.WriteLine("Temp on Freezing");
break;
case Temperature.Low:
Console.WriteLine("Temp on Low");
break;
case Temperature.Warm:
Console.WriteLine("Temp on Warm");
break;
case Temperature.Boil:
Console.WriteLine("Temp on Boil");
break;
}
// ---------- STRUCTS ----------
Customers bob = new Customers();
bob.createCust("Bob", 15.50, 12345);
bob.showCust();
// ---------- ANONYMOUS METHODS ----------
// An anonymous method has no name and its return type is defined by the return used in the method
GetSum sum = delegate (double num1, double num2) {
return num1 + num2;
};
Console.WriteLine("5 + 10 = " + sum(5, 10));
// ---------- LAMBDA EXPRESSIONS ----------
// A lambda expression is used to act as an anonymous function or expression tree
// You can assign the lambda expression to a function instance
Func<int, int, int> getSum = (x, y) => x + y;
Console.WriteLine("5 + 3 = " + getSum.Invoke(5, 3));
// Get odd numbers from a list
List<int> numList = new List<int> { 5, 10, 15, 20, 25 };
// With an Expression Lambda the input goes in the left (n) and the statements go on the right
List<int> oddNums = numList.Where(n => n % 2 == 1).ToList();
foreach (int num in oddNums) {
Console.Write(num + ", ");
}
// ---------- FILE I/O ----------
// The StreamReader and StreamWriter allows you to create text files while reading and
// writing to them
string[] custs = new string[] { "Tom", "Paul", "Greg" };
using (StreamWriter sw = new StreamWriter("custs.txt"))
{
foreach(string cust in custs)
{
sw.WriteLine(cust);
}
}
string custName = "";
using (StreamReader sr = new StreamReader("custs.txt"))
{
while ((custName = sr.ReadLine()) != null)
{
Console.WriteLine(custName);
}
}
Console.Write("Hit Enter to Exit");
string exitApp = Console.ReadLine();
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Newtonsoft.Json;
using QuantConnect.Brokerages.Bitfinex.Messages;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Util;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Order = QuantConnect.Orders.Order;
namespace QuantConnect.Brokerages.Bitfinex
{
/// <summary>
/// Bitfinex Brokerage implementation
/// </summary>
[BrokerageFactory(typeof(BitfinexBrokerageFactory))]
public partial class BitfinexBrokerage : BaseWebsocketsBrokerage, IDataQueueHandler
{
private readonly SymbolPropertiesDatabaseSymbolMapper _symbolMapper = new SymbolPropertiesDatabaseSymbolMapper(Market.Bitfinex);
#region IBrokerage
/// <summary>
/// Checks if the websocket connection is connected or in the process of connecting
/// </summary>
public override bool IsConnected => WebSocket.IsOpen;
/// <summary>
/// Places a new order and assigns a new broker ID to the order
/// </summary>
/// <param name="order">The order to be placed</param>
/// <returns>True if the request for a new order has been placed, false otherwise</returns>
public override bool PlaceOrder(Order order)
{
var parameters = new JsonObject
{
{ "symbol", _symbolMapper.GetBrokerageSymbol(order.Symbol) },
{ "amount", order.Quantity.ToStringInvariant() },
{ "type", ConvertOrderType(_algorithm.BrokerageModel.AccountType, order.Type) },
{ "price", GetOrderPrice(order).ToStringInvariant() }
};
var orderProperties = order.Properties as BitfinexOrderProperties;
if (orderProperties != null)
{
if (order.Type == OrderType.Limit)
{
var flags = 0;
if (orderProperties.Hidden) flags |= OrderFlags.Hidden;
if (orderProperties.PostOnly) flags |= OrderFlags.PostOnly;
parameters.Add("flags", flags);
}
}
var clientOrderId = GetNextClientOrderId();
parameters.Add("cid", clientOrderId);
_orderMap.TryAdd(clientOrderId, order);
var obj = new JsonArray { 0, "on", null, parameters };
var json = JsonConvert.SerializeObject(obj);
WebSocket.Send(json);
return true;
}
/// <summary>
/// Updates the order with the same id
/// </summary>
/// <param name="order">The new order information</param>
/// <returns>True if the request was made for the order to be updated, false otherwise</returns>
public override bool UpdateOrder(Order order)
{
if (order.BrokerId.Count == 0)
{
throw new ArgumentNullException(nameof(order.BrokerId), "BitfinexBrokerage.UpdateOrder: There is no brokerage id to be updated for this order.");
}
if (order.BrokerId.Count > 1)
{
throw new NotSupportedException("BitfinexBrokerage.UpdateOrder: Multiple orders update not supported. Please cancel and re-create.");
}
var parameters = new JsonObject
{
{ "id", Parse.Long(order.BrokerId.First()) },
{ "amount", order.Quantity.ToStringInvariant() },
{ "price", GetOrderPrice(order).ToStringInvariant() }
};
var obj = new JsonArray { 0, "ou", null, parameters };
var json = JsonConvert.SerializeObject(obj);
WebSocket.Send(json);
return true;
}
/// <summary>
/// Cancels the order with the specified ID
/// </summary>
/// <param name="order">The order to cancel</param>
/// <returns>True if the request was submitted for cancellation, false otherwise</returns>
public override bool CancelOrder(Order order)
{
Log.Trace("BitfinexBrokerage.CancelOrder(): {0}", order);
if (!order.BrokerId.Any())
{
// we need the brokerage order id in order to perform a cancellation
Log.Trace("BitfinexBrokerage.CancelOrder(): Unable to cancel order without BrokerId.");
return false;
}
var parameters = new JsonObject
{
{ "id", order.BrokerId.Select(Parse.Long).First() }
};
var obj = new JsonArray { 0, "oc", null, parameters };
var json = JsonConvert.SerializeObject(obj);
WebSocket.Send(json);
return true;
}
/// <summary>
/// Closes the websockets connection
/// </summary>
public override void Disconnect()
{
WebSocket.Close();
}
/// <summary>
/// Gets all orders not yet closed
/// </summary>
/// <returns></returns>
public override List<Order> GetOpenOrders()
{
var endpoint = GetEndpoint("auth/r/orders");
var request = new RestRequest(endpoint, Method.POST);
var parameters = new JsonObject();
request.AddJsonBody(parameters.ToString());
SignRequest(request, endpoint, parameters);
var response = ExecuteRestRequest(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BitfinexBrokerage.GetOpenOrders: request failed: " +
$"[{(int)response.StatusCode}] {response.StatusDescription}, " +
$"Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
var orders = JsonConvert.DeserializeObject<Messages.Order[]>(response.Content)
.Where(OrderFilter(_algorithm.BrokerageModel.AccountType));
var list = new List<Order>();
foreach (var item in orders)
{
Order order;
if (item.Type.Replace("EXCHANGE", "").Trim() == "MARKET")
{
order = new MarketOrder { Price = item.Price };
}
else if (item.Type.Replace("EXCHANGE", "").Trim() == "LIMIT")
{
order = new LimitOrder { LimitPrice = item.Price };
}
else if (item.Type.Replace("EXCHANGE", "").Trim() == "STOP")
{
order = new StopMarketOrder { StopPrice = item.Price };
}
else
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (int)response.StatusCode,
"BitfinexBrokerage.GetOpenOrders: Unsupported order type returned from brokerage: " + item.Type));
continue;
}
order.Quantity = item.Amount;
order.BrokerId = new List<string> { item.Id.ToStringInvariant() };
order.Symbol = _symbolMapper.GetLeanSymbol(item.Symbol, SecurityType.Crypto, Market.Bitfinex);
order.Time = Time.UnixMillisecondTimeStampToDateTime(item.MtsCreate);
order.Status = ConvertOrderStatus(item);
order.Price = item.Price;
list.Add(order);
}
foreach (var item in list)
{
if (item.Status.IsOpen())
{
var cached = CachedOrderIDs
.FirstOrDefault(c => c.Value.BrokerId.Contains(item.BrokerId.First()));
if (cached.Value != null)
{
CachedOrderIDs[cached.Key] = item;
}
}
}
return list;
}
/// <summary>
/// Gets all open positions
/// </summary>
/// <returns></returns>
public override List<Holding> GetAccountHoldings()
{
if (_algorithm.BrokerageModel.AccountType == AccountType.Cash)
{
// For cash account try loading pre - existing currency swaps from the job packet if provided
return base.GetAccountHoldings(_job?.BrokerageData, _algorithm?.Securities.Values);
}
var endpoint = GetEndpoint("auth/r/positions");
var request = new RestRequest(endpoint, Method.POST);
var parameters = new JsonObject();
request.AddJsonBody(parameters.ToString());
SignRequest(request, endpoint, parameters);
var response = ExecuteRestRequest(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BitfinexBrokerage.GetAccountHoldings: request failed: " +
$"[{(int)response.StatusCode}] {response.StatusDescription}, " +
$"Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
var positions = JsonConvert.DeserializeObject<Position[]>(response.Content);
return positions.Where(p => p.Amount != 0 && p.Symbol.StartsWith("t"))
.Select(ConvertHolding)
.ToList();
}
/// <summary>
/// Gets the total account cash balance for specified account type
/// </summary>
/// <returns></returns>
public override List<CashAmount> GetCashBalance()
{
var endpoint = GetEndpoint("auth/r/wallets");
var request = new RestRequest(endpoint, Method.POST);
var parameters = new JsonObject();
request.AddJsonBody(parameters.ToString());
SignRequest(request, endpoint, parameters);
var response = ExecuteRestRequest(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"BitfinexBrokerage.GetCashBalance: request failed: " +
$"[{(int)response.StatusCode}] {response.StatusDescription}, " +
$"Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
var availableWallets = JsonConvert.DeserializeObject<Wallet[]>(response.Content)
.Where(WalletFilter(_algorithm.BrokerageModel.AccountType));
var list = new List<CashAmount>();
foreach (var item in availableWallets)
{
if (item.Balance > 0)
{
list.Add(new CashAmount(item.Balance, GetLeanCurrency(item.Currency)));
}
}
var balances = list.ToDictionary(x => x.Currency);
if (_algorithm.BrokerageModel.AccountType == AccountType.Margin)
{
// include cash balances from currency swaps for open Crypto positions
foreach (var holding in GetAccountHoldings().Where(x => x.Symbol.SecurityType == SecurityType.Crypto))
{
var defaultQuoteCurrency = _algorithm.Portfolio.CashBook.AccountCurrency;
CurrencyPairUtil.DecomposeCurrencyPair(holding.Symbol, out var baseCurrency, out var quoteCurrency, defaultQuoteCurrency);
var baseQuantity = holding.Quantity;
CashAmount baseCurrencyAmount;
balances[baseCurrency] = balances.TryGetValue(baseCurrency, out baseCurrencyAmount)
? new CashAmount(baseQuantity + baseCurrencyAmount.Amount, baseCurrency)
: new CashAmount(baseQuantity, baseCurrency);
var quoteQuantity = -holding.Quantity * holding.AveragePrice;
CashAmount quoteCurrencyAmount;
balances[quoteCurrency] = balances.TryGetValue(quoteCurrency, out quoteCurrencyAmount)
? new CashAmount(quoteQuantity + quoteCurrencyAmount.Amount, quoteCurrency)
: new CashAmount(quoteQuantity, quoteCurrency);
}
}
return balances.Values.ToList();
}
/// <summary>
/// Gets the history for the requested security
/// </summary>
/// <param name="request">The historical data request</param>
/// <returns>An enumerable of bars covering the span specified in the request</returns>
public override IEnumerable<BaseData> GetHistory(Data.HistoryRequest request)
{
if (request.Symbol.SecurityType != SecurityType.Crypto)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidSecurityType",
$"{request.Symbol.SecurityType} security type not supported, no history returned"));
yield break;
}
if (request.Resolution == Resolution.Tick || request.Resolution == Resolution.Second)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidResolution",
$"{request.Resolution} resolution not supported, no history returned"));
yield break;
}
if (request.StartTimeUtc >= request.EndTimeUtc)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidDateRange",
"The history request start date must precede the end date, no history returned"));
yield break;
}
var symbol = _symbolMapper.GetBrokerageSymbol(request.Symbol);
var resultionTimeSpan = request.Resolution.ToTimeSpan();
var resolutionString = ConvertResolution(request.Resolution);
var resolutionTotalMilliseconds = (long)request.Resolution.ToTimeSpan().TotalMilliseconds;
var endpoint = $"{ApiVersion}/candles/trade:{resolutionString}:{symbol}/hist?limit=1000&sort=1";
// Bitfinex API only allows to support trade bar history requests.
// The start and end dates are expected to match exactly with the beginning of the first bar and ending of the last.
// So we need to round up dates accordingly.
var startTimeStamp = (long)Time.DateTimeToUnixTimeStamp(request.StartTimeUtc.RoundDown(resultionTimeSpan)) * 1000;
var endTimeStamp = (long)Time.DateTimeToUnixTimeStamp(request.EndTimeUtc.RoundDown(resultionTimeSpan)) * 1000;
do
{
var timeframe = $"&start={startTimeStamp}&end={endTimeStamp}";
var restRequest = new RestRequest(endpoint + timeframe, Method.GET);
var response = ExecuteRestRequest(restRequest);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(
$"BitfinexBrokerage.GetHistory: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, " +
$"Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
}
// Drop the last bar provided by the exchange as its open time is a history request's end time
var candles = JsonConvert.DeserializeObject<object[][]>(response.Content)
.Select(entries => new Candle(entries))
.Where(candle => candle.Timestamp != endTimeStamp)
.ToList();
// Bitfinex exchange may return us an empty result - if we request data for a small time interval
// during which no trades occurred - so it's rational to ensure 'candles' list is not empty before
// we proceed to avoid an exception to be thrown
if (candles.Any())
{
startTimeStamp = candles.Last().Timestamp + resolutionTotalMilliseconds;
}
else
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "NoHistoricalData",
$"Exchange returned no data for {symbol} on history request " +
$"from {request.StartTimeUtc:s} to {request.EndTimeUtc:s}"));
yield break;
}
foreach (var candle in candles)
{
yield return new TradeBar
{
Time = Time.UnixMillisecondTimeStampToDateTime(candle.Timestamp),
Symbol = request.Symbol,
Low = candle.Low,
High = candle.High,
Open = candle.Open,
Close = candle.Close,
Volume = candle.Volume,
Value = candle.Close,
DataType = MarketDataType.TradeBar,
Period = resultionTimeSpan,
EndTime = Time.UnixMillisecondTimeStampToDateTime(candle.Timestamp + (long)resultionTimeSpan.TotalMilliseconds)
};
}
} while (startTimeStamp < endTimeStamp);
}
#endregion IBrokerage
#region IDataQueueHandler
/// <summary>
/// Sets the job we're subscribing for
/// </summary>
/// <param name="job">Job we're subscribing for</param>
public void SetJob(LiveNodePacket job)
{
var apiKey = job.BrokerageData["bitfinex-api-key"];
var apiSecret = job.BrokerageData["bitfinex-api-secret"];
var aggregator = Composer.Instance.GetExportedValueByTypeName<IDataAggregator>(
Config.Get("data-aggregator", "QuantConnect.Lean.Engine.DataFeeds.AggregationManager"), forceTypeNameOnExisting: false);
Initialize(
wssUrl: WebSocketUrl,
websocket: new WebSocketClientWrapper(),
restClient: new RestClient(RestApiUrl),
apiKey: apiKey,
apiSecret: apiSecret,
algorithm: null,
aggregator: aggregator,
job: job
);
if (!IsConnected)
{
Connect();
}
}
/// <summary>
/// Subscribe to the specified configuration
/// </summary>
/// <param name="dataConfig">defines the parameters to subscribe to a data feed</param>
/// <param name="newDataAvailableHandler">handler to be fired on new data available</param>
/// <returns>The new enumerator for this subscription request</returns>
public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler)
{
if (!CanSubscribe(dataConfig.Symbol))
{
return null;
}
var enumerator = _aggregator.Add(dataConfig, newDataAvailableHandler);
SubscriptionManager.Subscribe(dataConfig);
return enumerator;
}
/// <summary>
/// Removes the specified configuration
/// </summary>
/// <param name="dataConfig">Subscription config to be removed</param>
public void Unsubscribe(SubscriptionDataConfig dataConfig)
{
SubscriptionManager.Unsubscribe(dataConfig);
_aggregator.Remove(dataConfig);
}
#endregion IDataQueueHandler
/// <summary>
/// Event invocator for the Message event
/// </summary>
/// <param name="e">The error</param>
public new void OnMessage(BrokerageMessageEvent e)
{
base.OnMessage(e);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
_aggregator.Dispose();
_restRateLimiter.Dispose();
_connectionRateLimiter.Dispose();
_onSubscribeEvent.Dispose();
_onUnsubscribeEvent.Dispose();
}
private bool CanSubscribe(Symbol symbol)
{
if (symbol.Value.Contains("UNIVERSE") || !_symbolMapper.IsKnownLeanSymbol(symbol))
{
return false;
}
return symbol.ID.Market == Market.Bitfinex;
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="TransactionInterop.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
using System;
using System.Configuration;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Transactions.Oletx;
using System.Transactions.Configuration;
using System.Transactions.Diagnostics;
namespace System.Transactions
{
// This is here for the "DTC" in the name.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[ComImport,
Guid("0fb15084-af41-11ce-bd2b-204c4f4f5020"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDtcTransaction
{
void Commit(int retaining,
[MarshalAs(UnmanagedType.I4)] int commitType,
int reserved);
void Abort(IntPtr reason,
int retaining,
int async);
void GetTransactionInfo( IntPtr transactionInformation);
}
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")]
public static class TransactionInterop
{
internal static OletxTransaction ConvertToOletxTransaction(
Transaction transaction
)
{
if ( null == transaction )
{
throw new ArgumentNullException( "transaction" );
}
if ( transaction.Disposed )
{
throw new ObjectDisposedException( "Transaction" );
}
if ( transaction.complete )
{
throw TransactionException.CreateTransactionCompletedException(SR.GetString(SR.TraceSourceLtm), transaction.DistributedTxId);
}
OletxTransaction oletxTx = transaction.Promote();
System.Diagnostics.Debug.Assert( oletxTx != null, "transaction.Promote returned null instead of throwing." );
return oletxTx;
}
// This is here for the DangerousGetHandle call. We need to do it.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
public static byte[] GetExportCookie(
Transaction transaction,
byte[] whereabouts
)
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
byte[] cookie = null;
if ( null == transaction )
{
throw new ArgumentNullException( "transaction" );
}
if ( null == whereabouts )
{
throw new ArgumentNullException( "whereabouts" );
}
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetExportCookie"
);
}
// Copy the whereabouts so that it cannot be modified later.
byte[] whereaboutsCopy = new byte[whereabouts.Length];
Array.Copy(whereabouts, whereaboutsCopy, whereabouts.Length);
whereabouts = whereaboutsCopy;
int cookieIndex = 0;
UInt32 cookieSize = 0;
CoTaskMemHandle cookieBuffer = null;
// First, make sure we are working with an OletxTransaction.
OletxTransaction oletxTx = TransactionInterop.ConvertToOletxTransaction( transaction );
try
{
oletxTx.realOletxTransaction.TransactionShim.Export(
Convert.ToUInt32(whereabouts.Length),
whereabouts,
out cookieIndex,
out cookieSize,
out cookieBuffer );
// allocate and fill in the cookie
cookie = new byte[cookieSize];
Marshal.Copy( cookieBuffer.DangerousGetHandle(), cookie, 0, Convert.ToInt32(cookieSize) );
}
catch (COMException comException)
{
OletxTransactionManager.ProxyException( comException );
// We are unsure of what the exception may mean. It is possible that
// we could get E_FAIL when trying to contact a transaction manager that is
// being blocked by a fire wall. On the other hand we may get a COMException
// based on bad data. The more common situation is that the data is fine
// (since it is generated by Microsoft code) and the problem is with
// communication. So in this case we default for unknown exceptions to
// assume that the problem is with communication.
throw TransactionManagerCommunicationException.Create( SR.GetString( SR.TraceSourceOletx ), comException );
}
finally
{
if ( null != cookieBuffer )
{
cookieBuffer.Close();
}
}
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetExportCookie"
);
}
return cookie;
}
public static Transaction GetTransactionFromExportCookie(
byte[] cookie
)
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
if ( null == cookie )
{
throw new ArgumentNullException( "cookie" );
}
if ( cookie.Length < 32 )
{
throw new ArgumentException( SR.GetString( SR.InvalidArgument ), "cookie" );
}
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromExportCookie"
);
}
byte[] cookieCopy = new byte[cookie.Length];
Array.Copy(cookie, cookieCopy, cookie.Length);
cookie = cookieCopy;
Transaction transaction = null;
ITransactionShim transactionShim = null;
Guid txIdentifier = Guid.Empty;
OletxTransactionIsolationLevel oletxIsoLevel = OletxTransactionIsolationLevel.ISOLATIONLEVEL_SERIALIZABLE;
OutcomeEnlistment outcomeEnlistment = null;
OletxTransaction oleTx = null;
// Extract the transaction guid from the propagation token to see if we already have a
// transaction object for the transaction.
byte[] guidByteArray = new byte[16];
for (int i = 0; i < guidByteArray.Length; i++ )
{
// In a cookie, the transaction guid is preceeded by a signature guid.
guidByteArray[i] = cookie[i + 16];
}
Guid txId = new Guid( guidByteArray );
// First check to see if there is a promoted LTM transaction with the same ID. If there
// is, just return that.
transaction = TransactionManager.FindPromotedTransaction( txId );
if ( null != transaction )
{
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromExportCookie"
);
}
return transaction;
}
// We need to create a new transaction
RealOletxTransaction realTx = null;
OletxTransactionManager oletxTm = TransactionManager.DistributedTransactionManager;
oletxTm.dtcTransactionManagerLock.AcquireReaderLock( -1 );
try
{
outcomeEnlistment = new OutcomeEnlistment();
IntPtr outcomeEnlistmentHandle = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
outcomeEnlistmentHandle = HandleTable.AllocHandle( outcomeEnlistment );
oletxTm.DtcTransactionManager.ProxyShimFactory.Import(
Convert.ToUInt32(cookie.Length),
cookie,
outcomeEnlistmentHandle,
out txIdentifier,
out oletxIsoLevel,
out transactionShim );
}
finally
{
if ( transactionShim == null && outcomeEnlistmentHandle != IntPtr.Zero )
{
HandleTable.FreeHandle( outcomeEnlistmentHandle );
}
}
}
catch ( COMException comException )
{
OletxTransactionManager.ProxyException( comException );
// We are unsure of what the exception may mean. It is possible that
// we could get E_FAIL when trying to contact a transaction manager that is
// being blocked by a fire wall. On the other hand we may get a COMException
// based on bad data. The more common situation is that the data is fine
// (since it is generated by Microsoft code) and the problem is with
// communication. So in this case we default for unknown exceptions to
// assume that the problem is with communication.
throw TransactionManagerCommunicationException.Create( SR.GetString( SR.TraceSourceOletx ), comException );
}
finally
{
oletxTm.dtcTransactionManagerLock.ReleaseReaderLock();
}
// We need to create a new RealOletxTransaction.
realTx = new RealOletxTransaction(
oletxTm,
transactionShim,
outcomeEnlistment,
txIdentifier,
oletxIsoLevel,
false );
// Now create the associated OletxTransaction.
oleTx = new OletxTransaction( realTx );
// If a transaction is found then FindOrCreate will Dispose the oletx
// created.
transaction = TransactionManager.FindOrCreatePromotedTransaction( txId, oleTx );
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromExportCookie"
);
}
return transaction;
}
public static byte[] GetTransmitterPropagationToken(
Transaction transaction
)
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
if ( null == transaction )
{
throw new ArgumentNullException( "transaction" );
}
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransmitterPropagationToken"
);
}
// First, make sure we are working with an OletxTransaction.
OletxTransaction oletxTx = TransactionInterop.ConvertToOletxTransaction( transaction );
byte[] token = GetTransmitterPropagationToken( oletxTx );
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransmitterPropagationToken"
);
}
return token;
}
// This is here for the DangerousGetHandle call. We need to do it.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
internal static byte[] GetTransmitterPropagationToken(
OletxTransaction oletxTx
)
{
byte[] propagationToken = null;
CoTaskMemHandle propagationTokenBuffer = null;
UInt32 tokenSize = 0;
try
{
oletxTx.realOletxTransaction.TransactionShim.GetPropagationToken(
out tokenSize,
out propagationTokenBuffer );
propagationToken = new byte[tokenSize];
Marshal.Copy( propagationTokenBuffer.DangerousGetHandle(), propagationToken, 0, Convert.ToInt32(tokenSize) );
}
catch (COMException comException)
{
OletxTransactionManager.ProxyException( comException );
throw;
}
finally
{
if ( null != propagationTokenBuffer )
{
propagationTokenBuffer.Close();
}
}
return propagationToken;
}
public static Transaction GetTransactionFromTransmitterPropagationToken(
byte[] propagationToken
)
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
Transaction returnValue = null;
if ( null == propagationToken )
{
throw new ArgumentNullException( "propagationToken" );
}
if ( propagationToken.Length < 24 )
{
throw new ArgumentException( SR.GetString( SR.InvalidArgument ), "propagationToken" );
}
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromTransmitterPropagationToken"
);
}
// Extract the transaction guid from the propagation token to see if we already have a
// transaction object for the transaction.
byte[] guidByteArray = new byte[16];
for (int i = 0; i < guidByteArray.Length; i++ )
{
// In a propagation token, the transaction guid is preceeded by two version DWORDs.
guidByteArray[i] = propagationToken[i + 8];
}
Guid txId = new Guid( guidByteArray );
// First check to see if there is a promoted LTM transaction with the same ID. If there
// is, just return that.
Transaction tx = TransactionManager.FindPromotedTransaction( txId );
if ( null != tx )
{
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromTransmitterPropagationToken"
);
}
return tx;
}
OletxTransaction oleTx = TransactionInterop.GetOletxTransactionFromTransmitterPropigationToken( propagationToken );
// If a transaction is found then FindOrCreate will Dispose the oletx
// created.
returnValue = TransactionManager.FindOrCreatePromotedTransaction( txId, oleTx );
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromTransmitterPropagationToken"
);
}
return returnValue;
}
internal static OletxTransaction GetOletxTransactionFromTransmitterPropigationToken(
byte[] propagationToken
)
{
Guid identifier;
OletxTransactionIsolationLevel oletxIsoLevel;
OutcomeEnlistment outcomeEnlistment;
ITransactionShim transactionShim = null;
if ( null == propagationToken )
{
throw new ArgumentNullException( "propagationToken" );
}
if ( propagationToken.Length < 24 )
{
throw new ArgumentException( SR.GetString( SR.InvalidArgument ), "propagationToken" );
}
byte[] propagationTokenCopy = new byte[propagationToken.Length];
Array.Copy(propagationToken, propagationTokenCopy, propagationToken.Length);
propagationToken = propagationTokenCopy;
// First we need to create an OletxTransactionManager from Config.
OletxTransactionManager oletxTm = TransactionManager.DistributedTransactionManager;
oletxTm.dtcTransactionManagerLock.AcquireReaderLock( -1 );
try
{
outcomeEnlistment = new OutcomeEnlistment();
IntPtr outcomeEnlistmentHandle = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
outcomeEnlistmentHandle = HandleTable.AllocHandle( outcomeEnlistment );
oletxTm.DtcTransactionManager.ProxyShimFactory.ReceiveTransaction(
Convert.ToUInt32(propagationToken.Length),
propagationToken,
outcomeEnlistmentHandle,
out identifier,
out oletxIsoLevel,
out transactionShim
);
}
finally
{
if ( transactionShim == null && outcomeEnlistmentHandle != IntPtr.Zero )
{
HandleTable.FreeHandle( outcomeEnlistmentHandle );
}
}
}
catch ( COMException comException )
{
OletxTransactionManager.ProxyException( comException );
// We are unsure of what the exception may mean. It is possible that
// we could get E_FAIL when trying to contact a transaction manager that is
// being blocked by a fire wall. On the other hand we may get a COMException
// based on bad data. The more common situation is that the data is fine
// (since it is generated by Microsoft code) and the problem is with
// communication. So in this case we default for unknown exceptions to
// assume that the problem is with communication.
throw TransactionManagerCommunicationException.Create( SR.GetString( SR.TraceSourceOletx ), comException );
}
finally
{
oletxTm.dtcTransactionManagerLock.ReleaseReaderLock();
}
RealOletxTransaction realTx = null;
realTx = new RealOletxTransaction(
oletxTm,
transactionShim,
outcomeEnlistment,
identifier,
oletxIsoLevel,
false );
return new OletxTransaction( realTx );
}
// This is here for the "Dtc" in the name.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public static IDtcTransaction GetDtcTransaction(
Transaction transaction
)
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
if ( null == transaction )
{
throw new ArgumentNullException( "transaction" );
}
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetDtcTransaction"
);
}
IDtcTransaction transactionNative = null;
// First, make sure we are working with an OletxTransaction.
OletxTransaction oletxTx = TransactionInterop.ConvertToOletxTransaction( transaction );
try
{
oletxTx.realOletxTransaction.TransactionShim.GetITransactionNative( out transactionNative );
}
catch ( COMException comException )
{
OletxTransactionManager.ProxyException( comException );
throw;
}
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetDtcTransaction"
);
}
return transactionNative;
}
// This is here for the "DTC" in the name.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public static Transaction GetTransactionFromDtcTransaction(
IDtcTransaction transactionNative
)
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
bool tooLate = false;
ITransactionShim transactionShim = null;
Guid txIdentifier = Guid.Empty;
OletxTransactionIsolationLevel oletxIsoLevel = OletxTransactionIsolationLevel.ISOLATIONLEVEL_SERIALIZABLE;
OutcomeEnlistment outcomeEnlistment = null;
RealOletxTransaction realTx = null;
OletxTransaction oleTx = null;
if ( null == transactionNative )
{
throw new ArgumentNullException( "transactionNative" );
}
Transaction transaction = null;
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromDtc"
);
}
// Let's get the guid of the transaction from the proxy to see if we already
// have an object.
ITransactionNativeInternal myTransactionNative = transactionNative as ITransactionNativeInternal;
if ( null == myTransactionNative )
{
throw new ArgumentException( SR.GetString( SR.InvalidArgument ), "transactionNative" );
}
OletxXactTransInfo xactInfo;
try
{
myTransactionNative.GetTransactionInfo( out xactInfo );
}
catch ( COMException ex )
{
if ( Oletx.NativeMethods.XACT_E_NOTRANSACTION != ex.ErrorCode )
{
throw;
}
// If we get here, the transaction has appraently already been committed or aborted. Allow creation of the
// OletxTransaction, but it will be marked with a status of InDoubt and attempts to get its Identifier
// property will result in a TransactionException.
tooLate = true;
xactInfo.uow = Guid.Empty;
}
OletxTransactionManager oletxTm = TransactionManager.DistributedTransactionManager;
if ( ! tooLate )
{
// First check to see if there is a promoted LTM transaction with the same ID. If there
// is, just return that.
transaction = TransactionManager.FindPromotedTransaction( xactInfo.uow );
if ( null != transaction )
{
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromDtcTransaction"
);
}
return transaction;
}
// We need to create a new RealOletxTransaction...
oletxTm.dtcTransactionManagerLock.AcquireReaderLock( -1 );
try
{
outcomeEnlistment = new OutcomeEnlistment();
IntPtr outcomeEnlistmentHandle = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
outcomeEnlistmentHandle = HandleTable.AllocHandle( outcomeEnlistment );
oletxTm.DtcTransactionManager.ProxyShimFactory.CreateTransactionShim(
transactionNative,
outcomeEnlistmentHandle,
out txIdentifier,
out oletxIsoLevel,
out transactionShim );
}
finally
{
if ( transactionShim == null && outcomeEnlistmentHandle != IntPtr.Zero )
{
HandleTable.FreeHandle( outcomeEnlistmentHandle );
}
}
}
catch ( COMException comException )
{
OletxTransactionManager.ProxyException( comException );
throw;
}
finally
{
oletxTm.dtcTransactionManagerLock.ReleaseReaderLock();
}
// We need to create a new RealOletxTransaction.
realTx = new RealOletxTransaction(
oletxTm,
transactionShim,
outcomeEnlistment,
txIdentifier,
oletxIsoLevel,
false );
oleTx = new OletxTransaction( realTx );
// If a transaction is found then FindOrCreate will Dispose the oletx
// created.
transaction = TransactionManager.FindOrCreatePromotedTransaction( xactInfo.uow, oleTx );
}
else
{
// It was too late to do a clone of the provided ITransactionNative, so we are just going to
// create a RealOletxTransaction without a transaction shim or outcome enlistment.
realTx = new RealOletxTransaction(
oletxTm,
null,
null,
txIdentifier,
OletxTransactionIsolationLevel.ISOLATIONLEVEL_SERIALIZABLE,
false );
oleTx = new OletxTransaction( realTx );
transaction = new Transaction( oleTx );
TransactionManager.FireDistributedTransactionStarted( transaction );
oleTx.savedLtmPromotedTransaction = transaction;
InternalTransaction.DistributedTransactionOutcome(transaction.internalTransaction, TransactionStatus.InDoubt);
}
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetTransactionFromDtc"
);
}
return transaction;
}
public static byte[] GetWhereabouts(
)
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
byte[] returnValue = null;
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetWhereabouts"
);
}
OletxTransactionManager oletxTm = TransactionManager.DistributedTransactionManager;
if ( null == oletxTm )
{
throw new ArgumentException( SR.GetString( SR.ArgumentWrongType ), "transactionManager" );
}
oletxTm.dtcTransactionManagerLock.AcquireReaderLock( -1 );
try
{
returnValue = oletxTm.DtcTransactionManager.Whereabouts;
}
finally
{
oletxTm.dtcTransactionManagerLock.ReleaseReaderLock();
}
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"TransactionInterop.GetWhereabouts"
);
}
return returnValue;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections;
namespace testing
{
/// <summary>
/// Serializable class for testing serializable tree.
/// </summary>
[Serializable]
public class SerializableThing
{
public int i, j, k;
public SerializableThing(int i, int j, int k)
{
this.i = i;
this.j = j;
this.k = k;
}
public override bool Equals(object obj)
{
if (! (obj is SerializableThing))
{
return false;
}
SerializableThing other = (SerializableThing) obj;
return (other.i == this.i) && (other.j == this.j) && (other.k == this.k);
}
public override int GetHashCode()
{
return this.i^(this.j<<8)^(this.k<<16);
}
}
/// <summary>
/// tests main entry point for bplusdotnet. Throws exception on failure.
/// </summary>
public class bplusTest
{
static string tempdirectory = @"c:\tmp"; // set to a directory to test storing to/from files
static Hashtable allinserts = new Hashtable();
static Hashtable lastcommittedinserts = new Hashtable();
static bool full = true;
static int keylength = 20;
static int prefixlength = 6;
static int nodesize = 6;
static int buffersize = 100;
static int bucketsizelimit = 100; // sanity check
static bool DoAllTests = true;
public static void Main()
{
if (DoAllTests)
{
byteStringTest();
intTests();
longTests();
shortTests();
//BplusDotNet.BufferFile nullbf = new BplusDotNet.BufferFile(null, 90);
testBufferFile();
LinkedFileTest();
BplusTreeLongTest();
//bplustreetest();
Test();
xTest();
hTest();
sTest();
}
CompatTest();
}
static string keyMaker(int i, int j, int k)
{
int selector = (i+j+k)%3;
string result = ""+i+"."+j+"."+k;
if (selector==0)
{
result = ""+k+"."+(j%5)+"."+i;
}
else if (selector==1)
{
result = ""+k+"."+j+"."+i;
}
return result;
}
static string xkeyMaker(int i, int j, int k)
{
string result = keyMaker(i,j,k);
result = result+result+result;
result = result + keyMaker(k,i,j);
return result;
}
static string ValueMaker(int i, int j, int k)
{
if ( ((i+j+k)%5) == 3 )
{
return "";
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("value");
for (int x=0; x<i+k*5; x++)
{
sb.Append(j);
sb.Append(k);
}
return sb.ToString();
}
public static void hTest()
{
string watchKey = ""; //"4.3.04.3.04.3.03.0.4";
Console.WriteLine("TESTING HBPLUSTREE");
System.IO.Stream treefile=null, blockfile=null;
BplusDotNet.hBplusTree bpt = getHTree(null, ref treefile, ref blockfile);
Hashtable allmaps = new Hashtable();
for (int i=0; i<10; i++)
{
Console.WriteLine("Pass "+i+" of 10");
bpt.SetFootPrintLimit(16-i);
for (int j=0; j<30; j++)
{
Hashtable record = new Hashtable();
for (int k=0; k<30; k++)
{
string thiskey = xkeyMaker(i,j,k);
string thisvalue = ValueMaker(j,k,i);
if (thiskey.Equals(watchKey))
{
Debug.WriteLine("<br> NOW SETTING "+watchKey);
}
record[thiskey] = thisvalue;
bpt[thiskey] = thisvalue;
if (thiskey.Equals(watchKey))
{
Debug.WriteLine("<br> AFTER SETTING "+bpt.toHtml());
}
}
if ((j%3)==1)
{
bpt.Recover(false);
}
if ( ((i+j)%2) == 1 )
{
bpt.Commit();
bpt.Abort(); // should have no effect
bpt.Commit(); // ditto
if ( (i+j)%5 < 2)
{
//Debug.WriteLine(bpt.toHtml());
foreach (DictionaryEntry d in record)
{
string thiskey = (string) d.Key;
bpt.RemoveKey(thiskey);
if (thiskey.Equals(watchKey))
{
Debug.WriteLine("<br> NOW REMOVING "+watchKey);
}
if (allmaps.ContainsKey(thiskey))
{
allmaps.Remove(thiskey);
}
}
//Debug.WriteLine(bpt.toHtml());
bpt.Commit();
//return;
}
else
{
foreach (DictionaryEntry d in record)
{
allmaps[d.Key] = d.Value;
}
}
}
else
{
bpt.Abort();
}
if ((j%4)==2)
{
bpt = getHTree(bpt, ref treefile, ref blockfile);
}
// now check the structure
//ArrayList allkeys = new ArrayList();
foreach (DictionaryEntry d in allmaps)
{
string thiskey = (string)d.Key;
string thisvalue = (string)d.Value;
if (thiskey.Equals(watchKey))
{
Debug.WriteLine(" retrieving "+thiskey);
}
string treemap = bpt[thiskey];
if (!treemap.Equals(thisvalue))
{
throw new ApplicationException("key "+thiskey+" maps to "+treemap+" but should map to "+thisvalue);
}
//allkeys.Add(thiskey);
}
string currentkey = bpt.FirstKey();
Hashtable visited = new Hashtable();
//allkeys.Sort();
while (currentkey!=null)
{
if (visited.ContainsKey(currentkey))
{
throw new ApplicationException("key visited twice in traversal "+currentkey);
}
visited[currentkey] = currentkey;
if (!allmaps.ContainsKey(currentkey))
{
throw new ApplicationException("key found in tree but not in hash table "+currentkey);
}
currentkey = bpt.NextKey(currentkey);
}
}
}
}
public static void xTest()
{
Console.WriteLine("TESTING XBPLUSTREE");
System.IO.Stream treefile=null, blockfile=null;
BplusDotNet.xBplusTree bpt = getXTree(null, ref treefile, ref blockfile);
Hashtable allmaps = new Hashtable();
for (int i=0; i<10; i++)
{
Console.WriteLine("Pass "+i+" of 10");
bpt.SetFootPrintLimit(16-i);
for (int j=0; j<30; j++)
{
Hashtable record = new Hashtable();
for (int k=0; k<30; k++)
{
string thiskey = xkeyMaker(i,j,k);
string thisvalue = ValueMaker(j,k,i);
record[thiskey] = thisvalue;
bpt[thiskey] = thisvalue;
}
if ((j%3)==1)
{
bpt.Recover(false);
}
if ( ((i+j)%2) == 1 )
{
bpt.Commit();
bpt.Abort(); // should have no effect
bpt.Commit(); // ditto
if ( (i+j)%5 < 2)
{
//Debug.WriteLine(bpt.toHtml());
foreach (DictionaryEntry d in record)
{
string thiskey = (string) d.Key;
bpt.RemoveKey(thiskey);
if (allmaps.ContainsKey(thiskey))
{
allmaps.Remove(thiskey);
}
}
//Debug.WriteLine(bpt.toHtml());
bpt.Commit();
//return;
}
else
{
foreach (DictionaryEntry d in record)
{
allmaps[d.Key] = d.Value;
}
}
}
else
{
bpt.Abort();
}
if ((j%4)==2)
{
bpt = getXTree(bpt, ref treefile, ref blockfile);
}
// now check the structure
ArrayList allkeys = new ArrayList();
foreach (DictionaryEntry d in allmaps)
{
string thiskey = (string)d.Key;
string thisvalue = (string)d.Value;
string treemap = bpt[thiskey];
if (!treemap.Equals(thisvalue))
{
throw new ApplicationException("key "+thiskey+" maps to "+treemap+" but should map to "+thisvalue);
}
allkeys.Add(thiskey);
}
string currentkey = bpt.FirstKey();
allkeys.Sort();
foreach (object thing in allkeys)
{
//Debug.WriteLine("currentkey = "+currentkey);
string recordedkey = (string) thing;
if (currentkey==null)
{
throw new ApplicationException("end of keys found when expecting "+recordedkey);
}
if (!currentkey.Equals(recordedkey))
{
Debug.WriteLine(bpt.toHtml());
throw new ApplicationException("key "+currentkey+" found where expecting "+recordedkey);
}
currentkey = bpt.NextKey(currentkey);
}
if (currentkey!=null)
{
throw new ApplicationException("found "+currentkey+" when expecting end of keys");
}
}
}
}
public static void sTest()
{
Console.WriteLine("TESTING SERIALIZEDTREE");
System.IO.Stream treefile=null, blockfile=null;
BplusDotNet.SerializedTree bpt = getsTree(null, ref treefile, ref blockfile);
Hashtable allmaps = new Hashtable();
for (int i=0; i<10; i++)
{
Console.WriteLine("Pass "+i+" of 10");
bpt.SetFootPrintLimit(16-i);
for (int j=0; j<30; j++)
{
Hashtable record = new Hashtable();
for (int k=0; k<30; k++)
{
string thiskey = keyMaker(i,j,k);
SerializableThing thisvalue = new SerializableThing(j,k,i);
record[thiskey] = thisvalue;
bpt[thiskey] = thisvalue;
}
if ((j%3)==1)
{
bpt.Recover(false);
}
if ( ((i+j)%2) == 1 )
{
bpt.Commit();
bpt.Abort(); // should have no effect
bpt.Commit(); // ditto
if ( (i+j)%5 < 2)
{
//Debug.WriteLine(bpt.toHtml());
foreach (DictionaryEntry d in record)
{
string thiskey = (string) d.Key;
bpt.RemoveKey(thiskey);
if (allmaps.ContainsKey(thiskey))
{
allmaps.Remove(thiskey);
}
}
//Debug.WriteLine(bpt.toHtml());
bpt.Commit();
//return;
}
else
{
foreach (DictionaryEntry d in record)
{
allmaps[d.Key] = d.Value;
}
}
}
else
{
bpt.Abort();
}
if ((j%4)==2)
{
bpt = getsTree(bpt, ref treefile, ref blockfile);
}
// now check the structure
ArrayList allkeys = new ArrayList();
foreach (DictionaryEntry d in allmaps)
{
string thiskey = (string)d.Key;
SerializableThing thisvalue = (SerializableThing)d.Value;
SerializableThing treemap = (SerializableThing)bpt[thiskey];
if (!treemap.Equals(thisvalue))
{
throw new ApplicationException("key "+thiskey+" maps to "+treemap+" but should map to "+thisvalue);
}
allkeys.Add(thiskey);
}
string currentkey = bpt.FirstKey();
allkeys.Sort();
foreach (object thing in allkeys)
{
string recordedkey = (string) thing;
if (currentkey==null)
{
throw new ApplicationException("end of keys found when expecting "+recordedkey);
}
if (!currentkey.Equals(recordedkey))
{
//Debug.WriteLine(bpt.toHtml());
throw new ApplicationException("key "+currentkey+" found where expecting "+recordedkey);
}
currentkey = bpt.NextKey(currentkey);
}
if (currentkey!=null)
{
throw new ApplicationException("found "+currentkey+" when expecting end of keys");
}
}
}
}
public static void Test()
{
Console.WriteLine("TESTING BPLUSTREE");
System.IO.Stream treefile=null, blockfile=null;
BplusDotNet.BplusTree bpt = getTree(null, ref treefile, ref blockfile);
Hashtable allmaps = new Hashtable();
for (int i=0; i<10; i++)
{
Console.WriteLine("Pass "+i+" of 10");
bpt.SetFootPrintLimit(16-i);
for (int j=0; j<30; j++)
{
Hashtable record = new Hashtable();
for (int k=0; k<30; k++)
{
string thiskey = keyMaker(i,j,k);
string thisvalue = ValueMaker(j,k,i);
record[thiskey] = thisvalue;
bpt[thiskey] = thisvalue;
}
if ((j%3)==1)
{
bpt.Recover(false);
}
if ( ((i+j)%2) == 1 )
{
bpt.Commit();
bpt.Abort(); // should have no effect
bpt.Commit(); // ditto
if ( (i+j)%5 < 2)
{
//Debug.WriteLine(bpt.toHtml());
foreach (DictionaryEntry d in record)
{
string thiskey = (string) d.Key;
bpt.RemoveKey(thiskey);
if (allmaps.ContainsKey(thiskey))
{
allmaps.Remove(thiskey);
}
}
//Debug.WriteLine(bpt.toHtml());
bpt.Commit();
//return;
}
else
{
foreach (DictionaryEntry d in record)
{
allmaps[d.Key] = d.Value;
}
}
}
else
{
bpt.Abort();
}
if ((j%4)==2)
{
bpt = getTree(bpt, ref treefile, ref blockfile);
}
// now check the structure
bool ReadOnly = ((i+j)%7)<2;
if (ReadOnly)
{
bpt = getTree(bpt, ref treefile, ref blockfile, true);
}
ArrayList allkeys = new ArrayList();
foreach (DictionaryEntry d in allmaps)
{
string thiskey = (string)d.Key;
string thisvalue = (string)d.Value;
string treemap = bpt[thiskey];
if (!treemap.Equals(thisvalue))
{
throw new ApplicationException("key "+thiskey+" maps to "+treemap+" but should map to "+thisvalue);
}
allkeys.Add(thiskey);
}
string currentkey = bpt.FirstKey();
allkeys.Sort();
foreach (object thing in allkeys)
{
string recordedkey = (string) thing;
if (currentkey==null)
{
throw new ApplicationException("end of keys found when expecting "+recordedkey);
}
if (!currentkey.Equals(recordedkey))
{
Debug.WriteLine(bpt.toHtml());
throw new ApplicationException("key "+currentkey+" found where expecting "+recordedkey);
}
currentkey = bpt.NextKey(currentkey);
}
if (currentkey!=null)
{
throw new ApplicationException("found "+currentkey+" when expecting end of keys");
}
// set up bpt for modification again...
if (ReadOnly)
{
bpt = getTree(bpt, ref treefile, ref blockfile, false);
}
}
}
}
public static BplusDotNet.BplusTree getTree(BplusDotNet.BplusTree bpt, ref System.IO.Stream treefile, ref System.IO.Stream blockfile)
{
return getTree(bpt, ref treefile, ref blockfile, false);
}
public static BplusDotNet.BplusTree getTree(BplusDotNet.BplusTree bpt, ref System.IO.Stream treefile, ref System.IO.Stream blockfile,
bool ReadOnly)
{
int CultureId = System.Globalization.CultureInfo.InvariantCulture.LCID;
if (tempdirectory!=null)
{
// allocate in filesystem
string treename = System.IO.Path.Combine(tempdirectory, "BPDNtree.dat");
string blockname = System.IO.Path.Combine(tempdirectory, "BPDNblock.dat");
treefile = null;
blockfile = null;
if (bpt == null)
{
// allocate new
if (System.IO.File.Exists(treename))
{
System.IO.File.Delete(treename);
}
if (System.IO.File.Exists(blockname))
{
System.IO.File.Delete(blockname);
}
bpt = BplusDotNet.BplusTree.Initialize(treename, blockname, keylength, CultureId, nodesize, buffersize);
}
else
{
// reopen old
bpt.Shutdown();
if (ReadOnly)
{
bpt = BplusDotNet.BplusTree.ReadOnly(treename, blockname);
}
else
{
bpt = BplusDotNet.BplusTree.ReOpen(treename, blockname);
}
}
}
else
{
// allocate in memory
if (bpt==null)
{
// allocate new
treefile = new System.IO.MemoryStream();
blockfile = new System.IO.MemoryStream();;
bpt = BplusDotNet.BplusTree.Initialize(treefile, blockfile, keylength, CultureId, nodesize, buffersize);
}
else
{
// reopen
bpt = BplusDotNet.BplusTree.ReOpen(treefile, blockfile);
}
}
return bpt;
}
public static BplusDotNet.SerializedTree getsTree(BplusDotNet.SerializedTree bpts, ref System.IO.Stream treefile, ref System.IO.Stream blockfile)
{
int CultureId = System.Globalization.CultureInfo.InvariantCulture.LCID;
BplusDotNet.IByteTree bpt = null;
if (tempdirectory!=null)
{
// allocate in filesystem
string treename = System.IO.Path.Combine(tempdirectory, "BPDNtreeS.dat");
string blockname = System.IO.Path.Combine(tempdirectory, "BPDNblockS.dat");
treefile = null;
blockfile = null;
if (bpts == null)
{
// allocate new
if (System.IO.File.Exists(treename))
{
System.IO.File.Delete(treename);
}
if (System.IO.File.Exists(blockname))
{
System.IO.File.Delete(blockname);
}
bpt = BplusDotNet.xBplusTreeBytes.Initialize(treename, blockname, prefixlength, CultureId, nodesize, buffersize);
}
else
{
// reopen old
bpts.Shutdown();
bpt = BplusDotNet.xBplusTreeBytes.ReOpen(treename, blockname);
}
}
else
{
// allocate in memory
if (bpts==null)
{
// allocate new
treefile = new System.IO.MemoryStream();
blockfile = new System.IO.MemoryStream();;
bpt = BplusDotNet.xBplusTreeBytes.Initialize(treefile, blockfile, prefixlength, CultureId, nodesize, buffersize);
}
else
{
// reopen
bpt = BplusDotNet.xBplusTreeBytes.ReOpen(treefile, blockfile);
}
}
return new BplusDotNet.SerializedTree(bpt);
}
public static BplusDotNet.hBplusTree getHTree(BplusDotNet.hBplusTree bpt, ref System.IO.Stream treefile, ref System.IO.Stream blockfile)
{
int CultureId = System.Globalization.CultureInfo.InvariantCulture.LCID;
if (tempdirectory!=null)
{
// allocate in filesystem
string treename = System.IO.Path.Combine(tempdirectory, "BPDNtreeH.dat");
string blockname = System.IO.Path.Combine(tempdirectory, "BPDNblockH.dat");
treefile = null;
blockfile = null;
if (bpt == null)
{
// allocate new
if (System.IO.File.Exists(treename))
{
System.IO.File.Delete(treename);
}
if (System.IO.File.Exists(blockname))
{
System.IO.File.Delete(blockname);
}
bpt = BplusDotNet.hBplusTree.Initialize(treename, blockname, prefixlength, CultureId, nodesize, buffersize);
}
else
{
// reopen old
bpt.Shutdown();
bpt = BplusDotNet.hBplusTree.ReOpen(treename, blockname);
}
}
else
{
// allocate in memory
if (bpt==null)
{
// allocate new
treefile = new System.IO.MemoryStream();
blockfile = new System.IO.MemoryStream();;
bpt = BplusDotNet.hBplusTree.Initialize(treefile, blockfile, prefixlength, CultureId, nodesize, buffersize);
}
else
{
// reopen
bpt = BplusDotNet.hBplusTree.ReOpen(treefile, blockfile);
}
}
return bpt;
}
public static BplusDotNet.xBplusTree getXTree(BplusDotNet.xBplusTree bpt, ref System.IO.Stream treefile, ref System.IO.Stream blockfile)
{
int CultureId = System.Globalization.CultureInfo.InvariantCulture.LCID;
if (tempdirectory!=null)
{
// allocate in filesystem
string treename = System.IO.Path.Combine(tempdirectory, "BPDNtreeX.dat");
string blockname = System.IO.Path.Combine(tempdirectory, "BPDNblockX.dat");
treefile = null;
blockfile = null;
if (bpt == null)
{
// allocate new
if (System.IO.File.Exists(treename))
{
System.IO.File.Delete(treename);
}
if (System.IO.File.Exists(blockname))
{
System.IO.File.Delete(blockname);
}
bpt = BplusDotNet.xBplusTree.Initialize(treename, blockname, prefixlength, CultureId, nodesize, buffersize);
}
else
{
// reopen old
bpt.Shutdown();
bpt = BplusDotNet.xBplusTree.ReOpen(treename, blockname);
}
}
else
{
// allocate in memory
if (bpt==null)
{
// allocate new
treefile = new System.IO.MemoryStream();
blockfile = new System.IO.MemoryStream();;
bpt = BplusDotNet.xBplusTree.Initialize(treefile, blockfile, keylength, CultureId, nodesize, buffersize);
}
else
{
// reopen
bpt = BplusDotNet.xBplusTree.ReOpen(treefile, blockfile);
}
}
bpt.LimitBucketSize(bucketsizelimit);
return bpt;
}
public static void bplustreetest()
{
allinserts = new Hashtable();
System.IO.Stream treestream = new System.IO.MemoryStream();
System.IO.Stream blockstream = new System.IO.MemoryStream();
int KeyLength = 15;
BplusDotNet.BplusTree bpt = BplusDotNet.BplusTree.Initialize(treestream, blockstream, KeyLength);
bpt["this"] = "that";
bpt["this2"] = "that";
bpt["a"] = "xxx";
bpt["c"] = "delete me";
bpt.Recover(true);
bpt.Commit();
bpt["b"] = "yyy";
bpt["a"] = "BAD VALUE";
bpt.Abort();
bpt.RemoveKey("c");
bpt.Recover(false);
string test = bpt["this"];
Debug.WriteLine("got "+test);
test = bpt.FirstKey();
while (test!=null)
{
Debug.WriteLine(test+" :: "+bpt[test]);
test = bpt.NextKey(test);
}
}
public static void abort(BplusDotNet.BplusTreeLong bpt)
{
Debug.WriteLine(" <h3>ABORT!</H3>");
bpt.Abort();
allinserts = (Hashtable) lastcommittedinserts.Clone();
checkit(bpt);
}
public static void commit(BplusDotNet.BplusTreeLong bpt)
{
Debug.WriteLine(" <h3>COMMIT!</H3>");
bpt.Commit();
lastcommittedinserts = (Hashtable)allinserts.Clone();
checkit(bpt);
}
public static BplusDotNet.BplusTreeLong restart(BplusDotNet.BplusTreeLong bpt)
{
Debug.WriteLine(" <h3>RESTART!</H3>");
commit(bpt);
return BplusDotNet.BplusTreeLong.SetupFromExistingStream(bpt.Fromfile, bpt.SeekStart);
}
public static void inserttest(BplusDotNet.BplusTreeLong bpt, string key, long map)
{
inserttest(bpt, key, map, false);
}
public static void deletetest(BplusDotNet.BplusTreeLong bpt, string key, long map)
{
inserttest(bpt, key, map, true);
}
public static void inserttest(BplusDotNet.BplusTreeLong bpt, string key, long map, bool del)
{
if (del)
{
Debug.WriteLine(" <h3>DELETE bpt["+key+"] = "+map+"</h3>");
bpt.RemoveKey(key);
allinserts.Remove(key);
}
else
{
Debug.WriteLine("<h3>bpt["+key+"] = "+map+"</h3>");
bpt[key] = map;
allinserts[key] = map;
}
checkit(bpt);
}
public static void checkit(BplusDotNet.BplusTreeLong bpt)
{
Debug.WriteLine(bpt.toHtml());
bpt.SanityCheck(true);
ArrayList allkeys = new ArrayList();
foreach (DictionaryEntry d in allinserts)
{
allkeys.Add(d.Key);
}
allkeys.Sort();
allkeys.Reverse();
foreach (object thing in allkeys)
{
string thekey = (string) thing;
long thevalue = (long) allinserts[thing];
if (thevalue!=bpt[thekey])
{
throw new ApplicationException("no match on retrieval "+thekey+" --> "+bpt[thekey]+" not "+thevalue);
}
}
allkeys.Reverse();
string currentkey = bpt.FirstKey();
foreach (object thing in allkeys)
{
string testkey = (string) thing;
if (currentkey==null)
{
throw new ApplicationException("end of keys found when expecting "+testkey);
}
if (!testkey.Equals(currentkey))
{
throw new ApplicationException("when walking found "+currentkey+" when expecting "+testkey);
}
currentkey = bpt.NextKey(testkey);
}
}
public static void BplusTreeLongTest()
{
Console.WriteLine("TESTING BPLUSTREELONG -- LOTS OF OUTPUT to Debug.WriteLine(...)");
for (int nodesize=2; nodesize<6; nodesize++)
{
allinserts = new Hashtable();
System.IO.Stream mstream = new System.IO.MemoryStream();
int keylength = 10+nodesize;
BplusDotNet.BplusTreeLong bpt = BplusDotNet.BplusTreeLong.InitializeInStream(mstream, keylength, nodesize);
bpt = restart(bpt);
//bpt["d"] = 15;
inserttest(bpt, "d", 15);
deletetest(bpt, "d", 15);
inserttest(bpt, "d", 15);
inserttest(bpt, "", 99);
bpt.SerializationCheck();
//bpt["ab"] = 55;
inserttest(bpt, "ab", 55);
//bpt["b"] = -5;
inserttest(bpt, "b", -5);
deletetest(bpt, "b", 0);
inserttest(bpt, "b", -5);
//return;
//bpt["c"] = 34;
inserttest(bpt, "c", 34);
//bpt["a"] = 8;
inserttest(bpt, "a", 8);
commit(bpt);
Debug.WriteLine("<h1>after commit</h1>\r\n");
Debug.WriteLine(bpt.toHtml());
//bpt["a"] = 800;
inserttest(bpt, "a", 800);
//bpt["ca"]= -999;
inserttest(bpt, "ca", -999);
//bpt["da"]= -999;
inserttest(bpt, "da", -999);
//bpt["ea"]= -9991;
inserttest(bpt, "ea", -9991);
//bpt["aa"]= -9992;
inserttest(bpt, "aa", -9992);
//bpt["ba"]= -9995;
inserttest(bpt, "ba", -9995);
commit(bpt);
//bpt["za"]= -9997;
inserttest(bpt, "za", -9997);
//bpt[" a"]= -9999;
inserttest(bpt, " a", -9999);
commit(bpt);
deletetest(bpt, "d", 0);
deletetest(bpt, "da", 0);
deletetest(bpt, "ca", 0);
bpt = restart(bpt);
inserttest(bpt, "aaa", 88);
Console.WriteLine(" now doing torture test for "+nodesize);
Debug.WriteLine("<h1>now doing torture test for "+nodesize+"</h1>");
if (full)
{
for (int i=0; i<33; i++)
{
for (int k=0; k<10; k++)
{
int m = (i*5+k*23)%77;
string s = "b"+m;
inserttest(bpt, s, m);
if (i%2==1 || k%3==1)
{
deletetest(bpt, s, m);
}
}
int j = i%3;
if (j==0)
{
abort(bpt);
}
else if (j==1)
{
commit(bpt);
}
else
{
bpt = restart(bpt);
}
}
}
commit(bpt);
deletetest(bpt, "za", 0);
deletetest(bpt, "ea", 0);
deletetest(bpt, "c", 0);
deletetest(bpt, "ba", 0);
deletetest(bpt, "b", 0);
deletetest(bpt, "ab", 0);
abort(bpt);
inserttest(bpt, "dog", 1);
commit(bpt);
deletetest(bpt, "dog", 1);
inserttest(bpt, "pig", 2);
abort(bpt);
inserttest(bpt, "cat", 3);
bpt.Recover(true);
}
}
public static String CompatKey(int i, int j, int k, int l)
{
String seed = "i="+i+" j="+j+" k="+k+" ";
String result = seed;
// for (int ii=0; ii<l; ii++)
// {
// result += seed;
// }
return ""+l+result;
}
public static String CompatValue(int i, int j, int k, int l)
{
String result = CompatKey(k,j,l,i)+CompatKey(l,k,j,i);
return result+result;
}
public static void CompatTest()
{
if (tempdirectory==null)
{
Console.WriteLine(" compatibility test requires temp directory to be defined: please edit test source file");
return;
}
string myTreeFileName = tempdirectory+"\\CsharpTree.dat";
string myBlocksFileName = tempdirectory+"\\CsharpBlocks.dat";
string otherTreeFileName = tempdirectory+"\\JavaTree.dat";
string otherBlocksFileName = tempdirectory+"\\JavaBlocks.dat";
Hashtable map = new Hashtable();
Console.WriteLine(" creating "+myTreeFileName+" and "+myBlocksFileName);
if (System.IO.File.Exists(myTreeFileName))
{
Console.WriteLine(" deleting existing files");
System.IO.File.Delete(myTreeFileName);
System.IO.File.Delete(myBlocksFileName);
}
BplusDotNet.hBplusTree myTree = BplusDotNet.hBplusTree.Initialize(myTreeFileName, myBlocksFileName, 6);
for (int i=0; i<10; i++)
{
Console.WriteLine(" "+i);
for (int j=0; j<10; j++)
{
for (int k=0; k<10; k++)
{
for (int l=0; l<10; l++)
{
String TheKey = CompatKey(i,j,k,l);
String TheValue = CompatValue(i,j,k,l);
map[TheKey] = TheValue;
myTree[TheKey] = TheValue;
}
}
}
}
myTree.Commit();
myTree.Shutdown();
Console.WriteLine(" trying to test "+otherTreeFileName+" and "+otherBlocksFileName);
if (!System.IO.File.Exists(otherTreeFileName))
{
Console.WriteLine(" file not created yet :(");
//return;
}
else
{
int count = 0;
BplusDotNet.hBplusTree otherTree = BplusDotNet.hBplusTree.ReadOnly(otherTreeFileName, otherBlocksFileName);
foreach (DictionaryEntry D in map)
{
if ( (count%1000)==1)
{
Console.WriteLine(" ... "+count);
}
String TheKey = (String) D.Key;
String TheValue = (String) D.Value;
String OtherValue = otherTree[TheKey];
if (!OtherValue.Equals(TheValue) )
{
throw new Exception(" Values don't match "+TheValue+" "+OtherValue);
}
count++;
}
}
otherTreeFileName = tempdirectory+"\\PyTree.dat";
otherBlocksFileName = tempdirectory+"\\PyBlocks.dat";
Console.WriteLine(" trying to test "+otherTreeFileName+" and "+otherBlocksFileName);
if (!System.IO.File.Exists(otherTreeFileName))
{
Console.WriteLine(" file not created yet :(");
//return;
}
else
{
int count = 0;
BplusDotNet.hBplusTree otherTree = BplusDotNet.hBplusTree.ReadOnly(otherTreeFileName, otherBlocksFileName);
foreach (DictionaryEntry D in map)
{
if ( (count%1000)==1)
{
Console.WriteLine(" ... "+count);
}
String TheKey = (String) D.Key;
String TheValue = (String) D.Value;
String OtherValue = otherTree[TheKey];
if (!OtherValue.Equals(TheValue) )
{
throw new Exception(" Values don't match "+TheValue+" "+OtherValue);
}
count++;
}
}
Console.WriteLine(" compatibility test ok");
}
public static void LinkedFileTest()
{
Console.WriteLine("TESTING LINKED FILE");
System.IO.Stream mstream = new System.IO.MemoryStream();
// make a bunch of sample data
int asize = 200;
//int asize = 2;
int maxsizing = 53;
int prime = 17;
int buffersize = 33;
string seedData = "a wop bop a loo bop";
byte[][] stuff = new byte[asize][];
for (int i=0; i<asize; i++)
{
stuff[i] = makeSampleData(seedData, (i*prime)%maxsizing);
}
// store them off
BplusDotNet.LinkedFile lf = BplusDotNet.LinkedFile.InitializeLinkedFileInStream(mstream, buffersize, prime);
lf.checkStructure();
long[] seeks = new long[asize];
for (int i=0; i<asize; i++)
{
seeks[i] = lf.StoreNewChunk(stuff[i], 0, stuff[i].Length);
// allocated it again and delete it off to mix things up...
long dummy = lf.StoreNewChunk(stuff[i], 0, stuff[i].Length);
lf.ReleaseBuffers(dummy);
lf.checkStructure();
}
// delete the last one
lf.ReleaseBuffers(seeks[asize-1]);
lf.checkStructure();
lf.Flush();
// create new handle
lf = BplusDotNet.LinkedFile.SetupFromExistingStream(mstream, prime);
// read them back and check (except for last)
for (int i=0; i<asize-1; i++)
{
byte[] retrieved = lf.GetChunk(seeks[i]);
testByteArrays(retrieved, stuff[i]);
// delete every so often
if (i%prime==1)
{
lf.ReleaseBuffers(seeks[i]);
lf.checkStructure();
}
}
lf.checkStructure();
Debug.WriteLine("");
Debug.WriteLine("linked file tests ok");
}
public static byte[] makeSampleData(string testdata, int sizing)
{
if (testdata.Length<1 || sizing<1)
{
return new byte[0];
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i=0; i<sizing; i++)
{
char c = testdata[i % testdata.Length];
sb.Append(testdata);
sb.Append(c);
}
string result = sb.ToString();
return System.Text.UTF8Encoding.ASCII.GetBytes(result);
}
public static void testBufferFile()
{
Console.WriteLine("TESTING BUFFERFILE");
int buffersize = 17;
int writesize = 10;
System.IO.Stream mstream = new System.IO.MemoryStream();
int offset = 55;
BplusDotNet.BufferFile bf = BplusDotNet.BufferFile.InitializeBufferFileInStream(mstream, buffersize, offset);
byte[] testheader = bf.MakeHeader();
byte[] inputarray = makeSampleData("THIS IS SOME sample data off the cuff...", 100);
byte[] outputarray = new byte[inputarray.Length];
int position = 0;
// shove in the testdata in reverse order
for (int i=inputarray.Length; i>writesize; i-=writesize)
{
Debug.Write(" "+position);
//Console.Write(" "+position);
bf.SetBuffer(position, inputarray, i-writesize, writesize);
position++;
}
bf.SetBuffer(position, inputarray, 0, writesize);
// extract it again
bf = BplusDotNet.BufferFile.SetupFromExistingStream(mstream, offset);
position = 0;
Debug.WriteLine("");
//Console.WriteLine("");
for (int i=inputarray.Length; i>writesize; i-=writesize)
{
Debug.Write(" "+position);
//Console.Write(" "+position);
bf.GetBuffer(position, outputarray, i-writesize, writesize);
position++;
}
bf.GetBuffer(position, outputarray, 0, writesize);
testByteArrays(inputarray, outputarray);
Debug.WriteLine("");
Debug.WriteLine(" buffer file test ok");
}
public static void testByteArrays(byte[] a, byte[] b)
{
if (a.Length!=b.Length)
{
throw new Exception("array lengths don't match "+a.Length+" "+b.Length);
}
for (int i=0; i<b.Length; i++)
{
if (a[i]!=b[i])
{
throw new Exception("first error at "+i+" "+a[i]+" "+b[i]);
}
}
}
public static void intTests()
{
int bsize = 13;
byte[] buffer = new byte[bsize];
int[] ints = {1, 566, -55, 32888, 4201010, 87878, -8989898};
int index = 99;
foreach (int theInt in ints)
{
index = Math.Abs(index) % (bsize-4);
BplusDotNet.BufferFile.Store(theInt, buffer, index);
int otherInt = BplusDotNet.BufferFile.Retrieve(buffer, index);
if (theInt!=otherInt)
{
throw new Exception("encode/decode int failed "+theInt+"!="+otherInt);
}
index = (index+theInt);
}
Debug.WriteLine("encode/decode of ints ok");
}
public static void shortTests()
{
int bsize = 13;
byte[] buffer = new byte[bsize];
short[] shorts = {1, 566, -32766, 32, 32755, 80, -8989};
int index = 99;
foreach (short theInt in shorts)
{
index = Math.Abs(index) % (bsize-4);
BplusDotNet.BufferFile.Store(theInt, buffer, index);
short otherInt = BplusDotNet.BufferFile.RetrieveShort(buffer, index);
if (theInt!=otherInt)
{
throw new Exception("encode/decode int failed "+theInt+"!="+otherInt);
}
index = (index+theInt);
}
Debug.WriteLine("encode/decode of longs ok");
}
public static void longTests()
{
int bsize = 17;
byte[] buffer = new byte[bsize];
long[] longs = {1, 566, -55, 32888, 4201010, 87878, -8989898, 0xefaefabbccddee, -0xefaefabbccddee};
int index = 99;
foreach (long theLong in longs)
{
index = Math.Abs(index) % (bsize-8);
BplusDotNet.BufferFile.Store(theLong, buffer, index);
long otherLong = BplusDotNet.BufferFile.RetrieveLong(buffer, index);
if (theLong!=otherLong)
{
throw new Exception("encode/decode int failed "+theLong+"!="+otherLong);
}
index = (index+((int)(theLong&0xffffff)));
}
Debug.WriteLine("encode/decode of longs ok");
}
public static void byteStringTest()
{
byte[] testbytes = new byte[128];
for (byte i=0; i<128; i++)
{
testbytes[i] = i;
}
string teststring = BplusDotNet.BplusTree.BytesToString(testbytes);
if (teststring.Length!=128)
{
throw new Exception("test string changed length "+teststring.Length);
}
testbytes = BplusDotNet.BplusTree.StringToBytes(teststring);
if (testbytes.Length!=128)
{
throw new Exception("test string changed length "+teststring.Length);
}
//string test = BplusDotNet.hBplusTreeBytes.PrefixForByteCount1("thisThing", 5);
//Debug.WriteLine("hash of thisThing is for len 5 '"+test+"'");
}
}
}
| |
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;
namespace UnrealBuildTool
{
public class UWPToolChain : UEToolChain
{
public override void RegisterToolChain()
{
if( UWPPlatform.bEnableUWPSupport )
{
// Register this tool chain for UWP
Log.TraceVerbose(" Registered for {0}", CPPTargetPlatform.UWP.ToString());
UEToolChain.RegisterPlatformToolChain(CPPTargetPlatform.UWP, this);
}
}
static void AppendCLArguments_Global(CPPEnvironment CompileEnvironment, VCEnvironment EnvVars, StringBuilder Arguments)
{
//Arguments.Append(" /showIncludes");
if( BuildConfiguration.bEnableCodeAnalysis )
{
Arguments.Append(" /analyze");
// Don't cause analyze warnings to be errors
Arguments.Append(" /analyze:WX-");
// Report functions that use a LOT of stack space. You can lower this value if you
// want more aggressive checking for functions that use a lot of stack memory.
Arguments.Append(" /analyze:stacksize81940");
// Don't bother generating code, only analyze code (may report fewer warnings though.)
//Arguments.Append(" /analyze:only");
}
// Prevents the compiler from displaying its logo for each invocation.
Arguments.Append(" /nologo");
// Enable intrinsic functions.
Arguments.Append(" /Oi");
// Pack struct members on 8-byte boundaries.
Arguments.Append(" /Zp8");
// Separate functions for linker.
Arguments.Append(" /Gy");
// Relaxes floating point precision semantics to allow more optimization.
Arguments.Append(" /fp:fast");
// Compile into an .obj file, and skip linking.
Arguments.Append(" /c");
// Allow 800% of the default memory allocation limit.
Arguments.Append(" /Zm800");
// Allow large object files to avoid hitting the 2^16 section limit when running with -StressTestUnity.
Arguments.Append(" /bigobj");
// Disable "The file contains a character that cannot be represented in the current code page" warning for non-US windows.
Arguments.Append(" /wd4819");
// @todo UWP: Disable "unreachable code" warning since auto-included vccorlib.h triggers it
Arguments.Append(" /wd4702");
// @todo UWP: Silence the hash_map deprecation errors for now. This should be replaced with unordered_map for the real fix.
if (WindowsPlatform.Compiler == WindowsCompiler.VisualStudio2015)
{
Arguments.Append(" /D_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS");
}
if ( BuildConfiguration.bUseSharedPCHs )
{
// @todo SharedPCH: Disable warning about PCH defines not matching .cpp defines. We "cheat" these defines a little
// bit to make shared PCHs work. But it's totally safe. Trust us.
Arguments.Append(" /wd4651");
// @todo SharedPCH: Disable warning about redefining *API macros. The PCH header is compiled with various DLLIMPORTs, but
// when a module that uses that PCH header *IS* one of those imports, that module is compiled with EXPORTS, so the macro
// is redefined on the command-line. We need to clobber those defines to make shared PCHs work properly!
Arguments.Append(" /wd4005");
}
// If compiling as a DLL, set the relevant defines
if (CompileEnvironment.Config.bIsBuildingDLL)
{
Arguments.Append(" /D_WINDLL");
}
// Handle Common Language Runtime support (C++/CLI)
if (CompileEnvironment.Config.CLRMode == CPPCLRMode.CLREnabled)
{
Arguments.Append(" /clr");
// Don't use default lib path, we override it explicitly to use the 4.0 reference assemblies.
Arguments.Append(" /clr:nostdlib");
}
//
// Debug
//
if (CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Debug)
{
// Disable compiler optimization.
Arguments.Append(" /Od");
// Favor code size (especially useful for embedded platforms).
Arguments.Append(" /Os");
// Allow inline method expansion unless E&C support is requested
if( !BuildConfiguration.bSupportEditAndContinue )
{
// @todo UWP: No inlining in Debug builds except in the editor where DLL exports/imports aren't handled properly in module _API macros.
if (UEBuildConfiguration.bBuildEditor)
{
Arguments.Append(" /Ob2");
}
}
// Runtime stack checks are not allowed when compiling for CLR
if (CompileEnvironment.Config.CLRMode == CPPCLRMode.CLRDisabled)
{
Arguments.Append(" /RTCs");
}
}
//
// Development and LTCG
//
else
{
// Maximum optimizations if desired.
if (CompileEnvironment.Config.OptimizeCode >= ModuleRules.CodeOptimization.InNonDebugBuilds)
{
Arguments.Append(" /Ox");
// Allow optimized code to be debugged more easily. This makes PDBs a bit larger, but doesn't noticeably affect
// compile times. The executable code is not affected at all by this switch, only the debugging information.
Arguments.Append(" /Zo");
}
// Favor code speed.
Arguments.Append(" /Ot");
// Only omit frame pointers on the PC (which is implied by /Ox) if wanted.
if ( BuildConfiguration.bOmitFramePointers == false
&& (CompileEnvironment.Config.Target.Platform == CPPTargetPlatform.UWP))
{
Arguments.Append(" /Oy-");
}
// Allow inline method expansion
Arguments.Append(" /Ob2");
//
// LTCG
//
if (CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Shipping)
{
if( BuildConfiguration.bAllowLTCG )
{
// Enable link-time code generation.
Arguments.Append(" /GL");
}
}
}
//
// PC
//
// Prompt the user before reporting internal errors to Microsoft.
Arguments.Append(" /errorReport:prompt");
// Enable C++ exception handling, but not C exceptions.
Arguments.Append(" /EHsc");
// If enabled, create debug information.
if (CompileEnvironment.Config.bCreateDebugInfo)
{
// Store debug info in .pdb files.
if (BuildConfiguration.bUsePDBFiles)
{
// Create debug info suitable for E&C if wanted.
if ( BuildConfiguration.bSupportEditAndContinue &&
// We only need to do this in debug as that's the only configuration that supports E&C.
CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Debug)
{
Arguments.Append(" /ZI");
}
// Regular PDB debug information.
else
{
Arguments.Append(" /Zi");
}
// We need to add this so VS won't lock the PDB file and prevent synchronous updates. This forces serialization through MSPDBSRV.exe.
// See http://msdn.microsoft.com/en-us/library/dn502518.aspx for deeper discussion of /FS switch.
if (BuildConfiguration.bUseIncrementalLinking && WindowsPlatform.Compiler >= WindowsCompiler.VisualStudio2013)
{
Arguments.Append(" /FS");
}
}
// Store C7-format debug info in the .obj files, which is faster.
else
{
Arguments.Append(" /Z7");
}
}
// Specify the appropriate runtime library based on the platform and config.
if (CompileEnvironment.Config.bUseStaticCRT)
{
if (CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT)
{
Arguments.Append(" /MTd");
}
else
{
Arguments.Append(" /MT");
}
}
else
{
if (CompileEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT)
{
Arguments.Append(" /MDd");
}
else
{
Arguments.Append(" /MD");
}
}
if (UWPPlatform.bBuildForStore)
{
Arguments.Append(" /D_BUILD_FOR_STORE=1");
}
if (WindowsPlatform.Compiler == WindowsCompiler.VisualStudio2015)
{
// @todo UWP: These must be appended to the end of the system include list, lest they override some of the third party sources includes
if (Directory.Exists(EnvVars.WindowsSDKExtensionDir))
{
CompileEnvironment.Config.CPPIncludeInfo.SystemIncludePaths.Add(string.Format(@"{0}\Include\{1}\ucrt", EnvVars.WindowsSDKExtensionDir, EnvVars.WindowsSDKExtensionHeaderLibVersion));
CompileEnvironment.Config.CPPIncludeInfo.SystemIncludePaths.Add(string.Format(@"{0}\Include\{1}\um", EnvVars.WindowsSDKExtensionDir, EnvVars.WindowsSDKExtensionHeaderLibVersion));
CompileEnvironment.Config.CPPIncludeInfo.SystemIncludePaths.Add(string.Format(@"{0}\Include\{1}\shared", EnvVars.WindowsSDKExtensionDir, EnvVars.WindowsSDKExtensionHeaderLibVersion));
CompileEnvironment.Config.CPPIncludeInfo.SystemIncludePaths.Add(string.Format(@"{0}\Include\{1}\winrt", EnvVars.WindowsSDKExtensionDir, EnvVars.WindowsSDKExtensionHeaderLibVersion));
}
}
if (CompileEnvironment.Config.bIsBuildingLibrary == false) // will put in a config option, but for now...
{
// Enable Windows Runtime extensions
Arguments.Append(" /ZW");
Arguments.Append(" /DUSE_WINRT_MAIN=1");
// TODO - richiem - this will have to be updated when final layout SDKs are available
if (WindowsPlatform.Compiler == WindowsCompiler.VisualStudio2015 &&
Directory.Exists(Path.Combine(EnvVars.WindowsSDKExtensionDir, "UnionMetadata")))
{
Arguments.AppendFormat(@" /AI""{0}\UnionMetadata""", EnvVars.WindowsSDKExtensionDir);
Arguments.AppendFormat(@" /FU""{0}\UnionMetadata\windows.winmd""", EnvVars.WindowsSDKExtensionDir);
}
Arguments.AppendFormat(@" /AI""{0}\..\..\VC\vcpackages""", EnvVars.BaseVSToolPath);
Arguments.AppendFormat(@" /FU""{0}\..\..\VC\vcpackages\platform.winmd""", EnvVars.BaseVSToolPath);
}
}
static void AppendCLArguments_CPP( CPPEnvironment CompileEnvironment, StringBuilder Arguments)
{
// Explicitly compile the file as C++.
Arguments.Append(" /TP");
if (!CompileEnvironment.Config.bEnableBufferSecurityChecks)
{
// This will disable buffer security checks (which are enabled by default) that the MS compiler adds around arrays on the stack,
// Which can add some performance overhead, especially in performance intensive code
// Only disable this if you know what you are doing, because it will be disabled for the entire module!
Arguments.Append(" /GS-");
}
// C++/CLI requires that RTTI is left enabled
if (CompileEnvironment.Config.CLRMode == CPPCLRMode.CLRDisabled)
{
if (CompileEnvironment.Config.bUseRTTI)
{
// Enable C++ RTTI.
Arguments.Append(" /GR");
}
else
{
// Disable C++ RTTI.
Arguments.Append(" /GR-");
}
}
// Level 4 warnings.
Arguments.Append(" /W3");
}
static void AppendCLArguments_C(StringBuilder Arguments)
{
// Explicitly compile the file as C.
Arguments.Append(" /TC");
// Level 0 warnings. Needed for external C projects that produce warnings at higher warning levels.
Arguments.Append(" /W0");
}
static void AppendLinkArguments(LinkEnvironment LinkEnvironment, StringBuilder Arguments)
{
// Don't create a side-by-side manifest file for the executable.
Arguments.Append(" /MANIFEST:NO");
// Prevents the linker from displaying its logo for each invocation.
Arguments.Append(" /NOLOGO");
if (LinkEnvironment.Config.bCreateDebugInfo)
{
// Output debug info for the linked executable.
Arguments.Append(" /DEBUG");
}
// Prompt the user before reporting internal errors to Microsoft.
Arguments.Append(" /errorReport:prompt");
//
// PC
//
// Set machine type/ architecture to be 64 bit, and set as a store app
if (UWPPlatform.bBuildForStore)
{
Arguments.Append(" /MACHINE:x64");
Arguments.Append(" /APPCONTAINER");
// this helps with store API compliance validation tools, adding additional pdb info
Arguments.Append(" /PROFILE");
}
if (LinkEnvironment.Config.bIsBuildingConsoleApplication)
{
Arguments.Append(" /SUBSYSTEM:CONSOLE");
}
else
{
Arguments.Append(" /SUBSYSTEM:WINDOWS");
}
if (LinkEnvironment.Config.bIsBuildingConsoleApplication && !LinkEnvironment.Config.bIsBuildingDLL && !String.IsNullOrEmpty( LinkEnvironment.Config.WindowsEntryPointOverride ) )
{
// Use overridden entry point
Arguments.Append(" /ENTRY:" + LinkEnvironment.Config.WindowsEntryPointOverride);
}
// Allow the OS to load the EXE at different base addresses than its preferred base address.
Arguments.Append(" /FIXED:No");
// Explicitly declare that the executable is compatible with Data Execution Prevention.
Arguments.Append(" /NXCOMPAT");
// Set the default stack size.
Arguments.Append(" /STACK:5000000");
// Allow delay-loaded DLLs to be explicitly unloaded.
Arguments.Append(" /DELAY:UNLOAD");
if (LinkEnvironment.Config.bIsBuildingDLL)
{
Arguments.Append(" /DLL");
}
if (LinkEnvironment.Config.CLRMode == CPPCLRMode.CLREnabled)
{
// DLLs built with managed code aren't allowed to have entry points as they will try to initialize
// complex static variables. Managed code isn't allowed to run during DLLMain, we can't allow
// these variables to be initialized here.
if (LinkEnvironment.Config.bIsBuildingDLL)
{
// NOTE: This appears to only be needed if we want to get call stacks for debugging exit crashes related to the above
// Arguments.Append(" /NOENTRY /NODEFAULTLIB:nochkclr.obj");
}
}
// Don't embed the full PDB path; we want to be able to move binaries elsewhere. They will always be side by side.
Arguments.Append(" /PDBALTPATH:%_PDB%");
//
// Shipping & LTCG
//
if( BuildConfiguration.bAllowLTCG &&
LinkEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Shipping)
{
// Use link-time code generation.
Arguments.Append(" /LTCG");
// This is where we add in the PGO-Lite linkorder.txt if we are using PGO-Lite
//Arguments.Append(" /ORDER:@linkorder.txt");
//Arguments.Append(" /VERBOSE");
}
//
// Shipping binary
//
if (LinkEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Shipping)
{
// Generate an EXE checksum.
Arguments.Append(" /RELEASE");
// Eliminate unreferenced symbols.
Arguments.Append(" /OPT:REF");
// Remove redundant COMDATs.
Arguments.Append(" /OPT:ICF");
}
//
// Regular development binary.
//
else
{
// Keep symbols that are unreferenced.
Arguments.Append(" /OPT:NOREF");
// Disable identical COMDAT folding.
Arguments.Append(" /OPT:NOICF");
}
// Enable incremental linking if wanted.
// NOTE: Don't bother using incremental linking for C++/CLI projects, as that's not supported and the option
// will silently be ignored anyway
if (BuildConfiguration.bUseIncrementalLinking && LinkEnvironment.Config.CLRMode != CPPCLRMode.CLREnabled)
{
Arguments.Append(" /INCREMENTAL");
}
else
{
Arguments.Append(" /INCREMENTAL:NO");
}
// Disable
//LINK : warning LNK4199: /DELAYLOAD:nvtt_64.dll ignored; no imports found from nvtt_64.dll
// type warning as we leverage the DelayLoad option to put third-party DLLs into a
// non-standard location. This requires the module(s) that use said DLL to ensure that it
// is loaded prior to using it.
Arguments.Append(" /ignore:4199");
// Suppress warnings about missing PDB files for statically linked libraries. We often don't want to distribute
// PDB files for these libraries.
Arguments.Append(" /ignore:4099"); // warning LNK4099: PDB '<file>' was not found with '<file>'
}
static void AppendLibArguments(LinkEnvironment LinkEnvironment, StringBuilder Arguments)
{
// Prevents the linker from displaying its logo for each invocation.
Arguments.Append(" /NOLOGO");
// Prompt the user before reporting internal errors to Microsoft.
Arguments.Append(" /errorReport:prompt");
//
// PC
//
// Set machine type/ architecture to be 64 bit.
Arguments.Append(" /MACHINE:x64");
if (LinkEnvironment.Config.bIsBuildingConsoleApplication)
{
Arguments.Append(" /SUBSYSTEM:CONSOLE");
}
else
{
Arguments.Append(" /SUBSYSTEM:WINDOWS");
}
//
// Shipping & LTCG
//
if (LinkEnvironment.Config.Target.Configuration == CPPTargetConfiguration.Shipping)
{
// Use link-time code generation.
Arguments.Append(" /LTCG");
}
}
public override CPPOutput CompileCPPFiles(UEBuildTarget Target, CPPEnvironment CompileEnvironment, List<FileItem> SourceFiles, string ModuleName)
{
var EnvVars = VCEnvironment.SetEnvironment(CompileEnvironment.Config.Target.Platform);
StringBuilder Arguments = new StringBuilder();
AppendCLArguments_Global(CompileEnvironment, EnvVars, Arguments);
// Add include paths to the argument list.
foreach (string IncludePath in CompileEnvironment.Config.CPPIncludeInfo.IncludePaths)
{
string IncludePathRelative = Utils.CleanDirectorySeparators(Utils.MakePathRelativeTo(IncludePath, Path.Combine(ProjectFileGenerator.RootRelativePath, "Engine/Source")), '/');
Arguments.AppendFormat(" /I \"{0}\"", IncludePathRelative);
}
foreach (string IncludePath in CompileEnvironment.Config.CPPIncludeInfo.SystemIncludePaths)
{
string IncludePathRelative = Utils.CleanDirectorySeparators(Utils.MakePathRelativeTo(IncludePath, Path.Combine(ProjectFileGenerator.RootRelativePath, "Engine/Source")), '/');
Arguments.AppendFormat(" /I \"{0}\"", IncludePathRelative);
}
if (CompileEnvironment.Config.CLRMode == CPPCLRMode.CLREnabled)
{
// Add .NET framework assembly paths. This is needed so that C++/CLI projects
// can reference assemblies with #using, without having to hard code a path in the
// .cpp file to the assembly's location.
foreach (string AssemblyPath in CompileEnvironment.Config.SystemDotNetAssemblyPaths)
{
Arguments.AppendFormat(" /AI \"{0}\"", AssemblyPath);
}
// Add explicit .NET framework assembly references
foreach (string AssemblyName in CompileEnvironment.Config.FrameworkAssemblyDependencies)
{
Arguments.AppendFormat( " /FU \"{0}\"", AssemblyName );
}
// Add private assembly references
foreach( PrivateAssemblyInfo CurAssemblyInfo in CompileEnvironment.PrivateAssemblyDependencies )
{
Arguments.AppendFormat( " /FU \"{0}\"", CurAssemblyInfo.FileItem.AbsolutePath );
}
}
// Add preprocessor definitions to the argument list.
foreach (string Definition in CompileEnvironment.Config.Definitions)
{
// Escape all quotation marks so that they get properly passed with the command line.
var DefinitionArgument = Definition.Contains("\"") ? Definition.Replace("\"", "\\\"") : Definition;
Arguments.AppendFormat(" /D\"{0}\"", DefinitionArgument);
}
var BuildPlatform = UEBuildPlatform.GetBuildPlatformForCPPTargetPlatform(CompileEnvironment.Config.Target.Platform);
// Create a compile action for each source file.
CPPOutput Result = new CPPOutput();
foreach (FileItem SourceFile in SourceFiles)
{
Action CompileAction = new Action(ActionType.Compile);
CompileAction.CommandDescription = "Compile";
StringBuilder FileArguments = new StringBuilder();
bool bIsPlainCFile = Path.GetExtension(SourceFile.AbsolutePath).ToUpperInvariant() == ".C";
// Add the C++ source file and its included files to the prerequisite item list.
AddPrerequisiteSourceFile(Target, BuildPlatform, CompileEnvironment, SourceFile, CompileAction.PrerequisiteItems);
// If this is a CLR file then make sure our dependent assemblies are added as prerequisites
if (CompileEnvironment.Config.CLRMode == CPPCLRMode.CLREnabled)
{
foreach( PrivateAssemblyInfo CurPrivateAssemblyDependency in CompileEnvironment.PrivateAssemblyDependencies )
{
CompileAction.PrerequisiteItems.Add( CurPrivateAssemblyDependency.FileItem );
}
}
bool bEmitsObjectFile = true;
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Create)
{
// Generate a CPP File that just includes the precompiled header.
string PCHCPPFilename = "PCH." + ModuleName + "." + Path.GetFileName(CompileEnvironment.Config.PrecompiledHeaderIncludeFilename) + ".cpp";
string PCHCPPPath = Path.Combine(CompileEnvironment.Config.OutputDirectory, PCHCPPFilename);
FileItem PCHCPPFile = FileItem.CreateIntermediateTextFile(
PCHCPPPath,
string.Format("#include \"{0}\"\r\n", CompileEnvironment.Config.PrecompiledHeaderIncludeFilename)
);
// Make sure the original source directory the PCH header file existed in is added as an include
// path -- it might be a private PCH header and we need to make sure that its found!
string OriginalPCHHeaderDirectory = Path.GetDirectoryName( SourceFile.AbsolutePath );
FileArguments.AppendFormat(" /I \"{0}\"", OriginalPCHHeaderDirectory);
var PrecompiledFileExtension = UEBuildPlatform.BuildPlatformDictionary[UnrealTargetPlatform.UWP].GetBinaryExtension(UEBuildBinaryType.PrecompiledHeader);
// Add the precompiled header file to the produced items list.
FileItem PrecompiledHeaderFile = FileItem.GetItemByPath(
Path.Combine(
CompileEnvironment.Config.OutputDirectory,
Path.GetFileName(SourceFile.AbsolutePath) + PrecompiledFileExtension
)
);
CompileAction.ProducedItems.Add(PrecompiledHeaderFile);
Result.PrecompiledHeaderFile = PrecompiledHeaderFile;
// Add the parameters needed to compile the precompiled header file to the command-line.
FileArguments.AppendFormat(" /Yc\"{0}\"", CompileEnvironment.Config.PrecompiledHeaderIncludeFilename);
FileArguments.AppendFormat(" /Fp\"{0}\"", PrecompiledHeaderFile.AbsolutePath);
// If we're creating a PCH that will be used to compile source files for a library, we need
// the compiled modules to retain a reference to PCH's module, so that debugging information
// will be included in the library. This is also required to avoid linker warning "LNK4206"
// when linking an application that uses this library.
if (CompileEnvironment.Config.bIsBuildingLibrary)
{
// NOTE: The symbol name we use here is arbitrary, and all that matters is that it is
// unique per PCH module used in our library
string FakeUniquePCHSymbolName = Path.GetFileNameWithoutExtension(CompileEnvironment.Config.PrecompiledHeaderIncludeFilename);
FileArguments.AppendFormat(" /Yl{0}", FakeUniquePCHSymbolName);
}
FileArguments.AppendFormat(" \"{0}\"", PCHCPPFile.AbsolutePath);
CompileAction.StatusDescription = PCHCPPFilename;
}
else
{
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Include)
{
CompileAction.bIsUsingPCH = true;
CompileAction.PrerequisiteItems.Add(CompileEnvironment.PrecompiledHeaderFile);
FileArguments.AppendFormat(" /Yu\"{0}\"", CompileEnvironment.Config.PCHHeaderNameInCode);
FileArguments.AppendFormat(" /Fp\"{0}\"", CompileEnvironment.PrecompiledHeaderFile.AbsolutePath);
// Is it unsafe to always force inclusion? Clang is doing it, and .generated.cpp files
// won't work otherwise, because they're not located in the context of the module,
// so they can't access the module's PCH without an absolute path.
//if( CompileEnvironment.Config.bForceIncludePrecompiledHeader )
{
// Force include the precompiled header file. This is needed because we may have selected a
// precompiled header that is different than the first direct include in the C++ source file, but
// we still need to make sure that our precompiled header is the first thing included!
FileArguments.AppendFormat( " /FI\"{0}\"", CompileEnvironment.Config.PCHHeaderNameInCode);
}
}
// Add the source file path to the command-line.
FileArguments.AppendFormat(" \"{0}\"", SourceFile.AbsolutePath);
CompileAction.StatusDescription = Path.GetFileName( SourceFile.AbsolutePath );
}
if( bEmitsObjectFile )
{
var ObjectFileExtension = UEBuildPlatform.BuildPlatformDictionary[UnrealTargetPlatform.UWP].GetBinaryExtension(UEBuildBinaryType.Object);
// Add the object file to the produced item list.
FileItem ObjectFile = FileItem.GetItemByPath(
Path.Combine(
CompileEnvironment.Config.OutputDirectory,
Path.GetFileName(SourceFile.AbsolutePath) + ObjectFileExtension
)
);
CompileAction.ProducedItems.Add(ObjectFile);
Result.ObjectFiles.Add(ObjectFile);
FileArguments.AppendFormat(" /Fo\"{0}\"", ObjectFile.AbsolutePath);
}
// Create PDB files if we were configured to do that.
//
// Also, when debug info is off and XGE is enabled, force PDBs, otherwise it will try to share
// a PDB file, which causes PCH creation to be serial rather than parallel (when debug info is disabled)
// --> See https://udn.epicgames.com/lists/showpost.php?id=50619&list=unprog3
if (BuildConfiguration.bUsePDBFiles ||
(BuildConfiguration.bAllowXGE && !CompileEnvironment.Config.bCreateDebugInfo))
{
string PDBFileName;
bool bActionProducesPDB = false;
// All files using the same PCH are required to share the same PDB that was used when compiling the PCH
if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Include)
{
PDBFileName = "PCH." + ModuleName + "." + Path.GetFileName(CompileEnvironment.Config.PrecompiledHeaderIncludeFilename);
}
// Files creating a PCH use a PDB per file.
else if (CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Create)
{
PDBFileName = "PCH." + ModuleName + "." + Path.GetFileName(CompileEnvironment.Config.PrecompiledHeaderIncludeFilename);
bActionProducesPDB = true;
}
// Ungrouped C++ files use a PDB per file.
else if( !bIsPlainCFile )
{
PDBFileName = Path.GetFileName( SourceFile.AbsolutePath );
bActionProducesPDB = true;
}
// Group all plain C files that doesn't use PCH into the same PDB
else
{
PDBFileName = "MiscPlainC";
}
// Specify the PDB file that the compiler should write to.
FileItem PDBFile = FileItem.GetItemByPath(
Path.Combine(
CompileEnvironment.Config.OutputDirectory,
PDBFileName + ".pdb"
)
);
FileArguments.AppendFormat(" /Fd\"{0}\"", PDBFile.AbsolutePath);
// Only use the PDB as an output file if we want PDBs and this particular action is
// the one that produces the PDB (as opposed to no debug info, where the above code
// is needed, but not the output PDB, or when multiple files share a single PDB, so
// only the action that generates it should count it as output directly)
if( BuildConfiguration.bUsePDBFiles && bActionProducesPDB )
{
CompileAction.ProducedItems.Add(PDBFile);
Result.DebugDataFiles.Add(PDBFile);
}
}
// Add C or C++ specific compiler arguments.
if (bIsPlainCFile)
{
AppendCLArguments_C(FileArguments);
}
else
{
AppendCLArguments_CPP(CompileEnvironment, FileArguments);
}
CompileAction.WorkingDirectory = Path.GetFullPath(".");
CompileAction.CommandPath = EnvVars.CompilerPath;
CompileAction.CommandArguments = Arguments.ToString() + FileArguments.ToString() + CompileEnvironment.Config.AdditionalArguments;
if( CompileEnvironment.Config.PrecompiledHeaderAction == PrecompiledHeaderAction.Create )
{
Log.TraceVerbose("Creating PCH: " + CompileEnvironment.Config.PrecompiledHeaderIncludeFilename);
Log.TraceVerbose(" Command: " + CompileAction.CommandArguments);
}
else
{
Log.TraceVerbose(" Compiling: " + CompileAction.StatusDescription);
Log.TraceVerbose(" Command: " + CompileAction.CommandArguments);
}
// VC++ always outputs the source file name being compiled, so we don't need to emit this ourselves
CompileAction.bShouldOutputStatusDescription = false;
// Don't farm out creation of precompiled headers as it is the critical path task.
CompileAction.bCanExecuteRemotely =
CompileEnvironment.Config.PrecompiledHeaderAction != PrecompiledHeaderAction.Create ||
BuildConfiguration.bAllowRemotelyCompiledPCHs
;
// @todo: XGE has problems remote compiling C++/CLI files that use .NET Framework 4.0
if (CompileEnvironment.Config.CLRMode == CPPCLRMode.CLREnabled)
{
CompileAction.bCanExecuteRemotely = false;
}
}
return Result;
}
public override CPPOutput CompileRCFiles(UEBuildTarget Target, CPPEnvironment Environment, List<FileItem> RCFiles)
{
var EnvVars = VCEnvironment.SetEnvironment(Environment.Config.Target.Platform);
CPPOutput Result = new CPPOutput();
var BuildPlatform = UEBuildPlatform.GetBuildPlatformForCPPTargetPlatform(Environment.Config.Target.Platform);
foreach (FileItem RCFile in RCFiles)
{
Action CompileAction = new Action(ActionType.Compile);
CompileAction.CommandDescription = "Resource";
CompileAction.WorkingDirectory = Path.GetFullPath(".");
CompileAction.CommandPath = EnvVars.ResourceCompilerPath;
CompileAction.StatusDescription = Path.GetFileName(RCFile.AbsolutePath);
// Suppress header spew
CompileAction.CommandArguments += " /nologo";
// If we're compiling for 64-bit Windows, also add the _WIN64 definition to the resource
// compiler so that we can switch on that in the .rc file using #ifdef.
CompileAction.CommandArguments += " /D_WIN64";
// Language
CompileAction.CommandArguments += " /l 0x409";
// Include paths.
foreach (string IncludePath in Environment.Config.CPPIncludeInfo.IncludePaths)
{
CompileAction.CommandArguments += string.Format( " /i \"{0}\"", IncludePath );
}
// System include paths.
foreach( var SystemIncludePath in Environment.Config.CPPIncludeInfo.SystemIncludePaths)
{
CompileAction.CommandArguments += string.Format( " /i \"{0}\"", SystemIncludePath );
}
// Preprocessor definitions.
foreach (string Definition in Environment.Config.Definitions)
{
CompileAction.CommandArguments += string.Format(" /d \"{0}\"", Definition);
}
// Add the RES file to the produced item list.
FileItem CompiledResourceFile = FileItem.GetItemByPath(
Path.Combine(
Environment.Config.OutputDirectory,
Path.GetFileName(RCFile.AbsolutePath) + ".res"
)
);
CompileAction.ProducedItems.Add(CompiledResourceFile);
CompileAction.CommandArguments += string.Format(" /fo \"{0}\"", CompiledResourceFile.AbsolutePath);
Result.ObjectFiles.Add(CompiledResourceFile);
// Add the RC file as a prerequisite of the action.
CompileAction.CommandArguments += string.Format(" \"{0}\"", RCFile.AbsolutePath);
// Add the C++ source file and its included files to the prerequisite item list.
AddPrerequisiteSourceFile(Target, BuildPlatform, Environment, RCFile, CompileAction.PrerequisiteItems);
}
return Result;
}
public override FileItem LinkFiles(LinkEnvironment LinkEnvironment, bool bBuildImportLibraryOnly)
{
var EnvVars = VCEnvironment.SetEnvironment(LinkEnvironment.Config.Target.Platform);
if (LinkEnvironment.Config.bIsBuildingDotNetAssembly)
{
return FileItem.GetItemByPath(LinkEnvironment.Config.OutputFilePath);
}
bool bIsBuildingLibrary = LinkEnvironment.Config.bIsBuildingLibrary || bBuildImportLibraryOnly;
bool bIncludeDependentLibrariesInLibrary = bIsBuildingLibrary && LinkEnvironment.Config.bIncludeDependentLibrariesInLibrary;
// Get link arguments.
StringBuilder Arguments = new StringBuilder();
if (bIsBuildingLibrary)
{
AppendLibArguments(LinkEnvironment, Arguments);
}
else
{
AppendLinkArguments(LinkEnvironment, Arguments);
}
// If we're only building an import library, add the '/DEF' option that tells the LIB utility
// to simply create a .LIB file and .EXP file, and don't bother validating imports
if (bBuildImportLibraryOnly)
{
Arguments.Append(" /DEF");
// Ensure that the import library references the correct filename for the linked binary.
Arguments.AppendFormat(" /NAME:\"{0}\"", Path.GetFileName(LinkEnvironment.Config.OutputFilePath));
}
// Add delay loaded DLLs.
if (!bIsBuildingLibrary)
{
// Delay-load these DLLs.
foreach (string DelayLoadDLL in LinkEnvironment.Config.DelayLoadDLLs)
{
Arguments.AppendFormat(" /DELAYLOAD:\"{0}\"", DelayLoadDLL);
}
}
// @todo UE4 DLL: Why do I need LIBPATHs to build only export libraries with /DEF? (tbbmalloc.lib)
if (!LinkEnvironment.Config.bIsBuildingLibrary || (LinkEnvironment.Config.bIsBuildingLibrary && bIncludeDependentLibrariesInLibrary))
{
// Add the library paths to the argument list.
foreach (string LibraryPath in LinkEnvironment.Config.LibraryPaths)
{
Arguments.AppendFormat(" /LIBPATH:\"{0}\"", LibraryPath);
}
// Add the excluded default libraries to the argument list.
foreach (string ExcludedLibrary in LinkEnvironment.Config.ExcludedLibraries)
{
Arguments.AppendFormat(" /NODEFAULTLIB:\"{0}\"", ExcludedLibrary);
}
}
// For targets that are cross-referenced, we don't want to write a LIB file during the link step as that
// file will clobber the import library we went out of our way to generate during an earlier step. This
// file is not needed for our builds, but there is no way to prevent MSVC from generating it when
// linking targets that have exports. We don't want this to clobber our LIB file and invalidate the
// existing timstamp, so instead we simply emit it with a different name
string ImportLibraryFilePath = Path.Combine( LinkEnvironment.Config.IntermediateDirectory,
Path.GetFileNameWithoutExtension(LinkEnvironment.Config.OutputFilePath) + ".lib" );
if (LinkEnvironment.Config.bIsCrossReferenced && !bBuildImportLibraryOnly)
{
ImportLibraryFilePath += ".suppressed";
}
FileItem OutputFile;
if (bBuildImportLibraryOnly)
{
OutputFile = FileItem.GetItemByPath(ImportLibraryFilePath);
}
else
{
OutputFile = FileItem.GetItemByPath(LinkEnvironment.Config.OutputFilePath);
OutputFile.bNeedsHotReloadNumbersDLLCleanUp = LinkEnvironment.Config.bIsBuildingDLL;
}
List<FileItem> ProducedItems = new List<FileItem>();
ProducedItems.Add(OutputFile);
List<FileItem> PrerequisiteItems = new List<FileItem>();
// Add the input files to a response file, and pass the response file on the command-line.
List<string> InputFileNames = new List<string>();
foreach (FileItem InputFile in LinkEnvironment.InputFiles)
{
InputFileNames.Add(string.Format("\"{0}\"", InputFile.AbsolutePath));
PrerequisiteItems.Add(InputFile);
}
if (!bBuildImportLibraryOnly)
{
// Add input libraries as prerequisites, too!
foreach (FileItem InputLibrary in LinkEnvironment.InputLibraries)
{
InputFileNames.Add(string.Format("\"{0}\"", InputLibrary.AbsolutePath));
PrerequisiteItems.Add(InputLibrary);
}
}
if (!bIsBuildingLibrary || (LinkEnvironment.Config.bIsBuildingLibrary && bIncludeDependentLibrariesInLibrary))
{
foreach (string AdditionalLibrary in LinkEnvironment.Config.AdditionalLibraries)
{
InputFileNames.Add(string.Format("\"{0}\"", AdditionalLibrary));
// If the library file name has a relative path attached (rather than relying on additional
// lib directories), then we'll add it to our prerequisites list. This will allow UBT to detect
// when the binary needs to be relinked because a dependent external library has changed.
//if( !String.IsNullOrEmpty( Path.GetDirectoryName( AdditionalLibrary ) ) )
{
PrerequisiteItems.Add(FileItem.GetItemByPath(AdditionalLibrary));
}
}
}
// Create a response file for the linker
string ResponseFileName = GetResponseFileName( LinkEnvironment, OutputFile );
// Never create response files when we are only generating IntelliSense data
if( !ProjectFileGenerator.bGenerateProjectFiles )
{
ResponseFile.Create( ResponseFileName, InputFileNames );
}
Arguments.AppendFormat(" @\"{0}\"", ResponseFileName);
// Add the output file to the command-line.
Arguments.AppendFormat(" /OUT:\"{0}\"", OutputFile.AbsolutePath);
if (bBuildImportLibraryOnly || (LinkEnvironment.Config.bHasExports && !bIsBuildingLibrary))
{
// An export file is written to the output directory implicitly; add it to the produced items list.
string ExportFilePath = Path.ChangeExtension(ImportLibraryFilePath, ".exp");
FileItem ExportFile = FileItem.GetItemByPath(ExportFilePath);
ProducedItems.Add(ExportFile);
}
if (!bIsBuildingLibrary)
{
// Xbox 360 LTCG does not seem to produce those.
if (LinkEnvironment.Config.bHasExports &&
(LinkEnvironment.Config.Target.Configuration != CPPTargetConfiguration.Shipping))
{
// Write the import library to the output directory for nFringe support.
FileItem ImportLibraryFile = FileItem.GetItemByPath(ImportLibraryFilePath);
Arguments.AppendFormat(" /IMPLIB:\"{0}\"", ImportLibraryFilePath);
ProducedItems.Add(ImportLibraryFile);
}
if (LinkEnvironment.Config.bCreateDebugInfo)
{
// Write the PDB file to the output directory.
string PDBFilePath = Path.Combine(LinkEnvironment.Config.OutputDirectory, Path.GetFileNameWithoutExtension(OutputFile.AbsolutePath) + ".pdb");
FileItem PDBFile = FileItem.GetItemByPath(PDBFilePath);
Arguments.AppendFormat(" /PDB:\"{0}\"", PDBFilePath);
ProducedItems.Add(PDBFile);
// Write the MAP file to the output directory.
#if false
if (true)
{
string MAPFilePath = Path.Combine(LinkEnvironment.Config.OutputDirectory, Path.GetFileNameWithoutExtension(OutputFile.AbsolutePath) + ".map");
FileItem MAPFile = FileItem.GetItemByPath(MAPFilePath);
LinkAction.CommandArguments += string.Format(" /MAP:\"{0}\"", MAPFilePath);
LinkAction.ProducedItems.Add(MAPFile);
}
#endif
}
// Add the additional arguments specified by the environment.
Arguments.Append(LinkEnvironment.Config.AdditionalArguments);
}
// Create an action that invokes the linker.
Action LinkAction = new Action(ActionType.Link);
LinkAction.CommandDescription = "Link";
LinkAction.WorkingDirectory = Path.GetFullPath(".");
LinkAction.CommandPath = bIsBuildingLibrary ? EnvVars.LibraryLinkerPath : EnvVars.LinkerPath;
LinkAction.CommandArguments = Arguments.ToString();
LinkAction.ProducedItems .AddRange(ProducedItems);
LinkAction.PrerequisiteItems.AddRange(PrerequisiteItems);
LinkAction.StatusDescription = Path.GetFileName(OutputFile.AbsolutePath);
// Tell the action that we're building an import library here and it should conditionally be
// ignored as a prerequisite for other actions
LinkAction.bProducesImportLibrary = bBuildImportLibraryOnly || LinkEnvironment.Config.bIsBuildingDLL;
// Only execute linking on the local PC.
LinkAction.bCanExecuteRemotely = false;
Log.TraceVerbose(" Linking: " + LinkAction.StatusDescription);
Log.TraceVerbose(" Command: " + LinkAction.CommandArguments);
return OutputFile;
}
/** Gets the default include paths for the given platform. */
public static string GetVCIncludePaths(CPPTargetPlatform Platform)
{
Debug.Assert(Platform == CPPTargetPlatform.UWP);
// Make sure we've got the environment variables set up for this target
VCEnvironment.SetEnvironment(Platform);
// Also add any include paths from the INCLUDE environment variable. MSVC is not necessarily running with an environment that
// matches what UBT extracted from the vcvars*.bat using SetEnvironmentVariablesFromBatchFile(). We'll use the variables we
// extracted to populate the project file's list of include paths
// @todo projectfiles: Should we only do this for VC++ platforms?
var IncludePaths = Environment.GetEnvironmentVariable("INCLUDE");
if (!String.IsNullOrEmpty(IncludePaths) && !IncludePaths.EndsWith(";"))
{
IncludePaths += ";";
}
return IncludePaths;
}
};
}
| |
// TODO: Ideally we wouldn't need this here in the UI.
using System;
using System.ComponentModel;
using System.Windows.Forms;
using SIL.Email;
using SIL.Reporting;
namespace SIL.Windows.Forms.Miscellaneous
{
/// <summary>
/// Summary description for UsageEmailDialog.
/// </summary>
public class UsageEmailDialog : Form
{
private TabControl tabControl1;
private TabPage tabPage1;
private PictureBox pictureBox1;
private RichTextBox richTextBox2;
private Button btnSend;
private LinkLabel btnNope;
private RichTextBox m_topLineText;
private IEmailProvider _emailProvider;
private IEmailMessage _emailMessage;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
internal UsageEmailDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
richTextBox2.Text = "May we ask you a favor? We would like to send a tiny e-mail back to the software developers telling us of your progress.\nYou will be able to view the e-mail before it goes out. You do not need to be connected to the Internet right now...the e-mail will just open and you can save it in your outbox.";
m_topLineText.Text = string.Format(this.m_topLineText.Text, UsageReporter.AppNameToUseInDialogs);
_emailProvider = EmailProviderFactory.PreferredEmailProvider();
_emailMessage = _emailProvider.CreateMessage();
}
/// <summary>
/// Check to see if the object has been disposed.
/// All public Properties and Methods should call this
/// before doing anything else.
/// </summary>
public void CheckDisposed()
{
if (IsDisposed)
throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name));
}
/// <summary>
///
/// </summary>
public string TopLineText
{
set
{
CheckDisposed();
m_topLineText.Text = value;
}
get
{
CheckDisposed();
return m_topLineText.Text;
}
}
public IEmailMessage EmailMessage
{
get
{
return _emailMessage;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
//Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************");
// Must not be run more than once.
if (IsDisposed)
return;
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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UsageEmailDialog));
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.m_topLineText = new System.Windows.Forms.RichTextBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
this.btnSend = new System.Windows.Forms.Button();
this.btnNope = new System.Windows.Forms.LinkLabel();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Location = new System.Drawing.Point(9, 10);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(590, 240);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.BackColor = System.Drawing.SystemColors.Window;
this.tabPage1.Controls.Add(this.m_topLineText);
this.tabPage1.Controls.Add(this.pictureBox1);
this.tabPage1.Controls.Add(this.richTextBox2);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(582, 214);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Report";
//
// m_topLineText
//
this.m_topLineText.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.m_topLineText.Location = new System.Drawing.Point(218, 29);
this.m_topLineText.Name = "m_topLineText";
this.m_topLineText.Size = new System.Drawing.Size(339, 31);
this.m_topLineText.TabIndex = 1;
this.m_topLineText.Text = "Thank you for checking out {0}.";
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(18, 38);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(165, 71);
this.pictureBox1.TabIndex = 2;
this.pictureBox1.TabStop = false;
//
// richTextBox2
//
this.richTextBox2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.richTextBox2.Location = new System.Drawing.Point(218, 74);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.Size = new System.Drawing.Size(339, 147);
this.richTextBox2.TabIndex = 1;
this.richTextBox2.Text = resources.GetString("richTextBox2.Text");
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(464, 263);
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(133, 23);
this.btnSend.TabIndex = 1;
this.btnSend.Text = "Create Email Message";
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// btnNope
//
this.btnNope.Location = new System.Drawing.Point(14, 271);
this.btnNope.Name = "btnNope";
this.btnNope.Size = new System.Drawing.Size(278, 23);
this.btnNope.TabIndex = 2;
this.btnNope.TabStop = true;
this.btnNope.Text = "I\'m unable to send this information.";
this.btnNope.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.btnNope_LinkClicked);
//
// UsageEmailDialog
//
this.AcceptButton = this.btnSend;
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.btnNope;
this.ClientSize = new System.Drawing.Size(618, 301);
this.ControlBox = false;
this.Controls.Add(this.btnNope);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.tabControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MinimizeBox = false;
this.Name = "UsageEmailDialog";
this.Text = "Field Usage Report System";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void btnSend_Click(object sender, EventArgs e)
{
try
{
// TODO: This can be moved out to the caller rather than in the UI.
_emailMessage.Send(_emailProvider);
}
catch
{
//swallow it
}
DialogResult = DialogResult.OK;
Close();
}
private void btnNope_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
DialogResult = DialogResult.No;
Close();
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using Delaunay.Geo;
using Delaunay.LR;
namespace Delaunay
{
// import com.nodename.geom.LineSegment;
//
// import flash.display.BitmapData;
// import flash.display.CapsStyle;
// import flash.display.Graphics;
// import flash.display.LineScaleMode;
// import flash.display.Sprite;
// import flash.geom.Point;
// import flash.geom.Rectangle;
// import flash.utils.Dictionary;
/**
* The line segment connecting the two Sites is part of the Delaunay triangulation;
* the line segment connecting the two Vertices is part of the Voronoi diagram
* @author ashaw
*
*/
public sealed class Edge
{
private static Stack<Edge> _pool = new Stack<Edge> ();
/**
* This is the only way to create a new Edge
* @param site0
* @param site1
* @return
*
*/
public static Edge CreateBisectingEdge (Site site0, Site site1)
{
float dx, dy, absdx, absdy;
float a, b, c;
dx = site1.x - site0.x;
dy = site1.y - site0.y;
absdx = dx > 0 ? dx : -dx;
absdy = dy > 0 ? dy : -dy;
c = site0.x * dx + site0.y * dy + (dx * dx + dy * dy) * 0.5f;
if (absdx > absdy) {
a = 1.0f;
b = dy / dx;
c /= dx;
} else {
b = 1.0f;
a = dx / dy;
c /= dy;
}
Edge edge = Edge.Create ();
edge.leftSite = site0;
edge.rightSite = site1;
site0.AddEdge (edge);
site1.AddEdge (edge);
edge._leftVertex = null;
edge._rightVertex = null;
edge.a = a;
edge.b = b;
edge.c = c;
//trace("createBisectingEdge: a ", edge.a, "b", edge.b, "c", edge.c);
return edge;
}
private static Edge Create ()
{
Edge edge;
if (_pool.Count > 0) {
edge = _pool.Pop ();
edge.Init ();
} else {
edge = new Edge ();
}
return edge;
}
// private static const LINESPRITE:Sprite = new Sprite();
// private static const GRAPHICS:Graphics = LINESPRITE.graphics;
//
// private var _delaunayLineBmp:BitmapData;
// internal function get delaunayLineBmp():BitmapData
// {
// if (!_delaunayLineBmp)
// {
// _delaunayLineBmp = makeDelaunayLineBmp();
// }
// return _delaunayLineBmp;
// }
//
// // making this available to Voronoi; running out of memory in AIR so I cannot cache the bmp
// internal function makeDelaunayLineBmp():BitmapData
// {
// var p0:Point = leftSite.coord;
// var p1:Point = rightSite.coord;
//
// GRAPHICS.clear();
// // clear() resets line style back to undefined!
// GRAPHICS.lineStyle(0, 0, 1.0, false, LineScaleMode.NONE, CapsStyle.NONE);
// GRAPHICS.moveTo(p0.x, p0.y);
// GRAPHICS.lineTo(p1.x, p1.y);
//
// var w:int = int(Math.ceil(Math.max(p0.x, p1.x)));
// if (w < 1)
// {
// w = 1;
// }
// var h:int = int(Math.ceil(Math.max(p0.y, p1.y)));
// if (h < 1)
// {
// h = 1;
// }
// var bmp:BitmapData = new BitmapData(w, h, true, 0);
// bmp.draw(LINESPRITE);
// return bmp;
// }
public LineSegment DelaunayLine ()
{
// draw a line connecting the input Sites for which the edge is a bisector:
return new LineSegment (leftSite.Coord, rightSite.Coord);
}
public LineSegment VoronoiEdge ()
{
if (!visible)
return new LineSegment (null, null);
return new LineSegment (_clippedVertices [LR.Side.LEFT],
_clippedVertices [LR.Side.RIGHT]);
}
private static int _nedges = 0;
public static readonly Edge DELETED = new Edge ();
// the equation of the edge: ax + by = c
public float a, b, c;
// the two Voronoi vertices that the edge connects
// (if one of them is null, the edge extends to infinity)
private Vertex _leftVertex;
public Vertex leftVertex {
get { return _leftVertex;}
}
private Vertex _rightVertex;
public Vertex rightVertex {
get { return _rightVertex;}
}
public Vertex Vertex (LR.Side leftRight)
{
return (leftRight == LR.Side.LEFT) ? _leftVertex : _rightVertex;
}
public void SetVertex (LR.Side leftRight, Vertex v)
{
if (leftRight == LR.Side.LEFT) {
_leftVertex = v;
} else {
_rightVertex = v;
}
}
public bool IsPartOfConvexHull ()
{
return (_leftVertex == null || _rightVertex == null);
}
public float SitesDistance ()
{
return Vector2.Distance (leftSite.Coord, rightSite.Coord);
}
public static int CompareSitesDistances_MAX (Edge edge0, Edge edge1)
{
float length0 = edge0.SitesDistance ();
float length1 = edge1.SitesDistance ();
if (length0 < length1) {
return 1;
}
if (length0 > length1) {
return -1;
}
return 0;
}
public static int CompareSitesDistances (Edge edge0, Edge edge1)
{
return - CompareSitesDistances_MAX (edge0, edge1);
}
// Once clipVertices() is called, this Dictionary will hold two Points
// representing the clipped coordinates of the left and right ends...
private Dictionary<LR.Side,Nullable<Vector2>> _clippedVertices;
public Dictionary<LR.Side,Nullable<Vector2>> clippedEnds {
get { return _clippedVertices;}
}
// unless the entire Edge is outside the bounds.
// In that case visible will be false:
public bool visible {
get { return _clippedVertices != null;}
}
// the two input Sites for which this Edge is a bisector:
private Dictionary<LR.Side,Site> _sites;
public Site leftSite {
get{ return _sites [LR.Side.LEFT];}
set{ _sites [LR.Side.LEFT] = value;}
}
public Site rightSite {
get { return _sites [LR.Side.RIGHT];}
set { _sites [LR.Side.RIGHT] = value;}
}
public Site Site (LR.Side leftRight)
{
return _sites [leftRight];
}
private int _edgeIndex;
public void Dispose ()
{
// if (_delaunayLineBmp) {
// _delaunayLineBmp.Dispose ();
// _delaunayLineBmp = null;
// }
_leftVertex = null;
_rightVertex = null;
if (_clippedVertices != null) {
_clippedVertices [LR.Side.LEFT] = null;
_clippedVertices [LR.Side.RIGHT] = null;
_clippedVertices = null;
}
_sites [LR.Side.LEFT] = null;
_sites [LR.Side.RIGHT] = null;
_sites = null;
_pool.Push (this);
}
private Edge ()
{
// if (lock != PrivateConstructorEnforcer)
// {
// throw new Error("Edge: constructor is private");
// }
_edgeIndex = _nedges++;
Init ();
}
private void Init ()
{
_sites = new Dictionary<LR.Side,Site> ();
}
public override string ToString ()
{
return "Edge " + _edgeIndex.ToString () + "; sites " + _sites [LR.Side.LEFT].ToString () + ", " + _sites [LR.Side.RIGHT].ToString ()
+ "; endVertices " + ((_leftVertex != null) ? _leftVertex.vertexIndex.ToString () : "null") + ", "
+ ((_rightVertex != null) ? _rightVertex.vertexIndex.ToString () : "null") + "::";
}
/**
* Set _clippedVertices to contain the two ends of the portion of the Voronoi edge that is visible
* within the bounds. If no part of the Edge falls within the bounds, leave _clippedVertices null.
* @param bounds
*
*/
public void ClipVertices (Rect bounds)
{
float xmin = bounds.xMin;
float ymin = bounds.yMin;
float xmax = bounds.xMax;
float ymax = bounds.yMax;
Vertex vertex0, vertex1;
float x0, x1, y0, y1;
if (a == 1.0 && b >= 0.0) {
vertex0 = _rightVertex;
vertex1 = _leftVertex;
} else {
vertex0 = _leftVertex;
vertex1 = _rightVertex;
}
if (a == 1.0) {
y0 = ymin;
if (vertex0 != null && vertex0.y > ymin) {
y0 = vertex0.y;
}
if (y0 > ymax) {
return;
}
x0 = c - b * y0;
y1 = ymax;
if (vertex1 != null && vertex1.y < ymax) {
y1 = vertex1.y;
}
if (y1 < ymin) {
return;
}
x1 = c - b * y1;
if ((x0 > xmax && x1 > xmax) || (x0 < xmin && x1 < xmin)) {
return;
}
if (x0 > xmax) {
x0 = xmax;
y0 = (c - x0) / b;
} else if (x0 < xmin) {
x0 = xmin;
y0 = (c - x0) / b;
}
if (x1 > xmax) {
x1 = xmax;
y1 = (c - x1) / b;
} else if (x1 < xmin) {
x1 = xmin;
y1 = (c - x1) / b;
}
} else {
x0 = xmin;
if (vertex0 != null && vertex0.x > xmin) {
x0 = vertex0.x;
}
if (x0 > xmax) {
return;
}
y0 = c - a * x0;
x1 = xmax;
if (vertex1 != null && vertex1.x < xmax) {
x1 = vertex1.x;
}
if (x1 < xmin) {
return;
}
y1 = c - a * x1;
if ((y0 > ymax && y1 > ymax) || (y0 < ymin && y1 < ymin)) {
return;
}
if (y0 > ymax) {
y0 = ymax;
x0 = (c - y0) / a;
} else if (y0 < ymin) {
y0 = ymin;
x0 = (c - y0) / a;
}
if (y1 > ymax) {
y1 = ymax;
x1 = (c - y1) / a;
} else if (y1 < ymin) {
y1 = ymin;
x1 = (c - y1) / a;
}
}
// _clippedVertices = new Dictionary(true); // XXX: Weak ref'd dict might be a problem to use standard
_clippedVertices = new Dictionary<LR.Side,Nullable<Vector2>> ();
if (vertex0 == _leftVertex) {
_clippedVertices [LR.Side.LEFT] = new Vector2 (x0, y0);
_clippedVertices [LR.Side.RIGHT] = new Vector2 (x1, y1);
} else {
_clippedVertices [LR.Side.RIGHT] = new Vector2 (x0, y0);
_clippedVertices [LR.Side.LEFT] = new Vector2 (x1, y1);
}
}
}
}
//class PrivateConstructorEnforcer {}
| |
//
// TypeDefinition.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
public sealed class TypeDefinition : TypeReference, IMemberDefinition, IHasSecurity {
TypeAttributes m_attributes;
TypeReference m_baseType;
bool m_hasInfo;
ushort m_packingSize;
uint m_classSize;
InterfaceCollection m_interfaces;
NestedTypeCollection m_nestedTypes;
MethodDefinitionCollection m_methods;
ConstructorCollection m_ctors;
FieldDefinitionCollection m_fields;
EventDefinitionCollection m_events;
PropertyDefinitionCollection m_properties;
SecurityDeclarationCollection m_secDecls;
public TypeAttributes Attributes {
get { return m_attributes; }
set { m_attributes = value; }
}
public TypeReference BaseType {
get { return m_baseType; }
set { m_baseType = value; }
}
public bool HasLayoutInfo {
get { return m_hasInfo; }
}
public ushort PackingSize {
get { return m_packingSize; }
set {
m_hasInfo = true;
m_packingSize = value;
}
}
public uint ClassSize {
get { return m_classSize; }
set {
m_hasInfo = true;
m_classSize = value;
}
}
public InterfaceCollection Interfaces {
get {
if (m_interfaces == null)
m_interfaces = new InterfaceCollection (this);
return m_interfaces;
}
}
public NestedTypeCollection NestedTypes {
get {
if (m_nestedTypes == null)
m_nestedTypes = new NestedTypeCollection (this);
return m_nestedTypes;
}
}
public MethodDefinitionCollection Methods {
get {
if (m_methods == null)
m_methods = new MethodDefinitionCollection (this);
return m_methods;
}
}
public ConstructorCollection Constructors {
get {
if (m_ctors == null)
m_ctors = new ConstructorCollection (this);
return m_ctors;
}
}
public FieldDefinitionCollection Fields {
get {
if (m_fields == null)
m_fields = new FieldDefinitionCollection (this);
return m_fields;
}
}
public EventDefinitionCollection Events {
get {
if (m_events == null)
m_events = new EventDefinitionCollection (this);
return m_events;
}
}
public PropertyDefinitionCollection Properties {
get {
if (m_properties == null)
m_properties = new PropertyDefinitionCollection (this);
return m_properties;
}
}
public SecurityDeclarationCollection SecurityDeclarations {
get {
if (m_secDecls == null)
m_secDecls = new SecurityDeclarationCollection (this);
return m_secDecls;
}
}
public bool IsAbstract {
get { return (m_attributes & TypeAttributes.Abstract) != 0; }
set {
if (value)
m_attributes |= TypeAttributes.Abstract;
else
m_attributes &= ~TypeAttributes.Abstract;
}
}
public bool IsBeforeFieldInit {
get { return (m_attributes & TypeAttributes.BeforeFieldInit) != 0; }
set {
if (value)
m_attributes |= TypeAttributes.BeforeFieldInit;
else
m_attributes &= ~TypeAttributes.BeforeFieldInit;
}
}
public bool IsInterface {
get { return (m_attributes & TypeAttributes.ClassSemanticMask) == TypeAttributes.Interface; }
set {
if (value)
m_attributes |= (TypeAttributes.ClassSemanticMask & TypeAttributes.Interface);
else
m_attributes &= ~(TypeAttributes.ClassSemanticMask & TypeAttributes.Interface);
}
}
public bool IsRuntimeSpecialName {
get { return (m_attributes & TypeAttributes.RTSpecialName) != 0; }
set {
if (value)
m_attributes |= TypeAttributes.RTSpecialName;
else
m_attributes &= ~TypeAttributes.RTSpecialName;
}
}
public bool IsSealed {
get { return (m_attributes & TypeAttributes.Sealed) != 0; }
set {
if (value)
m_attributes |= TypeAttributes.Sealed;
else
m_attributes &= ~TypeAttributes.Sealed;
}
}
public bool IsSpecialName {
get { return (m_attributes & TypeAttributes.SpecialName) != 0; }
set {
if (value)
m_attributes |= TypeAttributes.SpecialName;
else
m_attributes &= ~TypeAttributes.SpecialName;
}
}
public bool IsEnum {
get { return m_baseType != null && m_baseType.FullName == Constants.Enum; }
}
public override bool IsValueType {
get {
return m_baseType != null && (
this.IsEnum || m_baseType.FullName == Constants.ValueType);
}
}
internal TypeDefinition (string name, string ns, TypeAttributes attrs) :
base (name, ns)
{
m_hasInfo = false;
m_attributes = attrs;
}
public TypeDefinition (string name, string ns,
TypeAttributes attributes, TypeReference baseType) :
this (name, ns, attributes)
{
this.BaseType = baseType;
}
public TypeDefinition Clone ()
{
return Clone (this, new ImportContext (null, this));
}
internal static TypeDefinition Clone (TypeDefinition type, ImportContext context)
{
TypeDefinition nt = new TypeDefinition (
type.Name,
type.Namespace,
type.Attributes);
context.GenericContext.Type = nt;
foreach (GenericParameter p in type.GenericParameters)
nt.GenericParameters.Add (GenericParameter.Clone (p, context));
if (type.BaseType != null)
nt.BaseType = context.Import (type.BaseType);
if (type.HasLayoutInfo) {
nt.ClassSize = type.ClassSize;
nt.PackingSize = type.PackingSize;
}
foreach (FieldDefinition field in type.Fields)
nt.Fields.Add (FieldDefinition.Clone (field, context));
foreach (MethodDefinition ctor in type.Constructors)
nt.Constructors.Add (MethodDefinition.Clone (ctor, context));
foreach (MethodDefinition meth in type.Methods)
nt.Methods.Add (MethodDefinition.Clone (meth, context));
foreach (EventDefinition evt in type.Events)
nt.Events.Add (EventDefinition.Clone (evt, context));
foreach (PropertyDefinition prop in type.Properties)
nt.Properties.Add (PropertyDefinition.Clone (prop, context));
foreach (TypeReference intf in type.Interfaces)
nt.Interfaces.Add (context.Import (intf));
foreach (TypeDefinition nested in type.NestedTypes)
nt.NestedTypes.Add (Clone (nested, context));
foreach (CustomAttribute ca in type.CustomAttributes)
nt.CustomAttributes.Add (CustomAttribute.Clone (ca, context));
foreach (SecurityDeclaration dec in type.SecurityDeclarations)
nt.SecurityDeclarations.Add (SecurityDeclaration.Clone (dec));
return nt;
}
public override void Accept (IReflectionVisitor visitor)
{
visitor.VisitTypeDefinition (this);
this.GenericParameters.Accept (visitor);
this.Interfaces.Accept (visitor);
this.Constructors.Accept (visitor);
this.Methods.Accept (visitor);
this.Fields.Accept (visitor);
this.Properties.Accept (visitor);
this.Events.Accept (visitor);
this.NestedTypes.Accept (visitor);
this.CustomAttributes.Accept (visitor);
this.SecurityDeclarations.Accept (visitor);
}
}
}
| |
//
// 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.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.DataFactories.Core
{
/// <summary>
/// Operations for OAuth authorizations.
/// </summary>
internal partial class OAuthOperations : IServiceOperations<DataFactoryManagementClient>, IOAuthOperations
{
/// <summary>
/// Initializes a new instance of the OAuthOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal OAuthOperations(DataFactoryManagementClient client)
{
this._client = client;
}
private DataFactoryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient.
/// </summary>
public DataFactoryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets an OAuth authorization session.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='linkedServiceType'>
/// Required. The type of OAuth linked service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get authorization session operation response.
/// </returns>
public async Task<AuthorizationSessionGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, string linkedServiceType, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (linkedServiceType == null)
{
throw new ArgumentNullException("linkedServiceType");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("linkedServiceType", linkedServiceType);
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(resourceGroupName);
url = url + "/providers/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
url = url + "/oauth/authorizationsession/";
url = url + Uri.EscapeDataString(linkedServiceType);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-09-01");
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("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
AuthorizationSessionGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AuthorizationSessionGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AuthorizationSession authorizationSessionInstance = new AuthorizationSession();
result.AuthorizationSession = authorizationSessionInstance;
JToken endpointValue = responseDoc["endpoint"];
if (endpointValue != null && endpointValue.Type != JTokenType.Null)
{
Uri endpointInstance = TypeConversion.TryParseUri(((string)endpointValue));
authorizationSessionInstance.Endpoint = endpointInstance;
}
JToken sessionIdValue = responseDoc["sessionId"];
if (sessionIdValue != null && sessionIdValue.Type != JTokenType.Null)
{
string sessionIdInstance = ((string)sessionIdValue);
authorizationSessionInstance.SessionId = sessionIdInstance;
}
}
}
result.StatusCode = statusCode;
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.Diagnostics;
using System.IO;
using System.Linq;
using Mono.Cecil;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class ModuleTests : BaseTestFixture {
#if !READ_ONLY
[Test]
public void CreateModuleEscapesAssemblyName ()
{
var module = ModuleDefinition.CreateModule ("Test.dll", ModuleKind.Dll);
Assert.AreEqual ("Test", module.Assembly.Name.Name);
module = ModuleDefinition.CreateModule ("Test.exe", ModuleKind.Console);
Assert.AreEqual ("Test", module.Assembly.Name.Name);
}
#endif
[Test]
public void SingleModule ()
{
TestModule ("hello.exe", module => {
var assembly = module.Assembly;
Assert.AreEqual (1, assembly.Modules.Count);
Assert.IsNotNull (assembly.MainModule);
});
}
[Test]
public void EntryPoint ()
{
TestModule ("hello.exe", module => {
var entry_point = module.EntryPoint;
Assert.IsNotNull (entry_point);
Assert.AreEqual ("System.Void Program::Main()", entry_point.ToString ());
});
}
[Test]
public void MultiModules ()
{
if (Platform.OnCoreClr)
return;
TestModule("mma.exe", module => {
var assembly = module.Assembly;
Assert.AreEqual (3, assembly.Modules.Count);
Assert.AreEqual ("mma.exe", assembly.Modules [0].Name);
Assert.AreEqual (ModuleKind.Console, assembly.Modules [0].Kind);
Assert.AreEqual ("moda.netmodule", assembly.Modules [1].Name);
Assert.AreEqual ("eedb4721-6c3e-4d9a-be30-49021121dd92", assembly.Modules [1].Mvid.ToString ());
Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [1].Kind);
Assert.AreEqual ("modb.netmodule", assembly.Modules [2].Name);
Assert.AreEqual ("46c5c577-11b2-4ea0-bb3c-3c71f1331dd0", assembly.Modules [2].Mvid.ToString ());
Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [2].Kind);
});
}
[Test]
public void ModuleInformation ()
{
TestModule ("hello.exe", module => {
Assert.IsNotNull (module);
Assert.AreEqual ("hello.exe", module.Name);
Assert.AreEqual (new Guid ("C3BC2BD3-2576-4D00-A80E-465B5632415F"), module.Mvid);
});
}
[Test]
public void AssemblyReferences ()
{
TestModule ("hello.exe", module => {
Assert.AreEqual (1, module.AssemblyReferences.Count);
var reference = module.AssemblyReferences [0];
Assert.AreEqual ("mscorlib", reference.Name);
Assert.AreEqual (new Version (2, 0, 0, 0), reference.Version);
Assert.AreEqual (new byte [] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 }, reference.PublicKeyToken);
});
}
[Test]
public void ModuleReferences ()
{
TestModule ("pinvoke.exe", module => {
Assert.AreEqual (2, module.ModuleReferences.Count);
Assert.AreEqual ("kernel32.dll", module.ModuleReferences [0].Name);
Assert.AreEqual ("shell32.dll", module.ModuleReferences [1].Name);
});
}
[Test]
public void Types ()
{
TestModule ("hello.exe", module => {
Assert.AreEqual (2, module.Types.Count);
Assert.AreEqual ("<Module>", module.Types [0].FullName);
Assert.AreEqual ("<Module>", module.GetType ("<Module>").FullName);
Assert.AreEqual ("Program", module.Types [1].FullName);
Assert.AreEqual ("Program", module.GetType ("Program").FullName);
});
}
[Test]
public void LinkedResource ()
{
TestModule ("libres.dll", module => {
var resource = module.Resources.Where (res => res.Name == "linked.txt").First () as LinkedResource;
Assert.IsNotNull (resource);
Assert.AreEqual ("linked.txt", resource.Name);
Assert.AreEqual ("linked.txt", resource.File);
Assert.AreEqual (ResourceType.Linked, resource.ResourceType);
Assert.IsTrue (resource.IsPublic);
});
}
[Test]
public void EmbeddedResource ()
{
TestModule ("libres.dll", module => {
var resource = module.Resources.Where (res => res.Name == "embedded1.txt").First () as EmbeddedResource;
Assert.IsNotNull (resource);
Assert.AreEqual ("embedded1.txt", resource.Name);
Assert.AreEqual (ResourceType.Embedded, resource.ResourceType);
Assert.IsTrue (resource.IsPublic);
using (var reader = new StreamReader (resource.GetResourceStream ()))
Assert.AreEqual ("Hello", reader.ReadToEnd ());
resource = module.Resources.Where (res => res.Name == "embedded2.txt").First () as EmbeddedResource;
Assert.IsNotNull (resource);
Assert.AreEqual ("embedded2.txt", resource.Name);
Assert.AreEqual (ResourceType.Embedded, resource.ResourceType);
Assert.IsTrue (resource.IsPublic);
using (var reader = new StreamReader (resource.GetResourceStream ()))
Assert.AreEqual ("World", reader.ReadToEnd ());
});
}
[Test]
public void ExportedTypeFromNetModule ()
{
if (Platform.OnCoreClr)
return;
TestModule ("mma.exe", module => {
Assert.IsTrue (module.HasExportedTypes);
Assert.AreEqual (2, module.ExportedTypes.Count);
var exported_type = module.ExportedTypes [0];
Assert.AreEqual ("Module.A.Foo", exported_type.FullName);
Assert.AreEqual ("moda.netmodule", exported_type.Scope.Name);
exported_type = module.ExportedTypes [1];
Assert.AreEqual ("Module.B.Baz", exported_type.FullName);
Assert.AreEqual ("modb.netmodule", exported_type.Scope.Name);
});
}
[Test]
public void NestedTypeForwarder ()
{
TestCSharp ("CustomAttributes.cs", module => {
Assert.IsTrue (module.HasExportedTypes);
Assert.AreEqual (2, module.ExportedTypes.Count);
var exported_type = module.ExportedTypes [0];
Assert.AreEqual ("System.Diagnostics.DebuggableAttribute", exported_type.FullName);
Assert.AreEqual (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", exported_type.Scope.Name);
Assert.IsTrue (exported_type.IsForwarder);
var nested_exported_type = module.ExportedTypes [1];
Assert.AreEqual ("System.Diagnostics.DebuggableAttribute/DebuggingModes", nested_exported_type.FullName);
Assert.AreEqual (exported_type, nested_exported_type.DeclaringType);
Assert.AreEqual (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", nested_exported_type.Scope.Name);
});
}
[Test]
public void HasTypeReference ()
{
TestCSharp ("CustomAttributes.cs", module => {
Assert.IsTrue (module.HasTypeReference ("System.Attribute"));
Assert.IsTrue (module.HasTypeReference (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", "System.Attribute"));
Assert.IsFalse (module.HasTypeReference ("System.Core", "System.Attribute"));
Assert.IsFalse (module.HasTypeReference ("System.Linq.Enumerable"));
});
}
[Test]
public void Win32FileVersion ()
{
TestModule ("libhello.dll", module => {
var version = FileVersionInfo.GetVersionInfo (module.FileName);
Assert.AreEqual ("0.0.0.0", version.FileVersion);
});
}
[Test]
public void ModuleWithoutBlob ()
{
TestModule ("noblob.dll", module => {
Assert.IsNull (module.Image.BlobHeap);
});
}
[Test]
public void MixedModeModule ()
{
using (var module = GetResourceModule ("cppcli.dll")) {
Assert.AreEqual (1, module.ModuleReferences.Count);
Assert.AreEqual (string.Empty, module.ModuleReferences [0].Name);
}
}
[Test]
public void OpenIrrelevantFile ()
{
Assert.Throws<BadImageFormatException> (() => GetResourceModule ("text_file.txt"));
}
[Test]
public void GetTypeNamespacePlusName ()
{
using (var module = GetResourceModule ("moda.netmodule")) {
var type = module.GetType ("Module.A", "Foo");
Assert.IsNotNull (type);
}
}
[Test]
public void OpenModuleImmediate ()
{
using (var module = GetResourceModule ("hello.exe", ReadingMode.Immediate)) {
Assert.AreEqual (ReadingMode.Immediate, module.ReadingMode);
}
}
[Test]
public void OpenModuleDeferred ()
{
using (var module = GetResourceModule ("hello.exe", ReadingMode.Deferred)) {
Assert.AreEqual (ReadingMode.Deferred, module.ReadingMode);
}
}
[Test]
public void OwnedStreamModuleFileName ()
{
var path = GetAssemblyResourcePath ("hello.exe", GetType ().Assembly);
using (var file = File.Open (path, FileMode.Open))
{
using (var module = ModuleDefinition.ReadModule (file))
{
Assert.IsNotNull (module.FileName);
Assert.IsNotEmpty (module.FileName);
Assert.AreEqual (path, module.FileName);
}
}
}
#if !READ_ONLY
[Test]
public void ReadAndWriteFile ()
{
var path = Path.GetTempFileName ();
var original = ModuleDefinition.CreateModule ("FooFoo", ModuleKind.Dll);
var type = new TypeDefinition ("Foo", "Foo", TypeAttributes.Abstract | TypeAttributes.Sealed);
original.Types.Add (type);
original.Write (path);
using (var module = ModuleDefinition.ReadModule (path, new ReaderParameters { ReadWrite = true })) {
module.Write ();
}
using (var module = ModuleDefinition.ReadModule (path))
Assert.AreEqual ("Foo.Foo", module.Types [1].FullName);
}
[Test]
public void ExceptionInWriteDoesNotKeepLockOnFile ()
{
var path = Path.GetTempFileName ();
var module = ModuleDefinition.CreateModule ("FooFoo", ModuleKind.Dll);
// Mixed mode module that Cecil can not write
module.Attributes = (ModuleAttributes) 0;
Assert.Throws<NotSupportedException>(() => module.Write (path));
// Ensure you can still delete the file
File.Delete (path);
}
#endif
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
namespace SwarmCoordinator
{
partial class SwarmCoordinator
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing )
{
if( disposing && ( components != null ) )
{
components.Dispose();
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.AgentGridView = new System.Windows.Forms.DataGridView();
this.AgentName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.GroupName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Version = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.State = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.IPAddress = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.LastPingTime = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.NumLocalCores = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.NumRemoteCores = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.RestartAllAgentsButton = new System.Windows.Forms.Button();
this.RestartCoordinatorButton = new System.Windows.Forms.Button();
this.RestartQAAgentsButton = new System.Windows.Forms.Button();
( ( System.ComponentModel.ISupportInitialize )( this.AgentGridView ) ).BeginInit();
this.SuspendLayout();
//
// AgentGridView
//
this.AgentGridView.AllowUserToAddRows = false;
this.AgentGridView.AllowUserToDeleteRows = false;
this.AgentGridView.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom )
| System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.AgentGridView.Columns.AddRange( new System.Windows.Forms.DataGridViewColumn[] {
this.AgentName,
this.GroupName,
this.Version,
this.State,
this.IPAddress,
this.LastPingTime,
this.NumLocalCores,
this.NumRemoteCores} );
this.AgentGridView.Location = new System.Drawing.Point( 0, 0 );
this.AgentGridView.Margin = new System.Windows.Forms.Padding( 0 );
this.AgentGridView.Name = "AgentGridView";
this.AgentGridView.RowHeadersWidth = 4;
this.AgentGridView.Size = new System.Drawing.Size( 1091, 476 );
this.AgentGridView.TabIndex = 0;
//
// AgentName
//
this.AgentName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.AgentName.HeaderText = "Name";
this.AgentName.Name = "AgentName";
this.AgentName.ReadOnly = true;
this.AgentName.Width = 60;
//
// GroupName
//
this.GroupName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.GroupName.HeaderText = "Group Name";
this.GroupName.Name = "GroupName";
this.GroupName.ReadOnly = true;
this.GroupName.Width = 102;
//
// Version
//
this.Version.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.Version.HeaderText = "Agent Version";
this.Version.Name = "Version";
this.Version.ReadOnly = true;
this.Version.Width = 123;
//
// State
//
this.State.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.State.HeaderText = "State";
this.State.Name = "State";
this.State.ReadOnly = true;
this.State.Width = 48;
//
// IPAddress
//
this.IPAddress.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.IPAddress.HeaderText = "IP Address";
this.IPAddress.Name = "IPAddress";
this.IPAddress.ReadOnly = true;
this.IPAddress.Width = 102;
//
// LastPingTime
//
this.LastPingTime.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.LastPingTime.HeaderText = "Last Ping Time";
this.LastPingTime.Name = "LastPingTime";
this.LastPingTime.ReadOnly = true;
this.LastPingTime.Width = 130;
//
// NumLocalCores
//
this.NumLocalCores.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.NumLocalCores.HeaderText = "Cores for Local";
this.NumLocalCores.Name = "NumLocalCores";
this.NumLocalCores.ReadOnly = true;
this.NumLocalCores.Width = 137;
//
// NumRemoteCores
//
this.NumRemoteCores.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.NumRemoteCores.HeaderText = "Cores for Remote";
this.NumRemoteCores.Name = "NumRemoteCores";
this.NumRemoteCores.Width = 144;
//
// RestartAllAgentsButton
//
this.RestartAllAgentsButton.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.RestartAllAgentsButton.Location = new System.Drawing.Point( 1097, 50 );
this.RestartAllAgentsButton.Name = "RestartAllAgentsButton";
this.RestartAllAgentsButton.Size = new System.Drawing.Size( 155, 32 );
this.RestartAllAgentsButton.TabIndex = 1;
this.RestartAllAgentsButton.Text = "Restart All Agents";
this.RestartAllAgentsButton.UseVisualStyleBackColor = true;
this.RestartAllAgentsButton.Click += new System.EventHandler( this.RestartAllAgentsButton_Click );
//
// RestartCoordinatorButton
//
this.RestartCoordinatorButton.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.RestartCoordinatorButton.Location = new System.Drawing.Point( 1097, 88 );
this.RestartCoordinatorButton.Name = "RestartCoordinatorButton";
this.RestartCoordinatorButton.Size = new System.Drawing.Size( 155, 32 );
this.RestartCoordinatorButton.TabIndex = 2;
this.RestartCoordinatorButton.Text = "Restart Coordinator";
this.RestartCoordinatorButton.UseVisualStyleBackColor = true;
this.RestartCoordinatorButton.Click += new System.EventHandler( this.RestartCoordinatorButton_Click );
//
// RestartQAAgentsButton
//
this.RestartQAAgentsButton.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) );
this.RestartQAAgentsButton.Location = new System.Drawing.Point( 1097, 12 );
this.RestartQAAgentsButton.Name = "RestartQAAgentsButton";
this.RestartQAAgentsButton.Size = new System.Drawing.Size( 155, 32 );
this.RestartQAAgentsButton.TabIndex = 3;
this.RestartQAAgentsButton.Text = "Restart QA Agents";
this.RestartQAAgentsButton.UseVisualStyleBackColor = true;
this.RestartQAAgentsButton.Click += new System.EventHandler( this.RestartQAAgentsButton_Click );
//
// SwarmCoordinator
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 7F, 14F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size( 1264, 476 );
this.Controls.Add( this.RestartQAAgentsButton );
this.Controls.Add( this.RestartCoordinatorButton );
this.Controls.Add( this.RestartAllAgentsButton );
this.Controls.Add( this.AgentGridView );
this.Font = new System.Drawing.Font( "Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ( ( byte )( 0 ) ) );
this.Name = "SwarmCoordinator";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Text = "Swarm Coordinator";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler( this.SwarmCoordinator_Closing );
( ( System.ComponentModel.ISupportInitialize )( this.AgentGridView ) ).EndInit();
this.ResumeLayout( false );
}
#endregion
private System.Windows.Forms.DataGridView AgentGridView;
private System.Windows.Forms.Button RestartAllAgentsButton;
private System.Windows.Forms.Button RestartCoordinatorButton;
private System.Windows.Forms.DataGridViewTextBoxColumn AgentName;
private System.Windows.Forms.DataGridViewTextBoxColumn GroupName;
private System.Windows.Forms.DataGridViewTextBoxColumn Version;
private System.Windows.Forms.DataGridViewComboBoxColumn State;
private System.Windows.Forms.DataGridViewTextBoxColumn IPAddress;
private System.Windows.Forms.DataGridViewTextBoxColumn LastPingTime;
private System.Windows.Forms.DataGridViewTextBoxColumn NumLocalCores;
private System.Windows.Forms.DataGridViewTextBoxColumn NumRemoteCores;
private System.Windows.Forms.Button RestartQAAgentsButton;
}
}
| |
using System.Collections.Generic;
using UnityEngine;
public partial class ControlScript
{
#region var
private bool playOnce = false;
bool receivingFire = false;
bool flagRaised = false;
private int captureFlagBonus = 0;
private BoxCollider bcollider;
private int remainingOpp = 7;
bool activateStuck = false;
bool activateStuck2 = true;
bool checkAllEnemies = false;
#endregion
#region Utils
void ResetFlag()
{
flagRaised = false;
}
void Unstuck()
{
if (Mathf.Floor(GetComponent<Rigidbody>().velocity.magnitude * 3600 / 1000) < 1)
{
transform.Rotate(Vector3.up * 180);
}
activateStuck = false;
activateStuck2 = true;
}
void Restore()
{
this.transform.rotation = new Quaternion(0, 0, 0, 0);
GetComponent<Rigidbody>().velocity = Vector3.zero;
this.transform.position = new Vector3(transform.position.x, 15f);
GetComponent<Rigidbody>().freezeRotation = true;
StartCoroutine(WaitRestore());
GetComponent<Rigidbody>().freezeRotation = false;
}
public void EnableUser()
{
OverrideStart = false;
UserControl = true;
engineAudio = gameObject.AddComponent<AudioSource>();
/*engineAudio.loop = true;
engineAudio.playOnAwake = false;
engineAudio.clip = engineSound;
engineAudio.volume = volume;
*/
turboAudio = gameObject.AddComponent<AudioSource>();
/*turboAudio.loop = false;
turboAudio.playOnAwake = false;
turboAudio.clip = turbo;
turboAudio.volume = volume;
*/
ignitionAudio = gameObject.AddComponent<AudioSource>();
/*ignitionAudio.loop = false;
ignitionAudio.playOnAwake = true;
ignitionAudio.clip = ignitionSound;
ignitionAudio.volume = volume;
*/
exAudio = gameObject.AddComponent<AudioSource>();
/*exAudio.loop = false;
exAudio.playOnAwake = false;
exAudio.clip = exSound;
exAudio.volume = volume;
*/
Camera.main.SendMessage("SetTarget", transform);
Camera.main.SendMessage("setUpGamePlayGui", transform);
GameObject go;
go = GameObject.FindGameObjectWithTag("radarTag");
go.GetComponent<Radar>().centerObject = transform;
go.SendMessage("SetTarget", transform);
go.SendMessage("OpenRadar", 1);
}
public void DisableUser()
{
UserControl = false;
Invoke("setOverrideStart", 4);
}
void setOverrideStart()
{
OverrideStart = false;
}
#endregion
void populateWaypoints(List<Transform> path)
{
waypoints.Clear();
waypoints = new List<Transform>() { path[0] };
currentWaypoint = 0;
flagRaised = true;
}
void GetObstacles()
{
Transform[] potentialObstacles = obstacleMap.GetComponentsInChildren<Transform>();
obstacles = new List<Transform>();
obstacleColliders = new List<SphereCollider>();
foreach (Transform potentialObstacle in potentialObstacles)
{
if (potentialObstacle != obstacleMap.transform)
{
obstacles.Add(potentialObstacle);
}
}
SphereCollider[] potentialObstacleColliders = obstacleMap.GetComponentsInChildren<SphereCollider>();
foreach (SphereCollider potentialObstacleCollider in potentialObstacleColliders)
{
if (potentialObstacleCollider != obstacleMap.GetComponent<SphereCollider>())
{
obstacleColliders.Add(potentialObstacleCollider);
}
}
}
#region Navigation
void ObstacleDetection()
{
if (activateStuck && Mathf.Floor(GetComponent<Rigidbody>().velocity.magnitude * 3600 / 1000) < 1 && activateStuck2)
{
activateStuck2 = false;
Invoke("Unstuck", 2);
}
if (probeCheck)
{
//Closest Intersecting Obstacle
SphereCollider closestIntersectingObject = null;
//this will be used to track the distance to the CIB
float distToClosestIP = Mathf.Infinity; //maxDouble;
//this will record the transformed local coordinates of the CIB
Vector3 localPosOfClosestObstacle = new Vector3(0, 0, 0);
m_dDBox.height = 25;
m_dDBox.center = new Vector3(m_dDBox.center.x, m_dDBox.center.y, 10.59f);
int i = 0;
currentObstacle = 0;
for (i = 0; i < obstacles.Count; i++)
{
Vector3 relativeObstaclePosition =
transform.InverseTransformPoint(new Vector3(obstacles[currentObstacle].position.x,
transform.position.y, obstacles[currentObstacle].position.z));
if (relativeObstaclePosition.z >= 0)
{
//if the distance from the z axis to the object's position is less than it's radius
// + half the width of the detection box then there is a potential intersection
float expandedRadius = m_dDBox.radius +
obstacleColliders[currentObstacle].radius + 20;
//Debug.Log(" realtive : "+Mathf.Abs(relativeObstaclePosition.x)+" expandedRadius : "+expandedRadius);
if (Mathf.Abs(relativeObstaclePosition.x) < expandedRadius)
{
//now to do a line/circle intersection test. The center of the circle
//is represented by (cZ,cX).The intersection points are given by the formula
// z = cZ +/-sqrt(r^2-cX^2) for x=0.
//We only need to look at the smallest positive value of z because that will be the closest
//point of intersection.
float cZ = relativeObstaclePosition.z;
float cX = relativeObstaclePosition.x;
//we only need to calculate the sqrt part of the above equation once
float sqrtPart = Mathf.Sqrt(expandedRadius * expandedRadius - cX * cX);
float ip = cZ - sqrtPart;
if (ip <= 0)
{
ip = cZ + sqrtPart;
}
//test to see if this is the closest so far.If it is, keep a
//record of the obstacle and its local coordinates
if (ip < distToClosestIP)
{
distToClosestIP = ip;
closestIntersectingObject = obstacleColliders[currentObstacle];
localPosOfClosestObstacle = relativeObstaclePosition;
//Debug.Log("CIB "+Vector3( obstacles[currentObstacle].position.x, transform.position.y, obstacles[currentObstacle].position.z ));
}
}
}
currentObstacle++;
}
//if we have found an intersecting obstacle, calculate a steering
//force away from it
Vector3 steeringForce;
//---------------------------------------------------------------------------------------------------------------------------------
if (closestIntersectingObject != null)
{
//the closer the agent is to an object, the stronger the steering force
//should be
float multiplier = 1.0f + (m_dDBox.height - localPosOfClosestObstacle.z) / m_dDBox.height;
//calculate the lateral force
steeringForce.x = (closestIntersectingObject.radius - localPosOfClosestObstacle.x) * multiplier * 100;
//inputSteer = steeringForce.x;//localPosOfClosestObstacle.x/localPosOfClosestObstacle.magnitude ;
//apply a braking force proportional to the obstacle's distance from
//the vehicle
float brakingWeight = 100;
Vector3 gmt = transform.position;
gmt.z = gmt.z + 5;
steeringForce.z = (closestIntersectingObject.radius - localPosOfClosestObstacle.z) * brakingWeight;
inputHandbrake = 0;
inputSteer = Mathf.Clamp(steeringForce.x, -1.0f, 1.0f); //Mathf.Sign(steeringForce.x);//
inputBrake = 0;
inputMotor = 0.5f;
return;
}
}
return;
}
void NavigateTowardsWaypoint()
{
// now we just find the relative position of the waypoint from the car transform,
// that way we can determine how far to the left and right the waypoint is.
//Debug.Log("w "+currentWaypoint);
if (currentWaypoint < 0 || currentWaypoint >= waypoints.Count)
{
Debug.Log("flag status : " + flagRaised + " " + currentWaypoint);
}
Vector3 RelativeWaypointPosition =
transform.InverseTransformPoint(new Vector3(waypoints[currentWaypoint].position.x, transform.position.y,
waypoints[currentWaypoint].position.y));
// by dividing the horizontal position by the magnitude, we get a decimal percentage of the turn angle that we can use to drive the wheels
if (enableControlToWaypoints)
{
inputSteer = RelativeWaypointPosition.x / RelativeWaypointPosition.magnitude;
// now we do the same for torque, but make sure that it doesn't apply any engine torque when going around a sharp turn...
if (Mathf.Abs(inputSteer) < 0.1f) // || rigidbody.velocity.magnitude * 3600/1000 <30 )
{
//inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude ;
inputHandbrake = 0;
inputMotor = 1;
inputBrake = 0;
//Debug.Log("test");
}
else if (GetComponent<Rigidbody>().velocity.magnitude * 3600 / 1000 < 30)
{
inputHandbrake = 0;
inputBrake = 0;
inputMotor = 1;
}
else
{
inputHandbrake = 1;
inputBrake = 0;
inputMotor = 0;
//Debug.Log("test2");
}
}
// this just checks if the car's position is near enough to a waypoint to count as passing it, if it is, then change the target waypoint to the
// next in the list.
if (RelativeWaypointPosition.magnitude < 20)
{
currentWaypoint++;
if (currentWaypoint >= waypoints.Count - 1)
{
currentWaypoint = waypoints.Count - 1;
}
}
}
void NavigateTowardsSpecificWaypoint(Vector3 target)
{
if (enableControlToWaypoints)
{
Vector3 RelativeWaypointPosition =
transform.InverseTransformPoint(new Vector3(target.x, transform.position.y, target.z));
// by dividing the horizontal position by the magnitude, we get a decimal percentage of the turn angle that we can use to drive the wheels
inputSteer = RelativeWaypointPosition.x / RelativeWaypointPosition.magnitude;
// now we do the same for torque, but make sure that it doesn't apply any engine torque when going around a sharp turn...
if (Mathf.Abs(inputSteer) < 0.6f) // || rigidbody.velocity.magnitude * 3600/1000 <30 )
{
//inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude ;
inputHandbrake = 0;
inputMotor = 1;
inputBrake = 0;
}
else if (GetComponent<Rigidbody>().velocity.magnitude * 3600 / 1000 < 30)
{
inputHandbrake = 0;
inputBrake = 0;
inputMotor = 1;
}
else
{
inputHandbrake = 1;
inputBrake = 0;
inputMotor = 0;
}
}
}
#endregion
// Destroy everything that enters the trigger
void OnTriggerEnter(Collider other)
{
//Debug.Log("enter collider");
if (other.tag == "obstacleTag" || other.tag == "wallTag")
{
probeCheck = true;
enableControlToWaypoints = false;
}
if (other.tag == "flagTag")
{
captureFlagBonus++;
}
}
void OnTriggerExit(Collider other)
{
//Debug.Log("exit trigger");
if (other.tag == "obstacleTag" || other.tag == "wallTag")
{
Invoke("waiter", 1);
}
}
void OnTriggerStay(Collider other)
{
if (other.tag == "obstacleTag" || other.tag == "wallTag")
{
probeCheck = true;
enableControlToWaypoints = false;
}
}
void waiter()
{
probeCheck = false;
enableControlToWaypoints = true;
activateStuck = false;
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "homingMissileTag" || collision.gameObject.tag == "speedMissileTag" ||
collision.gameObject.tag == "powerMissileTag" || collision.gameObject.tag == "machineGunTag")
{
//receivingFire = true;
}
if ((collision.gameObject.tag == "wallTag" || collision.gameObject.tag == "obstacleTag") && !activateStuck)
{
activateStuck = true;
}
}
void OnCollisionStay(Collision collision)
{
if (collision.gameObject.tag == "homingMissileTag" || collision.gameObject.tag == "speedMissileTag" ||
collision.gameObject.tag == "powerMissileTag" || collision.gameObject.tag == "machineGunTag")
{
//receivingFire = true;
}
if ((collision.gameObject.tag == "wallTag" || collision.gameObject.tag == "obstacleTag") && !activateStuck)
{
activateStuck = true;
}
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.tag == "homingMissileTag" || collision.gameObject.tag == "speedMissileTag" ||
collision.gameObject.tag == "powerMissileTag" || collision.gameObject.tag == "machineGunTag")
{
//yield return new WaitForSeconds(3);
//receivingFire = false;
}
}
private GameObject obstacleMap;
private List<Transform> obstacles;
private List<SphereCollider> obstacleColliders;
private int currentObstacle = 0;
private CapsuleCollider m_dDBox;
private Transform criticalDistance;
private bool probeCheck = false;
GunControlScript guns;
// Here's all the variables for the AI, the waypoints are determined in the "GetWaypoints" function.
// the waypoint container is used to search for all the waypoints in the scene, and the current
// waypoint is used to determine which waypoint in the array the car is aiming for.
private GameObject waypointContainer;
private List<Transform> waypoints;
private int currentWaypoint = 0;
int showState = 0;
private GameObject enemy;
#region Sound
void StartEngineSound()
{
engineAudio.Play();
float timer = 0;
float fadeTime = 2;
playOnce = true;
}
public AudioClip engineSound;
public AudioClip ignitionSound;
public AudioClip turbo;
public AudioClip exSound;
static float volume = 1;
private AudioSource engineAudio;
private AudioSource turboAudio;
private AudioSource ignitionAudio;
private AudioSource exAudio;
static void SetVolume(float v)
{
volume = v;
//engineAudio.volume = volume;
//turboAudio.volume = volume;
//ignitionAudio.volume = volume;
}
#endregion
#region GUI
//-- GUI related variables
public GUISkin customSkin2;
public Texture GUIOverlayTexture;
public Texture enemySkull;
public Renderer muzzleFlash;
#endregion
#region HealthAndMissiles
private GameObject healthMap;
private List<Transform> healthPacks;
private int closestHealthPack = 0;
private GameObject missileMap;
private List<Transform> missilePacks;
private int closestMissilePack = 0;
GunControlScript ammo;
HealthControlScript health;
#endregion
//states
int chase = 1;
int evade = 2;
int loadHealth = 3;
int loadWeapons = 4;
private int state = 1;
private class Wheel
{
public bool powered = false;
public Transform geometry;
public WheelCollider coll;
public Quaternion originalRotation;
public float rotation = 0.0f;
public float maxSteerAngle = 0.0f;
public float lastSkidMark = -1;
public bool handbraked = false;
}
void Update()
{
if (UserControl)
{
enemyLocked = FindClosestEnemy();
ammo.SetEnemyLocked(enemyLocked);
if (Input.GetButtonDown("Restore"))
{
Restore();
}
/*
GetComponent<AudioSource>().pitch = Mathf.Abs(engineRPM / maxRPM) + 1;
if (GetComponent<AudioSource>().pitch > 2.0f)
{
GetComponent<AudioSource>().pitch = 2.0f;
}
*/
}
}
void GetHealthPacks()
{
Transform[] potentialHealthPacks = healthMap.GetComponentsInChildren<Transform>();
healthPacks = new List<Transform>();
foreach (Transform potentialHealthPack in potentialHealthPacks)
{
if (potentialHealthPack != healthMap.transform)
{
healthPacks.Add(potentialHealthPack);
}
}
}
void GetMissilePacks()
{
Transform[] potentialMissilePacks = missileMap.GetComponentsInChildren<Transform>();
missilePacks = new List<Transform>();
foreach (Transform potentialMissilePack in potentialMissilePacks)
{
if (potentialMissilePack != missileMap.transform)
{
missilePacks.Add(potentialMissilePack);
}
}
}
void GetWaypoints()
{
// Now, this function basically takes the container object for the waypoints, then finds all of the transforms in it,
// once it has the transforms, it checks to make sure it's not the container, and adds them to the array of waypoints.
Transform[] potentialWaypoints = waypointContainer.GetComponentsInChildren<Transform>();
waypoints = new List<Transform>();
foreach (Transform potentialWaypoint in potentialWaypoints)
{
if (potentialWaypoint != waypointContainer.transform)
{
waypoints.Add(potentialWaypoint);
}
}
}
// Find the name of the closest enemy
GameObject FindClosestEnemy()
{
// Find all game objects with tag Enemy
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("carTag");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
remainingOpp = gos.Length - 1;
if (UserControl && gos.Length == 8)
{
checkAllEnemies = true;
}
if (gos.Length == 1 && checkAllEnemies && UserControl)
{
float finalScore = health.pointsKeeper + 100 * health.fatalityBonus + health.GetHealth() +
200 * captureFlagBonus;
OverrideStart = true;
UserControl = false;
Camera.main.SendMessage("PlayerWon", 5);
}
// Iterate through them and find the closest one
foreach (GameObject go in gos)
{
if (go.transform.position != transform.position && !go.transform.IsChildOf(transform))
{
Vector3 diff = (go.transform.position - position);
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
}
return closest;
}
Vector3 FindClosestHealthPack()
{
GetHealthPacks();
float threshold = Mathf.Infinity;
int i = -1;
bool confirm = false;
for (i = 0; i < healthPacks.Count; i++)
{
Vector3 RelativeHealthPackPosition =
transform.InverseTransformPoint(new Vector3(healthPacks[i].position.x, transform.position.y,
healthPacks[i].position.z));
float temp;
temp = Mathf.Sqrt(Mathf.Pow(RelativeHealthPackPosition.x, 2) + Mathf.Pow(RelativeHealthPackPosition.z, 2));
if (temp < threshold)
{
threshold = temp;
closestHealthPack = i;
confirm = true;
}
}
if (closestHealthPack >= 0 && confirm)
{
confirm = false;
//Debug.Log("closestHealthPack : "+healthPacks[closestHealthPack].position);
return healthPacks[closestHealthPack].position;
}
else
{
confirm = false;
return new Vector3(-1, -1, -1);
}
}
Vector3 FindClosestMissilePack()
{
GetMissilePacks();
float threshold = Mathf.Infinity;
int i = -1;
bool confirm = false;
for (i = 0; i < missilePacks.Count; i++)
{
Vector3 RelativeMissilePackPosition =
transform.InverseTransformPoint(new Vector3(missilePacks[i].position.x, transform.position.y,
missilePacks[i].position.z));
float temp;
temp = Mathf.Sqrt(Mathf.Pow(RelativeMissilePackPosition.x, 2) + Mathf.Pow(RelativeMissilePackPosition.z, 2));
if (temp < threshold)
{
threshold = temp;
closestMissilePack = i;
confirm = true;
}
}
if (closestMissilePack >= 0 && confirm)
{
confirm = false;
return new Vector3(missilePacks[closestMissilePack].position.x, missilePacks[closestMissilePack].position.y,
missilePacks[closestMissilePack].position.z);
}
else
{
confirm = false;
return new Vector3(-1, -1, -1);
}
}
#region FUZZY LOGIC
void FuzzyLogic()
{
float tempHealth = health.GetHealth();
int tempAmmo = ammo.GetSpeedAmount() + ammo.GetHomingAmount() + ammo.GetPowerAmount();
GameObject tempEnemy = FindClosestEnemy();
if (tempEnemy != null)
{
enemy = tempEnemy;
}
if (enemy == null)
{
return;
}
ammo.SetEnemyLocked(enemy);
GunControlScript enemyMissileScript = enemy.GetComponent<GunControlScript>();
HealthControlScript enemyHealthScript = enemy.GetComponent<HealthControlScript>();
float enemyHealth = enemyHealthScript.GetHealth();
int enemyAmmo = enemyMissileScript.GetSpeedAmount() + enemyMissileScript.GetHomingAmount();
Vector3 enemyTransformPosition = enemy.transform.position;
Vector3 closestHealthPack = FindClosestHealthPack();
Vector3 closestMissilePack = FindClosestMissilePack();
float healthPriority = CalcHealthPriority(tempHealth, closestHealthPack);
float missilePriority = CalcMissilePriority(tempAmmo, closestMissilePack);
float chasePriority = CalcChasePriority(enemyHealth, tempAmmo, enemyTransformPosition);
float evadePriority = CalcEvadePriority(tempHealth, enemyAmmo, enemyTransformPosition);
showState = MaximumPriority(healthPriority, missilePriority, chasePriority, evadePriority);
switch (showState)
{
case 1:
ChaseFL(enemy);
break;
case 2:
EvadeFL(enemy);
break;
case 3:
LoadHealthFL(closestHealthPack);
break;
case 4:
LoadWeaponsFL(closestMissilePack);
break;
default:
break;
}
}
int MaximumPriority(float healthPriority, float missilePriority, float chasePriority, float evadePriority)
{
float temp = Mathf.Max(Mathf.Max(Mathf.Max(healthPriority, missilePriority), chasePriority), evadePriority);
if (temp == chasePriority)
{
return 1;
}
else if (temp == evadePriority)
{
return 2;
}
else if (temp == healthPriority)
{
return 3;
}
else if (temp == missilePriority)
{
return 4;
}
return -1;
}
//---------------------------------------------------------------------------------------------
void ChaseFL(GameObject enemy)
{
NavigateTowardsSpecificWaypoint(new Vector3(enemy.transform.position.x + 10, enemy.transform.position.y,
enemy.transform.position.z + 10));
Vector3 direction = transform.TransformDirection(Vector3.forward);
RaycastHit hit = new RaycastHit();
// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 10;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
// Did we hit anything?
if (Physics.Raycast(new Vector3(transform.position.x, transform.position.y, transform.position.z), direction,
out hit, 100, layerMask))
{
if (hit.collider.tag == "carColliderTag")
{
ammo.EnableAutoFire();
}
else
{
ammo.DisableAutoFire();
}
}
else
{
ammo.DisableAutoFire();
}
}
void EvadeFL(GameObject enemy)
{
ammo.DisableAutoFire();
Vector3 RelativeWaypointPosition = transform.InverseTransformPoint(enemy.transform.position);
// by dividing the horizontal position by the magnitude, we get a decimal percentage of the turn angle that we can use to drive the wheels
inputSteer = -RelativeWaypointPosition.x / RelativeWaypointPosition.magnitude;
inputHandbrake = 0;
inputMotor = 1;
inputBrake = 0;
}
void LoadHealthFL(Vector3 closestHealthPack)
{
ammo.DisableAutoFire();
NavigateTowardsSpecificWaypoint(closestHealthPack);
}
void LoadWeaponsFL(Vector3 closestMissilePack)
{
ammo.DisableAutoFire();
NavigateTowardsSpecificWaypoint(closestMissilePack);
}
//---------- Calculate Health Priority-----------------------------------------------
float CalcHealthPriority(float tempHealth, Vector3 closestHealthPack)
{
float lowHealth = FuzzyReverseGrade(tempHealth, 15, 30);
float mediumHealth = FuzzyTrapezoid(tempHealth, 15, 30, 60, 75);
float goodHealth = FuzzyGrade(tempHealth, 60, 75);
float distance = Vector3.Distance(closestHealthPack, transform.position);
float closeDistance = FuzzyReverseGrade(distance, 25, 50);
float mediumDistance = FuzzyTriangle(distance, 25, 50, 75);
float farDistance = FuzzyGrade(distance, 50, 75);
float rule1 = FuzzyAND(lowHealth, closeDistance); //critical
float rule2 = FuzzyAND(lowHealth, mediumDistance); //high
float rule3 = FuzzyAND(lowHealth, farDistance); //high
float rule4 = FuzzyAND(mediumHealth, closeDistance); //normal
float rule5 = FuzzyAND(mediumHealth, mediumDistance); //low
float rule6 = FuzzyAND(mediumHealth, farDistance); //low
float rule7 = FuzzyAND(goodHealth, closeDistance); //low
float rule8 = FuzzyAND(goodHealth, mediumDistance); //low
float rule9 = FuzzyAND(goodHealth, farDistance); //low
float critical = 0;
float high = 0;
float normal = 0;
float low = 0;
// --- Critical
critical = rule1;
// --- High
high = FuzzyOR(high, rule2);
high = FuzzyOR(high, rule3);
// --- Normal
normal = rule4;
// --- Low
low = FuzzyOR(low, rule5);
low = FuzzyOR(low, rule6);
low = FuzzyOR(low, rule7);
low = FuzzyOR(low, rule8);
low = FuzzyOR(low, rule9);
float representativeValue1 = DefuzzyReverseGrade(low, 20, 30);
float representativeValue2 = DefuzzyTriangle(normal, 20, 30, 50);
float representativeValue3 = DefuzzyTrapezoid(high, 30, 50, 60, 80);
float representativeValue4 = DefuzzyGrade(critical, 60, 80, 100);
return ((representativeValue1 * low + representativeValue2 * normal + representativeValue3 * high +
representativeValue4 * critical) / low + normal + high + critical);
}
float CalcMissilePriority(int tempAmmo, Vector3 closestMissilePack)
{
float lowAmmo = FuzzyReverseGrade(tempAmmo, 0, 4);
float okAmmo = FuzzyTrapezoid(tempAmmo, 0, 4, 8, 14);
float loadsAmmo = FuzzyGrade(tempAmmo, 8, 14);
float distance = Vector3.Distance(closestMissilePack, transform.position);
float closeDistance = FuzzyReverseGrade(distance, 25, 50);
float mediumDistance = FuzzyTriangle(distance, 25, 50, 75);
float farDistance = FuzzyGrade(distance, 50, 75);
float rule1 = FuzzyAND(lowAmmo, closeDistance); //critical
float rule2 = FuzzyAND(lowAmmo, mediumDistance); //high
float rule3 = FuzzyAND(lowAmmo, farDistance); //high
float rule4 = FuzzyAND(okAmmo, closeDistance); //normal
float rule5 = FuzzyAND(okAmmo, mediumDistance); //low
float rule6 = FuzzyAND(okAmmo, farDistance); //low
float rule7 = FuzzyAND(loadsAmmo, closeDistance); //low
float rule8 = FuzzyAND(loadsAmmo, mediumDistance); //low
float rule9 = FuzzyAND(loadsAmmo, farDistance); //low
float critical = 0;
float high = 0;
float normal = 0;
float low = 0;
// --- Critical
critical = rule1;
// --- High
high = FuzzyOR(high, rule2);
high = FuzzyOR(high, rule3);
// --- Normal
normal = rule4;
// --- Low
low = FuzzyOR(low, rule5);
low = FuzzyOR(low, rule6);
low = FuzzyOR(low, rule7);
low = FuzzyOR(low, rule8);
low = FuzzyOR(low, rule9);
float representativeValue1 = DefuzzyReverseGrade(low, 20, 30);
float representativeValue2 = DefuzzyTriangle(normal, 20, 30, 50);
float representativeValue3 = DefuzzyTrapezoid(high, 30, 50, 60, 80);
float representativeValue4 = DefuzzyGrade(critical, 60, 80, 100);
return ((representativeValue1 * low + representativeValue2 * normal + representativeValue3 * high +
representativeValue4 * critical) / low + normal + high + critical);
}
float CalcChasePriority(float enemyHealth, int tempAmmo, Vector3 enemyTransformPosition)
{
// --- Enemy Health
float lowHealth = FuzzyReverseGrade(enemyHealth, 15, 30);
float mediumHealth = FuzzyTrapezoid(enemyHealth, 15, 30, 60, 75);
float goodHealth = FuzzyGrade(enemyHealth, 60, 75);
// --- Our Ammo
float lowAmmo = FuzzyReverseGrade(tempAmmo, 0, 4);
float okAmmo = FuzzyTrapezoid(tempAmmo, 0, 4, 8, 14);
float loadsAmmo = FuzzyGrade(tempAmmo, 8, 14);
// --- Distance
float distance = Vector3.Distance(enemyTransformPosition, transform.position);
float closeDistance = FuzzyReverseGrade(distance, 25, 50);
float mediumDistance = FuzzyTriangle(distance, 25, 50, 75);
float farDistance = FuzzyGrade(distance, 50, 75);
// ----- Rules
float critical = 0;
float high = 0;
float normal = 0;
float low = 0;
float rule1 = FuzzyAND3(lowAmmo, lowHealth, closeDistance); //high
float rule2 = FuzzyAND3(lowAmmo, lowHealth, mediumDistance); //normal
float rule3 = FuzzyAND3(lowAmmo, lowHealth, farDistance); //low
float rule4 = FuzzyAND3(lowAmmo, mediumHealth, closeDistance); //normal
float rule5 = FuzzyAND3(lowAmmo, mediumHealth, mediumDistance); //normal
float rule6 = FuzzyAND3(lowAmmo, mediumHealth, farDistance); //low
float rule7 = FuzzyAND3(lowAmmo, goodHealth, closeDistance); //low
float rule8 = FuzzyAND3(lowAmmo, goodHealth, mediumDistance); //low
float rule9 = FuzzyAND3(lowAmmo, goodHealth, farDistance); //low
float rule10 = FuzzyAND3(okAmmo, lowHealth, closeDistance); //critical
float rule11 = FuzzyAND3(okAmmo, lowHealth, mediumDistance); //critical
float rule12 = FuzzyAND3(okAmmo, lowHealth, farDistance); //high
float rule13 = FuzzyAND3(okAmmo, mediumHealth, closeDistance); //critical
float rule14 = FuzzyAND3(okAmmo, mediumHealth, mediumDistance); //high
float rule15 = FuzzyAND3(okAmmo, mediumHealth, farDistance); //normal
float rule16 = FuzzyAND3(okAmmo, goodHealth, closeDistance); //high
float rule17 = FuzzyAND3(okAmmo, goodHealth, mediumDistance); //normal
float rule18 = FuzzyAND3(okAmmo, goodHealth, farDistance); //normal
float rule19 = FuzzyAND3(loadsAmmo, lowHealth, closeDistance); //critical
float rule20 = FuzzyAND3(loadsAmmo, lowHealth, mediumDistance); //critical
float rule21 = FuzzyAND3(loadsAmmo, lowHealth, farDistance); //high
float rule22 = FuzzyAND3(loadsAmmo, mediumHealth, closeDistance); //high
float rule23 = FuzzyAND3(loadsAmmo, mediumHealth, mediumDistance); //high
float rule24 = FuzzyAND3(loadsAmmo, mediumHealth, farDistance); //normal
float rule25 = FuzzyAND3(loadsAmmo, goodHealth, closeDistance); //normal
float rule26 = FuzzyAND3(loadsAmmo, goodHealth, mediumDistance); //normal
float rule27 = FuzzyAND3(loadsAmmo, goodHealth, farDistance); //normal
// --- Critical
critical = FuzzyOR(critical, rule10);
critical = FuzzyOR(critical, rule11);
critical = FuzzyOR(critical, rule13);
critical = FuzzyOR(critical, rule19);
critical = FuzzyOR(critical, rule20);
// --- High
high = FuzzyOR(high, rule1);
high = FuzzyOR(high, rule12);
high = FuzzyOR(high, rule14);
high = FuzzyOR(high, rule16);
high = FuzzyOR(high, rule21);
high = FuzzyOR(high, rule22);
high = FuzzyOR(high, rule23);
// --- Normal
normal = FuzzyOR(normal, rule2);
normal = FuzzyOR(normal, rule4);
normal = FuzzyOR(normal, rule5);
normal = FuzzyOR(normal, rule15);
normal = FuzzyOR(normal, rule17);
normal = FuzzyOR(normal, rule18);
normal = FuzzyOR(normal, rule24);
normal = FuzzyOR(normal, rule25);
normal = FuzzyOR(normal, rule26);
normal = FuzzyOR(normal, rule27);
// --- Low
low = FuzzyOR(low, rule3);
low = FuzzyOR(low, rule6);
low = FuzzyOR(low, rule7);
low = FuzzyOR(low, rule8);
low = FuzzyOR(low, rule9);
float representativeValue1 = DefuzzyReverseGrade(low, 20, 30);
float representativeValue2 = DefuzzyTriangle(normal, 20, 30, 50);
float representativeValue3 = DefuzzyTrapezoid(high, 30, 50, 60, 80);
float representativeValue4 = DefuzzyGrade(critical, 60, 80, 100);
return ((representativeValue1 * low + representativeValue2 * normal + representativeValue3 * high +
representativeValue4 * critical) / low + normal + high + critical);
}
float CalcEvadePriority(float tempHealth, int enemyAmmo, Vector3 enemyTransformPosition)
{
// ---- Our Health
float lowHealth = FuzzyReverseGrade(tempHealth, 15, 30);
float mediumHealth = FuzzyTrapezoid(tempHealth, 15, 30, 60, 75);
float goodHealth = FuzzyGrade(tempHealth, 60, 75);
// ---- Enemy Ammo
float lowAmmo = FuzzyReverseGrade(enemyAmmo, 0, 4);
float okAmmo = FuzzyTrapezoid(enemyAmmo, 0, 4, 8, 14);
float loadsAmmo = FuzzyGrade(enemyAmmo, 8, 14);
// ----- Distance
float distance = Vector3.Distance(enemyTransformPosition, transform.position);
float closeDistance = FuzzyReverseGrade(distance, 25, 50);
float mediumDistance = FuzzyTriangle(distance, 25, 50, 75);
float farDistance = FuzzyGrade(distance, 50, 75);
// ----- Rules
float critical = 0;
float high = 0;
float normal = 0;
float low = 0;
float rule1 = FuzzyAND3(lowAmmo, lowHealth, closeDistance); //normal
float rule2 = FuzzyAND3(lowAmmo, lowHealth, mediumDistance); //normal
float rule3 = FuzzyAND3(lowAmmo, lowHealth, farDistance); //low
float rule4 = FuzzyAND3(lowAmmo, mediumHealth, closeDistance); //normal
float rule5 = FuzzyAND3(lowAmmo, mediumHealth, mediumDistance); //low
float rule6 = FuzzyAND3(lowAmmo, mediumHealth, farDistance); //low
float rule7 = FuzzyAND3(lowAmmo, goodHealth, closeDistance); //low
float rule8 = FuzzyAND3(lowAmmo, goodHealth, mediumDistance); //low
float rule9 = FuzzyAND3(lowAmmo, goodHealth, farDistance); //low
float rule10 = FuzzyAND3(okAmmo, lowHealth, closeDistance); //high
float rule11 = FuzzyAND3(okAmmo, lowHealth, mediumDistance); //high
float rule12 = FuzzyAND3(okAmmo, lowHealth, farDistance); //normal
float rule13 = FuzzyAND3(okAmmo, mediumHealth, closeDistance); //normal
float rule14 = FuzzyAND3(okAmmo, mediumHealth, mediumDistance); //normal
float rule15 = FuzzyAND3(okAmmo, mediumHealth, farDistance); //low
float rule16 = FuzzyAND3(okAmmo, goodHealth, closeDistance); //low
float rule17 = FuzzyAND3(okAmmo, goodHealth, mediumDistance); //low
float rule18 = FuzzyAND3(okAmmo, goodHealth, farDistance); //low
float rule19 = FuzzyAND3(loadsAmmo, lowHealth, closeDistance); //critical
float rule20 = FuzzyAND3(loadsAmmo, lowHealth, mediumDistance); //high
float rule21 = FuzzyAND3(loadsAmmo, lowHealth, farDistance); //normal
float rule22 = FuzzyAND3(loadsAmmo, mediumHealth, closeDistance); //normal
float rule23 = FuzzyAND3(loadsAmmo, mediumHealth, mediumDistance); //normal
float rule24 = FuzzyAND3(loadsAmmo, mediumHealth, farDistance); //normal
float rule25 = FuzzyAND3(loadsAmmo, goodHealth, closeDistance); //low
float rule26 = FuzzyAND3(loadsAmmo, goodHealth, mediumDistance); //low
float rule27 = FuzzyAND3(loadsAmmo, goodHealth, farDistance); //low
// --- Critical
critical = rule19;
// --- High
high = FuzzyOR(high, rule10);
high = FuzzyOR(high, rule11);
high = FuzzyOR(high, rule20);
// --- Normal
normal = FuzzyOR(normal, rule1);
normal = FuzzyOR(normal, rule2);
normal = FuzzyOR(normal, rule4);
normal = FuzzyOR(normal, rule12);
normal = FuzzyOR(normal, rule13);
normal = FuzzyOR(normal, rule14);
normal = FuzzyOR(normal, rule21);
normal = FuzzyOR(normal, rule22);
normal = FuzzyOR(normal, rule23);
normal = FuzzyOR(normal, rule24);
// --- Low
low = FuzzyOR(low, rule3);
low = FuzzyOR(low, rule5);
low = FuzzyOR(low, rule6);
low = FuzzyOR(low, rule7);
low = FuzzyOR(low, rule8);
low = FuzzyOR(low, rule9);
low = FuzzyOR(low, rule15);
low = FuzzyOR(low, rule16);
low = FuzzyOR(low, rule17);
low = FuzzyOR(low, rule18);
low = FuzzyOR(low, rule25);
low = FuzzyOR(low, rule26);
low = FuzzyOR(low, rule27);
float representativeValue1 = DefuzzyReverseGrade(low, 20, 30);
float representativeValue2 = DefuzzyTriangle(normal, 20, 30, 50);
float representativeValue3 = DefuzzyTrapezoid(high, 30, 50, 60, 80);
float representativeValue4 = DefuzzyGrade(critical, 60, 80, 100);
return ((representativeValue1 * low + representativeValue2 * normal + representativeValue3 * high +
representativeValue4 * critical) / low + normal + high + critical);
}
float FuzzyGrade(float value, float x0, float x1)
{
float result = 0;
float x = value;
if (x <= x0)
{
result = 0;
}
else if (x >= x1)
{
result = 1;
}
else
{
result = (x / (x1 - x0)) - (x0 / (x1 - x0));
}
return result;
}
float DefuzzyGrade(float C1, float x0, float x1, float maxXValue)
{
float a = IntersectionX(0.0f, 1.0f, C1, (-1 / (x1 - x0)), 1, (-x0 / (x1 - x0)));
return (a + maxXValue) / 2;
}
float FuzzyReverseGrade(float value, float x0, float x1)
{
float result = 0;
float x = value;
if (x <= x0)
{
result = 1;
}
else if (x >= x1)
{
result = 0;
}
else
{
result = (-x / (x1 - x0)) + (x1 / (x1 - x0));
}
return result;
}
float DefuzzyReverseGrade(float C1, float x0, float x1)
{
float b = IntersectionX(0.0f, 1.0f, C1, (1 / (x1 - x0)), 1, x1 / (x1 - x0));
return b / 2;
}
float FuzzyTriangle(float value, float x0, float x1, float x2)
{
float result = 0;
float x = value;
if (x <= x0)
{
result = 0;
}
else if (x == x1)
{
result = 1;
}
else if ((x > x0) && (x < x1))
{
result = (x / (x1 - x0)) - (x0 / (x1 - x0));
}
else
{
result = (-x / (x2 - x1)) + (x2 / (x2 - x1));
}
return result;
}
float DefuzzyTriangle(float C1, float x0, float x1, float x2)
{
float a = IntersectionX(0.0f, 1.0f, C1, (-1 / (x1 - x0)), 1, (-x0 / (x1 - x0)));
float b = IntersectionX(0.0f, 1.0f, C1, (1 / (x2 - x1)), 1, x2 / (x2 - x1));
return (a + b) / 2;
}
float FuzzyTrapezoid(float value, float x0, float x1, float x2, float x3)
{
float result = 0;
float x = value;
if (x <= x0)
{
result = 0;
}
else if ((x >= x1) && (x <= x2))
{
result = 1;
}
else if ((x > x0) && (x < x1))
{
result = (x / (x1 - x0)) - (x0 / (x1 - x0));
}
else
{
result = (-x / (x3 - x2)) + (x3 / (x3 - x2));
}
return result;
}
float DefuzzyTrapezoid(float C1, float x0, float x1, float x2, float x3)
{
float a = IntersectionX(0.0f, 1.0f, C1, (-1 / (x1 - x0)), 1, (-x0 / (x1 - x0)));
float b = IntersectionX(0.0f, 1.0f, C1, (1 / (x3 - x2)), 1, x3 / (x3 - x2));
return (a + b) / 2;
}
float FuzzyAND(float a, float b)
{
return Mathf.Min(a, b);
}
float FuzzyAND3(float a, float b, float c)
{
float d = Mathf.Min(a, b);
return Mathf.Min(c, d);
}
float FuzzyOR(float a, float b)
{
return Mathf.Max(a, b);
}
float FuzzyOR3(float a, float b, float c)
{
float d = Mathf.Max(a, b);
return Mathf.Max(c, d);
}
float FuzzyNOT(float a)
{
return 1.0f - a;
}
float IntersectionX(float A1, float B1, float C1, float A2, float B2, float C2)
{
float det = A1 * B2 - A2 * B1;
if (det == 0)
{
//Lines are parallel
return -1;
}
else
{
return (B2 * C1 - B1 * C2) / det;
}
}
float IntersectionY(float A1, float B1, float C1, float A2, float B2, float C2)
{
float det = A1 * B2 - A2 * B1;
if (det == 0)
{
//Lines are parallel
return -1;
}
else
{
return (A1 * C2 - A2 * C1) / det;
}
}
#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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Linq.Expressions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed class ExpressionStringBuilder : ExpressionVisitor
{
private readonly StringBuilder _out;
// Associate every unique label or anonymous parameter in the tree with an integer.
// Labels are displayed as UnnamedLabel_#; parameters are displayed as Param_#.
private Dictionary<object, int> _ids;
private ExpressionStringBuilder()
{
_out = new StringBuilder();
}
public override string ToString()
{
return _out.ToString();
}
private int GetLabelId(LabelTarget label) => GetId(label);
private int GetParamId(ParameterExpression p) => GetId(p);
private int GetId(object o)
{
if (_ids == null)
{
_ids = new Dictionary<object, int>();
}
int id;
if (!_ids.TryGetValue(o, out id))
{
id = _ids.Count;
_ids.Add(o, id);
}
return id;
}
#region The printing code
private void Out(string s)
{
_out.Append(s);
}
private void Out(char c)
{
_out.Append(c);
}
#endregion
#region Output an expression tree to a string
/// <summary>
/// Output a given expression tree to a string.
/// </summary>
internal static string ExpressionToString(Expression node)
{
Debug.Assert(node != null);
ExpressionStringBuilder esb = new ExpressionStringBuilder();
esb.Visit(node);
return esb.ToString();
}
internal static string CatchBlockToString(CatchBlock node)
{
Debug.Assert(node != null);
ExpressionStringBuilder esb = new ExpressionStringBuilder();
esb.VisitCatchBlock(node);
return esb.ToString();
}
internal static string SwitchCaseToString(SwitchCase node)
{
Debug.Assert(node != null);
ExpressionStringBuilder esb = new ExpressionStringBuilder();
esb.VisitSwitchCase(node);
return esb.ToString();
}
/// <summary>
/// Output a given member binding to a string.
/// </summary>
internal static string MemberBindingToString(MemberBinding node)
{
Debug.Assert(node != null);
ExpressionStringBuilder esb = new ExpressionStringBuilder();
esb.VisitMemberBinding(node);
return esb.ToString();
}
/// <summary>
/// Output a given ElementInit to a string.
/// </summary>
internal static string ElementInitBindingToString(ElementInit node)
{
Debug.Assert(node != null);
ExpressionStringBuilder esb = new ExpressionStringBuilder();
esb.VisitElementInit(node);
return esb.ToString();
}
private void VisitExpressions<T>(char open, ReadOnlyCollection<T> expressions, char close) where T : Expression
{
VisitExpressions(open, expressions, close, ", ");
}
private void VisitExpressions<T>(char open, ReadOnlyCollection<T> expressions, char close, string seperator) where T : Expression
{
Out(open);
if (expressions != null)
{
bool isFirst = true;
foreach (T e in expressions)
{
if (isFirst)
{
isFirst = false;
}
else
{
Out(seperator);
}
Visit(e);
}
}
Out(close);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected internal override Expression VisitBinary(BinaryExpression node)
{
if (node.NodeType == ExpressionType.ArrayIndex)
{
Visit(node.Left);
Out('[');
Visit(node.Right);
Out(']');
}
else
{
string op;
switch (node.NodeType)
{
// AndAlso and OrElse were unintentionally changed in
// CLR 4. We changed them to "AndAlso" and "OrElse" to
// be 3.5 compatible, but it turns out 3.5 shipped with
// "&&" and "||". Oops.
case ExpressionType.AndAlso:
op = "AndAlso";
break;
case ExpressionType.OrElse:
op = "OrElse";
break;
case ExpressionType.Assign:
op = "=";
break;
case ExpressionType.Equal:
op = "==";
break;
case ExpressionType.NotEqual:
op = "!=";
break;
case ExpressionType.GreaterThan:
op = ">";
break;
case ExpressionType.LessThan:
op = "<";
break;
case ExpressionType.GreaterThanOrEqual:
op = ">=";
break;
case ExpressionType.LessThanOrEqual:
op = "<=";
break;
case ExpressionType.Add:
case ExpressionType.AddChecked:
op = "+";
break;
case ExpressionType.AddAssign:
case ExpressionType.AddAssignChecked:
op = "+=";
break;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
op = "-";
break;
case ExpressionType.SubtractAssign:
case ExpressionType.SubtractAssignChecked:
op = "-=";
break;
case ExpressionType.Divide:
op = "/";
break;
case ExpressionType.DivideAssign:
op = "/=";
break;
case ExpressionType.Modulo:
op = "%";
break;
case ExpressionType.ModuloAssign:
op = "%=";
break;
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
op = "*";
break;
case ExpressionType.MultiplyAssign:
case ExpressionType.MultiplyAssignChecked:
op = "*=";
break;
case ExpressionType.LeftShift:
op = "<<";
break;
case ExpressionType.LeftShiftAssign:
op = "<<=";
break;
case ExpressionType.RightShift:
op = ">>";
break;
case ExpressionType.RightShiftAssign:
op = ">>=";
break;
case ExpressionType.And:
op = IsBool(node) ? "And" : "&";
break;
case ExpressionType.AndAssign:
op = IsBool(node) ? "&&=" : "&=";
break;
case ExpressionType.Or:
op = IsBool(node) ? "Or" : "|";
break;
case ExpressionType.OrAssign:
op = IsBool(node) ? "||=" : "|=";
break;
case ExpressionType.ExclusiveOr:
op = "^";
break;
case ExpressionType.ExclusiveOrAssign:
op = "^=";
break;
case ExpressionType.Power:
op = "**";
break; // This was changed in CoreFx from ^ to **
case ExpressionType.PowerAssign:
op = "**=";
break;
case ExpressionType.Coalesce:
op = "??";
break;
default:
throw new InvalidOperationException();
}
Out('(');
Visit(node.Left);
Out(' ');
Out(op);
Out(' ');
Visit(node.Right);
Out(')');
}
return node;
}
protected internal override Expression VisitParameter(ParameterExpression node)
{
if (node.IsByRef)
{
Out("ref ");
}
string name = node.Name;
if (string.IsNullOrEmpty(name))
{
Out("Param_" + GetParamId(node));
}
else
{
Out(name);
}
return node;
}
protected internal override Expression VisitLambda<T>(Expression<T> node)
{
if (node.ParameterCount == 1)
{
// p => body
Visit(node.GetParameter(0));
}
else
{
// (p1, p2, ..., pn) => body
Out('(');
string sep = ", ";
for (int i = 0, n = node.ParameterCount; i < n; i++)
{
if (i > 0)
{
Out(sep);
}
Visit(node.GetParameter(i));
}
Out(')');
}
Out(" => ");
Visit(node.Body);
return node;
}
protected internal override Expression VisitListInit(ListInitExpression node)
{
Visit(node.NewExpression);
Out(" {");
for (int i = 0, n = node.Initializers.Count; i < n; i++)
{
if (i > 0)
{
Out(", ");
}
VisitElementInit(node.Initializers[i]);
}
Out('}');
return node;
}
protected internal override Expression VisitConditional(ConditionalExpression node)
{
Out("IIF(");
Visit(node.Test);
Out(", ");
Visit(node.IfTrue);
Out(", ");
Visit(node.IfFalse);
Out(')');
return node;
}
protected internal override Expression VisitConstant(ConstantExpression node)
{
if (node.Value != null)
{
string sValue = node.Value.ToString();
if (node.Value is string)
{
Out('\"');
Out(sValue);
Out('\"');
}
else if (sValue == node.Value.GetType().ToString())
{
Out("value(");
Out(sValue);
Out(')');
}
else
{
Out(sValue);
}
}
else
{
Out("null");
}
return node;
}
protected internal override Expression VisitDebugInfo(DebugInfoExpression node)
{
string s = string.Format(
CultureInfo.CurrentCulture,
"<DebugInfo({0}: {1}, {2}, {3}, {4})>",
node.Document.FileName,
node.StartLine,
node.StartColumn,
node.EndLine,
node.EndColumn
);
Out(s);
return node;
}
protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node)
{
VisitExpressions('(', node.Variables, ')');
return node;
}
// Prints ".instanceField" or "declaringType.staticField"
private void OutMember(Expression instance, MemberInfo member)
{
if (instance != null)
{
Visit(instance);
}
else
{
// For static members, include the type name
Out(member.DeclaringType.Name);
}
Out('.');
Out(member.Name);
}
protected internal override Expression VisitMember(MemberExpression node)
{
OutMember(node.Expression, node.Member);
return node;
}
protected internal override Expression VisitMemberInit(MemberInitExpression node)
{
if (node.NewExpression.ArgumentCount == 0 &&
node.NewExpression.Type.Name.Contains("<"))
{
// anonymous type constructor
Out("new");
}
else
{
Visit(node.NewExpression);
}
Out(" {");
for (int i = 0, n = node.Bindings.Count; i < n; i++)
{
MemberBinding b = node.Bindings[i];
if (i > 0)
{
Out(", ");
}
VisitMemberBinding(b);
}
Out('}');
return node;
}
protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{
Out(assignment.Member.Name);
Out(" = ");
Visit(assignment.Expression);
return assignment;
}
protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{
Out(binding.Member.Name);
Out(" = {");
for (int i = 0, n = binding.Initializers.Count; i < n; i++)
{
if (i > 0)
{
Out(", ");
}
VisitElementInit(binding.Initializers[i]);
}
Out('}');
return binding;
}
protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
Out(binding.Member.Name);
Out(" = {");
for (int i = 0, n = binding.Bindings.Count; i < n; i++)
{
if (i > 0)
{
Out(", ");
}
VisitMemberBinding(binding.Bindings[i]);
}
Out('}');
return binding;
}
protected override ElementInit VisitElementInit(ElementInit initializer)
{
Out(initializer.AddMethod.ToString());
string sep = ", ";
Out('(');
for (int i = 0, n = initializer.ArgumentCount; i < n; i++)
{
if (i > 0)
{
Out(sep);
}
Visit(initializer.GetArgument(i));
}
Out(')');
return initializer;
}
protected internal override Expression VisitInvocation(InvocationExpression node)
{
Out("Invoke(");
Visit(node.Expression);
string sep = ", ";
for (int i = 0, n = node.ArgumentCount; i < n; i++)
{
Out(sep);
Visit(node.GetArgument(i));
}
Out(')');
return node;
}
protected internal override Expression VisitMethodCall(MethodCallExpression node)
{
int start = 0;
Expression ob = node.Object;
if (node.Method.GetCustomAttribute(typeof(ExtensionAttribute)) != null)
{
start = 1;
ob = node.GetArgument(0);
}
if (ob != null)
{
Visit(ob);
Out('.');
}
Out(node.Method.Name);
Out('(');
for (int i = start, n = node.ArgumentCount; i < n; i++)
{
if (i > start)
Out(", ");
Visit(node.GetArgument(i));
}
Out(')');
return node;
}
protected internal override Expression VisitNewArray(NewArrayExpression node)
{
switch (node.NodeType)
{
case ExpressionType.NewArrayBounds:
// new MyType[](expr1, expr2)
Out("new ");
Out(node.Type.ToString());
VisitExpressions('(', node.Expressions, ')');
break;
case ExpressionType.NewArrayInit:
// new [] {expr1, expr2}
Out("new [] ");
VisitExpressions('{', node.Expressions, '}');
break;
}
return node;
}
protected internal override Expression VisitNew(NewExpression node)
{
Out("new ");
Out(node.Type.Name);
Out('(');
ReadOnlyCollection<MemberInfo> members = node.Members;
for (int i = 0; i < node.ArgumentCount; i++)
{
if (i > 0)
{
Out(", ");
}
if (members != null)
{
string name = members[i].Name;
Out(name);
Out(" = ");
}
Visit(node.GetArgument(i));
}
Out(')');
return node;
}
protected internal override Expression VisitTypeBinary(TypeBinaryExpression node)
{
Out('(');
Visit(node.Expression);
switch (node.NodeType)
{
case ExpressionType.TypeIs:
Out(" Is ");
break;
case ExpressionType.TypeEqual:
Out(" TypeEqual ");
break;
}
Out(node.TypeOperand.Name);
Out(')');
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected internal override Expression VisitUnary(UnaryExpression node)
{
switch (node.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked: Out('-'); break;
case ExpressionType.Not: Out("Not("); break;
case ExpressionType.IsFalse: Out("IsFalse("); break;
case ExpressionType.IsTrue: Out("IsTrue("); break;
case ExpressionType.OnesComplement: Out("~("); break;
case ExpressionType.ArrayLength: Out("ArrayLength("); break;
case ExpressionType.Convert: Out("Convert("); break;
case ExpressionType.ConvertChecked: Out("ConvertChecked("); break;
case ExpressionType.Throw: Out("throw("); break;
case ExpressionType.TypeAs: Out('('); break;
case ExpressionType.UnaryPlus: Out('+'); break;
case ExpressionType.Unbox: Out("Unbox("); break;
case ExpressionType.Increment: Out("Increment("); break;
case ExpressionType.Decrement: Out("Decrement("); break;
case ExpressionType.PreIncrementAssign: Out("++"); break;
case ExpressionType.PreDecrementAssign: Out("--"); break;
case ExpressionType.Quote:
case ExpressionType.PostIncrementAssign:
case ExpressionType.PostDecrementAssign:
break;
default:
throw new InvalidOperationException();
}
Visit(node.Operand);
switch (node.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.UnaryPlus:
case ExpressionType.PreDecrementAssign:
case ExpressionType.PreIncrementAssign:
case ExpressionType.Quote:
break;
case ExpressionType.TypeAs:
Out(" As ");
Out(node.Type.Name);
Out(')'); break;
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
Out(", ");
Out(node.Type.Name);
Out(')'); break; // These were changed in CoreFx to add the type name
case ExpressionType.PostIncrementAssign: Out("++"); break;
case ExpressionType.PostDecrementAssign: Out("--"); break;
default: Out(')'); break;
}
return node;
}
protected internal override Expression VisitBlock(BlockExpression node)
{
Out('{');
foreach (ParameterExpression v in node.Variables)
{
Out("var ");
Visit(v);
Out(';');
}
Out(" ... }");
return node;
}
protected internal override Expression VisitDefault(DefaultExpression node)
{
Out("default(");
Out(node.Type.Name);
Out(')');
return node;
}
protected internal override Expression VisitLabel(LabelExpression node)
{
Out("{ ... } ");
DumpLabel(node.Target);
Out(':');
return node;
}
protected internal override Expression VisitGoto(GotoExpression node)
{
string op;
switch (node.Kind)
{
case GotoExpressionKind.Goto: op = "goto"; break;
case GotoExpressionKind.Break: op = "break"; break;
case GotoExpressionKind.Continue: op = "continue"; break;
case GotoExpressionKind.Return: op = "return"; break;
default:
throw new InvalidOperationException();
}
Out(op);
Out(' ');
DumpLabel(node.Target);
if (node.Value != null)
{
Out(" (");
Visit(node.Value);
Out(")");
}
return node;
}
protected internal override Expression VisitLoop(LoopExpression node)
{
Out("loop { ... }");
return node;
}
protected override SwitchCase VisitSwitchCase(SwitchCase node)
{
Out("case ");
VisitExpressions('(', node.TestValues, ')');
Out(": ...");
return node;
}
protected internal override Expression VisitSwitch(SwitchExpression node)
{
Out("switch ");
Out('(');
Visit(node.SwitchValue);
Out(") { ... }");
return node;
}
protected override CatchBlock VisitCatchBlock(CatchBlock node)
{
Out("catch (");
Out(node.Test.Name);
if (!string.IsNullOrEmpty(node.Variable?.Name))
{
Out(' ');
Out(node.Variable.Name);
}
Out(") { ... }");
return node;
}
protected internal override Expression VisitTry(TryExpression node)
{
Out("try { ... }");
return node;
}
protected internal override Expression VisitIndex(IndexExpression node)
{
if (node.Object != null)
{
Visit(node.Object);
}
else
{
Debug.Assert(node.Indexer != null);
Out(node.Indexer.DeclaringType.Name);
}
if (node.Indexer != null)
{
Out('.');
Out(node.Indexer.Name);
}
Out('[');
for (int i = 0, n = node.ArgumentCount; i < n; i++)
{
if (i > 0)
Out(", ");
Visit(node.GetArgument(i));
}
Out(']');
return node;
}
protected internal override Expression VisitExtension(Expression node)
{
// Prefer an overridden ToString, if available.
MethodInfo toString = node.GetType().GetMethod("ToString", Type.EmptyTypes);
if (toString.DeclaringType != typeof(Expression) && !toString.IsStatic)
{
Out(node.ToString());
return node;
}
Out('[');
// For 3.5 subclasses, print the NodeType.
// For Extension nodes, print the class name.
Out(node.NodeType == ExpressionType.Extension ? node.GetType().FullName : node.NodeType.ToString());
Out(']');
return node;
}
private void DumpLabel(LabelTarget target)
{
if (!string.IsNullOrEmpty(target.Name))
{
Out(target.Name);
}
else
{
int labelId = GetLabelId(target);
Out("UnnamedLabel_" + labelId);
}
}
private static bool IsBool(Expression node)
{
return node.Type == typeof(bool) || node.Type == typeof(bool?);
}
#endregion
}
}
| |
using System;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class FormHandlingTests : DriverTestFixture
{
[Test]
public void ShouldClickOnSubmitInputElements()
{
driver.Url = formsPage;
driver.FindElement(By.Id("submitButton")).Click();
WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ClickingOnUnclickableElementsDoesNothing()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("//body")).Click();
}
[Test]
public void ShouldBeAbleToClickImageButtons()
{
driver.Url = formsPage;
driver.FindElement(By.Id("imageButton")).Click();
WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToSubmitForms()
{
driver.Url = formsPage;
driver.FindElement(By.Name("login")).Submit();
WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted()
{
driver.Url = formsPage;
driver.FindElement(By.Id("checky")).Submit();
WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("//form/p")).Submit();
WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.PhantomJS)]
public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist()
{
driver.Url = formsPage;
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Name("SearchableText")).Submit());
}
[Test]
public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue()
{
driver.Url = javascriptPage;
IWebElement textarea = driver.FindElement(By.Id("keyUpArea"));
string cheesey = "Brie and cheddar";
textarea.SendKeys(cheesey);
Assert.AreEqual(textarea.GetAttribute("value"), cheesey);
}
[Test]
public void SendKeysKeepsCapitalization()
{
driver.Url = javascriptPage;
IWebElement textarea = driver.FindElement(By.Id("keyUpArea"));
string cheesey = "BrIe And CheDdar";
textarea.SendKeys(cheesey);
Assert.AreEqual(textarea.GetAttribute("value"), cheesey);
}
[Test]
public void ShouldSubmitAFormUsingTheNewlineLiteral()
{
driver.Url = formsPage;
IWebElement nestedForm = driver.FindElement(By.Id("nested_form"));
IWebElement input = nestedForm.FindElement(By.Name("x"));
input.SendKeys("\n");
WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'");
Assert.AreEqual("We Arrive Here", driver.Title);
Assert.IsTrue(driver.Url.EndsWith("?x=name"));
}
[Test]
public void ShouldSubmitAFormUsingTheEnterKey()
{
driver.Url = formsPage;
IWebElement nestedForm = driver.FindElement(By.Id("nested_form"));
IWebElement input = nestedForm.FindElement(By.Name("x"));
input.SendKeys(Keys.Enter);
WaitFor(TitleToBe("We Arrive Here"), "Browser title is not 'We Arrive Here'");
Assert.AreEqual("We Arrive Here", driver.Title);
Assert.IsTrue(driver.Url.EndsWith("?x=name"));
}
[Test]
public void ShouldEnterDataIntoFormFields()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']"));
String originalValue = element.GetAttribute("value");
Assert.AreEqual(originalValue, "change");
element.Clear();
element.SendKeys("some text");
element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']"));
String newFormValue = element.GetAttribute("value");
Assert.AreEqual(newFormValue, "some text");
}
[Test]
[IgnoreBrowser(Browser.Android, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")]
public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement()
{
string testFileName = string.Format("test-{0}.txt", Guid.NewGuid().ToString("D"));
driver.Url = formsPage;
IWebElement uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, testFileName);
System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath);
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
uploadElement.SendKeys(inputFile.FullName);
System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value"));
Assert.AreEqual(inputFile.Name, outputFile.Name);
inputFile.Delete();
}
[Test]
[IgnoreBrowser(Browser.Android, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")]
public void ShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument()
{
// IE before 9 doesn't handle pages served with an XHTML content type, and just prompts for to
// download it
if (TestUtilities.IsOldIE(driver))
{
return;
}
driver.Url = xhtmlFormPage;
IWebElement uploadElement = driver.FindElement(By.Id("file"));
Assert.AreEqual(string.Empty, uploadElement.GetAttribute("value"));
string testFileName = string.Format("test-{0}.txt", Guid.NewGuid().ToString("D"));
string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, testFileName);
System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath);
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
uploadElement.SendKeys(inputFile.FullName);
System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value"));
Assert.AreEqual(inputFile.Name, outputFile.Name);
inputFile.Delete();
}
[Test]
[IgnoreBrowser(Browser.Android, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")]
public void ShouldBeAbleToUploadTheSameFileTwice()
{
string testFileName = string.Format("test-{0}.txt", Guid.NewGuid().ToString("D"));
string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, testFileName);
System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath);
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
for (int i = 0; i < 2; ++i)
{
driver.Url = formsPage;
IWebElement uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
uploadElement.SendKeys(inputFile.FullName);
uploadElement.Submit();
}
inputFile.Delete();
// If we get this far, then we're all good.
}
[Test]
public void SendingKeyboardEventsShouldAppendTextInInputs()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("working"));
element.SendKeys("Some");
String value = element.GetAttribute("value");
Assert.AreEqual(value, "Some");
element.SendKeys(" text");
value = element.GetAttribute("value");
Assert.AreEqual(value, "Some text");
}
[Test]
public void SendingKeyboardEventsShouldAppendTextInInputsWithExistingValue()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("inputWithText"));
element.SendKeys(". Some text");
string value = element.GetAttribute("value");
Assert.AreEqual("Example text. Some text", value);
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")]
public void SendingKeyboardEventsShouldAppendTextInTextAreas()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("withText"));
element.SendKeys(". Some text");
String value = element.GetAttribute("value");
Assert.AreEqual(value, "Example text. Some text");
}
[Test]
public void ShouldBeAbleToClearTextFromInputElements()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("working"));
element.SendKeys("Some text");
String value = element.GetAttribute("value");
Assert.IsTrue(value.Length > 0);
element.Clear();
value = element.GetAttribute("value");
Assert.AreEqual(value.Length, 0);
}
[Test]
public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull()
{
driver.Url = formsPage;
IWebElement emptyTextBox = driver.FindElement(By.Id("working"));
Assert.AreEqual(emptyTextBox.GetAttribute("value"), "");
IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea"));
Assert.AreEqual(emptyTextBox.GetAttribute("value"), "");
}
[Test]
public void ShouldBeAbleToClearTextFromTextAreas()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("withText"));
element.SendKeys("Some text");
String value = element.GetAttribute("value");
Assert.IsTrue(value.Length > 0);
element.Clear();
value = element.GetAttribute("value");
Assert.AreEqual(value.Length, 0);
}
[Test]
[IgnoreBrowser(Browser.Android, "Untested")]
[IgnoreBrowser(Browser.HtmlUnit, "Untested")]
[IgnoreBrowser(Browser.IPhone, "Untested")]
[IgnoreBrowser(Browser.Opera, "Untested")]
[IgnoreBrowser(Browser.PhantomJS, "Untested")]
[IgnoreBrowser(Browser.Safari, "Untested")]
[IgnoreBrowser(Browser.WindowsPhone, "Does not yet support alert handling")]
[IgnoreBrowser(Browser.Firefox, "Dismissing alert causes entire window to close.")]
public void HandleFormWithJavascriptAction()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("form_handling_js_submit.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("theForm"));
element.Submit();
IAlert alert = driver.SwitchTo().Alert();
string text = alert.Text;
alert.Dismiss();
Assert.AreEqual("Tasty cheese", text);
}
[Test]
[IgnoreBrowser(Browser.Android, "Untested")]
[IgnoreBrowser(Browser.IPhone, "Untested")]
public void CanClickOnASubmitButton()
{
CheckSubmitButton("internal_explicit_submit");
}
[Test]
[IgnoreBrowser(Browser.Android, "Untested")]
[IgnoreBrowser(Browser.IPhone, "Untested")]
public void CanClickOnAnImplicitSubmitButton()
{
CheckSubmitButton("internal_implicit_submit");
}
[Test]
[IgnoreBrowser(Browser.Android, "Untested")]
[IgnoreBrowser(Browser.IPhone, "Untested")]
[IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")]
[IgnoreBrowser(Browser.IE, "Fails on IE")]
public void CanClickOnAnExternalSubmitButton()
{
CheckSubmitButton("external_explicit_submit");
}
[Test]
[IgnoreBrowser(Browser.Android, "Untested")]
[IgnoreBrowser(Browser.IPhone, "Untested")]
[IgnoreBrowser(Browser.HtmlUnit, "Fails on HtmlUnit")]
[IgnoreBrowser(Browser.IE, "Fails on IE")]
public void CanClickOnAnExternalImplicitSubmitButton()
{
CheckSubmitButton("external_implicit_submit");
}
private void CheckSubmitButton(string buttonId)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/html5_submit_buttons.html");
string name = "Gromit";
driver.FindElement(By.Id("name")).SendKeys(name);
driver.FindElement(By.Id(buttonId)).Click();
WaitFor(TitleToBe("Submitted Successfully!"), "Browser title is not 'Submitted Successfully!'");
Assert.That(driver.Url.Contains("name=" + name), "URL does not contain 'name=" + name + "'. Actual URL:" + driver.Url);
}
private Func<bool> TitleToBe(string desiredTitle)
{
return () =>
{
return driver.Title == desiredTitle;
};
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using Dbg = System.Management.Automation;
namespace System.Management.Automation
{
/// <summary>
/// Exposes the Cmdlet Family Provider's drives to the Cmdlet base class. The methods of this class
/// get and set provider data in session state.
/// </summary>
public sealed class DriveManagementIntrinsics
{
#region Constructors
/// <summary>
/// Hide the default constructor since we always require an instance of SessionState.
/// </summary>
private DriveManagementIntrinsics()
{
Dbg.Diagnostics.Assert(
false,
"This constructor should never be called. Only the constructor that takes an instance of SessionState should be called.");
}
/// <summary>
/// Constructs a Drive management facade.
/// </summary>
/// <param name="sessionState">
/// The instance of session state that facade wraps.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="sessionState"/> is null.
/// </exception>
internal DriveManagementIntrinsics(SessionStateInternal sessionState)
{
if (sessionState == null)
{
throw PSTraceSource.NewArgumentNullException("sessionState");
}
_sessionState = sessionState;
}
#endregion Constructors
#region Public methods
/// <summary>
/// Gets the drive information for the current working drive.
/// </summary>
/// <remarks>
/// This property is readonly. To set the current drive use the
/// SetLocation method.
/// </remarks>
public PSDriveInfo Current
{
get
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
return _sessionState.CurrentDrive;
}
}
#region New
/// <summary>
/// Creates a new MSH drive in session state.
/// </summary>
/// <param name="drive">
/// The drive to be created.
/// </param>
/// <param name="scope">
/// The ID of the scope to create the drive in. This may be one of the scope
/// keywords like global or local, or it may be an numeric offset of the scope
/// generation relative to the current scope.
/// If the scopeID is null or empty the local scope is used.
/// </param>
/// <returns>
/// The drive that was created.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="drive"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the drive already exists,
/// or
/// If <paramref name="drive"/>.Name contains one or more invalid characters; ~ / \\ . :
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider is not a DriveCmdletProvider.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// The provider for the <paramref name="drive"/> could not be found.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception or returned null.
/// </exception>
public PSDriveInfo New(PSDriveInfo drive, string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.NewDrive(drive, scope);
}
/// <summary>
/// Creates a new MSH drive in session state.
/// </summary>
/// <param name="drive">
/// The drive to be created.
/// </param>
/// <param name="scope">
/// The ID of the scope to create the drive in. This may be one of the scope
/// keywords like global or local, or it may be an numeric offset of the scope
/// generation relative to the current scope.
/// If the scopeID is null or empty the local scope is used.
/// </param>
/// <param name="context">
/// The context under which this command is running.
/// </param>
/// <returns>
/// Nothing. The drive that is created is written to the context.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="drive"/> or <paramref name="context"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the drive already exists
/// or
/// If <paramref name="drive"/>.Name contains one or more invalid characters; ~ / \\ . :
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider is not a DriveCmdletProvider.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// The provider for the <paramref name="drive"/> could not be found.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception or returned null.
/// </exception>
internal void New(
PSDriveInfo drive,
string scope,
CmdletProviderContext context)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.NewDrive(drive, scope, context);
}
/// <summary>
/// Gets an object that defines the additional parameters for the NewDrive implementation
/// for a provider.
/// </summary>
/// <param name="providerId">
/// The provider ID for the drive that is being created.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerId"/> is not a DriveCmdletProvider.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If <paramref name="providerId"/> does not exist.
/// </exception>
internal object NewDriveDynamicParameters(
string providerId,
CmdletProviderContext context)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.NewDriveDynamicParameters(providerId, context);
}
#endregion New
#region Remove
/// <summary>
/// Removes the specified drive.
/// </summary>
/// <param name="driveName">
/// The name of the drive to be removed.
/// </param>
/// <param name="force">
/// Determines whether drive should be forcefully removed even if there was errors.
/// </param>
/// <param name="scope">
/// The ID of the scope to remove the drive from. This may be one of the scope
/// keywords like global or local, or it may be an numeric offset of the scope
/// generation relative to the current scope.
/// If the scopeID is null or empty the local scope is used.
/// </param>
public void Remove(string driveName, bool force, string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.RemoveDrive(driveName, force, scope);
}
/// <summary>
/// Removes the specified drive.
/// </summary>
/// <param name="driveName">
/// The name of the drive to be removed.
/// </param>
/// <param name="force">
/// Determines whether drive should be forcefully removed even if there was errors.
/// </param>
/// <param name="scope">
/// The ID of the scope to remove the drive from. This may be one of the scope
/// keywords like global or local, or it may be an numeric offset of the scope
/// generation relative to the current scope.
/// If the scopeID is null or empty the local scope is used.
/// </param>
/// <param name="context">
/// The context under which this command is running.
/// </param>
internal void Remove(
string driveName,
bool force,
string scope,
CmdletProviderContext context)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
_sessionState.RemoveDrive(driveName, force, scope, context);
}
#endregion Remove
#region Get
/// <summary>
/// Gets the drive information for the drive specified by name.
/// </summary>
/// <param name="driveName">
/// The name of the drive to get the drive information for.
/// </param>
/// <returns>
/// The drive information that represents the drive of the specified name.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="driveName"/> is null.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If there is no drive with <paramref name="driveName"/>.
/// </exception>
public PSDriveInfo Get(string driveName)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.GetDrive(driveName);
}
/// <summary>
/// Gets the drive information for the drive specified by name.
/// </summary>
/// <param name="driveName">
/// The name of the drive to get the drive information for.
/// </param>
/// <param name="scope">
/// The ID of the scope to get the drive from. This may be one of the scope
/// keywords like global or local, or it may be an numeric offset of the scope
/// generation relative to the current scope.
/// If the scopeID is null or empty the local scope is used.
/// </param>
/// <returns>
/// The drive information that represents the drive of the specified name.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="driveName"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="scope"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
public PSDriveInfo GetAtScope(string driveName, string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.GetDrive(driveName, scope);
}
/// <summary>
/// Retrieves all the drives in the specified scope.
/// </summary>
public Collection<PSDriveInfo> GetAll()
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
return _sessionState.Drives(null);
}
/// <summary>
/// Retrieves all the drives in the specified scope.
/// </summary>
/// <param name="scope">
/// The scope to retrieve the drives from. If null, the
/// drives in all the scopes will be returned.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="scope"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
public Collection<PSDriveInfo> GetAllAtScope(string scope)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
return _sessionState.Drives(scope);
}
/// <summary>
/// Gets all the drives for the specified provider.
/// </summary>
/// <param name="providerName">
/// The name of the provider to get the drives for.
/// </param>
/// <returns>
/// All the drives in all the scopes for the given provider.
/// </returns>
public Collection<PSDriveInfo> GetAllForProvider(string providerName)
{
Dbg.Diagnostics.Assert(
_sessionState != null,
"The only constructor for this class should always set the sessionState field");
// Parameter validation is done in the session state object
return _sessionState.GetDrivesForProvider(providerName);
}
#endregion GetDrive
#endregion Public methods
#region private data
// A private reference to the internal session state of the engine.
private SessionStateInternal _sessionState;
#endregion private data
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{
public class LocalAssetServicesConnector :
ISharedRegionModule, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IImprovedAssetCache m_Cache = null;
private IAssetService m_AssetService;
private bool m_Enabled = false;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalAssetServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetServices", "");
if (name == Name)
{
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
return;
}
string serviceDll = assetConfig.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[ASSET CONNECTOR]: No LocalServiceModule named in section AssetService");
return;
}
Object[] args = new Object[] { source };
m_AssetService =
ServerUtils.LoadPlugin<IAssetService>(serviceDll,
args);
if (m_AssetService == null)
{
m_log.Error("[ASSET CONNECTOR]: Can't load asset service");
return;
}
m_Enabled = true;
m_log.Info("[ASSET CONNECTOR]: Local asset connector enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IAssetService>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (m_Cache == null)
{
m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>();
if (!(m_Cache is ISharedRegionModule))
m_Cache = null;
}
m_log.InfoFormat("[ASSET CONNECTOR]: Enabled local assets for region {0}", scene.RegionInfo.RegionName);
if (m_Cache != null)
{
m_log.InfoFormat("[ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName);
}
else
{
// Short-circuit directly to storage layer
//
scene.UnregisterModuleInterface<IAssetService>(this);
scene.RegisterModuleInterface<IAssetService>(m_AssetService);
}
}
public AssetBase Get(string id)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset == null)
{
asset = m_AssetService.Get(id);
if ((m_Cache != null) && (asset != null))
m_Cache.Cache(asset);
}
return asset;
}
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
return asset.Metadata;
asset = m_AssetService.Get(id);
if (asset != null)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.Metadata;
}
return null;
}
public byte[] GetData(string id)
{
AssetBase asset = m_Cache.Get(id);
if (asset != null)
return asset.Data;
asset = m_AssetService.Get(id);
if (asset != null)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.Data;
}
return null;
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
AssetBase asset = null;
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
{
handler.BeginInvoke(id, sender, asset, null, null);
return true;
}
return m_AssetService.Get(id, sender, delegate (string assetID, Object s, AssetBase a)
{
if ((a != null) && (m_Cache != null))
m_Cache.Cache(a);
handler.BeginInvoke(assetID, s, a, null, null);
});
}
public string Store(AssetBase asset)
{
if (m_Cache != null)
m_Cache.Cache(asset);
if (asset.Temporary || asset.Local)
return asset.ID;
return m_AssetService.Store(asset);
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = null;
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
{
asset.Data = data;
if (m_Cache != null)
m_Cache.Cache(asset);
}
return m_AssetService.UpdateContent(id, data);
}
public bool Delete(string id)
{
if (m_Cache != null)
m_Cache.Expire(id);
return m_AssetService.Delete(id);
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE 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;
namespace Spine {
public class Animation {
internal ExposedList<Timeline> timelines;
internal float duration;
internal String name;
public String Name { get { return name; } }
public ExposedList<Timeline> Timelines { get { return timelines; } set { timelines = value; } }
public float Duration { get { return duration; } set { duration = value; } }
public Animation (String name, ExposedList<Timeline> timelines, float duration) {
if (name == null) throw new ArgumentNullException("name", "name cannot be null.");
if (timelines == null) throw new ArgumentNullException("timelines", "timelines cannot be null.");
this.name = name;
this.timelines = timelines;
this.duration = duration;
}
/// <summary>Poses the skeleton at the specified time for this animation.</summary>
/// <param name="lastTime">The last time the animation was applied.</param>
/// <param name="events">Any triggered events are added. May be null.</param>
public void Apply (Skeleton skeleton, float lastTime, float time, bool loop, ExposedList<Event> events) {
if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
if (loop && duration != 0) {
time %= duration;
if (lastTime > 0) lastTime %= duration;
}
ExposedList<Timeline> timelines = this.timelines;
for (int i = 0, n = timelines.Count; i < n; i++)
timelines.Items[i].Apply(skeleton, lastTime, time, events, 1);
}
/// <summary>Poses the skeleton at the specified time for this animation mixed with the current pose.</summary>
/// <param name="lastTime">The last time the animation was applied.</param>
/// <param name="events">Any triggered events are added. May be null.</param>
/// <param name="alpha">The amount of this animation that affects the current pose.</param>
public void Mix (Skeleton skeleton, float lastTime, float time, bool loop, ExposedList<Event> events, float alpha) {
if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
if (loop && duration != 0) {
time %= duration;
if (lastTime > 0) lastTime %= duration;
}
ExposedList<Timeline> timelines = this.timelines;
for (int i = 0, n = timelines.Count; i < n; i++)
timelines.Items[i].Apply(skeleton, lastTime, time, events, alpha);
}
/// <param name="target">After the first and before the last entry.</param>
internal static int binarySearch (float[] values, float target, int step) {
int low = 0;
int high = values.Length / step - 2;
if (high == 0) return step;
int current = (int)((uint)high >> 1);
while (true) {
if (values[(current + 1) * step] <= target)
low = current + 1;
else
high = current;
if (low == high) return (low + 1) * step;
current = (int)((uint)(low + high) >> 1);
}
}
/// <param name="target">After the first and before the last entry.</param>
internal static int binarySearch (float[] values, float target) {
int low = 0;
int high = values.Length - 2;
if (high == 0) return 1;
int current = (int)((uint)high >> 1);
while (true) {
if (values[(current + 1)] <= target)
low = current + 1;
else
high = current;
if (low == high) return (low + 1);
current = (int)((uint)(low + high) >> 1);
}
}
internal static int linearSearch (float[] values, float target, int step) {
for (int i = 0, last = values.Length - step; i <= last; i += step)
if (values[i] > target) return i;
return -1;
}
}
public interface Timeline {
/// <summary>Sets the value(s) for the specified time.</summary>
/// <param name="events">May be null to not collect fired events.</param>
void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> events, float alpha);
}
/// <summary>Base class for frames that use an interpolation bezier curve.</summary>
abstract public class CurveTimeline : Timeline {
protected const float LINEAR = 0, STEPPED = 1, BEZIER = 2;
protected const int BEZIER_SIZE = 10 * 2 - 1;
private float[] curves; // type, x, y, ...
public int FrameCount { get { return curves.Length / BEZIER_SIZE + 1; } }
public CurveTimeline (int frameCount) {
if (frameCount <= 0) throw new ArgumentException("frameCount must be > 0: " + frameCount, "frameCount");
curves = new float[(frameCount - 1) * BEZIER_SIZE];
}
abstract public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha);
public void SetLinear (int frameIndex) {
curves[frameIndex * BEZIER_SIZE] = LINEAR;
}
public void SetStepped (int frameIndex) {
curves[frameIndex * BEZIER_SIZE] = STEPPED;
}
/// <summary>Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next.
/// cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of
/// the difference between the keyframe's values.</summary>
public void SetCurve (int frameIndex, float cx1, float cy1, float cx2, float cy2) {
float tmpx = (-cx1 * 2 + cx2) * 0.03f, tmpy = (-cy1 * 2 + cy2) * 0.03f;
float dddfx = ((cx1 - cx2) * 3 + 1) * 0.006f, dddfy = ((cy1 - cy2) * 3 + 1) * 0.006f;
float ddfx = tmpx * 2 + dddfx, ddfy = tmpy * 2 + dddfy;
float dfx = cx1 * 0.3f + tmpx + dddfx * 0.16666667f, dfy = cy1 * 0.3f + tmpy + dddfy * 0.16666667f;
int i = frameIndex * BEZIER_SIZE;
float[] curves = this.curves;
curves[i++] = BEZIER;
float x = dfx, y = dfy;
for (int n = i + BEZIER_SIZE - 1; i < n; i += 2) {
curves[i] = x;
curves[i + 1] = y;
dfx += ddfx;
dfy += ddfy;
ddfx += dddfx;
ddfy += dddfy;
x += dfx;
y += dfy;
}
}
public float GetCurvePercent (int frameIndex, float percent) {
percent = MathUtils.Clamp (percent, 0, 1);
float[] curves = this.curves;
int i = frameIndex * BEZIER_SIZE;
float type = curves[i];
if (type == LINEAR) return percent;
if (type == STEPPED) return 0;
i++;
float x = 0;
for (int start = i, n = i + BEZIER_SIZE - 1; i < n; i += 2) {
x = curves[i];
if (x >= percent) {
float prevX, prevY;
if (i == start) {
prevX = 0;
prevY = 0;
} else {
prevX = curves[i - 2];
prevY = curves[i - 1];
}
return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
}
}
float y = curves[i - 1];
return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1.
}
public float GetCurveType (int frameIndex) {
return curves[frameIndex * BEZIER_SIZE];
}
}
public class RotateTimeline : CurveTimeline {
public const int ENTRIES = 2;
internal const int PREV_TIME = -2, PREV_ROTATION = -1;
internal const int ROTATION = 1;
internal int boneIndex;
internal float[] frames;
public int BoneIndex { get { return boneIndex; } set { boneIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, angle, ...
public RotateTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount << 1];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float degrees) {
frameIndex <<= 1;
frames[frameIndex] = time;
frames[frameIndex + ROTATION] = degrees;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
Bone bone = skeleton.bones.Items[boneIndex];
float amount;
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
amount = bone.data.rotation + frames[frames.Length + PREV_ROTATION] - bone.rotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
bone.rotation += amount * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float prevRotation = frames[frame + PREV_ROTATION];
float frameTime = frames[frame];
float percent = GetCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
amount = frames[frame + ROTATION] - prevRotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
amount = bone.data.rotation + (prevRotation + amount * percent) - bone.rotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
bone.rotation += amount * alpha;
}
}
public class TranslateTimeline : CurveTimeline {
public const int ENTRIES = 3;
protected const int PREV_TIME = -3, PREV_X = -2, PREV_Y = -1;
protected const int X = 1, Y = 2;
internal int boneIndex;
internal float[] frames;
public int BoneIndex { get { return boneIndex; } set { boneIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, value, value, ...
public TranslateTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * ENTRIES];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float x, float y) {
frameIndex *= ENTRIES;
frames[frameIndex] = time;
frames[frameIndex + X] = x;
frames[frameIndex + Y] = y;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
Bone bone = skeleton.bones.Items[boneIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
bone.x += (bone.data.x + frames[frames.Length + PREV_X] - bone.x) * alpha;
bone.y += (bone.data.y + frames[frames.Length + PREV_Y] - bone.y) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float prevX = frames[frame + PREV_X];
float prevY = frames[frame + PREV_Y];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
bone.x += (bone.data.x + prevX + (frames[frame + X] - prevX) * percent - bone.x) * alpha;
bone.y += (bone.data.y + prevY + (frames[frame + Y] - prevY) * percent - bone.y) * alpha;
}
}
public class ScaleTimeline : TranslateTimeline {
public ScaleTimeline (int frameCount)
: base(frameCount) {
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
Bone bone = skeleton.bones.Items[boneIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
bone.scaleX += (bone.data.scaleX * frames[frames.Length + PREV_X] - bone.scaleX) * alpha;
bone.scaleY += (bone.data.scaleY * frames[frames.Length + PREV_Y] - bone.scaleY) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float prevX = frames[frame + PREV_X];
float prevY = frames[frame + PREV_Y];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
bone.scaleX += (bone.data.scaleX * (prevX + (frames[frame + X] - prevX) * percent) - bone.scaleX) * alpha;
bone.scaleY += (bone.data.scaleY * (prevY + (frames[frame + Y] - prevY) * percent) - bone.scaleY) * alpha;
}
}
public class ShearTimeline : TranslateTimeline {
public ShearTimeline (int frameCount)
: base(frameCount) {
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
Bone bone = skeleton.bones.Items[boneIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
bone.shearX += (bone.data.shearX + frames[frames.Length + PREV_X] - bone.shearX) * alpha;
bone.shearY += (bone.data.shearY + frames[frames.Length + PREV_Y] - bone.shearY) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float prevX = frames[frame + PREV_X];
float prevY = frames[frame + PREV_Y];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
bone.shearX += (bone.data.shearX + (prevX + (frames[frame + X] - prevX) * percent) - bone.shearX) * alpha;
bone.shearY += (bone.data.shearY + (prevY + (frames[frame + Y] - prevY) * percent) - bone.shearY) * alpha;
}
}
public class ColorTimeline : CurveTimeline {
public const int ENTRIES = 5;
protected const int PREV_TIME = -5, PREV_R = -4, PREV_G = -3, PREV_B = -2, PREV_A = -1;
protected const int R = 1, G = 2, B = 3, A = 4;
internal int slotIndex;
internal float[] frames;
public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, r, g, b, a, ...
public ColorTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * ENTRIES];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float r, float g, float b, float a) {
frameIndex *= ENTRIES;
frames[frameIndex] = time;
frames[frameIndex + R] = r;
frames[frameIndex + G] = g;
frames[frameIndex + B] = b;
frames[frameIndex + A] = a;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
float r, g, b, a;
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
int i = frames.Length;
r = frames[i + PREV_R];
g = frames[i + PREV_G];
b = frames[i + PREV_B];
a = frames[i + PREV_A];
} else {
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
r = frames[frame + PREV_R];
g = frames[frame + PREV_G];
b = frames[frame + PREV_B];
a = frames[frame + PREV_A];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1,
1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
r += (frames[frame + R] - r) * percent;
g += (frames[frame + G] - g) * percent;
b += (frames[frame + B] - b) * percent;
a += (frames[frame + A] - a) * percent;
}
Slot slot = skeleton.slots.Items[slotIndex];
if (alpha < 1) {
slot.r += (r - slot.r) * alpha;
slot.g += (g - slot.g) * alpha;
slot.b += (b - slot.b) * alpha;
slot.a += (a - slot.a) * alpha;
} else {
slot.r = r;
slot.g = g;
slot.b = b;
slot.a = a;
}
}
}
public class AttachmentTimeline : Timeline {
internal int slotIndex;
internal float[] frames;
private String[] attachmentNames;
public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public String[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } }
public int FrameCount { get { return frames.Length; } }
public AttachmentTimeline (int frameCount) {
frames = new float[frameCount];
attachmentNames = new String[frameCount];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, String attachmentName) {
frames[frameIndex] = time;
attachmentNames[frameIndex] = attachmentName;
}
public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
int frameIndex;
if (time >= frames[frames.Length - 1]) // Time is after last frame.
frameIndex = frames.Length - 1;
else
frameIndex = Animation.binarySearch(frames, time, 1) - 1;
String attachmentName = attachmentNames[frameIndex];
skeleton.slots.Items[slotIndex]
.Attachment = attachmentName == null ? null : skeleton.GetAttachment(slotIndex, attachmentName);
}
}
public class EventTimeline : Timeline {
internal float[] frames;
private Event[] events;
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public Event[] Events { get { return events; } set { events = value; } }
public int FrameCount { get { return frames.Length; } }
public EventTimeline (int frameCount) {
frames = new float[frameCount];
events = new Event[frameCount];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, Event e) {
frames[frameIndex] = e.Time;
events[frameIndex] = e;
}
/// <summary>Fires events for frames > lastTime and <= time.</summary>
public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
if (firedEvents == null) return;
float[] frames = this.frames;
int frameCount = frames.Length;
if (lastTime > time) { // Fire events after last time for looped animations.
Apply(skeleton, lastTime, int.MaxValue, firedEvents, alpha);
lastTime = -1f;
} else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame.
return;
if (time < frames[0]) return; // Time is before first frame.
int frame;
if (lastTime < frames[0])
frame = 0;
else {
frame = Animation.binarySearch(frames, lastTime);
float frameTime = frames[frame];
while (frame > 0) { // Fire multiple events with the same frame.
if (frames[frame - 1] != frameTime) break;
frame--;
}
}
for (; frame < frameCount && time >= frames[frame]; frame++)
firedEvents.Add(events[frame]);
}
}
public class DrawOrderTimeline : Timeline {
internal float[] frames;
private int[][] drawOrders;
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public int[][] DrawOrders { get { return drawOrders; } set { drawOrders = value; } }
public int FrameCount { get { return frames.Length; } }
public DrawOrderTimeline (int frameCount) {
frames = new float[frameCount];
drawOrders = new int[frameCount][];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
/// <param name="drawOrder">May be null to use bind pose draw order.</param>
public void SetFrame (int frameIndex, float time, int[] drawOrder) {
frames[frameIndex] = time;
drawOrders[frameIndex] = drawOrder;
}
public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
int frame;
if (time >= frames[frames.Length - 1]) // Time is after last frame.
frame = frames.Length - 1;
else
frame = Animation.binarySearch(frames, time) - 1;
ExposedList<Slot> drawOrder = skeleton.drawOrder;
ExposedList<Slot> slots = skeleton.slots;
int[] drawOrderToSetupIndex = drawOrders[frame];
if (drawOrderToSetupIndex == null) {
drawOrder.Clear();
for (int i = 0, n = slots.Count; i < n; i++)
drawOrder.Add(slots.Items[i]);
} else {
var drawOrderItems = drawOrder.Items;
var slotsItems = slots.Items;
for (int i = 0, n = drawOrderToSetupIndex.Length; i < n; i++)
drawOrderItems[i] = slotsItems[drawOrderToSetupIndex[i]];
}
}
}
public class DeformTimeline : CurveTimeline {
internal int slotIndex;
internal float[] frames;
private float[][] frameVertices;
internal VertexAttachment attachment;
public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public float[][] Vertices { get { return frameVertices; } set { frameVertices = value; } }
public VertexAttachment Attachment { get { return attachment; } set { attachment = value; } }
public DeformTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount];
frameVertices = new float[frameCount][];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float[] vertices) {
frames[frameIndex] = time;
frameVertices[frameIndex] = vertices;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
Slot slot = skeleton.slots.Items[slotIndex];
VertexAttachment slotAttachment = slot.attachment as VertexAttachment;
if (slotAttachment == null || !slotAttachment.ApplyDeform(attachment)) return;
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
float[][] frameVertices = this.frameVertices;
int vertexCount = frameVertices[0].Length;
var verticesArray = slot.attachmentVertices;
if (verticesArray.Count != vertexCount) alpha = 1; // Don't mix from uninitialized slot vertices.
// verticesArray.SetSize(vertexCount) // Ensure size and preemptively set count.
if (verticesArray.Capacity < vertexCount) verticesArray.Capacity = vertexCount;
verticesArray.Count = vertexCount;
float[] vertices = verticesArray.Items;
if (time >= frames[frames.Length - 1]) { // Time is after last frame.
float[] lastVertices = frameVertices[frames.Length - 1];
if (alpha < 1) {
for (int i = 0; i < vertexCount; i++) {
float vertex = vertices[i];
vertices[i] = vertex + (lastVertices[i] - vertex) * alpha;
}
} else
Array.Copy(lastVertices, 0, vertices, 0, vertexCount);
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time);
float[] prevVertices = frameVertices[frame - 1];
float[] nextVertices = frameVertices[frame];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime));
if (alpha < 1) {
for (int i = 0; i < vertexCount; i++) {
float prev = prevVertices[i];
float vertex = vertices[i];
vertices[i] = vertex + (prev + (nextVertices[i] - prev) * percent - vertex) * alpha;
}
} else {
for (int i = 0; i < vertexCount; i++) {
float prev = prevVertices[i];
vertices[i] = prev + (nextVertices[i] - prev) * percent;
}
}
}
}
public class IkConstraintTimeline : CurveTimeline {
public const int ENTRIES = 3;
private const int PREV_TIME = -3, PREV_MIX = -2, PREV_BEND_DIRECTION = -1;
private const int MIX = 1, BEND_DIRECTION = 2;
internal int ikConstraintIndex;
internal float[] frames;
public int IkConstraintIndex { get { return ikConstraintIndex; } set { ikConstraintIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, mix, bendDirection, ...
public IkConstraintTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * ENTRIES];
}
/// <summary>Sets the time, mix and bend direction of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float mix, int bendDirection) {
frameIndex *= ENTRIES;
frames[frameIndex] = time;
frames[frameIndex + MIX] = mix;
frames[frameIndex + BEND_DIRECTION] = bendDirection;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
IkConstraint constraint = skeleton.ikConstraints.Items[ikConstraintIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
constraint.mix += (frames[frames.Length + PREV_MIX] - constraint.mix) * alpha;
constraint.bendDirection = (int)frames[frames.Length + PREV_BEND_DIRECTION];
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float mix = frames[frame + PREV_MIX];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
constraint.mix += (mix + (frames[frame + MIX] - mix) * percent - constraint.mix) * alpha;
constraint.bendDirection = (int)frames[frame + PREV_BEND_DIRECTION];
}
}
public class TransformConstraintTimeline : CurveTimeline {
public const int ENTRIES = 5;
private const int PREV_TIME = -5, PREV_ROTATE = -4, PREV_TRANSLATE = -3, PREV_SCALE = -2, PREV_SHEAR = -1;
private const int ROTATE = 1, TRANSLATE = 2, SCALE = 3, SHEAR = 4;
internal int transformConstraintIndex;
internal float[] frames;
public int TransformConstraintIndex { get { return transformConstraintIndex; } set { transformConstraintIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, rotate mix, translate mix, scale mix, shear mix, ...
public TransformConstraintTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * ENTRIES];
}
public void SetFrame (int frameIndex, float time, float rotateMix, float translateMix, float scaleMix, float shearMix) {
frameIndex *= ENTRIES;
frames[frameIndex] = time;
frames[frameIndex + ROTATE] = rotateMix;
frames[frameIndex + TRANSLATE] = translateMix;
frames[frameIndex + SCALE] = scaleMix;
frames[frameIndex + SHEAR] = shearMix;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
TransformConstraint constraint = skeleton.transformConstraints.Items[transformConstraintIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
int i = frames.Length;
constraint.rotateMix += (frames[i + PREV_ROTATE] - constraint.rotateMix) * alpha;
constraint.translateMix += (frames[i + PREV_TRANSLATE] - constraint.translateMix) * alpha;
constraint.scaleMix += (frames[i + PREV_SCALE] - constraint.scaleMix) * alpha;
constraint.shearMix += (frames[i + PREV_SHEAR] - constraint.shearMix) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
float rotate = frames[frame + PREV_ROTATE];
float translate = frames[frame + PREV_TRANSLATE];
float scale = frames[frame + PREV_SCALE];
float shear = frames[frame + PREV_SHEAR];
constraint.rotateMix += (rotate + (frames[frame + ROTATE] - rotate) * percent - constraint.rotateMix) * alpha;
constraint.translateMix += (translate + (frames[frame + TRANSLATE] - translate) * percent - constraint.translateMix)
* alpha;
constraint.scaleMix += (scale + (frames[frame + SCALE] - scale) * percent - constraint.scaleMix) * alpha;
constraint.shearMix += (shear + (frames[frame + SHEAR] - shear) * percent - constraint.shearMix) * alpha;
}
}
public class PathConstraintPositionTimeline : CurveTimeline {
public const int ENTRIES = 2;
protected const int PREV_TIME = -2, PREV_VALUE = -1;
protected const int VALUE = 1;
internal int pathConstraintIndex;
internal float[] frames;
public PathConstraintPositionTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * ENTRIES];
}
public int PathConstraintIndex { get { return pathConstraintIndex; } set { pathConstraintIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, position, ...
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float value) {
frameIndex *= ENTRIES;
frames[frameIndex] = time;
frames[frameIndex + VALUE] = value;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> events, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
PathConstraint constraint = skeleton.pathConstraints.Items[pathConstraintIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
int i = frames.Length;
constraint.position += (frames[i + PREV_VALUE] - constraint.position) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float position = frames[frame + PREV_VALUE];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
constraint.position += (position + (frames[frame + VALUE] - position) * percent - constraint.position) * alpha;
}
}
public class PathConstraintSpacingTimeline : PathConstraintPositionTimeline {
public PathConstraintSpacingTimeline (int frameCount)
: base(frameCount) {
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> events, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
PathConstraint constraint = skeleton.pathConstraints.Items[pathConstraintIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
int i = frames.Length;
constraint.spacing += (frames[i + PREV_VALUE] - constraint.spacing) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float spacing = frames[frame + PREV_VALUE];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
constraint.spacing += (spacing + (frames[frame + VALUE] - spacing) * percent - constraint.spacing) * alpha;
}
}
public class PathConstraintMixTimeline : CurveTimeline {
public const int ENTRIES = 3;
private const int PREV_TIME = -3, PREV_ROTATE = -2, PREV_TRANSLATE = -1;
private const int ROTATE = 1, TRANSLATE = 2;
internal int pathConstraintIndex;
internal float[] frames;
public int PathConstraintIndex { get { return pathConstraintIndex; } set { pathConstraintIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, rotate mix, translate mix, ...
public PathConstraintMixTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * ENTRIES];
}
/** Sets the time and mixes of the specified keyframe. */
public void SetFrame (int frameIndex, float time, float rotateMix, float translateMix) {
frameIndex *= ENTRIES;
frames[frameIndex] = time;
frames[frameIndex + ROTATE] = rotateMix;
frames[frameIndex + TRANSLATE] = translateMix;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> events, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
PathConstraint constraint = skeleton.pathConstraints.Items[pathConstraintIndex];
if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame.
int i = frames.Length;
constraint.rotateMix += (frames[i + PREV_ROTATE] - constraint.rotateMix) * alpha;
constraint.translateMix += (frames[i + PREV_TRANSLATE] - constraint.translateMix) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frame = Animation.binarySearch(frames, time, ENTRIES);
float rotate = frames[frame + PREV_ROTATE];
float translate = frames[frame + PREV_TRANSLATE];
float frameTime = frames[frame];
float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime));
constraint.rotateMix += (rotate + (frames[frame + ROTATE] - rotate) * percent - constraint.rotateMix) * alpha;
constraint.translateMix += (translate + (frames[frame + TRANSLATE] - translate) * percent - constraint.translateMix)
* alpha;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using System.IO;
using System.Diagnostics;
internal sealed partial class Parser
{
private SchemaType _schemaType;
private XmlNameTable _nameTable;
private SchemaNames _schemaNames;
private ValidationEventHandler _eventHandler;
private XmlNamespaceManager _namespaceManager;
private XmlReader _reader;
private PositionInfo _positionInfo;
private bool _isProcessNamespaces;
private int _schemaXmlDepth = 0;
private int _markupDepth;
private SchemaBuilder _builder;
private XmlSchema _schema;
private SchemaInfo _xdrSchema;
private XmlResolver _xmlResolver = null; //to be used only by XDRBuilder
//xs:Annotation perf fix
private XmlDocument _dummyDocument;
private bool _processMarkup;
private XmlNode _parentNode;
private XmlNamespaceManager _annotationNSManager;
private string _xmlns;
//Whitespace check for text nodes
private XmlCharType _xmlCharType = XmlCharType.Instance;
public Parser(SchemaType schemaType, XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
{
_schemaType = schemaType;
_nameTable = nameTable;
_schemaNames = schemaNames;
_eventHandler = eventHandler;
_xmlResolver = null;
_processMarkup = true;
_dummyDocument = new XmlDocument();
}
public SchemaType Parse(XmlReader reader, string targetNamespace)
{
StartParsing(reader, targetNamespace);
while (ParseReaderNode() && reader.Read()) { }
return FinishParsing();
}
public void StartParsing(XmlReader reader, string targetNamespace)
{
_reader = reader;
_positionInfo = PositionInfo.GetPositionInfo(reader);
_namespaceManager = reader.NamespaceManager;
if (_namespaceManager == null)
{
_namespaceManager = new XmlNamespaceManager(_nameTable);
_isProcessNamespaces = true;
}
else
{
_isProcessNamespaces = false;
}
while (reader.NodeType != XmlNodeType.Element && reader.Read()) { }
_markupDepth = int.MaxValue;
_schemaXmlDepth = reader.Depth;
SchemaType rootType = _schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI);
string code;
if (!CheckSchemaRoot(rootType, out code))
{
throw new XmlSchemaException(code, reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition);
}
if (_schemaType == SchemaType.XSD)
{
_schema = new XmlSchema();
_schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute);
_builder = new XsdBuilder(reader, _namespaceManager, _schema, _nameTable, _schemaNames, _eventHandler);
}
else
{
Debug.Assert(_schemaType == SchemaType.XDR);
_xdrSchema = new SchemaInfo();
_xdrSchema.SchemaType = SchemaType.XDR;
_builder = new XdrBuilder(reader, _namespaceManager, _xdrSchema, targetNamespace, _nameTable, _schemaNames, _eventHandler);
((XdrBuilder)_builder).XmlResolver = _xmlResolver;
}
}
private bool CheckSchemaRoot(SchemaType rootType, out string code)
{
code = null;
if (_schemaType == SchemaType.None)
{
_schemaType = rootType;
}
switch (rootType)
{
case SchemaType.XSD:
if (_schemaType != SchemaType.XSD)
{
code = SR.Sch_MixSchemaTypes;
return false;
}
break;
case SchemaType.XDR:
if (_schemaType == SchemaType.XSD)
{
code = SR.Sch_XSDSchemaOnly;
return false;
}
else if (_schemaType != SchemaType.XDR)
{
code = SR.Sch_MixSchemaTypes;
return false;
}
break;
case SchemaType.DTD: //Did not detect schema type that can be parsed by this parser
case SchemaType.None:
code = SR.Sch_SchemaRootExpected;
if (_schemaType == SchemaType.XSD)
{
code = SR.Sch_XSDSchemaRootExpected;
}
return false;
default:
Debug.Fail($"Unexpected root type {rootType}");
break;
}
return true;
}
public SchemaType FinishParsing()
{
return _schemaType;
}
public XmlSchema XmlSchema
{
get { return _schema; }
}
internal XmlResolver XmlResolver
{
set
{
_xmlResolver = value;
}
}
public SchemaInfo XdrSchema
{
get { return _xdrSchema; }
}
public bool ParseReaderNode()
{
if (_reader.Depth > _markupDepth)
{
if (_processMarkup)
{
ProcessAppInfoDocMarkup(false);
}
return true;
}
else if (_reader.NodeType == XmlNodeType.Element)
{
if (_builder.ProcessElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI))
{
_namespaceManager.PushScope();
if (_reader.MoveToFirstAttribute())
{
do
{
_builder.ProcessAttribute(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _reader.Value);
if (Ref.Equal(_reader.NamespaceURI, _schemaNames.NsXmlNs) && _isProcessNamespaces)
{
_namespaceManager.AddNamespace(_reader.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value);
}
}
while (_reader.MoveToNextAttribute());
_reader.MoveToElement(); // get back to the element
}
_builder.StartChildren();
if (_reader.IsEmptyElement)
{
_namespaceManager.PopScope();
_builder.EndChildren();
if (_reader.Depth == _schemaXmlDepth)
{
return false; // done
}
}
else if (!_builder.IsContentParsed())
{ //AppInfo and Documentation
_markupDepth = _reader.Depth;
_processMarkup = true;
if (_annotationNSManager == null)
{
_annotationNSManager = new XmlNamespaceManager(_nameTable);
_xmlns = _nameTable.Add("xmlns");
}
ProcessAppInfoDocMarkup(true);
}
}
else if (!_reader.IsEmptyElement)
{ //UnsupportedElement in that context
_markupDepth = _reader.Depth;
_processMarkup = false; //Hack to not process unsupported elements
}
}
else if (_reader.NodeType == XmlNodeType.Text)
{ //Check for whitespace
if (!_xmlCharType.IsOnlyWhitespace(_reader.Value))
{
_builder.ProcessCData(_reader.Value);
}
}
else if (_reader.NodeType == XmlNodeType.EntityReference ||
_reader.NodeType == XmlNodeType.SignificantWhitespace ||
_reader.NodeType == XmlNodeType.CDATA)
{
_builder.ProcessCData(_reader.Value);
}
else if (_reader.NodeType == XmlNodeType.EndElement)
{
if (_reader.Depth == _markupDepth)
{
if (_processMarkup)
{
Debug.Assert(_parentNode != null);
XmlNodeList list = _parentNode.ChildNodes;
XmlNode[] markup = new XmlNode[list.Count];
for (int i = 0; i < list.Count; i++)
{
markup[i] = list[i];
}
_builder.ProcessMarkup(markup);
_namespaceManager.PopScope();
_builder.EndChildren();
}
_markupDepth = int.MaxValue;
}
else
{
_namespaceManager.PopScope();
_builder.EndChildren();
}
if (_reader.Depth == _schemaXmlDepth)
{
return false; // done
}
}
return true;
}
private void ProcessAppInfoDocMarkup(bool root)
{
//First time reader is positioned on AppInfo or Documentation element
XmlNode currentNode = null;
switch (_reader.NodeType)
{
case XmlNodeType.Element:
_annotationNSManager.PushScope();
currentNode = LoadElementNode(root);
// Dev10 (TFS) #479761: The following code was to address the issue of where an in-scope namespace delaration attribute
// was not added when an element follows an empty element. This fix will result in persisting schema in a consistent form
// although it does not change the semantic meaning of the schema.
// Since it is as a breaking change and Dev10 needs to maintain the backward compatibility, this fix is being reverted.
// if (reader.IsEmptyElement) {
// annotationNSManager.PopScope();
// }
break;
case XmlNodeType.Text:
currentNode = _dummyDocument.CreateTextNode(_reader.Value);
goto default;
case XmlNodeType.SignificantWhitespace:
currentNode = _dummyDocument.CreateSignificantWhitespace(_reader.Value);
goto default;
case XmlNodeType.CDATA:
currentNode = _dummyDocument.CreateCDataSection(_reader.Value);
goto default;
case XmlNodeType.EntityReference:
currentNode = _dummyDocument.CreateEntityReference(_reader.Name);
goto default;
case XmlNodeType.Comment:
currentNode = _dummyDocument.CreateComment(_reader.Value);
goto default;
case XmlNodeType.ProcessingInstruction:
currentNode = _dummyDocument.CreateProcessingInstruction(_reader.Name, _reader.Value);
goto default;
case XmlNodeType.EndEntity:
break;
case XmlNodeType.Whitespace:
break;
case XmlNodeType.EndElement:
_annotationNSManager.PopScope();
_parentNode = _parentNode.ParentNode;
break;
default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc
Debug.Assert(currentNode != null);
Debug.Assert(_parentNode != null);
_parentNode.AppendChild(currentNode);
break;
}
}
private XmlElement LoadElementNode(bool root)
{
Debug.Assert(_reader.NodeType == XmlNodeType.Element);
XmlReader r = _reader;
bool fEmptyElement = r.IsEmptyElement;
XmlElement element = _dummyDocument.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI);
element.IsEmpty = fEmptyElement;
if (root)
{
_parentNode = element;
}
else
{
XmlAttributeCollection attributes = element.Attributes;
if (r.MoveToFirstAttribute())
{
do
{
if (Ref.Equal(r.NamespaceURI, _schemaNames.NsXmlNs))
{ //Namespace Attribute
_annotationNSManager.AddNamespace(r.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value);
}
XmlAttribute attr = LoadAttributeNode();
attributes.Append(attr);
} while (r.MoveToNextAttribute());
}
r.MoveToElement();
string ns = _annotationNSManager.LookupNamespace(r.Prefix);
if (ns == null)
{
XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix));
attributes.Append(attr);
}
else if (ns.Length == 0)
{ //string.Empty prefix is mapped to string.Empty NS by default
string elemNS = _namespaceManager.LookupNamespace(r.Prefix);
if (elemNS != string.Empty)
{
XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, elemNS);
attributes.Append(attr);
}
}
while (r.MoveToNextAttribute())
{
if (r.Prefix.Length != 0)
{
string attNS = _annotationNSManager.LookupNamespace(r.Prefix);
if (attNS == null)
{
XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix));
attributes.Append(attr);
}
}
}
r.MoveToElement();
_parentNode.AppendChild(element);
if (!r.IsEmptyElement)
{
_parentNode = element;
}
}
return element;
}
private XmlAttribute CreateXmlNsAttribute(string prefix, string value)
{
XmlAttribute attr;
if (prefix.Length == 0)
{
attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns, XmlReservedNs.NsXmlNs);
}
else
{
attr = _dummyDocument.CreateAttribute(_xmlns, prefix, XmlReservedNs.NsXmlNs);
}
attr.AppendChild(_dummyDocument.CreateTextNode(value));
_annotationNSManager.AddNamespace(prefix, value);
return attr;
}
private XmlAttribute LoadAttributeNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Attribute);
XmlReader r = _reader;
XmlAttribute attr = _dummyDocument.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI);
while (r.ReadAttributeValue())
{
switch (r.NodeType)
{
case XmlNodeType.Text:
attr.AppendChild(_dummyDocument.CreateTextNode(r.Value));
continue;
case XmlNodeType.EntityReference:
attr.AppendChild(LoadEntityReferenceInAttribute());
continue;
default:
throw XmlLoader.UnexpectedNodeType(r.NodeType);
}
}
return attr;
}
private XmlEntityReference LoadEntityReferenceInAttribute()
{
Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference);
XmlEntityReference eref = _dummyDocument.CreateEntityReference(_reader.LocalName);
if (!_reader.CanResolveEntity)
{
return eref;
}
_reader.ResolveEntity();
while (_reader.ReadAttributeValue())
{
switch (_reader.NodeType)
{
case XmlNodeType.Text:
eref.AppendChild(_dummyDocument.CreateTextNode(_reader.Value));
continue;
case XmlNodeType.EndEntity:
if (eref.ChildNodes.Count == 0)
{
eref.AppendChild(_dummyDocument.CreateTextNode(string.Empty));
}
return eref;
case XmlNodeType.EntityReference:
eref.AppendChild(LoadEntityReferenceInAttribute());
break;
default:
throw XmlLoader.UnexpectedNodeType(_reader.NodeType);
}
}
return eref;
}
};
} // namespace System.Xml
| |
// Copyright 2015, Google Inc. 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.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201502;
using System;
using System.Collections.Generic;
using System.IO;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201502 {
/// <summary>
/// This code example creates an experiment using a query percentage of 10,
/// which defines what fraction of auctions should go to the control split
/// (90%) vs. the experiment split (10%), then adds experimental bid changes
/// for criteria and ad groups. To get campaigns, run GetCampaigns.cs.
/// To get ad groups, run GetAdGroups.cs. To get criteria, run
/// GetKeywords.cs.
///
/// Tags: ExperimentService.mutate
/// </summary>
public class AddExperiment : ExampleBase {
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args) {
AddExperiment codeExample = new AddExperiment();
Console.WriteLine(codeExample.Description);
try {
long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
long criterionId = long.Parse("INSERT_CRITERION_ID_HERE");
codeExample.Run(new AdWordsUser(), campaignId, adGroupId, criterionId);
} catch (Exception ex) {
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(ex));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description {
get {
return "This code example creates an experiment using a query percentage of 10, which " +
"defines what fraction of auctions should go to the control split (90%) vs. the " +
"experiment split (10%), then adds experimental bid changes for criteria and ad " +
"groups. To get campaigns, run GetCampaigns.cs. To get ad groups, run " +
"GetAdGroups.cs. To get criteria, run GetKeywords.cs.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">Id of the campaign to which experiments are
/// added.</param>
/// <param name="adGroupId">Id of the ad group to which experiments are
/// added.</param>
/// <param name="criterionId">Id of the criterion for which experiments
/// are added.</param>
public void Run(AdWordsUser user, long campaignId, long adGroupId, long criterionId) {
// Get the ExperimentService.
ExperimentService experimentService =
(ExperimentService) user.GetService(AdWordsService.v201502.ExperimentService);
// Get the AdGroupService.
AdGroupService adGroupService =
(AdGroupService) user.GetService(AdWordsService.v201502.AdGroupService);
// Get the AdGroupCriterionService.
AdGroupCriterionService adGroupCriterionService =
(AdGroupCriterionService) user.GetService(AdWordsService.v201502.AdGroupCriterionService);
// Create the experiment.
Experiment experiment = new Experiment();
experiment.campaignId = campaignId;
experiment.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
experiment.queryPercentage = 10;
experiment.startDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss");
// Optional: Set the end date.
experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss");
// Optional: Set the status.
experiment.status = ExperimentStatus.ENABLED;
// Create the operation.
ExperimentOperation experimentOperation = new ExperimentOperation();
experimentOperation.@operator = Operator.ADD;
experimentOperation.operand = experiment;
try {
// Add the experiment.
ExperimentReturnValue experimentRetVal = experimentService.mutate(
new ExperimentOperation[] {experimentOperation});
// Display the results.
if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value.
Length > 0) {
long experimentId = 0;
Experiment newExperiment = experimentRetVal.value[0];
Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n",
newExperiment.name, newExperiment.id);
experimentId = newExperiment.id;
// Set ad group for the experiment.
AdGroup adGroup = new AdGroup();
adGroup.id = adGroupId;
// Create experiment bid multiplier rule that will modify ad group bid
// for the experiment.
ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier =
new ManualCPCAdGroupExperimentBidMultipliers();
adGroupBidMultiplier.maxCpcMultiplier = new BidMultiplier();
adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5;
// Set experiment data to the ad group.
AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData();
adGroupExperimentData.experimentId = experimentId;
adGroupExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier;
adGroup.experimentData = adGroupExperimentData;
// Create the operation.
AdGroupOperation adGroupOperation = new AdGroupOperation();
adGroupOperation.operand = adGroup;
adGroupOperation.@operator = Operator.SET;
// Update the ad group.
AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] {
adGroupOperation});
// Display the results.
if (adGroupRetVal != null && adGroupRetVal.value != null &&
adGroupRetVal.value.Length > 0) {
AdGroup updatedAdGroup = adGroupRetVal.value[0];
Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " +
"was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id,
updatedAdGroup.status);
} else {
Console.WriteLine("No ad groups were updated.");
}
// Set ad group criteria for the experiment.
Criterion criterion = new Criterion();
criterion.id = criterionId;
BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
adGroupCriterion.adGroupId = adGroupId;
adGroupCriterion.criterion = criterion;
// Create experiment bid multiplier rule that will modify criterion bid
// for the experiment.
ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier =
new ManualCPCAdGroupCriterionExperimentBidMultiplier();
bidMultiplier.maxCpcMultiplier = new BidMultiplier();
bidMultiplier.maxCpcMultiplier.multiplier = 1.5;
// Set experiment data to the criterion.
BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData =
new BiddableAdGroupCriterionExperimentData();
adGroupCriterionExperimentData.experimentId = experimentId;
adGroupCriterionExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier;
adGroupCriterion.experimentData = adGroupCriterionExperimentData;
// Create the operation.
AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation();
adGroupCriterionOperation.operand = adGroupCriterion;
adGroupCriterionOperation.@operator = Operator.SET;
// Update the ad group criteria.
AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate(
new AdGroupCriterionOperation[] {adGroupCriterionOperation});
// Display the results.
if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null &&
adGroupCriterionRetVal.value.Length > 0) {
AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0];
Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = "
+ "\"{1}\" and type = \"{2}\" was updated for the experiment.\n",
updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id,
updatedAdGroupCriterion.criterion.CriterionType);
} else {
Console.WriteLine("No ad group criteria were updated.");
}
} else {
Console.WriteLine("No experiments were added.");
}
} catch (Exception ex) {
throw new System.ApplicationException("Failed to add experiment.", ex);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/rpc/open_lodging_reservation_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.RPC {
/// <summary>Holder for reflection information generated from booking/rpc/open_lodging_reservation_svc.proto</summary>
public static partial class OpenLodgingReservationSvcReflection {
#region Descriptor
/// <summary>File descriptor for booking/rpc/open_lodging_reservation_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static OpenLodgingReservationSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci5ib29raW5nL3JwYy9vcGVuX2xvZGdpbmdfcmVzZXJ2YXRpb25fc3ZjLnBy",
"b3RvEhdob2xtcy50eXBlcy5ib29raW5nLnJwYxobZ29vZ2xlL3Byb3RvYnVm",
"L2VtcHR5LnByb3RvGi5ib29raW5nL2luZGljYXRvcnMvcmVzZXJ2YXRpb25f",
"aW5kaWNhdG9yLnByb3RvGjVvcGVyYXRpb25zL3Jvb21fY2xhaW1zL3Jvb21f",
"YXNzaWdubWVudF9ieV9uaWdodC5wcm90bxo/b3BlcmF0aW9ucy9yb29tX2Ns",
"YWltcy9yZXNlcnZhdGlvbl9yb29tX2Fzc2lnbm1lbnRfcmVzdWx0LnByb3Rv",
"Gj9ib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9yb29tX2Fzc2ln",
"bm1lbnRfc2NoZWR1bGUucHJvdG8aNWJvb2tpbmcvcmVzZXJ2YXRpb25zL3Jl",
"c2VydmF0aW9uX2NvbnRhY3RfcGVyc29uLnByb3RvGj1ib29raW5nL2luZGlj",
"YXRvcnMvcmVzZXJ2YXRpb25fY29udGFjdF9wZXJzb25faW5kaWNhdG9yLnBy",
"b3RvGiNib29raW5nL2hpc3RvcnkvaGlzdG9yeV9ldmVudC5wcm90bxo5b3Bl",
"cmF0aW9ucy9ob3VzZWtlZXBpbmcvaG91c2VrZWVwaW5nX3RpbWVfaW5kaWNh",
"dG9yLnByb3RvGixib29raW5nL3Jlc2VydmF0aW9uX2Fzc29jaWF0ZWRfcGFy",
"dGllcy5wcm90byK5AQocVXBkYXRlUm9vbUFzc2lnbm1lbnRzUmVxdWVzdBJJ",
"CgtyZXNlcnZhdGlvbhgBIAEoCzI0LmhvbG1zLnR5cGVzLmJvb2tpbmcuaW5k",
"aWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRvchJOCgthc3NpZ25tZW50cxgC",
"IAMoCzI5LmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucm9vbV9jbGFpbXMuUm9v",
"bUFzc2lnbm1lbnRCeU5pZ2h0InQKHVVwZGF0ZVJvb21Bc3NpZ25tZW50c1Jl",
"c3BvbnNlElMKBnJlc3VsdBgBIAEoDjJDLmhvbG1zLnR5cGVzLm9wZXJhdGlv",
"bnMucm9vbV9jbGFpbXMuUmVzZXJ2YXRpb25Sb29tQXNzaWdubWVudFJlc3Vs",
"dCKpAQodR2V0UmVzZXJ2YXRpb25IaXN0b3J5UmVzcG9uc2USQgoPcmVzX2hp",
"c3RvcnlfbG9nGAEgAygLMikuaG9sbXMudHlwZXMuYm9va2luZy5oaXN0b3J5",
"Lkhpc3RvcnlFdmVudBJEChFmb2xpb19oaXN0b3J5X2xvZxgCIAMoCzIpLmhv",
"bG1zLnR5cGVzLmJvb2tpbmcuaGlzdG9yeS5IaXN0b3J5RXZlbnQibgoeR2V0",
"UmVzZXJ2YXRpb25Db250YWN0c1Jlc3BvbnNlEkwKCGNvbnRhY3RzGAEgAygL",
"MjouaG9sbXMudHlwZXMuYm9va2luZy5yZXNlcnZhdGlvbnMuUmVzZXJ2YXRp",
"b25Db250YWN0UGVyc29uIsABCh9SZW1vdmVSZXNlcnZhdGlvbkNvbnRhY3RS",
"ZXF1ZXN0EkkKC3Jlc2VydmF0aW9uGAEgASgLMjQuaG9sbXMudHlwZXMuYm9v",
"a2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5kaWNhdG9yElIKB2NvbnRh",
"Y3QYAiABKAsyQS5ob2xtcy50eXBlcy5ib29raW5nLmluZGljYXRvcnMuUmVz",
"ZXJ2YXRpb25Db250YWN0UGVyc29uSW5kaWNhdG9yIoYBChxBZGRSZXNlcnZh",
"dGlvbkNvbnRhY3RSZXF1ZXN0EkkKC3Jlc2VydmF0aW9uGAEgASgLMjQuaG9s",
"bXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5kaWNh",
"dG9yEgwKBG5hbWUYAiABKAkSDQoFZW1haWwYAyABKAkiyQEKIUhvdXNla2Vl",
"cGluZ1RpbWVQcmVmZXJlbmNlUmVxdWVzdBJJCgtyZXNlcnZhdGlvbhgBIAEo",
"CzI0LmhvbG1zLnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlv",
"bkluZGljYXRvchJZChFyZXF1ZXN0ZWRfaGtfdGltZRgCIAEoCzI+LmhvbG1z",
"LnR5cGVzLm9wZXJhdGlvbnMuaG91c2VrZWVwaW5nLkhvdXNla2VlcGluZ1Rp",
"bWVJbmRpY2F0b3IilAEKJFZlaGljbGVQbGF0ZUluZm9ybWF0aW9uVXBkYXRl",
"UmVxdWVzdBJJCgtyZXNlcnZhdGlvbhgBIAEoCzI0LmhvbG1zLnR5cGVzLmJv",
"b2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRvchIhChl2ZWhp",
"Y2xlX3BsYXRlX2luZm9ybWF0aW9uGAIgASgJImsKHUdldFJBUHNGb3JSZXNl",
"cnZhdGlvbnNSZXF1ZXN0EkoKDHJlc2VydmF0aW9ucxgBIAMoCzI0LmhvbG1z",
"LnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRv",
"ciJhCh5HZXRSQVBzRm9yUmVzZXJ2YXRpb25zUmVzcG9uc2USPwoEcmFwcxgB",
"IAMoCzIxLmhvbG1zLnR5cGVzLmJvb2tpbmcuUmVzZXJ2YXRpb25Bc3NvY2lh",
"dGVkUGFydGllcyKWAQolR3Vlc3RQZXJzb25hbEluZm9ybWF0aW9uVXBkYXRl",
"UmVxdWVzdBJJCgtyZXNlcnZhdGlvbhgBIAEoCzI0LmhvbG1zLnR5cGVzLmJv",
"b2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRvchIiChpndWVz",
"dF9wZXJzb25hbF9pbmZvcm1hdGlvbhgCIAEoCTKwCwoZT3BlbkxvZGdpbmdS",
"ZXNlcnZhdGlvblN2YxKFAQoVR2V0UmVzZXJ2YXRpb25IaXN0b3J5EjQuaG9s",
"bXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5kaWNh",
"dG9yGjYuaG9sbXMudHlwZXMuYm9va2luZy5ycGMuR2V0UmVzZXJ2YXRpb25I",
"aXN0b3J5UmVzcG9uc2UShgEKFVVwZGF0ZVJvb21Bc3NpZ25tZW50cxI1Lmhv",
"bG1zLnR5cGVzLmJvb2tpbmcucnBjLlVwZGF0ZVJvb21Bc3NpZ25tZW50c1Jl",
"cXVlc3QaNi5ob2xtcy50eXBlcy5ib29raW5nLnJwYy5VcGRhdGVSb29tQXNz",
"aWdubWVudHNSZXNwb25zZRKPAQoSR2V0Um9vbUFzc2lnbm1lbnRzEjQuaG9s",
"bXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5kaWNh",
"dG9yGkMuaG9sbXMudHlwZXMuYm9va2luZy5yZXNlcnZhdGlvbnMuUmVzZXJ2",
"YXRpb25Sb29tQXNzaWdubWVudFNjaGVkdWxlEocBChZHZXRSZXNlcnZhdGlv",
"bkNvbnRhY3RzEjQuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJl",
"c2VydmF0aW9uSW5kaWNhdG9yGjcuaG9sbXMudHlwZXMuYm9va2luZy5ycGMu",
"R2V0UmVzZXJ2YXRpb25Db250YWN0c1Jlc3BvbnNlEmwKGFJlbW92ZVJlc2Vy",
"dmF0aW9uQ29udGFjdBI4LmhvbG1zLnR5cGVzLmJvb2tpbmcucnBjLlJlbW92",
"ZVJlc2VydmF0aW9uQ29udGFjdFJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYu",
"RW1wdHkSYQoQQWRkQ29udGFjdFBlcnNvbhI1LmhvbG1zLnR5cGVzLmJvb2tp",
"bmcucnBjLkFkZFJlc2VydmF0aW9uQ29udGFjdFJlcXVlc3QaFi5nb29nbGUu",
"cHJvdG9idWYuRW1wdHkScwodU2V0SG91c2VrZWVwaW5nVGltZVByZWZlcmVu",
"Y2USOi5ob2xtcy50eXBlcy5ib29raW5nLnJwYy5Ib3VzZWtlZXBpbmdUaW1l",
"UHJlZmVyZW5jZVJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkSigEK",
"H0dldFJlc2VydmF0aW9uQXNzb2NpYXRlZFBhcnRpZXMSNC5ob2xtcy50eXBl",
"cy5ib29raW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3IaMS5o",
"b2xtcy50eXBlcy5ib29raW5nLlJlc2VydmF0aW9uQXNzb2NpYXRlZFBhcnRp",
"ZXMSoQEKLkdldFJlc2VydmF0aW9uQXNzb2NpYXRlZFBhcnRpZXNGb3JSZXNl",
"cnZhdGlvbnMSNi5ob2xtcy50eXBlcy5ib29raW5nLnJwYy5HZXRSQVBzRm9y",
"UmVzZXJ2YXRpb25zUmVxdWVzdBo3LmhvbG1zLnR5cGVzLmJvb2tpbmcucnBj",
"LkdldFJBUHNGb3JSZXNlcnZhdGlvbnNSZXNwb25zZRJ2Ch1VcGRhdGVWZWhp",
"Y2xlUGxhdGVJbmZvcm1hdGlvbhI9LmhvbG1zLnR5cGVzLmJvb2tpbmcucnBj",
"LlZlaGljbGVQbGF0ZUluZm9ybWF0aW9uVXBkYXRlUmVxdWVzdBoWLmdvb2ds",
"ZS5wcm90b2J1Zi5FbXB0eRJ3Ch1VcGRhdGVHb3Zlcm5tZW50SWRJbmZvcm1h",
"dGlvbhI+LmhvbG1zLnR5cGVzLmJvb2tpbmcucnBjLkd1ZXN0UGVyc29uYWxJ",
"bmZvcm1hdGlvblVwZGF0ZVJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1w",
"dHlCJ1oLYm9va2luZy9ycGOqAhdIT0xNUy5UeXBlcy5Cb29raW5nLlJQQ2IG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNightReflection.Descriptor, global::HOLMS.Types.Operations.RoomClaims.ReservationRoomAssignmentResultReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationRoomAssignmentScheduleReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationContactPersonReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.History.HistoryEventReflection.Descriptor, global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.ReservationAssociatedPartiesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.UpdateRoomAssignmentsRequest), global::HOLMS.Types.Booking.RPC.UpdateRoomAssignmentsRequest.Parser, new[]{ "Reservation", "Assignments" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.UpdateRoomAssignmentsResponse), global::HOLMS.Types.Booking.RPC.UpdateRoomAssignmentsResponse.Parser, new[]{ "Result" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.GetReservationHistoryResponse), global::HOLMS.Types.Booking.RPC.GetReservationHistoryResponse.Parser, new[]{ "ResHistoryLog", "FolioHistoryLog" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.GetReservationContactsResponse), global::HOLMS.Types.Booking.RPC.GetReservationContactsResponse.Parser, new[]{ "Contacts" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.RemoveReservationContactRequest), global::HOLMS.Types.Booking.RPC.RemoveReservationContactRequest.Parser, new[]{ "Reservation", "Contact" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.AddReservationContactRequest), global::HOLMS.Types.Booking.RPC.AddReservationContactRequest.Parser, new[]{ "Reservation", "Name", "Email" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.HousekeepingTimePreferenceRequest), global::HOLMS.Types.Booking.RPC.HousekeepingTimePreferenceRequest.Parser, new[]{ "Reservation", "RequestedHkTime" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.VehiclePlateInformationUpdateRequest), global::HOLMS.Types.Booking.RPC.VehiclePlateInformationUpdateRequest.Parser, new[]{ "Reservation", "VehiclePlateInformation" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.GetRAPsForReservationsRequest), global::HOLMS.Types.Booking.RPC.GetRAPsForReservationsRequest.Parser, new[]{ "Reservations" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.GetRAPsForReservationsResponse), global::HOLMS.Types.Booking.RPC.GetRAPsForReservationsResponse.Parser, new[]{ "Raps" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.GuestPersonalInformationUpdateRequest), global::HOLMS.Types.Booking.RPC.GuestPersonalInformationUpdateRequest.Parser, new[]{ "Reservation", "GuestPersonalInformation" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class UpdateRoomAssignmentsRequest : pb::IMessage<UpdateRoomAssignmentsRequest> {
private static readonly pb::MessageParser<UpdateRoomAssignmentsRequest> _parser = new pb::MessageParser<UpdateRoomAssignmentsRequest>(() => new UpdateRoomAssignmentsRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateRoomAssignmentsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateRoomAssignmentsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateRoomAssignmentsRequest(UpdateRoomAssignmentsRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
assignments_ = other.assignments_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateRoomAssignmentsRequest Clone() {
return new UpdateRoomAssignmentsRequest(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "assignments" field.</summary>
public const int AssignmentsFieldNumber = 2;
private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight> _repeated_assignments_codec
= pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight> assignments_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight> Assignments {
get { return assignments_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateRoomAssignmentsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateRoomAssignmentsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if(!assignments_.Equals(other.assignments_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
hash ^= assignments_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
assignments_.WriteTo(output, _repeated_assignments_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
size += assignments_.CalculateSize(_repeated_assignments_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateRoomAssignmentsRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
assignments_.Add(other.assignments_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
assignments_.AddEntriesFrom(input, _repeated_assignments_codec);
break;
}
}
}
}
}
public sealed partial class UpdateRoomAssignmentsResponse : pb::IMessage<UpdateRoomAssignmentsResponse> {
private static readonly pb::MessageParser<UpdateRoomAssignmentsResponse> _parser = new pb::MessageParser<UpdateRoomAssignmentsResponse>(() => new UpdateRoomAssignmentsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateRoomAssignmentsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateRoomAssignmentsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateRoomAssignmentsResponse(UpdateRoomAssignmentsResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateRoomAssignmentsResponse Clone() {
return new UpdateRoomAssignmentsResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.Operations.RoomClaims.ReservationRoomAssignmentResult result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.RoomClaims.ReservationRoomAssignmentResult Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateRoomAssignmentsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateRoomAssignmentsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateRoomAssignmentsResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.Operations.RoomClaims.ReservationRoomAssignmentResult) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class GetReservationHistoryResponse : pb::IMessage<GetReservationHistoryResponse> {
private static readonly pb::MessageParser<GetReservationHistoryResponse> _parser = new pb::MessageParser<GetReservationHistoryResponse>(() => new GetReservationHistoryResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetReservationHistoryResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetReservationHistoryResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetReservationHistoryResponse(GetReservationHistoryResponse other) : this() {
resHistoryLog_ = other.resHistoryLog_.Clone();
folioHistoryLog_ = other.folioHistoryLog_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetReservationHistoryResponse Clone() {
return new GetReservationHistoryResponse(this);
}
/// <summary>Field number for the "res_history_log" field.</summary>
public const int ResHistoryLogFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.History.HistoryEvent> _repeated_resHistoryLog_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.History.HistoryEvent.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.History.HistoryEvent> resHistoryLog_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.History.HistoryEvent>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.History.HistoryEvent> ResHistoryLog {
get { return resHistoryLog_; }
}
/// <summary>Field number for the "folio_history_log" field.</summary>
public const int FolioHistoryLogFieldNumber = 2;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.History.HistoryEvent> _repeated_folioHistoryLog_codec
= pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Booking.History.HistoryEvent.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.History.HistoryEvent> folioHistoryLog_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.History.HistoryEvent>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.History.HistoryEvent> FolioHistoryLog {
get { return folioHistoryLog_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetReservationHistoryResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetReservationHistoryResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!resHistoryLog_.Equals(other.resHistoryLog_)) return false;
if(!folioHistoryLog_.Equals(other.folioHistoryLog_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= resHistoryLog_.GetHashCode();
hash ^= folioHistoryLog_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
resHistoryLog_.WriteTo(output, _repeated_resHistoryLog_codec);
folioHistoryLog_.WriteTo(output, _repeated_folioHistoryLog_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += resHistoryLog_.CalculateSize(_repeated_resHistoryLog_codec);
size += folioHistoryLog_.CalculateSize(_repeated_folioHistoryLog_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetReservationHistoryResponse other) {
if (other == null) {
return;
}
resHistoryLog_.Add(other.resHistoryLog_);
folioHistoryLog_.Add(other.folioHistoryLog_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
resHistoryLog_.AddEntriesFrom(input, _repeated_resHistoryLog_codec);
break;
}
case 18: {
folioHistoryLog_.AddEntriesFrom(input, _repeated_folioHistoryLog_codec);
break;
}
}
}
}
}
public sealed partial class GetReservationContactsResponse : pb::IMessage<GetReservationContactsResponse> {
private static readonly pb::MessageParser<GetReservationContactsResponse> _parser = new pb::MessageParser<GetReservationContactsResponse>(() => new GetReservationContactsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetReservationContactsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetReservationContactsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetReservationContactsResponse(GetReservationContactsResponse other) : this() {
contacts_ = other.contacts_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetReservationContactsResponse Clone() {
return new GetReservationContactsResponse(this);
}
/// <summary>Field number for the "contacts" field.</summary>
public const int ContactsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson> _repeated_contacts_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.Reservations.ReservationContactPerson.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson> contacts_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationContactPerson> Contacts {
get { return contacts_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetReservationContactsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetReservationContactsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!contacts_.Equals(other.contacts_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= contacts_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
contacts_.WriteTo(output, _repeated_contacts_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += contacts_.CalculateSize(_repeated_contacts_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetReservationContactsResponse other) {
if (other == null) {
return;
}
contacts_.Add(other.contacts_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
contacts_.AddEntriesFrom(input, _repeated_contacts_codec);
break;
}
}
}
}
}
public sealed partial class RemoveReservationContactRequest : pb::IMessage<RemoveReservationContactRequest> {
private static readonly pb::MessageParser<RemoveReservationContactRequest> _parser = new pb::MessageParser<RemoveReservationContactRequest>(() => new RemoveReservationContactRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RemoveReservationContactRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RemoveReservationContactRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RemoveReservationContactRequest(RemoveReservationContactRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
Contact = other.contact_ != null ? other.Contact.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RemoveReservationContactRequest Clone() {
return new RemoveReservationContactRequest(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "contact" field.</summary>
public const int ContactFieldNumber = 2;
private global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator contact_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator Contact {
get { return contact_; }
set {
contact_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RemoveReservationContactRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RemoveReservationContactRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (!object.Equals(Contact, other.Contact)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (contact_ != null) hash ^= Contact.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (contact_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Contact);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (contact_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Contact);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RemoveReservationContactRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.contact_ != null) {
if (contact_ == null) {
contact_ = new global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator();
}
Contact.MergeFrom(other.Contact);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
if (contact_ == null) {
contact_ = new global::HOLMS.Types.Booking.Indicators.ReservationContactPersonIndicator();
}
input.ReadMessage(contact_);
break;
}
}
}
}
}
public sealed partial class AddReservationContactRequest : pb::IMessage<AddReservationContactRequest> {
private static readonly pb::MessageParser<AddReservationContactRequest> _parser = new pb::MessageParser<AddReservationContactRequest>(() => new AddReservationContactRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AddReservationContactRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AddReservationContactRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AddReservationContactRequest(AddReservationContactRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
name_ = other.name_;
email_ = other.email_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AddReservationContactRequest Clone() {
return new AddReservationContactRequest(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 2;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "email" field.</summary>
public const int EmailFieldNumber = 3;
private string email_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Email {
get { return email_; }
set {
email_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AddReservationContactRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AddReservationContactRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (Name != other.Name) return false;
if (Email != other.Email) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Email.Length != 0) hash ^= Email.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (Name.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Name);
}
if (Email.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Email);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Email.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Email);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AddReservationContactRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Email.Length != 0) {
Email = other.Email;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
Name = input.ReadString();
break;
}
case 26: {
Email = input.ReadString();
break;
}
}
}
}
}
public sealed partial class HousekeepingTimePreferenceRequest : pb::IMessage<HousekeepingTimePreferenceRequest> {
private static readonly pb::MessageParser<HousekeepingTimePreferenceRequest> _parser = new pb::MessageParser<HousekeepingTimePreferenceRequest>(() => new HousekeepingTimePreferenceRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HousekeepingTimePreferenceRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HousekeepingTimePreferenceRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HousekeepingTimePreferenceRequest(HousekeepingTimePreferenceRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
RequestedHkTime = other.requestedHkTime_ != null ? other.RequestedHkTime.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HousekeepingTimePreferenceRequest Clone() {
return new HousekeepingTimePreferenceRequest(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "requested_hk_time" field.</summary>
public const int RequestedHkTimeFieldNumber = 2;
private global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator requestedHkTime_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator RequestedHkTime {
get { return requestedHkTime_; }
set {
requestedHkTime_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HousekeepingTimePreferenceRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HousekeepingTimePreferenceRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (!object.Equals(RequestedHkTime, other.RequestedHkTime)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (requestedHkTime_ != null) hash ^= RequestedHkTime.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (requestedHkTime_ != null) {
output.WriteRawTag(18);
output.WriteMessage(RequestedHkTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (requestedHkTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RequestedHkTime);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HousekeepingTimePreferenceRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.requestedHkTime_ != null) {
if (requestedHkTime_ == null) {
requestedHkTime_ = new global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator();
}
RequestedHkTime.MergeFrom(other.RequestedHkTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
if (requestedHkTime_ == null) {
requestedHkTime_ = new global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator();
}
input.ReadMessage(requestedHkTime_);
break;
}
}
}
}
}
public sealed partial class VehiclePlateInformationUpdateRequest : pb::IMessage<VehiclePlateInformationUpdateRequest> {
private static readonly pb::MessageParser<VehiclePlateInformationUpdateRequest> _parser = new pb::MessageParser<VehiclePlateInformationUpdateRequest>(() => new VehiclePlateInformationUpdateRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<VehiclePlateInformationUpdateRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VehiclePlateInformationUpdateRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VehiclePlateInformationUpdateRequest(VehiclePlateInformationUpdateRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
vehiclePlateInformation_ = other.vehiclePlateInformation_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public VehiclePlateInformationUpdateRequest Clone() {
return new VehiclePlateInformationUpdateRequest(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "vehicle_plate_information" field.</summary>
public const int VehiclePlateInformationFieldNumber = 2;
private string vehiclePlateInformation_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string VehiclePlateInformation {
get { return vehiclePlateInformation_; }
set {
vehiclePlateInformation_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as VehiclePlateInformationUpdateRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(VehiclePlateInformationUpdateRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (VehiclePlateInformation != other.VehiclePlateInformation) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (VehiclePlateInformation.Length != 0) hash ^= VehiclePlateInformation.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (VehiclePlateInformation.Length != 0) {
output.WriteRawTag(18);
output.WriteString(VehiclePlateInformation);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (VehiclePlateInformation.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(VehiclePlateInformation);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(VehiclePlateInformationUpdateRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.VehiclePlateInformation.Length != 0) {
VehiclePlateInformation = other.VehiclePlateInformation;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
VehiclePlateInformation = input.ReadString();
break;
}
}
}
}
}
public sealed partial class GetRAPsForReservationsRequest : pb::IMessage<GetRAPsForReservationsRequest> {
private static readonly pb::MessageParser<GetRAPsForReservationsRequest> _parser = new pb::MessageParser<GetRAPsForReservationsRequest>(() => new GetRAPsForReservationsRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetRAPsForReservationsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[8]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRAPsForReservationsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRAPsForReservationsRequest(GetRAPsForReservationsRequest other) : this() {
reservations_ = other.reservations_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRAPsForReservationsRequest Clone() {
return new GetRAPsForReservationsRequest(this);
}
/// <summary>Field number for the "reservations" field.</summary>
public const int ReservationsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> _repeated_reservations_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.Indicators.ReservationIndicator.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> reservations_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Indicators.ReservationIndicator>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> Reservations {
get { return reservations_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetRAPsForReservationsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetRAPsForReservationsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!reservations_.Equals(other.reservations_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= reservations_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
reservations_.WriteTo(output, _repeated_reservations_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += reservations_.CalculateSize(_repeated_reservations_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetRAPsForReservationsRequest other) {
if (other == null) {
return;
}
reservations_.Add(other.reservations_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
reservations_.AddEntriesFrom(input, _repeated_reservations_codec);
break;
}
}
}
}
}
public sealed partial class GetRAPsForReservationsResponse : pb::IMessage<GetRAPsForReservationsResponse> {
private static readonly pb::MessageParser<GetRAPsForReservationsResponse> _parser = new pb::MessageParser<GetRAPsForReservationsResponse>(() => new GetRAPsForReservationsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetRAPsForReservationsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[9]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRAPsForReservationsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRAPsForReservationsResponse(GetRAPsForReservationsResponse other) : this() {
raps_ = other.raps_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetRAPsForReservationsResponse Clone() {
return new GetRAPsForReservationsResponse(this);
}
/// <summary>Field number for the "raps" field.</summary>
public const int RapsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.ReservationAssociatedParties> _repeated_raps_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.ReservationAssociatedParties.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.ReservationAssociatedParties> raps_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.ReservationAssociatedParties>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.ReservationAssociatedParties> Raps {
get { return raps_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetRAPsForReservationsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetRAPsForReservationsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!raps_.Equals(other.raps_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= raps_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
raps_.WriteTo(output, _repeated_raps_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += raps_.CalculateSize(_repeated_raps_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetRAPsForReservationsResponse other) {
if (other == null) {
return;
}
raps_.Add(other.raps_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
raps_.AddEntriesFrom(input, _repeated_raps_codec);
break;
}
}
}
}
}
public sealed partial class GuestPersonalInformationUpdateRequest : pb::IMessage<GuestPersonalInformationUpdateRequest> {
private static readonly pb::MessageParser<GuestPersonalInformationUpdateRequest> _parser = new pb::MessageParser<GuestPersonalInformationUpdateRequest>(() => new GuestPersonalInformationUpdateRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GuestPersonalInformationUpdateRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.OpenLodgingReservationSvcReflection.Descriptor.MessageTypes[10]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GuestPersonalInformationUpdateRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GuestPersonalInformationUpdateRequest(GuestPersonalInformationUpdateRequest other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
guestPersonalInformation_ = other.guestPersonalInformation_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GuestPersonalInformationUpdateRequest Clone() {
return new GuestPersonalInformationUpdateRequest(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "guest_personal_information" field.</summary>
public const int GuestPersonalInformationFieldNumber = 2;
private string guestPersonalInformation_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GuestPersonalInformation {
get { return guestPersonalInformation_; }
set {
guestPersonalInformation_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GuestPersonalInformationUpdateRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GuestPersonalInformationUpdateRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (GuestPersonalInformation != other.GuestPersonalInformation) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (GuestPersonalInformation.Length != 0) hash ^= GuestPersonalInformation.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (GuestPersonalInformation.Length != 0) {
output.WriteRawTag(18);
output.WriteString(GuestPersonalInformation);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (GuestPersonalInformation.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GuestPersonalInformation);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GuestPersonalInformationUpdateRequest other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.GuestPersonalInformation.Length != 0) {
GuestPersonalInformation = other.GuestPersonalInformation;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
GuestPersonalInformation = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace WebApp.Migrations
{
public partial class CustomerIsSiteAccess : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "HousingCall");
migrationBuilder.DropColumn(name: "IsSite", table: "Customer");
migrationBuilder.AddColumn<bool>(
name: "IsSiteAccess",
table: "Customer",
nullable: false,
defaultValue: false);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Customer_City_CityId",
table: "Customer",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Customer_Sms_SmsId",
table: "Customer",
column: "SmsId",
principalTable: "Sms",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_City_CityId",
table: "Housing",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_District_DistrictId",
table: "Housing",
column: "DistrictId",
principalTable: "District",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_Street_StreetId",
table: "Housing",
column: "StreetId",
principalTable: "Street",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_TypesHousing_TypesHousingId",
table: "Housing",
column: "TypesHousingId",
principalTable: "TypesHousing",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_HousingCall_Housing_HousingId",
table: "HousingCall",
column: "HousingId",
principalTable: "Housing",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "HousingCall");
migrationBuilder.DropColumn(name: "IsSiteAccess", table: "Customer");
migrationBuilder.AddColumn<bool>(
name: "IsSite",
table: "Customer",
nullable: false,
defaultValue: false);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Customer_City_CityId",
table: "Customer",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Customer_Sms_SmsId",
table: "Customer",
column: "SmsId",
principalTable: "Sms",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_City_CityId",
table: "Housing",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_District_DistrictId",
table: "Housing",
column: "DistrictId",
principalTable: "District",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_Street_StreetId",
table: "Housing",
column: "StreetId",
principalTable: "Street",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_TypesHousing_TypesHousingId",
table: "Housing",
column: "TypesHousingId",
principalTable: "TypesHousing",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_HousingCall_Housing_HousingId",
table: "HousingCall",
column: "HousingId",
principalTable: "Housing",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based direct-message channel.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestDMChannel : RestChannel, IDMChannel, IRestPrivateChannel, IRestMessageChannel
{
/// <summary>
/// Gets the current logged-in user.
/// </summary>
public RestUser CurrentUser { get; }
/// <summary>
/// Gets the recipient of the channel.
/// </summary>
public RestUser Recipient { get; }
/// <summary>
/// Gets a collection that is the current logged-in user and the recipient.
/// </summary>
public IReadOnlyCollection<RestUser> Users => ImmutableArray.Create(CurrentUser, Recipient);
internal RestDMChannel(BaseDiscordClient discord, ulong id, ulong recipientId)
: base(discord, id)
{
Recipient = new RestUser(Discord, recipientId);
CurrentUser = new RestUser(Discord, discord.CurrentUser.Id);
}
internal new static RestDMChannel Create(BaseDiscordClient discord, Model model)
{
var entity = new RestDMChannel(discord, model.Id, model.Recipients.Value[0].Id);
entity.Update(model);
return entity;
}
internal override void Update(Model model)
{
Recipient.Update(model.Recipients.Value[0]);
}
/// <inheritdoc />
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetChannelAsync(Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task CloseAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
/// <summary>
/// Gets a user in this channel from the provided <paramref name="id"/>.
/// </summary>
/// <param name="id">The snowflake identifier of the user.</param>
/// <returns>
/// A <see cref="RestUser"/> object that is a recipient of this channel; otherwise <c>null</c>.
/// </returns>
public RestUser GetUser(ulong id)
{
if (id == Recipient.Id)
return Recipient;
else if (id == Discord.CurrentUser.Id)
return CurrentUser;
else
return null;
}
/// <inheritdoc />
public Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null)
=> ChannelHelper.GetMessageAsync(this, Discord, id, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, null, Direction.Before, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessageId, dir, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessage.Id, dir, limit, options);
/// <inheritdoc />
public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
=> ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options);
/// <inheritdoc />
/// <exception cref="ArgumentException">
/// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filePath" /> is <c>null</c>.
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260
/// characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified path is invalid, (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">
/// The file specified in <paramref name="filePath" /> was not found.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false)
=> ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options, isSpoiler);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false)
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options, isSpoiler);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
/// <summary>
/// Gets a string that represents the Username#Discriminator of the recipient.
/// </summary>
/// <returns>
/// A string that resolves to the Recipient of this channel.
/// </returns>
public override string ToString() => $"@{Recipient}";
private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)";
//IDMChannel
/// <inheritdoc />
IUser IDMChannel.Recipient => Recipient;
//IRestPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<RestUser> IRestPrivateChannel.Recipients => ImmutableArray.Create(Recipient);
//IPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<IUser> IPrivateChannel.Recipients => ImmutableArray.Create<IUser>(Recipient);
//IMessageChannel
/// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options).ConfigureAwait(false);
else
return null;
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return GetMessagesAsync(limit, options);
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return GetMessagesAsync(fromMessageId, dir, limit, options);
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return GetMessagesAsync(fromMessage, dir, limit, options);
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
=> await GetPinnedMessagesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler)
=> await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler)
=> await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
//IChannel
/// <inheritdoc />
string IChannel.Name => $"@{Recipient}";
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(id));
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareNotLessThanOrEqualScalarSingle()
{
var test = new SimpleBinaryOpTest__CompareNotLessThanOrEqualScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareNotLessThanOrEqualScalarSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single> _dataTable;
static SimpleBinaryOpTest__CompareNotLessThanOrEqualScalarSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareNotLessThanOrEqualScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareNotLessThanOrEqualScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse.CompareNotLessThanOrEqualScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareNotLessThanOrEqualScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotLessThanOrEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotLessThanOrEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotLessThanOrEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse.CompareNotLessThanOrEqualScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareNotLessThanOrEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareNotLessThanOrEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareNotLessThanOrEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareNotLessThanOrEqualScalarSingle();
var result = Sse.CompareNotLessThanOrEqualScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse.CompareNotLessThanOrEqualScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != (!(left[0] <= right[0]) ? -1 : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareNotLessThanOrEqualScalar)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Native;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
// ReSharper disable RedundantUsingDirective
using System.IO.Compression;
// ReSharper restore RedundantUsingDirective
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.Commands;
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
/// <summary>
/// DownloadManagerBase handles the interaction between CA and the Powershell download managers.
/// </summary>
public static class DownloadManagerBase
{
#region PLUGIN_CONSTANTS
// Cmdlets
private const string DownloadManagerGetConfiguration = "Get-DscDocument";
private const string DownloadManagerGetModules = "Get-DscModule";
private const string DownloadManagerGetAction = "Get-DscAction";
private const string WebDownloadManagerName = "WebDownloadManager";
private const string WebDownloadManagerLoadPath = "PSDesiredStateConfiguration\\WebDownloadManager";
private const string FileDownloadManagerName = "DSCFileDownloadManager";
private const string FileDownloadManagerLoadPath = "PSDesiredStateConfiguration\\DownloadManager\\DSCFileDownloadManager";
private static readonly Dictionary<string, string> DownloadManagerMap;
// PS DSC module cmdlets
private const string PsDscCmdletGet = "Get-TargetResource";
private const string PsDscCmdletSet = "Set-TargetResource";
private const string PsDscCmdletTest = "Test-TargetResource";
private const string BaseResourceClass = "OMI_BaseResource";
// Parameters
private const string ParamCredential = "Credential";
private const string ParamCredentialUserName = "UserName";
private const string ParamCredentialPassword = "Password";
private const string ParamCredentialDomain = "Domain";
private const string ParamConfigurationId = "ConfigurationID";
private const string ParamDestinationPath = "DestinationPath";
private const string ParamModules = "Module";
private const string ParamFileHash = "FileHash";
private const string ParamStatusCode = "StatusCode";
private const string ParamNotCompliant = "NotCompliant";
//Meta Config
private const string MetaConfigConfigurationId = "ConfigurationID";
private const string UseSystemUUIDValue = "UseSystemUUID";
private const string MetaConfigDownloadManagerName = "DownloadManagerName";
private const string MetaConfigDownloadManagerCustomData = "DownloadManagerCustomData"; //This is array of MSFT_KeyValuePair.
//static readonly string MetaConfig_Credential = "Credential";
private const string MetaConfigAllowModuleOverwrite = "AllowModuleOverwrite";
// Infrastructure defaults
private const int SchemaValidationOption = 4; //Ignore
//static readonly string BASE_RESOURCE_CLASSNAME = "OMI_BaseResource";
private const string BaseDocumentClassname = "OMI_ConfigurationDocument";
static readonly string[] NativeModules = { "MSFT_FileDirectoryConfiguration" };
// status result
private const string StatusOk = "OK";
private const string StatusGetMof = "GETCONFIGURATION";
private const string StatusRetry = "RETRY";
private const string WriteQualifier = "write";
#endregion PLUGIN_CONSTANTS
#region PLUGIN_STATE
//This is initialized only once and cached until process is unloaded.
// ReSharper disable FieldCanBeMadeReadOnly.Local
static private Runspace _pluginRunspace;
static private Runspace _validationRunspace;
// ReSharper restore FieldCanBeMadeReadOnly.Local
static private readonly bool PluginRunspaceInitialized;
static private string _pluginModuleName;
/// <summary>
/// Enumeration for Get Action Status Code
/// </summary>
internal enum GetActionStatusCodeTypes
{
Success = 0,
DownloadManagerInitializationFailure = 1,
GetConfigurationCommandFailure = 2,
UnexpectedGetConfigurationResponseFromServer = 3,
ConfigurationChecksumFileReadFailure = 4,
ConfigurationChecksumValidationFailure = 5,
InvalidConfigurationFile = 6,
AvailableModulesCheckFailure = 7,
InvalidConfigurationIdInMetaConfig = 8,
InvalidDownloadManagerCustomDataInMetaConfig = 9,
GetDscModuleCommandFailure = 10,
GetDscModuleInvalidOutput = 11,
ModuleChecksumFileNotFound = 12,
InvalidModuleFile = 13,
ModuleChecksumValidationFailure = 14,
ModuleExtractionFailure = 15,
ModuleValidationFailure = 16,
InvalidDownloadedModule = 17,
ConfigurationFileNotFound = 18,
MultipleConfigurationFilesFound = 19,
ConfigurationChecksumFileNotFound = 20,
ModuleNotFound = 21,
InvalidModuleVersionFormat = 22,
InvalidConfigurationIdFormat = 23,
GetDscActionCommandFailure = 24,
InvalidChecksumAlgorithm = 25,
};
#endregion PLUGIN_STATE
#region PLUGIN_CONSTRUCTORS
static DownloadManagerBase()
{
DownloadManagerMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
DownloadManagerMap.Add(WebDownloadManagerName, WebDownloadManagerLoadPath);
DownloadManagerMap.Add(FileDownloadManagerName, FileDownloadManagerLoadPath);
_pluginRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2());
_pluginRunspace.Open();
_validationRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2());
_validationRunspace.Open();
PluginRunspaceInitialized = false;
}
#endregion PLUGIN_CONSTRUCTORS
#region PLUGIN_GETCONFIGURATION
/*If this succeeds, the first object in the collection is a valid object.*/
private static MiResult ValidateGetConfigurationResult(System.Management.Automation.PowerShell powershell, Collection<PSObject> providerImportResult,
string downloadManagerName, out string importModuleResult, out ErrorRecord errorRecord,
out UInt32 getActionStatusCode)
{
var result = ValidateGetResult(powershell, providerImportResult, downloadManagerName, out importModuleResult,
out errorRecord, out getActionStatusCode);
if (result != MiResult.OK)
{
return result;
}
if (!(string.Compare(importModuleResult, StatusOk, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(importModuleResult, StatusRetry, StringComparison.OrdinalIgnoreCase) == 0))
{
errorRecord = GetErrorRecord("PsPluginManagerGetConfUnexpectedResult", ErrorCategory.InvalidResult,
PSinfrastructureStrings.PsPluginManagerGetConfUnexpectedResult, importModuleResult, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.UnexpectedGetConfigurationResponseFromServer;
return MiResult.FAILED;
}
return result;
}
/*If this succeeds, the first object in the collection is a valid object.*/
private static MiResult ValidateGetResult(System.Management.Automation.PowerShell powershell, Collection<PSObject> providerImportResult,
string downloadManagerName, out string importModuleResult, out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
importModuleResult = null;
HandleNonTerminatingErrors(powershell, downloadManagerName, DownloadManagerGetConfiguration, out errorRecord);
if (errorRecord != null)
{
getActionStatusCode = (int) GetActionStatusCodeTypes.GetConfigurationCommandFailure;
return MiResult.FAILED;
}
if (providerImportResult == null || providerImportResult.Count != 1)
{
errorRecord = GetErrorRecord("GetConfigurationResultNotExpected", ErrorCategory.ObjectNotFound,
PSinfrastructureStrings.GetConfigurationResultCountUnexpected, downloadManagerName);
getActionStatusCode = (int)GetActionStatusCodeTypes.GetConfigurationCommandFailure;
return MiResult.NOT_FOUND;
}
try
{
importModuleResult = LanguagePrimitives.ConvertTo<string>(providerImportResult[0]);
}
catch (PSInvalidCastException ex)
{
errorRecord = GetErrorRecord("GetConfigurationResultNotExpected", ex, ErrorCategory.InvalidType,
PSinfrastructureStrings.GetConfigurationResultCountUnexpected, downloadManagerName);
getActionStatusCode = (int)GetActionStatusCodeTypes.GetConfigurationCommandFailure;
return MiResult.NOT_FOUND;
}
if (importModuleResult == null || string.IsNullOrEmpty(importModuleResult))
{
errorRecord = GetErrorRecord("GetConfigurationResultNotExpected", ErrorCategory.ObjectNotFound,
PSinfrastructureStrings.GetConfigurationResultCountUnexpected, downloadManagerName);
getActionStatusCode = (int)GetActionStatusCodeTypes.GetConfigurationCommandFailure;
return MiResult.NOT_FOUND;
}
getActionStatusCode = (int)GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
/*If this succeeds, the first object in the collection is a valid object.*/
private static MiResult ValidateGetActionResult(System.Management.Automation.PowerShell powershell, Collection<PSObject> providerImportResult,
string downloadManagerName, out string importModuleResult, out ErrorRecord errorRecord,
out UInt32 getActionStatusCode)
{
var result = ValidateGetResult(powershell, providerImportResult, downloadManagerName, out importModuleResult,
out errorRecord, out getActionStatusCode);
if (result != MiResult.OK)
{
return result;
}
if (!(string.Compare(importModuleResult, StatusOk, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(importModuleResult, StatusGetMof, StringComparison.OrdinalIgnoreCase) == 0))
{
errorRecord = GetErrorRecord("PluginGetActionUnsuccessful", ErrorCategory.InvalidResult,
PSinfrastructureStrings.PluginGetActionUnsuccessful, importModuleResult, _pluginModuleName);
return MiResult.FAILED;
}
return result;
}
#endregion PLUGIN_GETCONFIGURATION
#region PLUGIN_GETMODULE
/*If this succeeds, the first object in the collection is a valid object.*/
private static MiResult ValidateModuleForVersion(System.Management.Automation.PowerShell powershell,
IEnumerable<PSModuleInfo> availableModules,
string downloadManagerName,
string moduleVersion,
out bool isModuleAvailable,
out ErrorRecord errorRecord)
{
isModuleAvailable = false;
HandleNonTerminatingErrors(powershell, downloadManagerName, "Import-Module", out errorRecord);
if (errorRecord != null)
{
return MiResult.FAILED;
}
if (availableModules == null)
{
return MiResult.OK; // cached module not available.
}
// ReSharper disable LoopCanBeConvertedToQuery
foreach (PSModuleInfo localModule in availableModules)
// ReSharper restore LoopCanBeConvertedToQuery
{
if (string.IsNullOrEmpty(moduleVersion) ||
string.Compare(moduleVersion, localModule.Version.ToString(), StringComparison.OrdinalIgnoreCase) == 0)
{
// Module is a default module available in system cache.
S_DscCoreR.EventWriteLCMPullModuleSkippedAsModuleIsAvailable(S_DscCoreR.JobGuidString, localModule.Name, localModule.Version.ToString(), localModule.Path);
isModuleAvailable = true;
return MiResult.OK;
}
}
return MiResult.OK;
}
private static ModuleSpecification[] GetModuleSpecification(Dictionary<string, Tuple<string, List<string>>> moduleVersionTable)
{
List<ModuleSpecification> moduleSpecifications = new List<ModuleSpecification>();
foreach (var entry in moduleVersionTable)
{
if (string.IsNullOrEmpty(entry.Value.Item1))
{
moduleSpecifications.Add(new ModuleSpecification(entry.Key));
}
else
{
Hashtable h = new Hashtable(StringComparer.OrdinalIgnoreCase);
h.Add("ModuleName", entry.Key);
h.Add("ModuleVersion", entry.Value.Item1);
moduleSpecifications.Add(new ModuleSpecification(h));
}
}
return moduleSpecifications.ToArray();
}
private static MiResult GetGetModuleParams(IntPtr metaConfigHandle, out PSCredential pscredential,
Hashtable arguments, out string configurationId,
out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
//Get info from MetaConfig
MiResult statusCode = GetMetaConfigParams(metaConfigHandle, out pscredential, arguments, out configurationId, out errorRecord, out getActionStatusCode);
return statusCode;
}
private static MiResult GetModuleNameVersionTable(string mofFileLocation, Dictionary<string, Tuple<string, List<string>>> moduleNameTable, out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
Debug.Assert(moduleNameTable != null, "moduleNameTable can not be null");
//Load the mof file.
errorRecord = null;
List<CimInstance> cimInstances;
try
{
CimClassCache.InitializeInfraStructureMof();
cimInstances = CimClassCache.ImportInstances(mofFileLocation, SchemaValidationOption);
}
catch (CimException exception)
{
errorRecord = GetErrorRecord("ConfigurationFileInvalid", ErrorCategory.InvalidResult,
PSinfrastructureStrings.ConfigurationFileInvalid, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.InvalidConfigurationFile;
return (MiResult)exception.StatusCode;
}
foreach (var inst in cimInstances)
{
string moduleName = inst.CimSystemProperties.ClassName;
string moduleVersion = "";
string providerClassName = inst.CimSystemProperties.ClassName;
// check for resource class and get module Name and Version
if (string.Compare(inst.CimSystemProperties.ClassName, BaseDocumentClassname, StringComparison.OrdinalIgnoreCase) != 0)
{
if (inst.CimInstanceProperties["ModuleName"] != null && inst.CimInstanceProperties["ModuleName"].Value != null)
{
moduleName = inst.CimInstanceProperties["ModuleName"].Value.ToString();
}
if (inst.CimInstanceProperties["ModuleVersion"] != null && inst.CimInstanceProperties["ModuleVersion"].Value != null)
{
moduleVersion = inst.CimInstanceProperties["ModuleVersion"].Value.ToString();
}
if (!string.IsNullOrEmpty(moduleName) && (string.IsNullOrEmpty(moduleVersion) || IsModuleVersionValidFormat(moduleVersion)))
{
Tuple<string, List<string>> moduleEntry;
if (moduleNameTable.ContainsKey(moduleName))
{
moduleEntry = moduleNameTable[moduleName];
if (!moduleEntry.Item2.Contains(providerClassName))
{
moduleEntry.Item2.Add(providerClassName);
}
}
else
{
moduleEntry = new Tuple<string, List<string>>(moduleVersion, new List<string>());
moduleEntry.Item2.Add(providerClassName);
moduleNameTable[moduleName] = moduleEntry;
}
}
else
{
getActionStatusCode = (int) GetActionStatusCodeTypes.InvalidModuleVersionFormat;
S_DscCoreR.EventWriteLCMPullModuleInvalidVersionFormat(S_DscCoreR.JobGuidString, moduleName, moduleVersion);
errorRecord = GetErrorRecord("InvalidModuleVersionFormat", null, ErrorCategory.InvalidArgument, PSinfrastructureStrings.InvalidModuleVersionFormat, moduleVersion, moduleName);
return MiResult.INVALID_PARAMETER;
}
}
}
// check with cached modules and remove them from the list.
return FilterUsingCachedModules(moduleNameTable, out errorRecord, out getActionStatusCode);
}
private static bool IsModuleVersionValidFormat(string moduleVersion)
{
Version throwAwayVersion;
return Version.TryParse(moduleVersion, out throwAwayVersion);
}
private static MiResult FilterUsingCachedModules(Dictionary<string, Tuple<string, List<string>>> moduleNameTable, out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
errorRecord = null;
// if it is known Native Module, remove it from the list.
foreach (string nativeModule in NativeModules)
{
if (moduleNameTable.ContainsKey(nativeModule))
{
//remove it
moduleNameTable.Remove(nativeModule);
}
}
// Find if modules are present locally
var cachedModules = new List<string>();
foreach (var entry in moduleNameTable)
{
// Find if modules are present as internal DSC module
var corePsProvidersModuleRelativePath = Path.Combine(Constants.CorePsProvidersRelativePath, entry.Key);
var corePsProvidersModulePath = Path.Combine(Environment.SystemDirectory, corePsProvidersModuleRelativePath);
if (Directory.Exists(corePsProvidersModulePath))
{
S_DscCoreR.EventWriteLCMPullModuleSkippedAsModuleIsAvailable(S_DscCoreR.JobGuidString, entry.Key, entry.Value.Item1, corePsProvidersModulePath);
cachedModules.Add(entry.Key);
continue;
}
System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create();
powershell.Runspace = _pluginRunspace;
Collection<PSModuleInfo> availableModules;
try
{
// check if the module exists.
powershell.AddCommand("Get-Module").AddParameter("Name", entry.Key).AddParameter("ListAvailable");
powershell.Streams.Error.Clear();
availableModules = powershell.Invoke<PSModuleInfo>();
if (powershell.Streams.Error.Count > 0)
{
errorRecord = GetErrorRecord("GetModuleListAvailableError", ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetModuleListAvailableError, entry.Key);
powershell.Dispose();
getActionStatusCode = (int)GetActionStatusCodeTypes.AvailableModulesCheckFailure;
return MiResult.FAILED;
}
}
catch (Exception ex)
{
errorRecord = GetErrorRecord("GetModuleListAvailableError", ex, ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetModuleListAvailableError, entry.Key);
getActionStatusCode = (int)GetActionStatusCodeTypes.AvailableModulesCheckFailure;
return MiResult.FAILED;
}
bool isModuleAvailable;
var statusCode = ValidateModuleForVersion(powershell, availableModules, entry.Key, entry.Value.Item1, out isModuleAvailable, out errorRecord);
powershell.Dispose();
if (statusCode != MiResult.OK)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.AvailableModulesCheckFailure;
return statusCode;
}
if (isModuleAvailable)
{
cachedModules.Add(entry.Key);
}
}
// Remove the cached item from the list so we don't need to pull those
foreach (var cachedModule in cachedModules)
{
moduleNameTable.Remove(cachedModule);
}
getActionStatusCode = (int)GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
private static MiResult ValidatePsdscModule(string moduleName, string schemaFileName, out UInt32 getActionStatusCode, out ErrorRecord errorRecord)
{
errorRecord = null;
CimClassCache.InitializeInfraStructureMof();
List<CimClass> newCimClasses;
PSModuleInfo moduleInfo;
if (!File.Exists(schemaFileName))
{
getActionStatusCode = (int) GetActionStatusCodeTypes.ModuleValidationFailure;
errorRecord = Utility.CreateErrorRecord(
"ProviderSchemaFileNotFound",
ErrorCategory.ObjectNotFound,
null,
PSinfrastructureStrings.SchemaFileNotFound,
new object[] { moduleName, schemaFileName });
return MiResult.NOT_FOUND;
}
try
{
newCimClasses = CimClassCache.ImportClasses(schemaFileName);
// Get Module Info by importing module.
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.Runspace = _validationRunspace;
moduleInfo = ps.AddCommand("Import-Module").AddParameter("Name", moduleName).AddParameter("Force", true).AddParameter("PassThru", true).Invoke<PSModuleInfo>().FirstOrDefault();
_validationRunspace.ResetRunspaceState();
}
}
catch (Exception e)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.ModuleValidationFailure;
errorRecord = GetErrorRecord(
"InvalidModuleOrSchema",
e,
ErrorCategory.InvalidOperation,
PSinfrastructureStrings.InvalidModuleFileOrMOF, moduleName, schemaFileName);
return MiResult.NOT_FOUND;
}
if (moduleInfo == null)
{
errorRecord = GetErrorRecord(
"CannotLoadModuleFileForValidation",
null,
ErrorCategory.InvalidOperation,
PSinfrastructureStrings.MissingModuleFileForValidation, moduleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.ModuleValidationFailure;
return MiResult.NO_SUCH_PROPERTY;
}
// Validate schema.
var resourceClass = newCimClasses.FirstOrDefault(
cimClass => cimClass.CimSuperClassName != null &&
string.Compare(cimClass.CimSuperClassName, BaseResourceClass, StringComparison.OrdinalIgnoreCase) == 0);
if (resourceClass == null)
{
errorRecord = GetErrorRecord(
"InvalidModuleMissingSchemaClass",
null,
ErrorCategory.InvalidOperation,
PSinfrastructureStrings.InvalidModuleMissingSchemaClass, moduleName, schemaFileName);
getActionStatusCode = (int)GetActionStatusCodeTypes.ModuleValidationFailure;
return MiResult.NOT_FOUND;
}
// Validate required exported commands.
CommandInfo exportedCommand;
if (!moduleInfo.ExportedCommands.TryGetValue(PsDscCmdletGet, out exportedCommand))
{
errorRecord = GetErrorRecord(
"InvalidModuleMissingCommand",
null,
ErrorCategory.InvalidOperation,
PSinfrastructureStrings.InvalidModuleMissingCommand, moduleName, PsDscCmdletGet);
getActionStatusCode = (int)GetActionStatusCodeTypes.ModuleValidationFailure;
return MiResult.NO_SUCH_PROPERTY;
}
if (!moduleInfo.ExportedCommands.TryGetValue(PsDscCmdletSet, out exportedCommand))
{
errorRecord = GetErrorRecord(
"InvalidModuleMissingCommand",
null,
ErrorCategory.InvalidOperation,
PSinfrastructureStrings.InvalidModuleMissingCommand, moduleName, PsDscCmdletSet);
getActionStatusCode = (int)GetActionStatusCodeTypes.ModuleValidationFailure;
return MiResult.NO_SUCH_PROPERTY;
}
if (!moduleInfo.ExportedCommands.TryGetValue(PsDscCmdletTest, out exportedCommand))
{
errorRecord = GetErrorRecord(
"InvalidModuleMissingCommand",
null,
ErrorCategory.InvalidOperation,
PSinfrastructureStrings.InvalidModuleMissingCommand, moduleName, PsDscCmdletTest);
getActionStatusCode = (int)GetActionStatusCodeTypes.ModuleValidationFailure;
return MiResult.NO_SUCH_PROPERTY;
}
// Validate required exported command parameters.
return ValidateExportedCommandParameters(resourceClass, moduleInfo, out getActionStatusCode, out errorRecord);
}
private static MiResult ValidateExportedCommandParameters(
CimClass resourceClass,
PSModuleInfo moduleInfo,
out UInt32 getActionStatusCode,
out ErrorRecord errorRecord)
{
// Get key and write parameter data from MOF schema.
List<CimPropertyDeclaration> keyProperties;
List<CimPropertyDeclaration> writeProperties;
List<CimPropertyDeclaration> requiredProperties;
Utility.GetKeyWriteRequiredProperties(resourceClass, out keyProperties, out writeProperties, out requiredProperties);
// Validate Get command against key parameters.
string moduleName = moduleInfo.Name;
CommandInfo cmdInfo = moduleInfo.ExportedCommands[PsDscCmdletGet];
MiResult result = ValidateCommandParameters(cmdInfo, keyProperties, moduleName, out getActionStatusCode, out errorRecord);
if (result != MiResult.OK) { return result; }
// Validate Set command against key and write parameters.
cmdInfo = moduleInfo.ExportedCommands[PsDscCmdletSet];
result = ValidateCommandParameters(cmdInfo, keyProperties, moduleName, out getActionStatusCode, out errorRecord);
if (result != MiResult.OK) { return result; }
result = ValidateCommandParameters(cmdInfo, writeProperties, moduleName, out getActionStatusCode, out errorRecord);
if (result != MiResult.OK) { return result; }
// Validate Test command against key and write parameters.
cmdInfo = moduleInfo.ExportedCommands[PsDscCmdletTest];
result = ValidateCommandParameters(cmdInfo, keyProperties, moduleName, out getActionStatusCode, out errorRecord);
if (result != MiResult.OK) { return result; }
return ValidateCommandParameters(cmdInfo, writeProperties, moduleName, out getActionStatusCode, out errorRecord);
}
private static MiResult ValidateCommandParameters(
CommandInfo cmdInfo,
List<CimPropertyDeclaration> keyOrWriteProperties,
string moduleName,
out UInt32 getActionStatusCode,
out ErrorRecord errorRecord)
{
errorRecord = null;
foreach (var currentKeyOrWriteProperty in keyOrWriteProperties)
{
if (!cmdInfo.Parameters.ContainsKey(currentKeyOrWriteProperty.Name))
{
errorRecord = GetErrorRecord(
"KeyParameterNotImplemented",
null,
ErrorCategory.InvalidOperation,
PSinfrastructureStrings.MismatchedPsModuleCommandParameterWithSchema, moduleName, cmdInfo.Name, currentKeyOrWriteProperty.Name);
getActionStatusCode = (uint) GetActionStatusCodeTypes.ModuleValidationFailure;
return MiResult.INVALID_PARAMETER;
}
}
getActionStatusCode = (uint) GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
private static MiResult ValidateModuleWithChecksum(string moduleFileName, string checksumFileName,
out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
errorRecord = null;
// Read mof file content and get the checksum.
byte[] moduleContent;
byte[] checkSumContent;
try
{
using (var fs = File.OpenRead(moduleFileName))
{
moduleContent = new byte[fs.Length];
fs.Read(moduleContent, 0, Convert.ToInt32(fs.Length));
fs.Close();
}
using (var fs = File.OpenRead(checksumFileName))
{
checkSumContent = new byte[fs.Length];
fs.Read(checkSumContent, 0, Convert.ToInt32(fs.Length));
fs.Close();
}
}
catch (Exception exception)
{
errorRecord = GetErrorRecord("ModuleFileInvalid", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.ModuleFileInvalid, moduleFileName, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.InvalidModuleFile;
return MiResult.FAILED;
}
//Compute checksum of mof file.
var sha = new SHA256Managed();
byte[] computedHash = sha.ComputeHash(moduleContent);
var hashStringFromMof = BitConverter.ToString(computedHash).Replace("-", "");
var hashStringFromChecksum = System.Text.Encoding.Default.GetString(checkSumContent);
if (string.Compare(hashStringFromMof, hashStringFromChecksum, StringComparison.OrdinalIgnoreCase) != 0)
{
errorRecord = GetErrorRecord("ChecksumValidationModuleFailed", ErrorCategory.InvalidResult,
PSinfrastructureStrings.ChecksumValidationModuleFailed, moduleFileName, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.ModuleChecksumValidationFailure;
return MiResult.FAILED;
}
getActionStatusCode = (int) GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
private static MiResult ValidateMofWithChecksum(string mofFileName, string checksumFileName,
out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
errorRecord = null;
// Read mof file content and get the checksum.
byte[] mofContent;
byte[] checkSumContent;
try
{
using (var fs = File.OpenRead(mofFileName))
{
mofContent = new byte[fs.Length];
fs.Read(mofContent, 0, Convert.ToInt32(fs.Length));
fs.Close();
}
using (var fs = File.OpenRead(checksumFileName))
{
checkSumContent = new byte[fs.Length];
fs.Read(checkSumContent, 0, Convert.ToInt32(fs.Length));
fs.Close();
}
}
catch (Exception exception)
{
errorRecord = GetErrorRecord("ConfigurationFileInvalid", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.ConfigurationFileInvalid, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.ConfigurationChecksumFileReadFailure;
return MiResult.FAILED;
}
//Compute checksum of mof file.
var sha = new SHA256Managed();
byte[] computedHash = sha.ComputeHash(mofContent);
var hashStringFromMof = BitConverter.ToString(computedHash).Replace("-", "");
var hashStringFromChecksum = System.Text.Encoding.Default.GetString(checkSumContent);
if (string.Compare(hashStringFromMof, hashStringFromChecksum, StringComparison.OrdinalIgnoreCase) != 0)
{
errorRecord = GetErrorRecord("ChecksumValidationConfigurationFailed", ErrorCategory.InvalidResult,
PSinfrastructureStrings.ChecksumValidationConfigurationFailed, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.ConfigurationChecksumValidationFailure;
return MiResult.FAILED;
}
getActionStatusCode = (int) GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
private static MiResult ValidateConfigurationChecksum(string downloadLocation,
out string mofFileName, out ErrorRecord errorRecord,
out UInt32 getActionStatusCode)
{
mofFileName = null;
// DownloadLocation contain .mof file and .mof.checksum file.
// We will fail if both the files are not available.
string mofFileLocation = null;
try
{
string[] mofFiles = Directory.GetFiles(downloadLocation, "*.mof");
if (mofFiles.Length == 0)
{
errorRecord = GetErrorRecord("ConfigurationFileNotExist", ErrorCategory.InvalidResult,
PSinfrastructureStrings.ConfigurationFileNotExist, _pluginModuleName);
getActionStatusCode = (int) GetActionStatusCodeTypes.ConfigurationFileNotFound;
return MiResult.NOT_FOUND;
}
if (mofFiles.Length > 1)
{
errorRecord = GetErrorRecord("ConfigurationFileMultipleExist", ErrorCategory.InvalidResult,
PSinfrastructureStrings.ConfigurationFileMultipleExist, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.MultipleConfigurationFilesFound;
return MiResult.FAILED;
}
mofFileLocation = mofFiles[0];
//get the checksum now.
if (!File.Exists(mofFiles[0] + ".checksum"))
{
errorRecord = GetErrorRecord("ConfigurationChecksumFileNotExist", ErrorCategory.InvalidResult,
PSinfrastructureStrings.ConfigurationChecksumFileNotExist, _pluginModuleName, mofFileLocation);
getActionStatusCode = (int)GetActionStatusCodeTypes.ConfigurationChecksumFileNotFound;
return MiResult.NOT_FOUND;
}
//compute checksum
MiResult statusCode = ValidateMofWithChecksum(mofFileLocation, mofFiles[0] + ".checksum", out errorRecord, out getActionStatusCode);
S_DscCoreR.EventWriteLCMPullConfigurationChecksumValidationResult(S_DscCoreR.JobGuidString, mofFileLocation, (uint)statusCode);
if (statusCode != MiResult.OK)
{
return statusCode;
}
}
catch (Exception ex)
{
errorRecord = GetErrorRecord("ConfigurationFileGenericFailure", ex, ErrorCategory.InvalidResult,
PSinfrastructureStrings.ConfigurationFileGenericFailure, _pluginModuleName);
getActionStatusCode = (int) GetActionStatusCodeTypes.ConfigurationChecksumValidationFailure;
return MiResult.FAILED;
}
mofFileName = mofFileLocation;
return MiResult.OK;
}
private static MiResult InstallModules(IntPtr metaConfigHandle, string downloadLocation, string mofFileName, bool allowModuleOverwrite, out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
// Get module Names with Version and required resource names
var moduleNameVersionTable = new Dictionary<string, Tuple<string, List<string>>>();
MiResult statusCode = GetModuleNameVersionTable(mofFileName, moduleNameVersionTable, out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
return statusCode;
}
if (moduleNameVersionTable.Count == 0)
{
S_DscCoreR.EventWriteLCMPullModuleSkippedAsAllModulesAreAvailable(S_DscCoreR.JobGuidString, mofFileName);
return MiResult.OK;
}
string configurationId;
// This holds the download manager specific properties - ServerUrl, SourcePath, etc.
Hashtable arguments;
// We use this collection to hold the PSObjects that we create from arguments. We pass this down to the download manager cmdlets (The parameters have ValueFromPipelineByPropertyName specified)
Collection<PSObject> argumentParameters;
ModuleSpecification[] moduleSpecifications;
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(InitialSessionState.CreateDefault2()))
{
PSCommand powershellCommand;
statusCode = DoInitializationForGetModule(metaConfigHandle, moduleNameVersionTable, downloadLocation,
out configurationId, out moduleSpecifications, powershell,
out powershellCommand, out arguments, out argumentParameters,
out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
return statusCode;
}
for (int i = 0; i < moduleNameVersionTable.Count; i++)
{
string downloadedModule;
Collection<PSObject> pullOneModuleResult;
powershell.Commands.Clear();
powershell.Commands = powershellCommand;
powershell.Streams.Error.Clear();
statusCode = PullOneModule(powershell, moduleSpecifications[i], configurationId, downloadLocation,
arguments, argumentParameters, out downloadedModule,
out pullOneModuleResult, out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
return statusCode;
}
// This validation is maybe not necessary.
// This validation checks if the module that we got from the Pull Server is what we asked for
// This used to make sense when we were downloading a bunch of modules.
// TODO : Remove this
statusCode = ValidateForExpectedModule(powershell, pullOneModuleResult, moduleNameVersionTable,
out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
return statusCode;
}
var moduleSpecification = moduleSpecifications[i];
statusCode = ValidateAndInstallOneModule(downloadLocation, moduleSpecification,
moduleNameVersionTable[moduleSpecification.Name].Item2, allowModuleOverwrite,
out errorRecord, out getActionStatusCode);
if (statusCode != (UInt32)MiResult.OK)
{
return statusCode;
}
}
}
// Log to ETW Channel:Microsoft-Windows-DSC/Operational
S_DscCoreR.EventWriteLCMPullGetModuleSuccess(S_DscCoreR.JobGuidString, _pluginModuleName);
return MiResult.OK;
}
// Does the initialization for Get-DscModule. This initialization needs to only happen once for all the modules.
// As part of this initialization, the following is done
// 1) Download manager is imported
// 2) Configuration is parsed to get the list of modules and the download-manager specific properties
// 3) For the download manager specific properties, we create PSObjects so we can pass those down to the download manager cmdlets.
// 4) We construct a PowerShell that has all the parameters added (except for the Module parameter. This parameter gets added for each module)
private static MiResult DoInitializationForGetModule(IntPtr metaConfigHandle, Dictionary<string, Tuple<string, List<string>>> moduleNameVersionTable,
string downloadLocation, out string configurationId, out ModuleSpecification[] moduleSpecifications,
System.Management.Automation.PowerShell powershell, out PSCommand powershellCommand, out Hashtable arguments, out Collection<PSObject> argumentParameters,
out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
configurationId = null;
powershellCommand = null;
moduleSpecifications = null;
argumentParameters = null;
arguments = new Hashtable();
// Initialize DownloadManager
MiResult statusCode = InitializePlugin(metaConfigHandle, out errorRecord);
if (statusCode != MiResult.OK)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.DownloadManagerInitializationFailure;
return statusCode;
}
//Get parameters for Get-Module cmdlet
PSCredential pscredential;
statusCode = GetGetModuleParams(metaConfigHandle, out pscredential, arguments, out configurationId, out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
return statusCode;
}
moduleSpecifications = GetModuleSpecification(moduleNameVersionTable);
powershell.Runspace = _pluginRunspace;
if (arguments.Count > 0)
{
argumentParameters = powershell.AddCommand("New-Object").AddParameter("Type", "psobject").AddParameter("Property", arguments).Invoke();
powershell.Commands.Clear();
}
powershellCommand = new PSCommand();
powershellCommand.AddCommand(_pluginModuleName + "\\" + DownloadManagerGetModules);
powershellCommand.AddParameter(ParamConfigurationId, configurationId);
powershellCommand.AddParameter(ParamDestinationPath, downloadLocation);
if (pscredential != null)
{
powershellCommand.AddParameter(ParamCredential, pscredential);
}
return MiResult.OK;
}
// Powershell object passed here will be disposed off by the caller
private static MiResult PullOneModule(System.Management.Automation.PowerShell powershell, ModuleSpecification moduleSpecification, string configurationId, string downloadLocation,
Hashtable arguments, Collection<PSObject> argumentParameters, out string downloadedModule, out Collection<PSObject> pullOneModuleResult,
out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
pullOneModuleResult = null;
downloadedModule = null;
string moduleVersionString = GetModuleVersionStringFromModuleSpecification(moduleSpecification);
try
{
powershell.AddParameter(ParamModules, moduleSpecification);
// Log to ETW Channel:Microsoft-Windows-DSC/Operational
S_DscCoreR.EventWriteLCMPullGetModuleAttempt(S_DscCoreR.JobGuidString, _pluginModuleName, configurationId, moduleVersionString);
powershell.Streams.Error.Clear();
pullOneModuleResult = arguments.Count > 0 ? powershell.Invoke(argumentParameters) : powershell.Invoke();
if (powershell.Streams.Error.Count > 0)
{
errorRecord = powershell.Streams.Error[0];
powershell.Dispose();
if( string.Compare(errorRecord.FullyQualifiedErrorId, "WebDownloadManagerUnknownChecksumAlgorithm", StringComparison.OrdinalIgnoreCase) == 0 )
{
getActionStatusCode = (int)GetActionStatusCodeTypes.InvalidChecksumAlgorithm;
}
else
{
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscModuleCommandFailure;
}
return MiResult.FAILED;
}
}
catch (Exception ex)
{
errorRecord = GetErrorRecord("GetModuleExecutionFailure", ex, ErrorCategory.InvalidType,
PSinfrastructureStrings.GetModuleExecutionFailure, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscModuleCommandFailure;
return MiResult.FAILED;
}
S_DscCoreR.EventWriteLCMPullModuleDownloadLocation(S_DscCoreR.JobGuidString, moduleVersionString, downloadLocation);
errorRecord = null;
getActionStatusCode = (int)GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
// Validates that the module we have is the module we asked for from the Pull Server
// This validation is maybe not necessary.
// This used to make sense when we were downloading a bunch of modules.
// TODO : Remove this
private static MiResult ValidateForExpectedModule(System.Management.Automation.PowerShell powershell, Collection<PSObject> pullOneModuleResult,
Dictionary<string, Tuple<string, List<string>>> moduleNameVersionTable,
out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
ModuleSpecification[] pullOneModuleInternalResult;
HandleNonTerminatingErrors(powershell, _pluginModuleName, DownloadManagerGetConfiguration, out errorRecord);
if (errorRecord != null)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscModuleCommandFailure;
return MiResult.FAILED;
}
if (pullOneModuleResult == null || pullOneModuleResult.Count == 0)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscModuleCommandFailure;
errorRecord = GetErrorRecord("GetModuleResultNotExpected", ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetModuleResultCountUnexpected, _pluginModuleName);
return MiResult.NOT_FOUND;
}
try
{
pullOneModuleInternalResult = LanguagePrimitives.ConvertTo<ModuleSpecification[]>(pullOneModuleResult);
}
catch (PSInvalidCastException ex)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscModuleInvalidOutput;
errorRecord = GetErrorRecord("GetModuleResultNotExpected", ex, ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetModuleResultCountUnexpected, _pluginModuleName);
return MiResult.NOT_FOUND;
}
// We are always downloading only one module at at a time
if (pullOneModuleInternalResult == null || pullOneModuleInternalResult.Count() > 1)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscModuleInvalidOutput;
errorRecord = GetErrorRecord("GetModuleResultNotExpected", ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetModuleResultCountUnexpected, _pluginModuleName);
return MiResult.NOT_FOUND;
}
if (!moduleNameVersionTable.ContainsKey(pullOneModuleInternalResult[0].Name))
{
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscModuleInvalidOutput;
errorRecord = GetErrorRecord("GetModuleResultNotExpected", ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetModuleResultCountUnexpected, _pluginModuleName);
return MiResult.NO_SUCH_PROPERTY;
}
getActionStatusCode = (int)GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
private static MiResult ValidateAndInstallOneModule(string downloadLocation, ModuleSpecification moduleSpecification,
IEnumerable<string> requiredResources,
bool allowModuleOverwrite, out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
// Powershell modules are not supported by Linux DSC.
return MiResult.NOT_SUPPORTED;
}
#endregion PLUGIN_GETMODULE
#region PLUGIN_COMMONHELPERS
private static string GetModuleVersionStringFromModuleSpecification(ModuleSpecification moduleSpecification)
{
StringBuilder result = new StringBuilder();
result.Append("(").Append(moduleSpecification.Name);
if (moduleSpecification.Version != null)
{
result.Append(",").Append(moduleSpecification.Version).Append(")");
}
else
{
result.Append(")");
}
return result.ToString();
}
internal static ErrorRecord GetErrorRecord(string errorId, ErrorCategory errorCategory, string errorResourceId, params object[] errorResourceIdParams)
{
return Utility.CreateErrorRecord(errorId, errorCategory, null, errorResourceId, errorResourceIdParams);
}
internal static ErrorRecord GetErrorRecord(string errorId, Exception exception, ErrorCategory errorCategory, string errorResourceId, params object[] errorResourceIdParams)
{
return Utility.CreateErrorRecord(errorId, errorCategory, exception, errorResourceId, errorResourceIdParams);
}
// ReSharper disable UnusedMember.Local
private static string GetPsProgramFilesModulePath()
// ReSharper restore UnusedMember.Local
{
//return @"c:\Program Files\Microsoft\Windows\Powershell\Modules\";
return Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\WindowsPowerShell\Modules\";
}
private static void HandleNonTerminatingErrors(System.Management.Automation.PowerShell powerShell,
string providerName,
string operationCmd,
out ErrorRecord errorRecord)
{
errorRecord = null;
if (powerShell != null &&
powerShell.Streams != null &&
powerShell.Streams.Error != null &&
powerShell.Streams.Error.Count > 0 &&
!string.IsNullOrEmpty(providerName) &&
!string.IsNullOrEmpty(operationCmd))
{
string errorMessage = string.Format(
CultureInfo.CurrentCulture,
PSinfrastructureStrings.NonTerminatingErrorFromProvider,
providerName,
operationCmd);
InvalidOperationException invalidOperationException;
// If there is only one non-terminting error then the surface it's inner execetion (if it exists) to the commandline.
if (powerShell.Streams.Error.Count == 1 && powerShell.Streams.Error[0].Exception != null)
{
invalidOperationException = new InvalidOperationException(errorMessage, powerShell.Streams.Error[0].Exception);
}
else
{
invalidOperationException = new InvalidOperationException(errorMessage);
}
errorRecord = new ErrorRecord(
invalidOperationException,
"NonTerminatingErrorFromProvider",
ErrorCategory.InvalidOperation,
null);
}
}
private static string GetSystemUuid()
{
var cimSession = CimSession.Create("localhost");
var cimInstance = cimSession.EnumerateInstances(@"root/cimv2", "Win32_ComputerSystemProduct").First();
if (cimInstance.CimInstanceProperties["UUID"] != null)
{
return cimInstance.CimInstanceProperties["UUID"].Value.ToString();
}
return String.Empty;
}
private static MiResult GetAllowModuleOverwriteFromMetaConfig(IntPtr metaConfigHandle, out Boolean allowModuleOverwrite, out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
errorRecord = null;
allowModuleOverwrite = false;
var metaConfigInstance = new CimInstance(new InstanceHandle(metaConfigHandle, false), null);
if (metaConfigInstance.CimInstanceProperties[MetaConfigAllowModuleOverwrite] != null &&
metaConfigInstance.CimInstanceProperties[MetaConfigAllowModuleOverwrite].Value != null)
{
LanguagePrimitives.TryConvertTo(metaConfigInstance.CimInstanceProperties[MetaConfigAllowModuleOverwrite].Value, out allowModuleOverwrite);
}
getActionStatusCode = (int)GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
private static MiResult GetMetaConfigParams(IntPtr metaConfigHandle, out PSCredential pscredential, Hashtable arguments, out string configurationId, out ErrorRecord errorRecord, out UInt32 getActionStatusCode)
{
configurationId = null;
errorRecord = null;
pscredential = null;
var metaConfigInstance = new CimInstance(new InstanceHandle(metaConfigHandle, false), null);
// Get ConfigurationID.
try
{
if (metaConfigInstance.CimInstanceProperties[MetaConfigConfigurationId] != null &&
metaConfigInstance.CimInstanceProperties[MetaConfigConfigurationId].Value != null)
{
string tempConfigurationId = metaConfigInstance.CimInstanceProperties[MetaConfigConfigurationId].Value.ToString();
/* We will use System UUID only if user has explicitly asked for.*/
if (string.Compare(tempConfigurationId, UseSystemUUIDValue, StringComparison.OrdinalIgnoreCase) == 0)
{
tempConfigurationId = GetSystemUuid();
}
Guid throwAwayGuid = Guid.Empty;
if (Guid.TryParse(tempConfigurationId, out throwAwayGuid))
{
configurationId = tempConfigurationId;
}
else
{
getActionStatusCode = (int) GetActionStatusCodeTypes.InvalidConfigurationIdFormat;
errorRecord = GetErrorRecord("InvalidConfigurationIdFormat", null, ErrorCategory.InvalidArgument, PSinfrastructureStrings.InvalidConfigurationIdFormat, tempConfigurationId);
return MiResult.INVALID_PARAMETER;
}
}
else
{
getActionStatusCode = (int) GetActionStatusCodeTypes.InvalidConfigurationIdFormat;
errorRecord = GetErrorRecord("ConfigurationIdNotSpecified", null, ErrorCategory.InvalidArgument, PSinfrastructureStrings.ConfigurationIdNotSpecified);
return MiResult.INVALID_PARAMETER;
}
}
catch (CimException exception)
{
errorRecord = GetErrorRecord("MetaConfigConfigurationIdInvalid", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.MetaConfigConfigurationIdInvalid,
_pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.InvalidConfigurationIdInMetaConfig;
return (MiResult)exception.StatusCode;
}
//Get PS Credential
if (metaConfigInstance.CimInstanceProperties[ParamCredential] != null &&
metaConfigInstance.CimInstanceProperties[ParamCredential].Value != null)
{
string userName = null;
string password = null;
string domain = null;
var cimCredentialInstance = metaConfigInstance.CimInstanceProperties[ParamCredential].Value as CimInstance;
if (cimCredentialInstance != null)
{
if (cimCredentialInstance.CimInstanceProperties[ParamCredentialUserName] != null &&
cimCredentialInstance.CimInstanceProperties[ParamCredentialUserName].Value != null)
{
userName = cimCredentialInstance.CimInstanceProperties[ParamCredentialUserName].Value.ToString();
}
if (cimCredentialInstance.CimInstanceProperties[ParamCredentialPassword] != null &&
cimCredentialInstance.CimInstanceProperties[ParamCredentialPassword].Value != null)
{
password = cimCredentialInstance.CimInstanceProperties[ParamCredentialPassword].Value.ToString();
}
if (cimCredentialInstance.CimInstanceProperties[ParamCredentialDomain] != null &&
cimCredentialInstance.CimInstanceProperties[ParamCredentialDomain].Value != null)
{
domain = cimCredentialInstance.CimInstanceProperties[ParamCredentialDomain].Value.ToString();
}
if (userName != null &&
password != null)
{
// Extract the password into a SecureString.
var securePassword = new SecureString();
foreach (var t in password)
{
securePassword.AppendChar(t);
}
securePassword.MakeReadOnly();
if (!string.IsNullOrEmpty(domain))
{
userName = Path.Combine(domain, userName);
}
pscredential = new PSCredential(userName, securePassword);
}
}
}
// Get cmdlet arguments as hashtable.
try
{
if (metaConfigInstance.CimInstanceProperties[MetaConfigDownloadManagerCustomData] != null &&
metaConfigInstance.CimInstanceProperties[MetaConfigDownloadManagerCustomData].Value != null)
{
var cimInstances = metaConfigInstance.CimInstanceProperties[MetaConfigDownloadManagerCustomData].Value as CimInstance[];
if (cimInstances != null)
{
foreach (var inst in cimInstances)
{
arguments.Add(inst.CimInstanceProperties["Key"].Value.ToString(), inst.CimInstanceProperties["Value"].Value.ToString());
}
}
}
}
catch (CimException exception)
{
errorRecord = GetErrorRecord("MetaConfigCustomDataInvalid", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.MetaConfigCustomDataInvalid,
_pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.InvalidDownloadManagerCustomDataInMetaConfig;
return (MiResult)exception.StatusCode;
}
getActionStatusCode = (int) GetActionStatusCodeTypes.Success;
return MiResult.OK;
}
private static MiResult InitializePlugin(IntPtr metaConfigHandle, out ErrorRecord errorRecord)
{
errorRecord = null;
if (PluginRunspaceInitialized == false)
{
MiResult statusCode = ImportDownloadManager(metaConfigHandle, out errorRecord);
if (statusCode != MiResult.OK)
{
return statusCode;
}
}
return MiResult.OK;
}
private static MiResult ImportDownloadManager(IntPtr metaConfigHandle, out ErrorRecord errorRecord)
{
string downloadManagerName;
// Get Module Name
MiResult statusCode = GetDownloadManagerModuleName(metaConfigHandle, out downloadManagerName, out errorRecord);
if (statusCode != MiResult.OK)
{
return statusCode;
}
// if it is webDownloadManager, it is implemented inside PSDesiredStateConfiguration\WebDownloadManager.
// if it is FileDownloadManager, it is implemented inside PSDesiredStateConfiguration\DownloadManager\DSCFileDownloadManager.
string downloadManagerPath = GetDownloadManagerModuleLoadPath(downloadManagerName);
try
{
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
powershell.Runspace = _pluginRunspace;
// Load the module
powershell.Streams.Error.Clear();
powershell.AddCommand("Import-Module")
.AddParameter("Name", downloadManagerPath)
.AddParameter("PassThru", true)
.Invoke<PSModuleInfo>()
.FirstOrDefault();
if (powershell.Streams.Error.Count > 0)
{
errorRecord = GetErrorRecord("ImportDownloadManagerException", powershell.Streams.Error[0].Exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.ImportDownloadManagerException, _pluginModuleName);
return MiResult.FAILED;
}
}
}
catch (Exception exception)
{
errorRecord = GetErrorRecord("ImportDownloadManagerException", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.ImportDownloadManagerException, _pluginModuleName);
return MiResult.FAILED;
}
if (statusCode != MiResult.OK)
{
return statusCode;
}
_pluginModuleName = downloadManagerName;
return MiResult.OK;
}
private static string GetDownloadManagerModuleLoadPath(string downloadManagerName)
{
string downloadManagerLoadPath;
if (!DownloadManagerMap.TryGetValue(downloadManagerName, out downloadManagerLoadPath))
{
downloadManagerLoadPath = downloadManagerName;
}
return downloadManagerLoadPath;
}
private static MiResult GetDownloadManagerModuleName(IntPtr metaConfigHandle, out string downloadManagerName,
out ErrorRecord errorRecord)
{
downloadManagerName = null;
errorRecord = null;
var metaConfigInstance = new CimInstance(new InstanceHandle(metaConfigHandle, false), null);
try
{
if (metaConfigInstance.CimInstanceProperties[MetaConfigDownloadManagerName] != null &&
metaConfigInstance.CimInstanceProperties[MetaConfigDownloadManagerName].Value != null)
{
downloadManagerName = metaConfigInstance.CimInstanceProperties[MetaConfigDownloadManagerName].Value.ToString();
}
else
{
errorRecord = GetErrorRecord("MetaConfigDownloadManagerInvalid", ErrorCategory.InvalidResult,
PSinfrastructureStrings.MetaConfigDownloadManagerInvalid);
return MiResult.NOT_FOUND;
}
}
catch (CimException exception)
{
errorRecord = GetErrorRecord("MetaConfigDownloadManagerInvalid", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.MetaConfigDownloadManagerInvalid);
return (MiResult)exception.StatusCode;
}
return MiResult.OK;
}
#endregion PLUGIN_COMMONHELPERS
#region PLUGIN_PUBLICMETHODS
/// <summary>
/// Install API used to install the modules as necessary from the mof file..
/// </summary>
/// <param name="metaConfigHandle"></param>
/// <param name="downloadLocation"></param>
/// <param name="mofFileName"></param>
/// <param name="allowModuleOverwrite"></param>
/// <param name="errorInstanceHandle"></param>
/// <param name="getActionStatusCode"></param>
/// <returns>If InstallModules operation is successful, 0 is returned or else a status code indicating the error is returned.</returns>
public static UInt32 GetDscModule(IntPtr metaConfigHandle, string downloadLocation, string mofFileName, bool allowModuleOverwrite, out IntPtr errorInstanceHandle, out UInt32 getActionStatusCode)
{
ErrorRecord errorRecord;
errorInstanceHandle = IntPtr.Zero;
MiResult statusCode = InstallModules(metaConfigHandle, downloadLocation, mofFileName, allowModuleOverwrite, out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
return (uint)MiResult.OK;
}
/// <summary>
/// Get Api facilitates to execute Get-Configuration functionality on the provider mentioned in the meta configuration..
/// </summary>
/// <param name="metaConfigHandle"></param>
/// <param name="fileHash"></param>
/// <param name="complianceStatus"></param>
/// <param name="lastGetActionStatusCode"></param>
/// <param name="errorInstanceHandle"></param>
/// <param name="outputResult"></param>
/// <param name="getActionStatusCode"></param>
/// <returns>If GetDscAction operation is successful, 0 is returned or else a status code indicating the error is returned.</returns>
public static UInt32 GetDscAction(IntPtr metaConfigHandle, string fileHash, bool complianceStatus, UInt32 lastGetActionStatusCode, out IntPtr errorInstanceHandle, out string outputResult, out UInt32 getActionStatusCode)
{
ErrorRecord errorRecord;
errorInstanceHandle = IntPtr.Zero;
MiResult statusCode = InitializePlugin(metaConfigHandle, out errorRecord);
outputResult = null;
if (statusCode != MiResult.OK)
{
getActionStatusCode = (int) GetActionStatusCodeTypes.DownloadManagerInitializationFailure;
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
//Get parameters for Get-Status cmdlet
PSCredential pscredential;
var arguments = new Hashtable();
string configurationId;
statusCode = GetMetaConfigParams(metaConfigHandle, out pscredential, arguments, out configurationId, out errorRecord, out getActionStatusCode);
if (getActionStatusCode != (uint)GetActionStatusCodeTypes.Success)
{
lastGetActionStatusCode = getActionStatusCode;
}
if (statusCode != MiResult.OK)
{
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
System.Management.Automation.PowerShell powershell;
Collection<PSObject> providerResult;
//Create PowerShell object and invoke the command.
try
{
powershell = System.Management.Automation.PowerShell.Create();
powershell.Runspace = _pluginRunspace;
Collection<PSObject> argumentParameters = null;
if (arguments.Count > 0)
{
argumentParameters = powershell.AddCommand("New-Object").AddParameter("Type", "psobject").AddParameter("Property", arguments).Invoke();
powershell.Commands.Clear();
}
powershell.Commands.AddCommand(_pluginModuleName + "\\" + DownloadManagerGetAction);
powershell.AddParameter(ParamConfigurationId, configurationId);
powershell.AddParameter(ParamNotCompliant, !complianceStatus);
powershell.AddParameter(ParamFileHash, fileHash);
powershell.AddParameter(ParamStatusCode, lastGetActionStatusCode);
if (pscredential != null)
{
powershell.AddParameter(ParamCredential, pscredential);
}
// Log to ETW Channel:Microsoft-Windows-DSC/Operational
S_DscCoreR.EventWriteLCMPullGetActionAttempt(S_DscCoreR.JobGuidString,
_pluginModuleName, configurationId, fileHash, complianceStatus);
powershell.Streams.Error.Clear();
providerResult = arguments.Count > 0 ? powershell.Invoke(argumentParameters) : powershell.Invoke();
if (powershell.Streams.Error.Count > 0)
{
errorRecord = powershell.Streams.Error[0];
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)MiResult.FAILED, errorRecord);
powershell.Dispose();
getActionStatusCode = (int) GetActionStatusCodeTypes.GetDscActionCommandFailure;
return (UInt32)MiResult.FAILED;
}
}
catch (Exception exception)
{
errorRecord = GetErrorRecord("GetActionException", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetActionException, _pluginModuleName);
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)MiResult.FAILED, errorRecord);
getActionStatusCode = (int)GetActionStatusCodeTypes.GetDscActionCommandFailure;
return (UInt32)MiResult.FAILED;
}
statusCode = ValidateGetActionResult(powershell, providerResult, _pluginModuleName, out outputResult, out errorRecord, out getActionStatusCode);
powershell.Dispose();
if (statusCode != MiResult.OK)
{
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
// Log to ETW Channel:Microsoft-Windows-DSC/Operational
S_DscCoreR.EventWriteLCMPullGetActionSuccess(S_DscCoreR.JobGuidString,
outputResult,
_pluginModuleName);
return (uint)MiResult.OK;
}
/// <summary>
/// Get Api facilitates to execute Get-Configuration functionality on the provider mentioned in the meta configuration..
/// </summary>
/// <param name="metaConfigHandle"></param>
/// <param name="errorInstanceHandle"></param>
/// <param name="mofFileName"></param>
/// <param name="outputResult"></param>
/// <param name="getActionStatusCode"></param>
/// <returns>If GetDscDocument operation is successful, 0 is returned or else a status code indicating the error is returned.</returns>
public static UInt32 GetDscDocument(IntPtr metaConfigHandle, out IntPtr errorInstanceHandle, out string mofFileName, out string outputResult, out UInt32 getActionStatusCode)
{
ErrorRecord errorRecord;
errorInstanceHandle = IntPtr.Zero;
string destinationPath = Path.GetTempPath() + "\\" + DateTime.Now.Ticks;
MiResult statusCode = InitializePlugin(metaConfigHandle, out errorRecord);
outputResult = null;
mofFileName = null;
if (statusCode != MiResult.OK)
{
getActionStatusCode = (int)GetActionStatusCodeTypes.DownloadManagerInitializationFailure;
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
if (Directory.Exists(destinationPath))
{
errorRecord = GetErrorRecord("DownloadLocationDirectoryExists", ErrorCategory.InvalidResult,
PSinfrastructureStrings.DownloadLocationDirectoryExists);
getActionStatusCode = (int)GetActionStatusCodeTypes.DownloadManagerInitializationFailure;
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((UInt32)MiResult.ALREADY_EXISTS, errorRecord);
return (uint)MiResult.ALREADY_EXISTS;
}
Directory.CreateDirectory(destinationPath);
//Get parameters for Get-Configuration cmdlet
PSCredential pscredential;
var arguments = new Hashtable(StringComparer.OrdinalIgnoreCase);
string configurationId;
statusCode = GetMetaConfigParams(metaConfigHandle, out pscredential, arguments, out configurationId, out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
bool allowModuleOverwrite;
statusCode = GetAllowModuleOverwriteFromMetaConfig(metaConfigHandle, out allowModuleOverwrite, out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
System.Management.Automation.PowerShell powershell;
Collection<PSObject> providerResult;
//Create PowerShell object and invoke the command.
try
{
powershell = System.Management.Automation.PowerShell.Create();
powershell.Runspace = _pluginRunspace;
Collection<PSObject> argumentParameters = null;
if (arguments.Count > 0)
{
argumentParameters = powershell.AddCommand("New-Object").AddParameter("Type", "psobject").AddParameter("Property", arguments).Invoke();
powershell.Commands.Clear();
}
powershell.Commands.AddCommand(_pluginModuleName + "\\" + DownloadManagerGetConfiguration);
powershell.AddParameter(ParamConfigurationId, configurationId);
powershell.AddParameter(ParamDestinationPath, destinationPath);
if (pscredential != null)
{
powershell.AddParameter(ParamCredential, pscredential);
}
// Log to ETW Channel:Microsoft-Windows-DSC/Operational
S_DscCoreR.EventWriteLCMPullGetConfigAttempt(S_DscCoreR.JobGuidString,
_pluginModuleName, configurationId);
powershell.Streams.Error.Clear();
providerResult = arguments.Count > 0 ? powershell.Invoke(argumentParameters) : powershell.Invoke();
if (powershell.Streams.Error.Count > 0)
{
Directory.Delete(destinationPath, true);
errorRecord = powershell.Streams.Error[0];
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)MiResult.FAILED, errorRecord);
powershell.Dispose();
if( string.Compare(errorRecord.FullyQualifiedErrorId, "WebDownloadManagerUnknownChecksumAlgorithm", StringComparison.OrdinalIgnoreCase) == 0 )
{
getActionStatusCode = (int)GetActionStatusCodeTypes.InvalidChecksumAlgorithm;
}
else
{
getActionStatusCode = (int)GetActionStatusCodeTypes.GetConfigurationCommandFailure;
}
return (uint)MiResult.FAILED;
}
}
catch (Exception exception)
{
Directory.Delete(destinationPath, true);
errorRecord = GetErrorRecord("GetConfigurationException", exception, ErrorCategory.InvalidResult,
PSinfrastructureStrings.GetConfigurationException, _pluginModuleName);
getActionStatusCode = (int)GetActionStatusCodeTypes.GetConfigurationCommandFailure;
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)MiResult.FAILED, errorRecord);
return (uint)MiResult.FAILED;
}
statusCode = ValidateGetConfigurationResult(powershell, providerResult, _pluginModuleName, out outputResult, out errorRecord, out getActionStatusCode);
S_DscCoreR.EventWriteLCMPullConfigurationChecksumValidationResult(S_DscCoreR.JobGuidString, configurationId, (uint)statusCode);
powershell.Dispose();
if (statusCode != MiResult.OK)
{
Directory.Delete(destinationPath, true);
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
// if it is ok, we will validate checksum here.
if (string.Compare(outputResult, StatusOk, StringComparison.OrdinalIgnoreCase) == 0)
{
statusCode = ValidateConfigurationChecksum(destinationPath, out mofFileName, out errorRecord, out getActionStatusCode);
}
if (statusCode != MiResult.OK)
{
Directory.Delete(destinationPath, true);
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
// If checksum validation passes, we go on to pull the module
statusCode = InstallModules(metaConfigHandle, destinationPath, mofFileName, allowModuleOverwrite, out errorRecord, out getActionStatusCode);
if (statusCode != MiResult.OK)
{
Directory.Delete(destinationPath, true);
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)statusCode, errorRecord);
return (uint)statusCode;
}
// Log to ETW Channel:Microsoft-Windows-DSC/Operational
S_DscCoreR.EventWriteLCMPullGetConfigSuccess(S_DscCoreR.JobGuidString,
_pluginModuleName);
return (uint)MiResult.OK;
}
/// <summary>
/// This API installs a private certificate (.pfx).
/// </summary>
/// <param name="certificatePath"></param>
/// <param name="password"></param>
/// <param name="certificateThumbprint"></param>
/// <param name="errorInstanceHandle"></param>
/// <returns>If successfully installed return 0 and certificateThumbprint or else a status code indicating the error is returned.</returns>
public static uint InstallCertificate(string certificatePath, SecureString password,
out string certificateThumbprint, out IntPtr errorInstanceHandle)
{
certificateThumbprint = null;
errorInstanceHandle = IntPtr.Zero;
X509Store store = null;
try
{
var cert = new X509Certificate2(certificatePath, password);
// open certificate store
store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
// install certificate.
if (!store.Certificates.Contains(cert))
{
store.Add(cert);
}
certificateThumbprint = cert.Thumbprint;
}
catch (Exception ex)
{
var errorRecord = GetErrorRecord("InstallCertificateException", ex, ErrorCategory.InvalidType,
PSinfrastructureStrings.InstallCertificateException, certificatePath);
errorInstanceHandle = Utility.ConvertErrorRecordToMiInstance((uint)MiResult.FAILED, errorRecord);
return (uint)MiResult.FAILED;
}
finally
{
if (store != null)
{
store.Close();
}
}
return (uint)MiResult.OK;
}
#endregion PLUGIN_PUBLICMETHODS
}
}
| |
/*
[The "BSD licence"]
Copyright (c) 2005-2007 Kunle Odutola
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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior WRITTEN permission.
4. Unless explicitly state otherwise, any contribution intentionally
submitted for inclusion in this work to the copyright owner or licensor
shall be under the terms and conditions of this license, without any
additional terms or conditions.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Antlr.Runtime.Collections
{
using System;
using IDictionary = System.Collections.IDictionary;
using IDictionaryEnumerator = System.Collections.IDictionaryEnumerator;
using ICollection = System.Collections.ICollection;
using IEnumerator = System.Collections.IEnumerator;
using Hashtable = System.Collections.Hashtable;
using ArrayList = System.Collections.ArrayList;
using DictionaryEntry = System.Collections.DictionaryEntry;
using StringBuilder = System.Text.StringBuilder;
/// <summary>
/// An Hashtable-backed dictionary that enumerates Keys and Values in
/// insertion order.
/// </summary>
public sealed class HashList : IDictionary
{
#region Helper classes
private sealed class HashListEnumerator : IDictionaryEnumerator
{
internal enum EnumerationMode
{
Key,
Value,
Entry
}
private HashList _hashList;
private ArrayList _orderList;
private EnumerationMode _mode;
private int _index;
private int _version;
private object _key;
private object _value;
#region Constructors
internal HashListEnumerator()
{
_index = 0;
_key = null;
_value = null;
}
internal HashListEnumerator(HashList hashList, EnumerationMode mode)
{
_hashList = hashList;
_mode = mode;
_version = hashList._version;
_orderList = hashList._insertionOrderList;
_index = 0;
_key = null;
_value = null;
}
#endregion
#region IDictionaryEnumerator Members
public object Key
{
get
{
if (_key == null)
{
throw new InvalidOperationException("Enumeration has either not started or has already finished.");
}
return _key;
}
}
public object Value
{
get
{
if (_key == null)
{
throw new InvalidOperationException("Enumeration has either not started or has already finished.");
}
return _value;
}
}
public DictionaryEntry Entry
{
get
{
if (_key == null)
{
throw new InvalidOperationException("Enumeration has either not started or has already finished.");
}
return new DictionaryEntry(_key, _value);
}
}
#endregion
#region IEnumerator Members
public void Reset()
{
if (_version != _hashList._version)
{
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
_index = 0;
_key = null;
_value = null;
}
public object Current
{
get
{
if (_key == null)
{
throw new InvalidOperationException("Enumeration has either not started or has already finished.");
}
if (_mode == EnumerationMode.Key)
return _key;
else if (_mode == EnumerationMode.Value)
return _value;
return new DictionaryEntry(_key, _value);
}
}
public bool MoveNext()
{
if (_version != _hashList._version)
{
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
if (_index < _orderList.Count)
{
_key = _orderList[_index];
_value = _hashList[_key];
_index++;
return true;
}
_key = null;
return false;
}
#endregion
}
private sealed class KeyCollection : ICollection
{
private HashList _hashList;
#region Constructors
internal KeyCollection()
{
}
internal KeyCollection(HashList hashList)
{
_hashList = hashList;
}
#endregion
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.Append("[");
ArrayList keys = _hashList._insertionOrderList;
for (int i = 0; i < keys.Count; i++)
{
if (i > 0)
{
result.Append(", ");
}
result.Append(keys[i]);
}
result.Append("]");
return result.ToString();
}
public override bool Equals(object o)
{
if (o is KeyCollection)
{
KeyCollection other = (KeyCollection) o;
if ((Count == 0) && (other.Count == 0))
return true;
else if (Count == other.Count)
{
for (int i = 0; i < Count; i++)
{
if ((_hashList._insertionOrderList[i] == other._hashList._insertionOrderList[i]) ||
(_hashList._insertionOrderList[i].Equals(other._hashList._insertionOrderList[i])))
return true;
}
}
}
return false;
}
public override int GetHashCode()
{
return _hashList._insertionOrderList.GetHashCode();
}
#region ICollection Members
public bool IsSynchronized
{
get { return _hashList.IsSynchronized; }
}
public int Count
{
get { return _hashList.Count; }
}
public void CopyTo(Array array, int index)
{
_hashList.CopyKeysTo(array, index);
}
public object SyncRoot
{
get { return _hashList.SyncRoot; }
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new HashListEnumerator(_hashList, HashListEnumerator.EnumerationMode.Key);
}
#endregion
}
private sealed class ValueCollection : ICollection
{
private HashList _hashList;
#region Constructors
internal ValueCollection()
{
}
internal ValueCollection(HashList hashList)
{
_hashList = hashList;
}
#endregion
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.Append("[");
IEnumerator iter = new HashListEnumerator(_hashList, HashListEnumerator.EnumerationMode.Value);
if (iter.MoveNext())
{
result.Append((iter.Current == null) ? "null" : iter.Current);
while (iter.MoveNext())
{
result.Append(", ");
result.Append((iter.Current == null) ? "null" : iter.Current);
}
}
result.Append("]");
return result.ToString();
}
#region ICollection Members
public bool IsSynchronized
{
get { return _hashList.IsSynchronized; }
}
public int Count
{
get { return _hashList.Count; }
}
public void CopyTo(Array array, int index)
{
_hashList.CopyValuesTo(array, index);
}
public object SyncRoot
{
get { return _hashList.SyncRoot; }
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new HashListEnumerator(_hashList, HashListEnumerator.EnumerationMode.Value);
}
#endregion
}
#endregion
private Hashtable _dictionary = new Hashtable();
private ArrayList _insertionOrderList = new ArrayList();
private int _version;
#region Constructors
public HashList() : this(-1)
{
}
public HashList(int capacity)
{
if (capacity < 0)
{
_dictionary = new Hashtable();
_insertionOrderList = new ArrayList();
}
else
{
_dictionary = new Hashtable(capacity);
_insertionOrderList = new ArrayList(capacity);
}
_version = 0;
}
#endregion
#region IDictionary Members
public bool IsReadOnly { get { return _dictionary.IsReadOnly; } }
public IDictionaryEnumerator GetEnumerator()
{
return new HashListEnumerator(this, HashListEnumerator.EnumerationMode.Entry);
}
public object this[object key]
{
get { return _dictionary[key]; }
set
{
bool isNewEntry = !_dictionary.Contains(key);
_dictionary[key] = value;
if (isNewEntry)
_insertionOrderList.Add(key);
_version++;
}
}
public void Remove(object key)
{
_dictionary.Remove(key);
_insertionOrderList.Remove(key);
_version++;
}
public bool Contains(object key)
{
return _dictionary.Contains(key);
}
public void Clear()
{
_dictionary.Clear();
_insertionOrderList.Clear();
_version++;
}
public ICollection Values
{
get { return new ValueCollection(this); }
}
public void Add(object key, object value)
{
_dictionary.Add(key, value);
_insertionOrderList.Add(key);
_version++;
}
public ICollection Keys
{
get { return new KeyCollection(this); }
}
public bool IsFixedSize
{
get { return _dictionary.IsFixedSize; }
}
#endregion
#region ICollection Members
public bool IsSynchronized
{
get { return _dictionary.IsSynchronized; }
}
public int Count
{
get { return _dictionary.Count; }
}
public void CopyTo(Array array, int index)
{
int len = _insertionOrderList.Count;
for (int i = 0; i < len; i++)
{
DictionaryEntry e = new DictionaryEntry(_insertionOrderList[i], _dictionary[_insertionOrderList[i]]);
array.SetValue(e, index++);
}
}
public object SyncRoot
{
get { return _dictionary.SyncRoot; }
}
#endregion
#region IEnumerable Members
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new HashListEnumerator(this, HashListEnumerator.EnumerationMode.Entry);
}
#endregion
private void CopyKeysTo(Array array, int index)
{
int len = _insertionOrderList.Count;
for (int i = 0; i < len; i++)
{
array.SetValue(_insertionOrderList[i], index++);
}
}
private void CopyValuesTo(Array array, int index)
{
int len = _insertionOrderList.Count;
for (int i = 0; i < len; i++)
{
array.SetValue(_dictionary[_insertionOrderList[i]], index++);
}
}
}
}
| |
// 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.Network.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Network;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Effective network security rules.
/// </summary>
public partial class EffectiveNetworkSecurityRule
{
/// <summary>
/// Initializes a new instance of the EffectiveNetworkSecurityRule
/// class.
/// </summary>
public EffectiveNetworkSecurityRule()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the EffectiveNetworkSecurityRule
/// class.
/// </summary>
/// <param name="name">The name of the security rule specified by the
/// user (if created by the user).</param>
/// <param name="protocol">The network protocol this rule applies to.
/// Possible values are: 'Tcp', 'Udp', and 'All'. Possible values
/// include: 'Tcp', 'Udp', 'All'</param>
/// <param name="sourcePortRange">The source port or range.</param>
/// <param name="destinationPortRange">The destination port or
/// range.</param>
/// <param name="sourcePortRanges">The source port ranges. Expected
/// values include a single integer between 0 and 65535, a range using
/// '-' as seperator (e.g. 100-400), or an asterix (*)</param>
/// <param name="destinationPortRanges">The destination port ranges.
/// Expected values include a single integer between 0 and 65535, a
/// range using '-' as seperator (e.g. 100-400), or an asterix
/// (*)</param>
/// <param name="sourceAddressPrefix">The source address
/// prefix.</param>
/// <param name="destinationAddressPrefix">The destination address
/// prefix.</param>
/// <param name="sourceAddressPrefixes">The source address prefixes.
/// Expected values include CIDR IP ranges, Default Tags
/// (VirtualNetwork, AureLoadBalancer, Internet), System Tags, and the
/// asterix (*).</param>
/// <param name="destinationAddressPrefixes">The destination address
/// prefixes. Expected values include CIDR IP ranges, Default Tags
/// (VirtualNetwork, AureLoadBalancer, Internet), System Tags, and the
/// asterix (*).</param>
/// <param name="expandedSourceAddressPrefix">The expanded source
/// address prefix.</param>
/// <param name="expandedDestinationAddressPrefix">Expanded destination
/// address prefix.</param>
/// <param name="access">Whether network traffic is allowed or denied.
/// Possible values are: 'Allow' and 'Deny'. Possible values include:
/// 'Allow', 'Deny'</param>
/// <param name="priority">The priority of the rule.</param>
/// <param name="direction">The direction of the rule. Possible values
/// are: 'Inbound and Outbound'. Possible values include: 'Inbound',
/// 'Outbound'</param>
public EffectiveNetworkSecurityRule(string name = default(string), string protocol = default(string), string sourcePortRange = default(string), string destinationPortRange = default(string), IList<string> sourcePortRanges = default(IList<string>), IList<string> destinationPortRanges = default(IList<string>), string sourceAddressPrefix = default(string), string destinationAddressPrefix = default(string), IList<string> sourceAddressPrefixes = default(IList<string>), IList<string> destinationAddressPrefixes = default(IList<string>), IList<string> expandedSourceAddressPrefix = default(IList<string>), IList<string> expandedDestinationAddressPrefix = default(IList<string>), string access = default(string), int? priority = default(int?), string direction = default(string))
{
Name = name;
Protocol = protocol;
SourcePortRange = sourcePortRange;
DestinationPortRange = destinationPortRange;
SourcePortRanges = sourcePortRanges;
DestinationPortRanges = destinationPortRanges;
SourceAddressPrefix = sourceAddressPrefix;
DestinationAddressPrefix = destinationAddressPrefix;
SourceAddressPrefixes = sourceAddressPrefixes;
DestinationAddressPrefixes = destinationAddressPrefixes;
ExpandedSourceAddressPrefix = expandedSourceAddressPrefix;
ExpandedDestinationAddressPrefix = expandedDestinationAddressPrefix;
Access = access;
Priority = priority;
Direction = direction;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the name of the security rule specified by the user
/// (if created by the user).
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the network protocol this rule applies to. Possible
/// values are: 'Tcp', 'Udp', and 'All'. Possible values include:
/// 'Tcp', 'Udp', 'All'
/// </summary>
[JsonProperty(PropertyName = "protocol")]
public string Protocol { get; set; }
/// <summary>
/// Gets or sets the source port or range.
/// </summary>
[JsonProperty(PropertyName = "sourcePortRange")]
public string SourcePortRange { get; set; }
/// <summary>
/// Gets or sets the destination port or range.
/// </summary>
[JsonProperty(PropertyName = "destinationPortRange")]
public string DestinationPortRange { get; set; }
/// <summary>
/// Gets or sets the source port ranges. Expected values include a
/// single integer between 0 and 65535, a range using '-' as seperator
/// (e.g. 100-400), or an asterix (*)
/// </summary>
[JsonProperty(PropertyName = "sourcePortRanges")]
public IList<string> SourcePortRanges { get; set; }
/// <summary>
/// Gets or sets the destination port ranges. Expected values include a
/// single integer between 0 and 65535, a range using '-' as seperator
/// (e.g. 100-400), or an asterix (*)
/// </summary>
[JsonProperty(PropertyName = "destinationPortRanges")]
public IList<string> DestinationPortRanges { get; set; }
/// <summary>
/// Gets or sets the source address prefix.
/// </summary>
[JsonProperty(PropertyName = "sourceAddressPrefix")]
public string SourceAddressPrefix { get; set; }
/// <summary>
/// Gets or sets the destination address prefix.
/// </summary>
[JsonProperty(PropertyName = "destinationAddressPrefix")]
public string DestinationAddressPrefix { get; set; }
/// <summary>
/// Gets or sets the source address prefixes. Expected values include
/// CIDR IP ranges, Default Tags (VirtualNetwork, AureLoadBalancer,
/// Internet), System Tags, and the asterix (*).
/// </summary>
[JsonProperty(PropertyName = "sourceAddressPrefixes")]
public IList<string> SourceAddressPrefixes { get; set; }
/// <summary>
/// Gets or sets the destination address prefixes. Expected values
/// include CIDR IP ranges, Default Tags (VirtualNetwork,
/// AureLoadBalancer, Internet), System Tags, and the asterix (*).
/// </summary>
[JsonProperty(PropertyName = "destinationAddressPrefixes")]
public IList<string> DestinationAddressPrefixes { get; set; }
/// <summary>
/// Gets or sets the expanded source address prefix.
/// </summary>
[JsonProperty(PropertyName = "expandedSourceAddressPrefix")]
public IList<string> ExpandedSourceAddressPrefix { get; set; }
/// <summary>
/// Gets or sets expanded destination address prefix.
/// </summary>
[JsonProperty(PropertyName = "expandedDestinationAddressPrefix")]
public IList<string> ExpandedDestinationAddressPrefix { get; set; }
/// <summary>
/// Gets or sets whether network traffic is allowed or denied. Possible
/// values are: 'Allow' and 'Deny'. Possible values include: 'Allow',
/// 'Deny'
/// </summary>
[JsonProperty(PropertyName = "access")]
public string Access { get; set; }
/// <summary>
/// Gets or sets the priority of the rule.
/// </summary>
[JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets or sets the direction of the rule. Possible values are:
/// 'Inbound and Outbound'. Possible values include: 'Inbound',
/// 'Outbound'
/// </summary>
[JsonProperty(PropertyName = "direction")]
public string Direction { get; set; }
}
}
| |
// Listener class.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// 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.
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/4/23
* Time: 19:40
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using Lextm.SharpSnmpLib.Security;
namespace Lextm.SharpSnmpLib.Messaging
{
/// <summary>
/// Listener class.
/// </summary>
public sealed class Listener : IDisposable
{
private UserRegistry _users;
private bool _disposed;
/// <summary>
/// Error message for non IP v4 OS.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pv")]
public const string ErrorIPv4NotSupported = "cannot use IP v4 as the OS does not support it";
/// <summary>
/// Error message for non IP v6 OS.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Pv")]
public const string ErrorIPv6NotSupported = "cannot use IP v6 as the OS does not support it";
/// <summary>
/// Initializes a new instance of the <see cref="Listener"/> class.
/// </summary>
public Listener()
{
Bindings = new List<ListenerBinding>();
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="Listener"/> is reclaimed by garbage collection.
/// </summary>
~Listener()
{
Dispose(false);
}
/// <summary>
/// Disposes resources in use.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.ComponentModel.Component"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
if (Bindings != null)
{
foreach (var binding in Bindings)
{
binding.Dispose();
}
Bindings.Clear();
Bindings = null;
}
}
_disposed = true;
}
/// <summary>
/// Gets or sets the users.
/// </summary>
/// <value>The users.</value>
public UserRegistry Users
{
get
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
return _users ?? (_users = new UserRegistry());
}
set
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
_users = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Listener"/> is active.
/// </summary>
/// <value><c>true</c> if active; otherwise, <c>false</c>.</value>
public bool Active { get; private set; }
/// <summary>
/// Stops this instance.
/// </summary>
public void Stop()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Active)
{
return;
}
foreach (var binding in Bindings)
{
binding.Stop();
}
Active = false;
}
/// <summary>
/// Starts this instance.
/// </summary>
/// <exception cref="PortInUseException"/>
public void Start()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (Active)
{
return;
}
try
{
foreach (var binding in Bindings)
{
binding.Start();
}
}
catch (PortInUseException)
{
Stop(); // stop all started bindings.
throw;
}
Active = true;
}
/// <summary>
/// Gets or sets the bindings.
/// </summary>
/// <value>The bindings.</value>
internal IList<ListenerBinding> Bindings { get; set; }
/// <summary>
/// Occurs when an exception is raised.
/// </summary>
public event EventHandler<ExceptionRaisedEventArgs> ExceptionRaised;
/// <summary>
/// Occurs when a message is received.
/// </summary>
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
/// <summary>
/// Adds the binding.
/// </summary>
/// <param name="endpoint">The endpoint.</param>
public void AddBinding(IPEndPoint endpoint)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (Active)
{
throw new InvalidOperationException("Must be called when Active == false");
}
if (Bindings.Any(existed => existed.Endpoint.Equals(endpoint)))
{
return;
}
var binding = new ListenerBinding(Users, endpoint);
binding.ExceptionRaised += (o, args) =>
{
var handler = ExceptionRaised;
if (handler != null)
{
handler(o, args);
}
};
binding.MessageReceived += (o, args) =>
{
var handler = MessageReceived;
if (handler != null)
{
handler(o, args);
}
};
Bindings.Add(binding);
}
/// <summary>
/// Removes the binding.
/// </summary>
/// <param name="endpoint">The endpoint.</param>
public void RemoveBinding(IPEndPoint endpoint)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (Active)
{
throw new InvalidOperationException("Must be called when Active == false");
}
for (var i = 0; i < Bindings.Count; i++)
{
if (Bindings[i].Endpoint.Equals(endpoint))
{
Bindings.RemoveAt(i);
}
}
}
/// <summary>
/// Clears the bindings.
/// </summary>
public void ClearBindings()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
foreach (var binding in Bindings)
{
binding.Stop();
binding.Dispose();
}
Bindings.Clear();
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// PipelinelatestRun
/// </summary>
[DataContract(Name = "PipelinelatestRun")]
public partial class PipelinelatestRun : IEquatable<PipelinelatestRun>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PipelinelatestRun" /> class.
/// </summary>
/// <param name="artifacts">artifacts.</param>
/// <param name="durationInMillis">durationInMillis.</param>
/// <param name="estimatedDurationInMillis">estimatedDurationInMillis.</param>
/// <param name="enQueueTime">enQueueTime.</param>
/// <param name="endTime">endTime.</param>
/// <param name="id">id.</param>
/// <param name="organization">organization.</param>
/// <param name="pipeline">pipeline.</param>
/// <param name="result">result.</param>
/// <param name="runSummary">runSummary.</param>
/// <param name="startTime">startTime.</param>
/// <param name="state">state.</param>
/// <param name="type">type.</param>
/// <param name="commitId">commitId.</param>
/// <param name="_class">_class.</param>
public PipelinelatestRun(List<PipelinelatestRunartifacts> artifacts = default(List<PipelinelatestRunartifacts>), int durationInMillis = default(int), int estimatedDurationInMillis = default(int), string enQueueTime = default(string), string endTime = default(string), string id = default(string), string organization = default(string), string pipeline = default(string), string result = default(string), string runSummary = default(string), string startTime = default(string), string state = default(string), string type = default(string), string commitId = default(string), string _class = default(string))
{
this.Artifacts = artifacts;
this.DurationInMillis = durationInMillis;
this.EstimatedDurationInMillis = estimatedDurationInMillis;
this.EnQueueTime = enQueueTime;
this.EndTime = endTime;
this.Id = id;
this.Organization = organization;
this.Pipeline = pipeline;
this.Result = result;
this.RunSummary = runSummary;
this.StartTime = startTime;
this.State = state;
this.Type = type;
this.CommitId = commitId;
this.Class = _class;
}
/// <summary>
/// Gets or Sets Artifacts
/// </summary>
[DataMember(Name = "artifacts", EmitDefaultValue = false)]
public List<PipelinelatestRunartifacts> Artifacts { get; set; }
/// <summary>
/// Gets or Sets DurationInMillis
/// </summary>
[DataMember(Name = "durationInMillis", EmitDefaultValue = false)]
public int DurationInMillis { get; set; }
/// <summary>
/// Gets or Sets EstimatedDurationInMillis
/// </summary>
[DataMember(Name = "estimatedDurationInMillis", EmitDefaultValue = false)]
public int EstimatedDurationInMillis { get; set; }
/// <summary>
/// Gets or Sets EnQueueTime
/// </summary>
[DataMember(Name = "enQueueTime", EmitDefaultValue = false)]
public string EnQueueTime { get; set; }
/// <summary>
/// Gets or Sets EndTime
/// </summary>
[DataMember(Name = "endTime", EmitDefaultValue = false)]
public string EndTime { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Organization
/// </summary>
[DataMember(Name = "organization", EmitDefaultValue = false)]
public string Organization { get; set; }
/// <summary>
/// Gets or Sets Pipeline
/// </summary>
[DataMember(Name = "pipeline", EmitDefaultValue = false)]
public string Pipeline { get; set; }
/// <summary>
/// Gets or Sets Result
/// </summary>
[DataMember(Name = "result", EmitDefaultValue = false)]
public string Result { get; set; }
/// <summary>
/// Gets or Sets RunSummary
/// </summary>
[DataMember(Name = "runSummary", EmitDefaultValue = false)]
public string RunSummary { get; set; }
/// <summary>
/// Gets or Sets StartTime
/// </summary>
[DataMember(Name = "startTime", EmitDefaultValue = false)]
public string StartTime { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name = "state", EmitDefaultValue = false)]
public string State { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name = "type", EmitDefaultValue = false)]
public string Type { get; set; }
/// <summary>
/// Gets or Sets CommitId
/// </summary>
[DataMember(Name = "commitId", EmitDefaultValue = false)]
public string CommitId { get; set; }
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { 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 PipelinelatestRun {\n");
sb.Append(" Artifacts: ").Append(Artifacts).Append("\n");
sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n");
sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n");
sb.Append(" EnQueueTime: ").Append(EnQueueTime).Append("\n");
sb.Append(" EndTime: ").Append(EndTime).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Organization: ").Append(Organization).Append("\n");
sb.Append(" Pipeline: ").Append(Pipeline).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append(" RunSummary: ").Append(RunSummary).Append("\n");
sb.Append(" StartTime: ").Append(StartTime).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" CommitId: ").Append(CommitId).Append("\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PipelinelatestRun);
}
/// <summary>
/// Returns true if PipelinelatestRun instances are equal
/// </summary>
/// <param name="input">Instance of PipelinelatestRun to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PipelinelatestRun input)
{
if (input == null)
return false;
return
(
this.Artifacts == input.Artifacts ||
this.Artifacts != null &&
input.Artifacts != null &&
this.Artifacts.SequenceEqual(input.Artifacts)
) &&
(
this.DurationInMillis == input.DurationInMillis ||
this.DurationInMillis.Equals(input.DurationInMillis)
) &&
(
this.EstimatedDurationInMillis == input.EstimatedDurationInMillis ||
this.EstimatedDurationInMillis.Equals(input.EstimatedDurationInMillis)
) &&
(
this.EnQueueTime == input.EnQueueTime ||
(this.EnQueueTime != null &&
this.EnQueueTime.Equals(input.EnQueueTime))
) &&
(
this.EndTime == input.EndTime ||
(this.EndTime != null &&
this.EndTime.Equals(input.EndTime))
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Organization == input.Organization ||
(this.Organization != null &&
this.Organization.Equals(input.Organization))
) &&
(
this.Pipeline == input.Pipeline ||
(this.Pipeline != null &&
this.Pipeline.Equals(input.Pipeline))
) &&
(
this.Result == input.Result ||
(this.Result != null &&
this.Result.Equals(input.Result))
) &&
(
this.RunSummary == input.RunSummary ||
(this.RunSummary != null &&
this.RunSummary.Equals(input.RunSummary))
) &&
(
this.StartTime == input.StartTime ||
(this.StartTime != null &&
this.StartTime.Equals(input.StartTime))
) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
) &&
(
this.CommitId == input.CommitId ||
(this.CommitId != null &&
this.CommitId.Equals(input.CommitId))
) &&
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Artifacts != null)
hashCode = hashCode * 59 + this.Artifacts.GetHashCode();
hashCode = hashCode * 59 + this.DurationInMillis.GetHashCode();
hashCode = hashCode * 59 + this.EstimatedDurationInMillis.GetHashCode();
if (this.EnQueueTime != null)
hashCode = hashCode * 59 + this.EnQueueTime.GetHashCode();
if (this.EndTime != null)
hashCode = hashCode * 59 + this.EndTime.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Organization != null)
hashCode = hashCode * 59 + this.Organization.GetHashCode();
if (this.Pipeline != null)
hashCode = hashCode * 59 + this.Pipeline.GetHashCode();
if (this.Result != null)
hashCode = hashCode * 59 + this.Result.GetHashCode();
if (this.RunSummary != null)
hashCode = hashCode * 59 + this.RunSummary.GetHashCode();
if (this.StartTime != null)
hashCode = hashCode * 59 + this.StartTime.GetHashCode();
if (this.State != null)
hashCode = hashCode * 59 + this.State.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
if (this.CommitId != null)
hashCode = hashCode * 59 + this.CommitId.GetHashCode();
if (this.Class != null)
hashCode = hashCode * 59 + this.Class.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//this is full of bugs probably, related to state from old rendering sessions being all messed up. its only barely good enough to work at all
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using sd = System.Drawing;
using System.Drawing.Imaging;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace BizHawk.Bizware.BizwareGL.Drivers.GdiPlus
{
public class GDIPlusGuiRenderer : IGuiRenderer
{
public GDIPlusGuiRenderer(IGL_GdiPlus gl)
{
Owner = gl;
Gdi = gl as IGL_GdiPlus;
}
OpenTK.Graphics.Color4[] CornerColors = new OpenTK.Graphics.Color4[4] {
new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f),new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f),new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f),new OpenTK.Graphics.Color4(1.0f,1.0f,1.0f,1.0f)
};
public void SetCornerColor(int which, OpenTK.Graphics.Color4 color)
{
CornerColors[which] = color;
}
public void SetCornerColors(OpenTK.Graphics.Color4[] colors)
{
Flush(); //dont really need to flush with current implementation. we might as well roll modulate color into it too.
if (colors.Length != 4) throw new ArgumentException("array must be size 4", "colors");
for (int i = 0; i < 4; i++)
CornerColors[i] = colors[i];
}
public void Dispose()
{
if (CurrentImageAttributes != null)
CurrentImageAttributes.Dispose();
}
public void SetPipeline(Pipeline pipeline)
{
}
public void SetDefaultPipeline()
{
}
public void SetModulateColorWhite()
{
SetModulateColor(sd.Color.White);
}
ImageAttributes CurrentImageAttributes;
public void SetModulateColor(sd.Color color)
{
//white is really no color at all
if (color.ToArgb() == sd.Color.White.ToArgb())
{
CurrentImageAttributes.ClearColorMatrix(ColorAdjustType.Bitmap);
return;
}
float r = color.R / 255.0f;
float g = color.G / 255.0f;
float b = color.B / 255.0f;
float a = color.A / 255.0f;
float[][] colorMatrixElements = {
new float[] {r, 0, 0, 0, 0},
new float[] {0, g, 0, 0, 0},
new float[] {0, 0, b, 0, 0},
new float[] {0, 0, 0, a, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
CurrentImageAttributes.SetColorMatrix(colorMatrix,ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
}
sd.Color CurrentModulateColor = sd.Color.White;
IBlendState CurrentBlendState;
public void SetBlendState(IBlendState rsBlend)
{
CurrentBlendState = rsBlend;
}
MatrixStack _Projection, _Modelview;
public MatrixStack Projection
{
get { return _Projection; }
set
{
_Projection = value;
_Projection.IsDirty = true;
}
}
public MatrixStack Modelview
{
get { return _Modelview; }
set
{
_Modelview = value;
_Modelview.IsDirty = true;
}
}
public void Begin(sd.Size size) { Begin(size.Width, size.Height); }
public void Begin(int width, int height)
{
Begin();
CurrentBlendState = Gdi.BlendNormal;
Projection = Owner.CreateGuiProjectionMatrix(width, height);
Modelview = Owner.CreateGuiViewMatrix(width, height);
}
public void Begin()
{
//uhhmmm I want to throw an exception if its already active, but its annoying.
IsActive = true;
CurrentImageAttributes = new ImageAttributes();
}
public void Flush()
{
//no batching, nothing to do here yet
}
public void End()
{
if (!IsActive)
throw new InvalidOperationException("GuiRenderer is not active!");
IsActive = false;
if (CurrentImageAttributes != null)
{
CurrentImageAttributes.Dispose();
CurrentImageAttributes = null;
}
}
public void RectFill(float x, float y, float w, float h)
{
}
public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
{
var tw = tex.Opaque as IGL_GdiPlus.TextureWrapper;
var g = Gdi.GetCurrentGraphics();
PrepDraw(g, tex);
SetupMatrix(g);
float x0 = u0 * tex.Width;
float y0 = v0 * tex.Height;
float x1 = u1 * tex.Width;
float y1 = v1 * tex.Height;
sd.PointF[] destPoints = new sd.PointF[] {
new sd.PointF(x,y),
new sd.PointF(x+w,y),
new sd.PointF(x,y+h),
};
g.DrawImage(tw.SDBitmap, destPoints, new sd.RectangleF(x0, y0, x1 - x0, y1 - y0), sd.GraphicsUnit.Pixel, CurrentImageAttributes);
g.Transform = new sd.Drawing2D.Matrix(); //.Reset() doesnt work ? ?
}
public void Draw(Art art) { DrawInternal(art, 0, 0, art.Width, art.Height, false, false); }
public void Draw(Art art, float x, float y) { DrawInternal(art, x, y, art.Width, art.Height, false, false); }
public void Draw(Art art, float x, float y, float width, float height) { DrawInternal(art, x, y, width, height, false, false); }
public void Draw(Art art, Vector2 pos) { DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false); }
public void Draw(Texture2d tex) { DrawInternal(tex, 0, 0, tex.Width, tex.Height); }
public void Draw(Texture2d tex, float x, float y) { DrawInternal(tex, x, y, tex.Width, tex.Height); }
public void DrawFlipped(Art art, bool xflip, bool yflip) { DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip); }
public void Draw(Texture2d art, float x, float y, float width, float height)
{
DrawInternal(art, x, y, width, height);
}
void PrepDraw(sd.Graphics g, Texture2d tex)
{
var tw = tex.Opaque as IGL_GdiPlus.TextureWrapper;
//TODO - we can support bicubic for the final presentation..
if ((int)tw.MagFilter != (int)tw.MinFilter)
throw new InvalidOperationException("tw.MagFilter != tw.MinFilter");
if (tw.MagFilter == TextureMagFilter.Linear)
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
if (tw.MagFilter == TextureMagFilter.Nearest)
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
//---------
if (CurrentBlendState == Gdi.BlendNormal)
{
g.CompositingMode = sd.Drawing2D.CompositingMode.SourceOver;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default; //?
//CurrentImageAttributes.ClearColorMatrix(ColorAdjustType.Bitmap);
}
else
//if(CurrentBlendState == Gdi.BlendNoneCopy)
//if(CurrentBlendState == Gdi.BlendNoneOpaque)
{
g.CompositingMode = sd.Drawing2D.CompositingMode.SourceCopy;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
//WARNING : DO NOT USE COLOR MATRIX TO WIPE THE ALPHA
//ITS SOOOOOOOOOOOOOOOOOOOOOOOOOOOO SLOW
//instead, we added kind of hacky support for 24bpp images
}
}
private void SetupMatrix(sd.Graphics g)
{
//projection is always identity, so who cares i guess
//Matrix4 mat = Projection.Top * Modelview.Top;
Matrix4 mat = Modelview.Top;
g.Transform = new sd.Drawing2D.Matrix(mat.M11, mat.M12, mat.M21, mat.M22, mat.M41, mat.M42);
}
unsafe void DrawInternal(Texture2d tex, float x, float y, float w, float h)
{
var g = Gdi.GetCurrentGraphics();
PrepDraw(g, tex);
SetupMatrix(g);
sd.PointF[] destPoints = new sd.PointF[] {
new sd.PointF(x,y),
new sd.PointF(x+w,y),
new sd.PointF(x,y+h),
};
var tw = tex.Opaque as IGL_GdiPlus.TextureWrapper;
g.PixelOffsetMode = sd.Drawing2D.PixelOffsetMode.Half;
g.DrawImage(tw.SDBitmap, destPoints, new sd.RectangleF(0, 0, tex.Width, tex.Height), sd.GraphicsUnit.Pixel, CurrentImageAttributes);
g.Transform = new sd.Drawing2D.Matrix(); //.Reset() doesnt work ? ?
}
unsafe void DrawInternal(Art art, float x, float y, float w, float h, bool fx, bool fy)
{
}
public bool IsActive { get; private set; }
public IGL Owner { get; private set; }
public IGL_GdiPlus Gdi;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.IO
{
/// <summary>
/// Wrapper to help with path normalization.
/// </summary>
unsafe internal class PathHelper
{
// Can't be over 8.3 and be a short name
private const int MaxShortName = 12;
private const char LastAnsi = (char)255;
private const char Delete = (char)127;
// Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space.
// string.WhitespaceChars will trim more aggressively than what the underlying FS does (for ex, NTFS, FAT).
private static readonly char[] s_trimEndChars =
{
(char)0x9, // Horizontal tab
(char)0xA, // Line feed
(char)0xB, // Vertical tab
(char)0xC, // Form feed
(char)0xD, // Carriage return
(char)0x20, // Space
(char)0x85, // Next line
(char)0xA0 // Non breaking space
};
[ThreadStatic]
private static StringBuffer t_fullPathBuffer;
/// <summary>
/// Normalize the given path.
/// </summary>
/// <remarks>
/// Normalizes via Win32 GetFullPathName(). It will also trim all "typical" whitespace at the end of the path (see s_trimEndChars). Will also trim initial
/// spaces if the path is determined to be rooted.
///
/// Note that invalid characters will be checked after the path is normalized, which could remove bad characters. (C:\|\..\a.txt -- C:\a.txt)
/// </remarks>
/// <param name="path">Path to normalize</param>
/// <param name="checkInvalidCharacters">True to check for invalid characters</param>
/// <param name="expandShortPaths">Attempt to expand short paths if true</param>
/// <exception cref="ArgumentException">Thrown if the path is an illegal UNC (does not contain a full server/share) or contains illegal characters.</exception>
/// <exception cref="PathTooLongException">Thrown if the path or a path segment exceeds the filesystem limits.</exception>
/// <exception cref="FileNotFoundException">Thrown if Windows returns ERROR_FILE_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception>
/// <exception cref="DirectoryNotFoundException">Thrown if Windows returns ERROR_PATH_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception>
/// <exception cref="UnauthorizedAccessException">Thrown if Windows returns ERROR_ACCESS_DENIED. (See Win32Marshal.GetExceptionForWin32Error)</exception>
/// <exception cref="IOException">Thrown if Windows returns an error that doesn't map to the above. (See Win32Marshal.GetExceptionForWin32Error)</exception>
/// <returns>Normalized path</returns>
internal static string Normalize(string path, bool checkInvalidCharacters, bool expandShortPaths)
{
// Get the full path
StringBuffer fullPath = t_fullPathBuffer ?? (t_fullPathBuffer = new StringBuffer(PathInternal.MaxShortPath));
try
{
GetFullPathName(path, fullPath);
// Trim whitespace off the end of the string. Win32 normalization trims only U+0020.
fullPath.TrimEnd(s_trimEndChars);
if (fullPath.Length >= PathInternal.MaxLongPath)
{
// Fullpath is genuinely too long
throw new PathTooLongException(SR.IO_PathTooLong);
}
// Checking path validity used to happen before getting the full path name. To avoid additional input allocation
// (to trim trailing whitespace) we now do it after the Win32 call. This will allow legitimate paths through that
// used to get kicked back (notably segments with invalid characters might get removed via "..").
//
// There is no way that GetLongPath can invalidate the path so we'll do this (cheaper) check before we attempt to
// expand short file names.
// Scan the path for:
//
// - Illegal path characters.
// - Invalid UNC paths like \\, \\server, \\server\.
// - Segments that are too long (over MaxComponentLength)
// As the path could be > 30K, we'll combine the validity scan. None of these checks are performed by the Win32
// GetFullPathName() API.
bool possibleShortPath = false;
bool foundTilde = false;
bool possibleBadUnc = IsUnc(fullPath);
ulong index = possibleBadUnc ? (ulong)2 : 0;
ulong lastSeparator = possibleBadUnc ? (ulong)1 : 0;
ulong segmentLength;
char* start = fullPath.CharPointer;
char current;
while (index < fullPath.Length)
{
current = start[index];
// Try to skip deeper analysis. '?' and higher are valid/ignorable except for '\', '|', and '~'
if (current < '?' || current == '\\' || current == '|' || current == '~')
{
switch (current)
{
case '|':
case '>':
case '<':
case '\"':
if (checkInvalidCharacters) throw new ArgumentException(SR.Argument_InvalidPathChars, "path");
foundTilde = false;
break;
case '~':
foundTilde = true;
break;
case '\\':
segmentLength = index - lastSeparator - 1;
if (segmentLength > (ulong)PathInternal.MaxComponentLength)
throw new PathTooLongException(SR.IO_PathTooLong);
lastSeparator = index;
if (foundTilde)
{
if (segmentLength <= MaxShortName)
{
// Possibly a short path.
possibleShortPath = true;
}
foundTilde = false;
}
if (possibleBadUnc)
{
// If we're at the end of the path and this is the first separator, we're missing the share.
// Otherwise we're good, so ignore UNC tracking from here.
if (index == fullPath.Length - 1)
throw new ArgumentException(SR.Arg_PathIllegalUNC);
else
possibleBadUnc = false;
}
break;
default:
if (checkInvalidCharacters && current < ' ') throw new ArgumentException(SR.Argument_InvalidPathChars, "path");
break;
}
}
index++;
}
if (possibleBadUnc)
throw new ArgumentException(SR.Arg_PathIllegalUNC);
segmentLength = fullPath.Length - lastSeparator - 1;
if (segmentLength > (ulong)PathInternal.MaxComponentLength)
throw new PathTooLongException(SR.IO_PathTooLong);
if (foundTilde && segmentLength <= MaxShortName)
possibleShortPath = true;
// Check for a short filename path and try and expand it. Technically you don't need to have a tilde for a short name, but
// this is how we've always done this. This expansion is costly so we'll continue to let other short paths slide.
if (expandShortPaths && possibleShortPath)
{
return TryExpandShortFileName(fullPath, originalPath: path);
}
else
{
if (fullPath.Length == (ulong)path.Length && fullPath.StartsWith(path))
{
// If we have the exact same string we were passed in, don't bother to allocate another string from the StringBuilder.
return path;
}
else
{
return fullPath.ToString();
}
}
}
finally
{
// Clear the buffer
fullPath.Free();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsUnc(StringBuffer buffer)
{
return buffer.Length > 1 && buffer[0] == '\\' && buffer[1] == '\\';
}
private static void GetFullPathName(string path, StringBuffer fullPath)
{
// If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as
// it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here.
Debug.Assert(PathInternal.IsRelative(path) || !PathInternal.IsExtended(path));
// Historically we would skip leading spaces *only* if the path started with a drive " C:" or a UNC " \\"
int startIndex = PathInternal.PathStartSkip(path);
fixed (char* pathStart = path)
{
uint result = 0;
while ((result = Interop.mincore.GetFullPathNameW(pathStart + startIndex, (uint)fullPath.CharCapacity, fullPath.GetHandle(), IntPtr.Zero)) > fullPath.CharCapacity)
{
// Reported size (which does not include the null) is greater than the buffer size. Increase the capacity.
fullPath.EnsureCharCapacity(result);
}
if (result == 0)
{
// Failure, get the error and throw
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == 0)
errorCode = Interop.mincore.Errors.ERROR_BAD_PATHNAME;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, path);
}
fullPath.Length = result;
}
}
private static ulong GetInputBuffer(StringBuffer content, bool isUnc, out StringBuffer buffer)
{
ulong length = content.Length;
length += isUnc ? (ulong)PathInternal.UncExtendedPrefixToInsert.Length : (ulong)PathInternal.ExtendedPathPrefix.Length;
buffer = new StringBuffer(length);
if (isUnc)
{
buffer.CopyFrom(bufferIndex: 0, source: PathInternal.UncExtendedPathPrefix);
ulong prefixDifference = (ulong)(PathInternal.UncExtendedPathPrefix.Length - PathInternal.UncPathPrefix.Length);
content.CopyTo(bufferIndex: prefixDifference, destination: buffer, destinationIndex: (ulong)PathInternal.ExtendedPathPrefix.Length, count: content.Length - prefixDifference);
return prefixDifference;
}
else
{
ulong prefixSize = (ulong)PathInternal.ExtendedPathPrefix.Length;
buffer.CopyFrom(bufferIndex: 0, source: PathInternal.ExtendedPathPrefix);
content.CopyTo(bufferIndex: 0, destination: buffer, destinationIndex: prefixSize, count: content.Length);
return prefixSize;
}
}
private static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath)
{
// We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To
// avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls.
Debug.Assert(!PathInternal.IsRelative(outputBuffer), "should have resolved by now");
Debug.Assert(!PathInternal.IsExtended(outputBuffer), "expanding short names expects normal paths");
// Add the extended prefix before expanding to allow growth over MAX_PATH
StringBuffer inputBuffer = null;
ulong rootLength = PathInternal.GetRootLength(outputBuffer);
bool isUnc = IsUnc(outputBuffer);
ulong rootDifference = GetInputBuffer(outputBuffer, isUnc, out inputBuffer);
rootLength += rootDifference;
ulong inputLength = inputBuffer.Length;
bool success = false;
ulong foundIndex = inputBuffer.Length - 1;
while (!success)
{
uint result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), (uint)outputBuffer.CharCapacity);
// Replace any temporary null we added
if (inputBuffer[foundIndex] == '\0') inputBuffer[foundIndex] = '\\';
if (result == 0)
{
// Look to see if we couldn't find the file
int error = Marshal.GetLastWin32Error();
if (error != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND && error != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)
{
// Some other failure, give up
break;
}
// We couldn't find the path at the given index, start looking further back in the string.
foundIndex--;
for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) ;
if (foundIndex == rootLength)
{
// Can't trim the path back any further
break;
}
else
{
// Temporarily set a null in the string to get Windows to look further up the path
inputBuffer[foundIndex] = '\0';
}
}
else if (result > outputBuffer.CharCapacity)
{
// Not enough space. The result count for this API does not include the null terminator.
outputBuffer.EnsureCharCapacity(result);
result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), (uint)outputBuffer.CharCapacity);
}
else
{
// Found the path
success = true;
outputBuffer.Length = result;
if (foundIndex < inputLength - 1)
{
// It was a partial find, put the non-existant part of the path back
outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex);
}
}
}
// Strip out the prefix and return the string
StringBuffer bufferToUse = success ? outputBuffer : inputBuffer;
string returnValue = null;
int newLength = (int)(bufferToUse.Length - rootDifference);
if (isUnc)
{
// Need to go from \\?\UNC\ to \\?\UN\\
bufferToUse[(ulong)PathInternal.UncExtendedPathPrefix.Length - 1] = '\\';
}
if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength))
{
// Use the original path to avoid allocating
returnValue = originalPath;
}
else
{
returnValue = bufferToUse.Substring(rootDifference, newLength);
}
inputBuffer.Dispose();
return returnValue;
}
}
}
| |
/*
* 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.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapSearchModule")]
public class MapSearchModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Scene m_scene = null; // only need one for communication with GridService
List<Scene> m_scenes = new List<Scene>();
List<UUID> m_Clients;
#region ISharedRegionModule Members
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
{
m_scene = scene;
}
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
m_Clients = new List<UUID>();
}
public void RemoveRegion(Scene scene)
{
m_scenes.Remove(scene);
if (m_scene == scene && m_scenes.Count > 0)
m_scene = m_scenes[0];
scene.EventManager.OnNewClient -= OnNewClient;
}
public void PostInitialise()
{
}
public void Close()
{
m_scene = null;
m_scenes.Clear();
}
public string Name
{
get { return "MapSearchModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void RegionLoaded(Scene scene)
{
}
#endregion
private void OnNewClient(IClientAPI client)
{
client.OnMapNameRequest += OnMapNameRequestHandler;
}
private void OnMapNameRequestHandler(IClientAPI remoteClient, string mapName, uint flags)
{
lock (m_Clients)
{
if (m_Clients.Contains(remoteClient.AgentId))
return;
m_Clients.Add(remoteClient.AgentId);
}
try
{
OnMapNameRequest(remoteClient, mapName, flags);
}
finally
{
lock (m_Clients)
m_Clients.Remove(remoteClient.AgentId);
}
}
private void OnMapNameRequest(IClientAPI remoteClient, string mapName, uint flags)
{
List<MapBlockData> blocks = new List<MapBlockData>();
MapBlockData data;
if (mapName.Length < 3 || (mapName.EndsWith("#") && mapName.Length < 4))
{
// final block, closing the search result
AddFinalBlock(blocks);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
remoteClient.SendAlertMessage("Use a search string with at least 3 characters");
return;
}
//m_log.DebugFormat("MAP NAME=({0})", mapName);
// Hack to get around the fact that ll V3 now drops the port from the
// map name. See https://jira.secondlife.com/browse/VWR-28570
//
// Caller, use this magic form instead:
// secondlife://http|!!mygrid.com|8002|Region+Name/128/128
// or url encode if possible.
// the hacks we do with this viewer...
//
string mapNameOrig = mapName;
if (mapName.Contains("|"))
mapName = mapName.Replace('|', ':');
if (mapName.Contains("+"))
mapName = mapName.Replace('+', ' ');
if (mapName.Contains("!"))
mapName = mapName.Replace('!', '/');
// try to fetch from GridServer
List<GridRegion> regionInfos = m_scene.GridService.GetRegionsByName(m_scene.RegionInfo.ScopeID, mapName, 20);
m_log.DebugFormat("[MAPSEARCHMODULE]: search {0} returned {1} regions. Flags={2}", mapName, regionInfos.Count, flags);
if (regionInfos.Count > 0)
{
foreach (GridRegion info in regionInfos)
{
data = new MapBlockData();
data.Agents = 0;
data.Access = info.Access;
if (flags == 2) // V2 sends this
data.MapImageId = UUID.Zero;
else
data.MapImageId = info.TerrainImage;
// ugh! V2-3 is very sensitive about the result being
// exactly the same as the requested name
if (regionInfos.Count == 1 && mapNameOrig.Contains("|") || mapNameOrig.Contains("+"))
data.Name = mapNameOrig;
else
data.Name = info.RegionName;
data.RegionFlags = 0; // TODO not used?
data.WaterHeight = 0; // not used
data.X = (ushort)(info.RegionLocX / Constants.RegionSize);
data.Y = (ushort)(info.RegionLocY / Constants.RegionSize);
blocks.Add(data);
}
}
// final block, closing the search result
AddFinalBlock(blocks);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
// send extra user messages for V3
// because the UI is very confusing
// while we don't fix the hard-coded urls
if (flags == 2)
{
if (regionInfos.Count == 0)
remoteClient.SendAlertMessage("No regions found with that name.");
else if (regionInfos.Count == 1)
remoteClient.SendAlertMessage("Region found!");
}
}
private void AddFinalBlock(List<MapBlockData> blocks)
{
// final block, closing the search result
MapBlockData data = new MapBlockData();
data.Agents = 0;
data.Access = 255;
data.MapImageId = UUID.Zero;
data.Name = "";
data.RegionFlags = 0;
data.WaterHeight = 0; // not used
data.X = 0;
data.Y = 0;
blocks.Add(data);
}
// private Scene GetClientScene(IClientAPI client)
// {
// foreach (Scene s in m_scenes)
// {
// if (client.Scene.RegionInfo.RegionHandle == s.RegionInfo.RegionHandle)
// return s;
// }
// return m_scene;
// }
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Windows.UI.Xaml.Controls;
using Windows.Devices.Enumeration;
using System.Threading;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.WiFiDirect;
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Windows.UI.Core;
using System.IO;
using System.Threading.Tasks;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Linq;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario2 : Page
{
private MainPage rootPage;
DeviceWatcher _deviceWatcher;
ReaderWriterLockSlim _discoveryRWLock;
bool _fWatcherStarted;
public ObservableCollection<DiscoveredDevice> _discoveredDevices
{
get;
private set;
}
CancellationTokenSource _cancellationTokenSource;
public ObservableCollection<ConnectedDevice> _connectedDevices
{
get;
private set;
}
public Scenario2()
{
this.InitializeComponent();
_discoveryRWLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
_fWatcherStarted = false;
_discoveredDevices = new ObservableCollection<DiscoveredDevice>();
_connectedDevices = new ObservableCollection<ConnectedDevice>();
lvDiscoveredDevices.ItemsSource = _discoveredDevices;
lvDiscoveredDevices.SelectionMode = ListViewSelectionMode.Single;
lvConnectedDevices.ItemsSource = _connectedDevices;
lvConnectedDevices.SelectionMode = ListViewSelectionMode.Single;
}
private void btnWatcher_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (_fWatcherStarted == false)
{
btnWatcher.Content = "Stop Watcher";
_fWatcherStarted = true;
_discoveredDevices.Clear();
rootPage.NotifyUser("Finding Devices...", NotifyType.StatusMessage);
_deviceWatcher = null;
String deviceSelector = WiFiDirectDevice.GetDeviceSelector((cmbDeviceSelector.ToString().Equals("Device Interface") == true) ?
WiFiDirectDeviceSelectorType.DeviceInterface : WiFiDirectDeviceSelectorType.AssociationEndpoint);
_deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });
_deviceWatcher.Added += OnDeviceAdded;
_deviceWatcher.Removed += OnDeviceRemoved;
_deviceWatcher.Updated += OnDeviceUpdated;
_deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
_deviceWatcher.Stopped += OnStopped;
_deviceWatcher.Start();
}
else
{
btnWatcher.Content = "Start Watcher";
_fWatcherStarted = false;
_deviceWatcher.Added -= OnDeviceAdded;
_deviceWatcher.Removed -= OnDeviceRemoved;
_deviceWatcher.Updated -= OnDeviceUpdated;
_deviceWatcher.EnumerationCompleted -= OnEnumerationCompleted;
_deviceWatcher.Stopped -= OnStopped;
_deviceWatcher.Stop();
}
}
#region DeviceWatcherEvents
private async void OnDeviceAdded(DeviceWatcher deviceWatcher, DeviceInformation deviceInfo)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
_discoveryRWLock.EnterWriteLock();
var deviceInfoDisplay = new DiscoveredDevice(deviceInfo);
_discoveredDevices.Add(deviceInfoDisplay);
_discoveryRWLock.ExitWriteLock();
});
}
private async void OnDeviceRemoved(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
_discoveryRWLock.EnterWriteLock();
foreach (DiscoveredDevice devInfodisplay in _discoveredDevices)
{
if (devInfodisplay.DeviceInfo.Id == deviceInfoUpdate.Id)
{
_discoveredDevices.Remove(devInfodisplay);
break;
}
}
_discoveryRWLock.ExitWriteLock();
});
}
private async void OnDeviceUpdated(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
_discoveryRWLock.EnterWriteLock();
for (int idx = 0; idx < _discoveredDevices.Count; idx++)
{
DiscoveredDevice devInfodisplay = _discoveredDevices[idx];
if (devInfodisplay.DeviceInfo.Id == deviceInfoUpdate.Id)
{
devInfodisplay.DeviceInfo.Update(deviceInfoUpdate);
break;
}
}
});
}
private void OnEnumerationCompleted(DeviceWatcher deviceWatcher, object o)
{
rootPage.NotifyUserFromBackground("DeviceWatcher enumeration completed", NotifyType.StatusMessage);
}
private void OnStopped(DeviceWatcher deviceWatcher, object o)
{
rootPage.NotifyUserFromBackground("DeviceWatcher stopped", NotifyType.StatusMessage);
}
#endregion
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
private void btnIe_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (lvDiscoveredDevices.SelectedItems.Count == 0)
{
rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage);
return;
}
var selectedDevices = lvDiscoveredDevices.SelectedItems;
foreach (DiscoveredDevice discoveredDevice in selectedDevices)
{
try
{
var iECollection = WiFiDirectInformationElement.CreateFromDeviceInformation(discoveredDevice.DeviceInfo);
if (iECollection.Count == 0)
{
rootPage.NotifyUser("No Information Elements found", NotifyType.StatusMessage);
return;
}
StringWriter strIeOutput = new StringWriter();
String strIe = "N/A";
foreach (WiFiDirectInformationElement ie in iECollection)
{
Byte[] bOui = ie.Oui.ToArray();
if (bOui.SequenceEqual(Globals.MsftOui))
{
strIeOutput.Write("Microsoft IE: ");
}
else if (bOui.SequenceEqual(Globals.WfaOui))
{
strIeOutput.Write("WFA IE: ");
}
else if (bOui.SequenceEqual(Globals.CustomOui))
{
strIeOutput.Write("Custom IE: ");
DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(ie.Value);
dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
dataReader.ByteOrder = ByteOrder.LittleEndian;
// Read the string.
strIe = dataReader.ReadString(dataReader.ReadUInt32());
}
else
{
strIeOutput.Write("Unknown IE: ");
}
strIeOutput.WriteLine(String.Format("OUI Type: {0} OUI: 0x{1} 0x{2} 0x{3} IE Data: {4}\n",
Convert.ToString(ie.OuiType), Convert.ToString(bOui[0], 16), Convert.ToString(bOui[1], 16),
Convert.ToString(bOui[2], 16), strIe));
strIe = "N/A";
}
rootPage.NotifyUser(strIeOutput.ToString(), NotifyType.StatusMessage);
}
catch (Exception ex)
{
rootPage.NotifyUser("No Information element found: " + ex.Message, NotifyType.ErrorMessage);
}
}
}
private async void btnFromId_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (lvDiscoveredDevices.SelectedItems.Count == 0)
{
rootPage.NotifyUser("No device selected, please select atleast one.", NotifyType.ErrorMessage);
return;
}
var selectedDevices = lvDiscoveredDevices.SelectedItems;
foreach (DiscoveredDevice discoveredDevice in selectedDevices)
{
rootPage.NotifyUser("Connecting to " + discoveredDevice.DeviceInfo.Name + "...", NotifyType.StatusMessage);
try
{
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text);
_cancellationTokenSource = new CancellationTokenSource();
// IMPORTANT: FromIdAsync needs to be called from the UI thread
var wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id, connectionParams).AsTask(_cancellationTokenSource.Token);
// Register for the ConnectionStatusChanged event handler
wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;
var endpointPairs = wfdDevice.GetConnectionEndpointPairs();
rootPage.NotifyUser("Devices connected on L2 layer, connecting to IP Address: " + endpointPairs[0].RemoteHostName +
" Port: " + Globals.strServerPort, NotifyType.StatusMessage);
// Wait for server to start listening on a socket
await Task.Delay(2000);
// Connect to Advertiser on L4 layer
StreamSocket clientSocket = new StreamSocket();
await clientSocket.ConnectAsync(endpointPairs[0].RemoteHostName, Globals.strServerPort);
SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);
string sessionId = "Session: " + Path.GetRandomFileName();
ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);
_connectedDevices.Add(connectedDevice);
socketRW.ReadMessage();
socketRW.WriteMessage(sessionId);
rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
}
catch (TaskCanceledException)
{
rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
}
catch (Exception ex)
{
rootPage.NotifyUser("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
}
_cancellationTokenSource = null;
}
}
private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
{
rootPage.NotifyUserFromBackground("Connection status changed: " + sender.ConnectionStatus, NotifyType.StatusMessage);
}
private void btnSendMessage_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (lvConnectedDevices.SelectedItems.Count == 0)
{
rootPage.NotifyUser("Please select a Session to send data", NotifyType.ErrorMessage);
return;
}
if (txtSendMessage.Text == "")
{
rootPage.NotifyUser("Please type a message to send", NotifyType.ErrorMessage);
return;
}
try
{
foreach (ConnectedDevice connectedDevice in lvConnectedDevices.SelectedItems)
{
connectedDevice.SocketRW.WriteMessage(txtSendMessage.Text);
}
}
catch (Exception ex)
{
rootPage.NotifyUser("Send threw an exception: " + ex.Message, NotifyType.ErrorMessage);
}
}
private void btnClose_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (lvConnectedDevices.SelectedItems.Count == 0)
{
rootPage.NotifyUser("Please select a device to close", NotifyType.ErrorMessage);
return;
}
try
{
foreach (ConnectedDevice connectedDevice in lvConnectedDevices.SelectedItems)
{
// Close socket
connectedDevice.SocketRW.Dispose();
// Close WiFiDirectDevice object
connectedDevice.WfdDevice.Dispose();
_connectedDevices.Remove(connectedDevice);
rootPage.NotifyUser(connectedDevice.DisplayName + " closed successfully", NotifyType.StatusMessage);
}
}
catch (Exception ex)
{
rootPage.NotifyUser("Close threw an exception: " + ex.Message, NotifyType.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
public class ArrayBinarySearch1
{
private const int c_MIN_SIZE = 64;
private const int c_MAX_SIZE = 1024;
private const int c_MIN_STRLEN = 1;
private const int c_MAX_STRLEN = 1024;
public static int Main()
{
ArrayBinarySearch1 ac = new ArrayBinarySearch1();
TestLibrary.TestFramework.BeginTestCase("Array.BinarySearch(Array, int, int, object, IComparer)");
if (ac.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("");
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
retVal = NegTest9() && retVal;
retVal = NegTest10() && retVal;
retVal = NegTest11() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
Array array;
int length;
int element;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest1: Array.BinarySearch(Array, int, int, object, IComparer) where element is found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
element = TestLibrary.Generator.GetInt32(-55);
// fill the array
for (int i=0; i<array.Length; i++)
{
do
{
array.SetValue((object)TestLibrary.Generator.GetInt32(-55), i);
}
while(element == (int)array.GetValue(i));
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
Array.Sort(array);
newIndex = Array.BinarySearch(array, 0, array.Length, (object)element, null);
if (element != (int)array.GetValue(newIndex))
{
TestLibrary.TestFramework.LogError("000", "Unexpected value: Expected(" + element + ") Actual(" + (int)array.GetValue(newIndex) + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Array array;
int length;
MyStruct element;
int index;
int newIndex;
MyStructComparer msc = new MyStructComparer();
TestLibrary.TestFramework.BeginScenario("PosTest2: Array.BinarySearch(Array, int, int, object, IComparer) non-primitive type (not derived from object)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(MyStruct), length);
element = new MyStruct(TestLibrary.Generator.GetSingle(-55));
// fill the array
for (int i=0; i<array.Length; i++)
{
do
{
array.SetValue(new MyStruct(TestLibrary.Generator.GetSingle(-55)), i);
}
while(element.f == ((MyStruct)array.GetValue(i)).f);
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
Array.Sort(array);
newIndex = Array.BinarySearch(array, 0, array.Length, (object)element, msc);
if (element.f != ((MyStruct)array.GetValue(newIndex)).f)
{
TestLibrary.TestFramework.LogError("002", "Unexpected value: Expected(" + element.f + ") Actual(" + ((MyStruct)array.GetValue(newIndex)).f + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
Array array;
int length;
int element;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest1: Array.BinarySearch(Array, int, int, object, IComparer) where element is not found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
element = TestLibrary.Generator.GetInt32(-55);
// fill the array
for (int i=0; i<array.Length; i++)
{
do
{
array.SetValue((object)TestLibrary.Generator.GetInt32(-55), i);
}
while(element == (int)array.GetValue(i));
}
Array.Sort(array);
newIndex = Array.BinarySearch(array, 0, array.Length, (object)element, null);
if (0 <= newIndex)
{
TestLibrary.TestFramework.LogError("004", "Unexpected index: Expected(<0) Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Array array;
int length;
MyStruct element;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest2: Array.BinarySearch(Array, int, int, object, IComparer) non-primitive type (not derived from object) not found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(MyStruct), length);
element = new MyStruct(TestLibrary.Generator.GetSingle(-55));
// fill the array
for (int i=0; i<array.Length; i++)
{
do
{
array.SetValue(new MyStruct(TestLibrary.Generator.GetSingle(-55)), i);
}
while(element.f == ((MyStruct)array.GetValue(i)).f);
}
Array.Sort(array);
newIndex = Array.BinarySearch(array, 0, array.Length, (object)element, null);
if (0 <= newIndex)
{
TestLibrary.TestFramework.LogError("006", "Unexpected index: Expected(<0) Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
Array array;
int length;
int element;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest3: Array.BinarySearch(Array, int, int, object, IComparer) array full of null's");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
element = TestLibrary.Generator.GetInt32(-55);
// fill the array
for (int i=0; i<array.Length; i++)
{
array.SetValue(null, i);
}
newIndex = Array.BinarySearch(array, 0, array.Length, (object)element, null);
if (0 <= newIndex)
{
TestLibrary.TestFramework.LogError("008", "Unexpected index: Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: Array.BinarySearch(Array, int, int, object, IComparer) array is null");
try
{
Array.BinarySearch(null, 0, 0, (object)1, null);
TestLibrary.TestFramework.LogError("010", "Should have thrown an expection");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
Array array;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest5: Array.BinarySearch(Array, int, int, object, IComparer) array of length 0");
try
{
// creat the array
array = Array.CreateInstance(typeof(Int32), 0);
newIndex = Array.BinarySearch(array, 0, array.Length, (object)null, null);
if (0 <= newIndex)
{
TestLibrary.TestFramework.LogError("012", "Unexpected index: Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest6: Array.BinarySearch(Array, int, int, object, IComparer) start index less than lower bound");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.BinarySearch(array, -1, array.Length, (object)null, null);
TestLibrary.TestFramework.LogError("014", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("015", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest7: Array.BinarySearch(Array, int, int, object, IComparer) start index greater than upper bound");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.BinarySearch(array, array.Length, array.Length, (object)null, null);
TestLibrary.TestFramework.LogError("016", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("017", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest8()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest8: Array.BinarySearch(Array, int, int, object, IComparer) count less than 0");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.BinarySearch(array, 0, -1, (object)null, null);
TestLibrary.TestFramework.LogError("018", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("019", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest9()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest9: Array.BinarySearch(Array, int, int, object, IComparer) (startindex < 0)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.BinarySearch(array, -1, array.Length, (object)null, null);
TestLibrary.TestFramework.LogError("020", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("021", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest10()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest10: Array.BinarySearch(Array, int, int, object, IComparer) multi dim array");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), new int[2] {length, length});
Array.BinarySearch(array, 0, array.Length, (object)null, null);
TestLibrary.TestFramework.LogError("022", "Should have thrown an exception");
retVal = false;
}
catch (RankException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("023", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest11()
{
bool retVal = true;
Array array;
int length;
MyStruct2 element;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest11: Array.BinarySearch(Array, int, int, object, IComparer) non-primitive type (not derived from object or IComparable)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(MyStruct2), length);
element = new MyStruct2(TestLibrary.Generator.GetSingle(-55));
// fill the array
for (int i=0; i<array.Length; i++)
{
do
{
array.SetValue(new MyStruct2(TestLibrary.Generator.GetSingle(-55)), i);
}
while(element.f == ((MyStruct2)array.GetValue(i)).f);
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
Array.Sort(array);
newIndex = Array.BinarySearch(array, 0, array.Length, (object)element, null);
TestLibrary.TestFramework.LogError("024", "Exception expected");
retVal = false;
}
catch (InvalidOperationException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("025", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public struct MyStruct : IComparable
{
public float f;
public MyStruct(float ff) { f = ff; }
public int CompareTo(object obj)
{
MyStruct m1 = (MyStruct)obj;
if (m1.f == f) return 0;
return ((m1.f < f)?1:-1);
}
}
public struct MyStruct2
{
public float f;
public MyStruct2(float ff) { f = ff; }
}
public class MyStructComparer : IComparer
{
public int Compare(object x, object y)
{
MyStruct m1 = (MyStruct)x;
MyStruct m2 = (MyStruct)y;
if (m1.f == m2.f) return 0;
return ((m1.f < m2.f)?-1:1);
}
}
}
| |
using System;
using System.Collections.Generic;
using Gtk;
using Moscrif.IDE.Tool;
using Pango;
using System.Linq;
namespace Moscrif.IDE.Task
{
public class TodoOutput : Gtk.ScrolledWindow,ITaskOutput
{
private ListStore outputModel = new ListStore(typeof(string), typeof(string), typeof(string), typeof(string), typeof(TaskMessage));
private TreeView treeView = null;
Queue<QueuedUpdate> updates = new Queue<QueuedUpdate>();
QueuedTextWrite lastTextWrite;
bool outputDispatcherRunning = false;
GLib.TimeoutHandler outputDispatcher;
private List<TaskMessage> oldError;
#region ITaskOutput implementation
void ITaskOutput.ClearOutput ()
{
Clear();
}
#endregion
public TodoOutput()
{
this.ShadowType = ShadowType.Out;
treeView = new TreeView();
treeView.Selection.Mode = Gtk.SelectionMode.Single;
treeView.Model = outputModel;
FontDescription customFont = Pango.FontDescription.FromString(MainClass.Settings.ConsoleTaskFont);
treeView.ModifyFont(customFont);
Gtk.CellRendererText fileNameRenderer = new Gtk.CellRendererText();
TreeViewColumn tvcName = new TreeViewColumn (MainClass.Languages.Translate("description"), fileNameRenderer, "text", 0);
tvcName.MinWidth = 350;
tvcName.Resizable = true;
treeView.AppendColumn(tvcName);
TreeViewColumn tvcState = new TreeViewColumn (MainClass.Languages.Translate("file"), fileNameRenderer, "text", 3);
tvcState.MinWidth = 50;
tvcState.Resizable = true;
treeView.AppendColumn(tvcState);
TreeViewColumn tvcMessage = new TreeViewColumn ( MainClass.Languages.Translate("line"), fileNameRenderer, "text", 2);
tvcMessage.MinWidth = 25;
tvcMessage.Resizable = true;
tvcMessage.Visible = false;
treeView.AppendColumn(tvcMessage);
treeView.HeadersVisible = true;
treeView.EnableTreeLines = true;
treeView.RowActivated += new RowActivatedHandler(OnRowActivate);
treeView.EnableSearch =false;
treeView.HasFocus = false;
treeView.ButtonReleaseEvent += delegate(object o, ButtonReleaseEventArgs args) {
if (args.Event.Button != 3) return;
Menu popupMenu = new Menu();
/*
MenuItem miClear = new MenuItem( MainClass.Languages.Translate("clear" ));
miClear.Activated+= delegate(object sender, EventArgs e) {
Clear();
};
popupMenu.Append(miClear);*/
TreeSelection ts = treeView.Selection;
Gtk.TreePath[] selRow = ts.GetSelectedRows();
MenuItem miCopy = new MenuItem( MainClass.Languages.Translate("copy_f2" ));
miCopy.Activated+= delegate(object sender, EventArgs e) {
Gtk.TreePath tp = selRow[0];
TreeIter ti = new TreeIter();
outputModel.GetIter(out ti, tp);
string type = outputModel.GetValue(ti, 0).ToString();
string timeStamp = outputModel.GetValue(ti, 1).ToString();
//string message = outputModel.GetValue(ti, 2).ToString();
Gtk.Clipboard clipboard = this.GetClipboard(Gdk.Selection.Clipboard);
string txt =type +"\t"+timeStamp;//+"\t"+message;
clipboard.Text=txt;
};
popupMenu.Append(miCopy);
if(selRow.Length<1){
miCopy.Sensitive = false;
}
popupMenu.Popup();
popupMenu.ShowAll();
};
outputDispatcher = new GLib.TimeoutHandler(OutputDispatchHandler);
this.Add(treeView);
oldError = new List<TaskMessage>();
this.ShowAll();
}
private void OnRowActivate(object o, RowActivatedArgs args)
{
TreeIter ti = new TreeIter();
//filter.GetIter(out ti, args.Path);
//TreePath childTP = outputModel.ConvertPathToChildPath(args.Path);
try {
outputModel.GetIter(out ti, args.Path);
//if (ti != TreeIter.Zero) {
string pFile = outputModel.GetValue(ti, 1).ToString();
string pLine = outputModel.GetValue(ti, 2).ToString();
if (!String.IsNullOrEmpty(pFile)) {
MainClass.MainWindow.GoToFile(pFile, (object)pLine);
}
//}
} catch {
}
}
public void SetFont(string fontname){
FontDescription customFont = Pango.FontDescription.FromString(MainClass.Settings.ConsoleTaskFont);
treeView.ModifyFont(customFont);
}
public void WriteTask(string name, string status, List<string> errors)
{
//raw text has an extra optimisation here, as we can append it to existing updates
lock (updates) {
if (errors != null) {
foreach (string str in errors)
outputModel.AppendValues("ERROR", str, "","");
}
}
}
public void WriteTask(object task, string name, string status, List<TaskMessage> error, bool clearOutput)
{
//if (clearOutput)
// Clear();
//Console.WriteLine("WriteTask error ->{0}",error.Count);
//TaskResult tr = new TaskResult(name, status, error);
//raw text has an extra optimisation here, as we can append it to existing updates
/*lock (updates) {
if (lastTextWrite != null) {
if (lastTextWrite.Tag == null) {
lastTextWrite.Write(tr);
return;
}
}
}*/
QueuedTextWrite qtw = new QueuedTextWrite(error);
AddQueuedUpdate(qtw);
}
public void WriteTask(object sender, string name, string status,TaskMessage error)
{
List<TaskMessage> list = new List<TaskMessage>();
list.Add(error);
WriteTask(sender, name, status, list, false);
}
public void Clear()
{
lock (updates) {
updates.Clear();
lastTextWrite = null;
outputDispatcherRunning = false;
}
outputModel.Clear();
}
//**//
void AddQueuedUpdate(QueuedUpdate update)
{
lock (updates) {
updates.Enqueue(update);
if (!outputDispatcherRunning) {
GLib.Timeout.Add(50, outputDispatcher);
outputDispatcherRunning = true;
}
lastTextWrite = update as QueuedTextWrite;
}
}
bool OutputDispatchHandler()
{
lock (updates) {
lastTextWrite = null;
if (updates.Count == 0) {
outputDispatcherRunning = false;
return false;
} else if (!outputDispatcherRunning) {
updates.Clear();
return false;
} else {
while (updates.Count > 0) {
QueuedUpdate up = updates.Dequeue();
up.Execute(this);
}
}
}
return true;
}
//
protected void UnsafeAddText(List<TaskMessage> list)
{
try {
TreeSelection ts = treeView.Selection;
Gtk.TreePath[] selRow = ts.GetSelectedRows();
bool isSelected = false;
Gtk.TreePath tpSelected = null;
if(selRow.Length>0){
tpSelected = selRow[0];
isSelected = true;
}
List<TaskMessage> addRecord = new List<TaskMessage>();
List<TaskMessage> removeRecord= new List<TaskMessage>();
if(oldError.Count > 0){
addRecord = new List<TaskMessage>(list.Except(oldError).ToArray());
removeRecord = new List<TaskMessage>(oldError.Except(list).ToArray());
foreach(TaskMessage ti in removeRecord)
oldError.Remove(ti);
oldError.AddRange(addRecord);
} else {
oldError.AddRange(list);
addRecord = list;
}
if(removeRecord.Count()>0){
List<TreeIter> listIterr = new List<TreeIter>();
outputModel.Foreach((model, path, iterr) =>
{
TaskMessage tm = (TaskMessage)outputModel.GetValue(iterr, 4);
//Console.WriteLine("tm.->"+tm.Message);
if(removeRecord.Contains(tm)){
//Console.WriteLine("Find TM - >"+tm.Message);
listIterr.Add(iterr);
}
if(path == tpSelected)
isSelected = false;
return false;
});
foreach(TreeIter ti in listIterr){
TreeIter ti2 =ti;
outputModel.Remove(ref ti2);
}
}
if (addRecord != null) {
foreach (TaskMessage tm in addRecord){
//Console.WriteLine("UnsafeAddText->"+tm.Message);
string message = tm.Message.Replace("\r","");
message = message.Replace("\n","");
message = message.Replace("//","");
message = message.Replace(@"/*","");
message = message.Replace(@"*/","");
message= message.TrimStart();
outputModel.AppendValues(message,tm.File, tm.Line, System.IO.Path.GetFileName(tm.File),tm);
}
}
if(isSelected)
treeView.Selection.SelectPath(tpSelected);
/*ScrolledWindow window = treeView.Parent as ScrolledWindow;
bool scrollToEnd = true;
if (window != null) {
scrollToEnd = window.Vadjustment.Value >= window.Vadjustment.Upper - 2 * window.Vadjustment.PageSize;
}
//if (extraTag != null)
// buffer.InsertWithTags(ref it, text, tag, extraTag);
//else
// buffer.InsertWithTags(ref it, text, tag);
if (scrollToEnd) {
//it.LineOffset = 0;
//TreePath path = outputModel.GetPath(iter);
//treeView.ScrollToCell(path, null, false, 0, 0);
//outputModel.MoveBefore(iter,TreeIter.Zero);
//buffer.MoveMark(endMark, it);
//treeView.ScrollToCell() ScrollToMark(endMark, 0, false, 0, 0);
}*/
} catch(Exception ex) {
Logger.Error(ex.Message,null);
}
}
private abstract class QueuedUpdate
{
public abstract void Execute(TodoOutput pad);
}
private class QueuedTextWrite : QueuedUpdate
{
private List<TaskMessage> list;
public override void Execute(TodoOutput pad)
{
pad.UnsafeAddText(list);
}
public QueuedTextWrite(List<TaskMessage> list)
{
this.list = list;
}
public void Write(string s)
{
Console.WriteLine("ERROR Write TODOOutput");
//Text.Append(s);
//if (Text.Length > MAX_BUFFER_LENGTH)
/// Text.Remove(0, Text.Length - MAX_BUFFER_LENGTH);
}
}
}
}
| |
using System.Collections.Generic;
namespace DotLua.Ast
{
public enum BinaryOp
{
Addition,
Subtraction,
Multiplication,
Division,
Power,
Modulo,
Concat,
GreaterThan,
GreaterOrEqual,
LessThan,
LessOrEqual,
Equal,
Different,
And,
Or
}
public enum UnaryOp
{
Negate,
Invert,
Length
}
public abstract class AstElement
{
public int lineNumber, columnNumber;
public string filename;
}
public interface IStatement
{
}
public interface IExpression
{
}
public interface ILiteral
{
LuaObject GetValue();
}
public interface IAssignable : IExpression
{
}
public class Variable : AstElement, IExpression, IAssignable
{
// Prefix.Name
//public IExpression Prefix;
public string Name;
}
public class Argument : AstElement
{
public string Name;
}
public class StringLiteral : AstElement, IExpression
{
public string Value;
public LuaObject GetValue()
{
return LuaObject.FromString(Value);
}
}
public class NumberLiteral : AstElement, IExpression
{
public double Value;
public LuaObject GetValue()
{
return LuaObject.FromNumber(Value);
}
}
public class NilLiteral : AstElement, IExpression
{
public LuaObject GetValue()
{
return LuaObject.Nil;
}
}
public class BoolLiteral : AstElement, IExpression
{
public bool Value;
public LuaObject GetValue()
{
return LuaObject.FromBool(Value);
}
}
public class VarargsLiteral : AstElement, IExpression
{
}
public class FunctionCall : AstElement, IStatement, IExpression
{
public IExpression Function;
public List<IExpression> Arguments = new List<IExpression>();
}
public class TableAccess : AstElement, IExpression, IAssignable
{
// Expression[Index]
public IExpression Expression;
public IExpression Index;
}
public class FunctionDefinition : AstElement, IExpression
{
// function(Arguments) Body end
public List<Argument> Arguments = new List<Argument>();
public bool isVarargs;
public Block Body;
}
public class BinaryExpression : AstElement, IExpression
{
public IExpression Left, Right;
public BinaryOp Operation;
}
public class UnaryExpression : AstElement, IExpression
{
public IExpression Expression;
public UnaryOp Operation;
}
public class TableConstructor : AstElement, IExpression
{
public Dictionary<IExpression, IExpression> Values = new Dictionary<IExpression, IExpression>();
}
public class Assignment : AstElement, IStatement
{
// Var1, Var2, Var3 = Exp1, Exp2, Exp3
//public Variable[] Variables;
//public IExpression[] Expressions;
public List<IAssignable> Variables = new List<IAssignable>();
public List<IExpression> Expressions = new List<IExpression>();
}
public class ReturnStat : AstElement, IStatement
{
public List<IExpression> Expressions = new List<IExpression>();
}
public class BreakStat : AstElement, IStatement
{
}
public class LocalAssignment : AstElement, IStatement
{
public List<string> Names = new List<string>();
public List<IExpression> Values = new List<IExpression>();
}
public class Block : AstElement, IStatement
{
public List<IStatement> Statements = new List<IStatement>();
}
public class WhileStat : AstElement, IStatement
{
public Block Block;
public IExpression Condition;
}
public class RepeatStat : AstElement, IStatement
{
public Block Block;
public IExpression Condition;
}
public class NumericFor : AstElement, IStatement
{
public Block Block;
public IExpression Var, Limit, Step;
public string Variable;
}
public class GenericFor : AstElement, IStatement
{
public Block Block;
public List<IExpression> Expressions = new List<IExpression>();
public List<string> Variables = new List<string>();
}
public class IfStat : AstElement, IStatement
{
public Block Block;
public IExpression Condition;
public Block ElseBlock;
public List<IfStat> ElseIfs = new List<IfStat>();
}
}
| |
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;
using System.Globalization;
namespace com.esri.gpt.csw
{
/// <summary>
/// CswProfile class represents CswProfile object
/// </summary>
public class CswProfile
{
private string id;
private string name;
private string cswnamespace;
private string kvp;
private string description;
private string requestxslt;
private string responsexslt;
private string metadataxslt;
private string displayResponseXslt;
private bool filter_livedatamap;
private bool filter_extentsearch;
private bool filter_spatialboundary;
private XslCompiledTransform requestxsltobj;
private XslCompiledTransform responsexsltobj;
private XslCompiledTransform metadataxsltobj;
private XslCompiledTransform displayResponseXsltObj;
#region "Properties"
/// <summary>
/// ID parameter
/// </summary>
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
/// <summary>
/// Name parameter
/// </summary>
public string Name
{
set
{
name = value;
}
get
{
return name;
}
}
/// <summary>
/// CswNamespace parameter
/// </summary>
public string CswNamespace
{
get
{
return cswnamespace;
}
set
{
cswnamespace = value;
}
}
/// <summary>
/// Description parameter
/// </summary>
public string Description
{
set
{
description = value;
}
get
{
return description;
}
}
/// <summary>
/// SupportContentTypeQuery parameter
/// </summary>
public bool SupportContentTypeQuery
{
set
{
filter_livedatamap = value;
}
get
{
return filter_livedatamap;
}
}
/// <summary>
/// SupportSpatialQuery parameter
/// </summary>
public bool SupportSpatialQuery
{
set
{
filter_extentsearch = value;
}
get
{
return filter_extentsearch;
}
}
/// <summary>
/// SupportSpatialBoundary parameter
/// </summary>
public bool SupportSpatialBoundary
{
get
{
return filter_spatialboundary;
}
set
{
filter_spatialboundary = value;
}
}
#endregion
# region "ConstructorDefinition"
/// <summary>
/// Constructor
/// </summary>
/// <param name="sid"></param>
/// <param name="sname"></param>
/// <param name="sdescription"></param>
public CswProfile(string sid, string sname, string sdescription)
{
ID = sid;
Name = sname;
Description = sdescription;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="sid"></param>
/// <param name="sname"></param>
/// <param name="sdescription"></param>
/// <param name="skvp"></param>
/// <param name="srequestxslt"></param>
/// <param name="sresponsexslt"></param>
/// <param name="smetadataxslt"></param>
/// <param name="sdisplayResponseXslt"></param>
/// <param name="livedatamap"></param>
/// <param name="extentsearch"></param>
/// <param name="spatialboundary"></param>
public CswProfile(string sid, string sname, string sdescription, string skvp, string srequestxslt, string sresponsexslt, string smetadataxslt, string sdisplayResponseXslt, bool livedatamap, bool extentsearch, bool spatialboundary)
{
ID = sid;
Name = sname;
CswNamespace = CswProfiles.DEFAULT_CSW_NAMESPACE;
Description = sdescription;
kvp = skvp;
requestxslt = srequestxslt;
responsexslt = sresponsexslt;
metadataxslt = smetadataxslt;
displayResponseXslt = sdisplayResponseXslt;
filter_livedatamap = livedatamap;
filter_extentsearch = extentsearch;
filter_spatialboundary = spatialboundary;
//enable document() support
XsltSettings settings = new XsltSettings(true, true);
XmlUrlResolver xmlurlresolver = new XmlUrlResolver();
responsexsltobj = new XslCompiledTransform();
responsexsltobj.Load(responsexslt, settings, xmlurlresolver);
requestxsltobj = new XslCompiledTransform();
requestxsltobj.Load(requestxslt, settings, xmlurlresolver);
if (metadataxslt.Length > 0)
{
metadataxsltobj = new XslCompiledTransform();
//enable document() support
metadataxsltobj.Load(metadataxslt, settings, xmlurlresolver);
}
if (displayResponseXslt.Length > 0)
{
displayResponseXsltObj = new XslCompiledTransform();
//enable document() support
displayResponseXsltObj.Load(displayResponseXslt, settings, xmlurlresolver);
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="sid"></param>
/// <param name="sname"></param>
/// <param name="scswnamespace"></param>
/// <param name="sdescription"></param>
/// <param name="skvp"></param>
/// <param name="srequestxslt"></param>
/// <param name="sresponsexslt"></param>
/// <param name="smetadataxslt"></param>
/// <param name="sdisplayResponseXslt"></param>
/// <param name="livedatamap"></param>
/// <param name="extentsearch"></param>
/// <param name="spatialboundary"></param>
public CswProfile(string sid, string sname, string scswnamespace, string sdescription, string skvp, string srequestxslt, string sresponsexslt, string smetadataxslt, string sdisplayResponseXslt, bool livedatamap, bool extentsearch, bool spatialboundary)
{
ID = sid;
Name = sname;
CswNamespace = scswnamespace;
Description = sdescription;
kvp = skvp;
requestxslt = srequestxslt;
responsexslt = sresponsexslt;
metadataxslt = smetadataxslt;
displayResponseXslt = sdisplayResponseXslt;
filter_livedatamap = livedatamap;
filter_extentsearch = extentsearch;
filter_spatialboundary = spatialboundary;
//enable document() support
XsltSettings settings = new XsltSettings(true, true);
XmlUrlResolver xmlurlresolver = new XmlUrlResolver();
responsexsltobj = new XslCompiledTransform();
responsexsltobj.Load(responsexslt, settings, xmlurlresolver);
requestxsltobj = new XslCompiledTransform();
requestxsltobj.Load(requestxslt, settings, xmlurlresolver);
if (metadataxslt.Length > 0)
{
metadataxsltobj = new XslCompiledTransform();
metadataxsltobj.Load(metadataxslt, settings, xmlurlresolver);
}
if (displayResponseXslt.Length > 0)
{
displayResponseXsltObj = new XslCompiledTransform();
//enable document() support
displayResponseXsltObj.Load(displayResponseXslt, settings, xmlurlresolver);
}
}
#endregion
# region "PublicFunctions"
/// <summary>
/// Parse a CSW response.
/// </summary>
/// <remarks>
/// The CSW response is parsed and the records collection is populated
/// with the result.The reponse is parsed based on the response xslt.
/// </remarks>
/// <param name="param1">The string response</param>
/// <param name="param2">The recordlist which needs to be populated</param>
public void ReadCSWGetRecordsResponse(string responsestring, CswRecords recordslist)
{
try
{
TextReader textreader = new StringReader(responsestring);
XmlTextReader xmltextreader = new XmlTextReader(textreader);
//load the Xml doc
XPathDocument xPathDoc = new XPathDocument(xmltextreader);
if (responsexsltobj == null)
{
responsexsltobj = new XslCompiledTransform();
XsltSettings settings = new XsltSettings(true, true);
responsexsltobj.Load(responsexslt, settings, new XmlUrlResolver());
}
//create the output stream
StringWriter writer = new StringWriter();
//do the actual transform of Xml
responsexsltobj.Transform(xPathDoc, null, writer);
writer.Close();
//populate CswRecords
XmlDocument doc = new XmlDocument();
doc.LoadXml(writer.ToString());
XmlNodeList xmlnodes = doc.GetElementsByTagName("Record");
foreach (XmlNode xmlnode in xmlnodes)
{
CswRecord record = new CswRecord();
record.ID = xmlnode.SelectSingleNode("ID").InnerText;
record.Title = xmlnode.SelectSingleNode("Title").InnerText;
record.Abstract = xmlnode.SelectSingleNode("Abstract").InnerText;
String lowercorner = "";
if (this.SupportSpatialBoundary)
{
lowercorner = xmlnode.SelectSingleNode("LowerCorner").InnerText;
}
String uppercorner = "";
if (this.SupportSpatialBoundary)
{
uppercorner = xmlnode.SelectSingleNode("UpperCorner").InnerText;
}
if ((lowercorner.Length > 0 && uppercorner.Length > 0))
{
/* record.BoundingBox.Maxx = Double.Parse(lowercorner.Substring(0, lowercorner.IndexOf(' ')));
record.BoundingBox.Miny = Double.Parse(lowercorner.Substring(lowercorner.IndexOf(' ') + 1));
record.BoundingBox.Minx = Double.Parse(uppercorner.Substring(0, uppercorner.IndexOf(' ')));
record.BoundingBox.Maxy = Double.Parse(uppercorner.Substring(uppercorner.IndexOf(' ') + 1));*/
Boolean parseFlag = false;
CultureInfo cultureInfo = new CultureInfo("en-us");
double pareseResult = 0.0;
parseFlag = Double.TryParse(lowercorner.Substring(0, lowercorner.IndexOf(' ')), NumberStyles.Number, cultureInfo, out pareseResult);
record.BoundingBox.Minx = pareseResult;
parseFlag = Double.TryParse(lowercorner.Substring(lowercorner.IndexOf(' ') + 1), NumberStyles.Number, cultureInfo, out pareseResult);
record.BoundingBox.Miny = pareseResult;
parseFlag = Double.TryParse(uppercorner.Substring(0, uppercorner.IndexOf(' ')), NumberStyles.Number, cultureInfo, out pareseResult);
record.BoundingBox.Maxx = pareseResult;
parseFlag = Double.TryParse(uppercorner.Substring(uppercorner.IndexOf(' ') + 1), NumberStyles.Number, cultureInfo, out pareseResult);
record.BoundingBox.Maxy = pareseResult;
if (parseFlag == false)
{
throw new Exception("Number format error");
}
}
else
{
record.BoundingBox.Maxx = 500.00;
record.BoundingBox.Miny = 500.00;
record.BoundingBox.Minx = 500.00;
record.BoundingBox.Maxy = 500.00;
}
XmlNode node = xmlnode.SelectSingleNode("Type");
if (node != null)
{
record.IsLiveDataOrMap = node.InnerText.Equals("liveData", StringComparison.OrdinalIgnoreCase);
}
else
{
record.IsLiveDataOrMap = false;
}
XmlNode referencesNode = xmlnode.SelectSingleNode("References");
if (referencesNode != null)
{
String references = referencesNode.InnerText;
DcList list = new DcList();
list.add(references);
determineResourceUrl(record, list);
/* LinkedList<String> serverList = list.get(DcList.getScheme(DcList.Scheme.SERVER));
if (serverList.Count > 0)
{
String serviceType = getServiceType(serverList.First.Value);
if (serviceType.Equals("aims") || serviceType.Equals("ags") || serviceType.Equals("wms") || serviceType.Equals("wcs"))
{
record.MapServerURL = serverList.First.Value;
}
}*/
}
else
record.MapServerURL = "";
recordslist.AddRecord(record.ID.GetHashCode(), record);
}
}
catch (Exception e)
{
throw e;
}
//return recordslist;
}
/// <summary>
/// Determins resource urls
/// </summary>
/// <param name="cswRecord">CswRecord object</param>
/// <param name="references">List of references</param>
private void determineResourceUrl(CswRecord cswRecord, DcList references)
{
// initialize
String resourceUrl = "";
String serviceType = "";
String serviceName = "";
// determine the service url, name and type
LinkedList<String> schemeVals = references.get(DcList.getScheme(DcList.Scheme.SERVER));
if (schemeVals.Count > 0)
{
resourceUrl = chkStr(schemeVals.First.Value);
}
schemeVals = references.get(DcList.getScheme(DcList.Scheme.SERVICE));
if (schemeVals.Count > 0)
{
serviceName = chkStr((schemeVals.First.Value));
}
schemeVals = references.get(DcList.getScheme(DcList.Scheme.SERVICE_TYPE));
if (schemeVals.Count > 0)
{
serviceType = (schemeVals.First.Value);
}
if ((resourceUrl.Length > 0) && (serviceType.Length == 0))
{
serviceType = getServiceType(resourceUrl);
}
// handle the case where an ArcIMS service has been specified with
// server/service/serviceType parameters
if ((resourceUrl.Length > 0) &&
(serviceType.Equals("image", StringComparison.CurrentCultureIgnoreCase) ||
serviceType.Equals("feature") ||
serviceType.Equals("metadata")))
{
if ((serviceName.Length > 0))
{
String esrimap = "servlet/com.esri.esrimap.Esrimap";
if (resourceUrl.IndexOf("esrimap") == -1)
{
if (resourceUrl.IndexOf("?") == -1)
{
if (!resourceUrl.EndsWith("/")) resourceUrl += "/";
resourceUrl = resourceUrl + esrimap + "?ServiceName=" + serviceName;
}
}
else
{
if (resourceUrl.IndexOf("?") == -1)
{
resourceUrl = resourceUrl + "?ServiceName=" + serviceName;
}
else if (resourceUrl.IndexOf("ServiceName=") == -1)
{
resourceUrl = resourceUrl + "&ServiceName=" + serviceName;
}
}
}
if (serviceType.Equals("image"))
{
serviceType = "aims";
}
}
// if the resource url has not been directly specified through a "scheme" attribute,
// then attempt to pick the best fit for the collection of references
if (resourceUrl.Length == 0)
{
foreach (DcList.Value reference in references)
{
if (reference != null)
{
String url = reference.getValue();
String type = getServiceType(url);
if (type.Length > 0)
{
resourceUrl = url;
serviceType = type;
break;
}
}
}
}
// update the record
cswRecord.MapServerURL = resourceUrl;
cswRecord.ServiceName = serviceName;
cswRecord.ServiceType = serviceType;
}
/// <summary>
/// Checks if a string is null or empty
/// </summary>
/// <param name="s">string to check</param>
/// <returns></returns>
public static String chkStr(String s)
{
if (s == null)
{
return "";
}
else
{
return s.Trim();
}
}
/// <summary>
/// Parses service information from url
/// </summary>
/// <param name="msinfo">map service information</param>
/// <param name="mapServerUrl">map service url</param>
/// <param name="serviceType">map service type</param>
public static void ParseServiceInfoFromUrl(MapServiceInfo msinfo, String mapServerUrl, String serviceType)
{
msinfo.Service = "Generic " + serviceType + " Service Name";
String[] urlParts = mapServerUrl.Trim().Split('?');
if (urlParts.Length > 0)
msinfo.Server = urlParts[0];
else
msinfo.Server = mapServerUrl;
String[] s = msinfo.Server.Split(new String[] { "/servlet/com.esri.esrimap.Esrimap" }, StringSplitOptions.RemoveEmptyEntries);
msinfo.Server = s[0];
if (urlParts.Length > 1)
{
String[] urlParams = urlParts[1].Trim().Split('&');
foreach (String param in urlParams)
{
String paramPrefix = param.ToLower().Trim();
if (paramPrefix.StartsWith("service=") || paramPrefix.StartsWith("servicename="))
{
msinfo.Service = param.Trim().Split('=')[1];
}
else if (paramPrefix.StartsWith("map="))
{
msinfo.ServiceParam = param.Trim();
}
}
}
}
/// <summary>
/// Generate a CSW request string.
/// </summary>
/// <remarks>
/// The CSW request string is built.
/// The request is string is build based on the request xslt.
/// </remarks>
/// <param name="param1">The search criteria</param>
/// <returns>The request string</returns>
public string GenerateCSWGetRecordsRequest(CswSearchCriteria search)
{
//build xml
StringWriter writer = new StringWriter();
StringBuilder request = new StringBuilder();
request.Append("<?xml version='1.0' encoding='UTF-8'?>");
request.Append("<GetRecords>");
request.Append("<StartPosition>" + search.StartPosition + "</StartPosition>");
request.Append("<MaxRecords>" + search.MaxRecords + "</MaxRecords>");
request.Append("<KeyWord>" + this.XmlEscape(search.SearchText) + "</KeyWord>");
request.Append("<LiveDataMap>" + search.LiveDataAndMapOnly.ToString() + "</LiveDataMap>");
if (search.Envelope != null)
{
request.Append("<Envelope>");
request.Append("<MinX>" + search.Envelope.MinX + "</MinX>");
request.Append("<MinY>" + search.Envelope.MinY + "</MinY>");
request.Append("<MaxX>" + search.Envelope.MaxX + "</MaxX>");
request.Append("<MaxY>" + search.Envelope.MaxY + "</MaxY>");
request.Append("</Envelope>");
}
request.Append("</GetRecords>");
try
{
TextReader textreader = new StringReader(request.ToString());
XmlTextReader xmltextreader = new XmlTextReader(textreader);
//load the Xml doc
XPathDocument myXPathDoc = new XPathDocument(xmltextreader);
if (requestxsltobj == null)
{
requestxsltobj = new XslCompiledTransform();
XsltSettings settings = new XsltSettings(true, true);
requestxsltobj.Load(requestxslt, settings, new XmlUrlResolver());
}
//do the actual transform of Xml
requestxsltobj.Transform(myXPathDoc, null, writer);
//requestxsltobj.Transform(myXPathDoc, null, writer);
writer.Close();
}
catch (Exception e)
{
throw e;
}
return writer.ToString();
}
/// <summary>
/// Generate a CSW request string to get metadata by ID.
/// </summary>
/// <remarks>
/// The CSW request string is built.
/// The request is string is build based on the baseurl and record id
/// </remarks>
/// <param name="param1">The base url</param>
/// <param name="param2">The record ID string</param>
/// <returns>The request string</returns>
public string GenerateCSWGetMetadataByIDRequestURL(string baseURL, string recordId)
{
StringBuilder requeststring = new StringBuilder();
requeststring.Append(baseURL);
if (baseURL.LastIndexOf("?") == (baseURL.Length - 1)) { requeststring.Append(kvp); }
else { requeststring.Append("?" + kvp); }
requeststring.Append("&ID=" + recordId);
return requeststring.ToString();
}
/// <summary>
/// Read a CSW metadata response.
/// </summary>
/// <remarks>
/// The CSW metadata response is read.
/// The CSw record is updated with the metadata
/// </remarks>
/// <param name="param1">The metadata response string</param>
/// <param name="param2">The CSW record for the record</param>
public void ReadCSWGetMetadataByIDResponse(string response, CswRecord record)
{
if (metadataxslt == null || metadataxslt.Equals(""))
{
record.FullMetadata = response;
record.MetadataResourceURL = "";
}
else
{
//create the output stream
StringWriter writer = new StringWriter();
TextReader textreader = new StringReader(response);
XmlTextReader xmltextreader = new XmlTextReader(textreader);
//load the Xml doc
XPathDocument xpathDoc = new XPathDocument(xmltextreader);
if (metadataxsltobj == null)
{
metadataxsltobj = new XslCompiledTransform();
//enable document() support
XsltSettings settings = new XsltSettings(true, true);
metadataxsltobj.Load(metadataxslt, settings, new XmlUrlResolver());
}
//do the actual transform of Xml
metadataxsltobj.Transform(xpathDoc, null, writer);
writer.Close();
// full metadata or resource url
String outputStr = writer.ToString();
if (IsUrl(outputStr))
{
if (outputStr.Contains("\u2715"))
{
DcList list = new DcList();
list.add(outputStr);
LinkedList<String> serverList = list.get(DcList.getScheme(DcList.Scheme.SERVER));
LinkedList<String> documentList = list.get(DcList.getScheme(DcList.Scheme.METADATA_DOCUMENT));
if (serverList.Count > 0)
{
String serviceType = getServiceType(serverList.First.Value);
if (serviceType.Equals("aims") || serviceType.Equals("ags") || serviceType.Equals("wms") || serviceType.Equals("wcs"))
{
record.MapServerURL = serverList.First.Value;
}
}
else
record.MapServerURL = "";
if (documentList.Count > 0)
record.MetadataResourceURL = documentList.First.Value;
}
else
{
if (getServiceType(response).Equals("ags"))
{
outputStr = outputStr.Replace("http", "|http");
string[] s = outputStr.Split('|');
for (int i = 0; i < s.Length; i++)
{
if (s[i].ToString().Contains("MapServer"))
record.MapServerURL = s[i];
else
record.MetadataResourceURL = s[i];
}
}
else
{
record.MapServerURL = "";
record.MetadataResourceURL = outputStr;
}
}
record.FullMetadata = "";
}
else
{
record.MapServerURL = "";
record.MetadataResourceURL = "";
record.FullMetadata = outputStr;
}
}
}
/// <summary>
/// Transform a CSW metadata response.
/// </summary>
/// <remarks>
/// The CSW metadata response is read.
/// The CSw record is updated with the metadata
/// </remarks>
/// <param name="param1">The metadata response string</param>
/// <param name="param2">The CSW record for the record</param>
public bool TransformCSWGetMetadataByIDResponse(string response, CswRecord record)
{
if (displayResponseXslt == null || displayResponseXslt.Equals(""))
{
record.FullMetadata = response;
record.MetadataResourceURL = "";
return false;
}
else
{
//create the output stream
StringWriter writer = new StringWriter();
TextReader textreader = new StringReader(response);
XmlTextReader xmltextreader = new XmlTextReader(textreader);
//load the Xml doc
XPathDocument xpathDoc = new XPathDocument(xmltextreader);
if (displayResponseXsltObj == null)
{
displayResponseXsltObj = new XslCompiledTransform();
//enable document() support
XsltSettings settings = new XsltSettings(true, true);
displayResponseXsltObj.Load(displayResponseXslt, settings, new XmlUrlResolver());
}
//do the actual transform of Xml
displayResponseXsltObj.Transform(xpathDoc, null, writer);
writer.Close();
// full metadata or resource url
String outputStr = writer.ToString();
record.MapServerURL = "";
record.MetadataResourceURL = "";
record.FullMetadata = outputStr;
return true;
}
}
/// <summary>
/// Returns service type derieved from a url
/// </summary>
/// <param name="url">service url</param>
/// <returns>servuce type</returns>
public static String getServiceType(String url)
{
String serviceType = "unknown";
url = url.ToLower();
if (url.Contains("service=wms") || url.Contains("com.esri.wms.esrimap") || url.Contains("/mapserver/wmsserver") || url.Contains("/wmsserver") || url.Contains("wms"))
{
serviceType = "wms";
}
else if (url.Contains("service=wfs") || url.Contains("wfsserver"))
{
serviceType = "wfs";
}
else if (url.Contains("service=wcs") || url.Contains("wcsserver"))
{
serviceType = "wcs";
}
else if (url.Contains("com.esri.esrimap.esrimap"))
{
serviceType = "aims";
}
else if ((url.Contains("arcgis/rest") || url.Contains("arcgis/services") || url.Contains("rest/services")) && url.Contains("mapserver"))
{
serviceType = "ags";
}
else if (url.IndexOf("service=csw") > 0)
{
serviceType = "csw";
}
else if (url.EndsWith(".nmf"))
{
serviceType = "ArcGIS:nmf";
}
else if (url.EndsWith(".lyr"))
{
serviceType = "ArcGIS:lyr";
}
else if (url.EndsWith(".mxd"))
{
serviceType = "ArcGIS:mxd";
}
else if (url.EndsWith(".kml"))
{
serviceType = "kml";
}
if (serviceType.Equals("image") || serviceType.Equals("feature"))
{
serviceType = "aims";
}
return serviceType;
}
/// <summary>
/// Check if a string is a URL.
/// </summary>
/// <remarks>
/// This function only checks it the string contains http, https or ftp protocol. It doesn't validate the URL.
/// </remarks>
/// <param name="theString">string to be checked</param>
/// <returns>true if the string is a URL</returns>
private bool IsUrl(String theString)
{
if (theString.Length < 4)
return false;
else
{
if (theString.Substring(0, 5).Equals("http:", StringComparison.CurrentCultureIgnoreCase))
return true;
else if (theString.Substring(0, 6).Equals("https:", StringComparison.CurrentCultureIgnoreCase))
return true;
else if (theString.Substring(0, 4).Equals("ftp:", StringComparison.CurrentCultureIgnoreCase))
return true;
else if (theString.Substring(0, 5).Equals("file:", StringComparison.CurrentCultureIgnoreCase))
return true;
else if (theString.Contains("Server\u2715http:"))
return true;
else
return false;
}
}
#endregion
#region "PrivateFunctions"
/// <summary>
/// replace specia lxml character
/// </summary>
/// <remarks>
/// Encode special characters (such as &, ", <, >, ') to percent values.
/// </remarks>
/// <param name="data">Text to be encoded</param>
/// <returns>Encoded text.</returns>
private string XmlEscape(string data)
{
data = data.Replace("&", "&");
data = data.Replace("<", "<");
data = data.Replace(">", ">");
data = data.Replace("\"", """);
data = data.Replace("'", "'");
return data;
}
#endregion
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Rename.ConflictEngine
{
internal static partial class ConflictResolver
{
private static readonly SymbolDisplayFormat s_metadataSymbolDisplayFormat = new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
private static readonly string s_metadataNameSeparators = " .,:<`>()\r\n";
/// <summary>
/// Performs the renaming of the symbol in the solution, identifies renaming conflicts and automatically resolves them where possible.
/// </summary>
/// <param name="renameLocationSet">The locations to perform the renaming at.</param>
/// <param name="originalText">The original name of the identifier.</param>
/// <param name="replacementText">The new name of the identifier</param>
/// <param name="optionSet">The option for rename</param>
/// <param name="hasConflict">Called after renaming references. Can be used by callers to
/// indicate if the new symbols that the reference binds to should be considered to be ok or
/// are in conflict. 'true' means they are conflicts. 'false' means they are not conflicts.
/// 'null' means that the default conflict check should be used.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A conflict resolution containing the new solution.</returns>
public static Task<ConflictResolution> ResolveConflictsAsync(
RenameLocations renameLocationSet,
string originalText,
string replacementText,
OptionSet optionSet,
Func<IEnumerable<ISymbol>, bool?> hasConflict,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// when someone e.g. renames a symbol from metadata through the API (IDE blocks this), we need to return
var renameSymbolDeclarationLocation = renameLocationSet.Symbol.Locations.Where(loc => loc.IsInSource).FirstOrDefault();
if (renameSymbolDeclarationLocation == null)
{
// Symbol "{0}" is not from source.
throw new ArgumentException(string.Format(WorkspacesResources.Symbol_0_is_not_from_source, renameLocationSet.Symbol.Name));
}
var session = new Session(renameLocationSet, renameSymbolDeclarationLocation, originalText, replacementText, optionSet, hasConflict, cancellationToken);
return session.ResolveConflictsAsync();
}
/// <summary>
/// Used to find the symbols associated with the Invocation Expression surrounding the Token
/// </summary>
private static IEnumerable<ISymbol> SymbolsForEnclosingInvocationExpressionWorker(SyntaxNode invocationExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken);
IEnumerable<ISymbol> symbols = null;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
return symbols;
}
}
private static SyntaxNode GetExpansionTargetForLocationPerLanguage(SyntaxToken tokenOrNode, Document document)
{
var renameRewriterService = document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
var complexifiedTarget = renameRewriterService.GetExpansionTargetForLocation(tokenOrNode);
return complexifiedTarget;
}
private static bool LocalVariableConflictPerLanguage(SyntaxToken tokenOrNode, Document document, IEnumerable<ISymbol> newReferencedSymbols)
{
var renameRewriterService = document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
var isConflict = renameRewriterService.LocalVariableConflict(tokenOrNode, newReferencedSymbols);
return isConflict;
}
private static bool IsIdentifierValid_Worker(Solution solution, string replacementText, IEnumerable<ProjectId> projectIds, CancellationToken cancellationToken)
{
foreach (var language in projectIds.Select(p => solution.GetProject(p).Language).Distinct())
{
var languageServices = solution.Workspace.Services.GetLanguageServices(language);
var renameRewriterLanguageService = languageServices.GetService<IRenameRewriterLanguageService>();
var syntaxFactsLanguageService = languageServices.GetService<ISyntaxFactsService>();
if (!renameRewriterLanguageService.IsIdentifierValid(replacementText, syntaxFactsLanguageService))
{
return false;
}
}
return true;
}
private static bool IsRenameValid(ConflictResolution conflictResolution, ISymbol renamedSymbol)
{
// if we rename an identifier and it now binds to a symbol from metadata this should be treated as
// an invalid rename.
return conflictResolution.ReplacementTextValid && renamedSymbol != null && renamedSymbol.Locations.Any(loc => loc.IsInSource);
}
private static async Task AddImplicitConflictsAsync(
ISymbol renamedSymbol,
ISymbol originalSymbol,
IEnumerable<ReferenceLocation> implicitReferenceLocations,
SemanticModel semanticModel,
Location originalDeclarationLocation,
int newDeclarationLocationStartingPosition,
ConflictResolution conflictResolution,
CancellationToken cancellationToken)
{
{
var renameRewriterService = conflictResolution.NewSolution.Workspace.Services.GetLanguageServices(renamedSymbol.Language).GetService<IRenameRewriterLanguageService>();
var implicitUsageConflicts = renameRewriterService.ComputePossibleImplicitUsageConflicts(renamedSymbol, semanticModel, originalDeclarationLocation, newDeclarationLocationStartingPosition, cancellationToken);
foreach (var implicitUsageConflict in implicitUsageConflicts)
{
conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(implicitUsageConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(implicitUsageConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
}
}
if (implicitReferenceLocations.IsEmpty())
{
return;
}
foreach (var implicitReferenceLocationsPerLanguage in implicitReferenceLocations.GroupBy(loc => loc.Document.Project.Language))
{
// the location of the implicit reference defines the language rules to check.
// E.g. foreach in C# using a MoveNext in VB that is renamed to MOVENEXT (within VB)
var renameRewriterService = implicitReferenceLocationsPerLanguage.First().Document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
var implicitConflicts = await renameRewriterService.ComputeImplicitReferenceConflictsAsync(
originalSymbol,
renamedSymbol,
implicitReferenceLocationsPerLanguage,
cancellationToken).ConfigureAwait(false);
foreach (var implicitConflict in implicitConflicts)
{
conflictResolution.AddRelatedLocation(new RelatedLocation(implicitConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(implicitConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
}
}
}
/// <summary>
/// Computes an adds conflicts relating to declarations, which are independent of
/// location-based checks. Examples of these types of conflicts include renaming a member to
/// the same name as another member of a type: binding doesn't change (at least from the
/// perspective of find all references), but we still need to track it.
/// </summary>
internal static async Task AddDeclarationConflictsAsync(
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<SymbolAndProjectId> referencedSymbols,
ConflictResolution conflictResolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
if (renamedSymbol.ContainingSymbol.IsKind(SymbolKind.NamedType))
{
var otherThingsNamedTheSame = renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name)
.Where(s => !s.Equals(renamedSymbol) &&
string.Equals(s.MetadataName, renamedSymbol.MetadataName, StringComparison.Ordinal) &&
(s.Kind != SymbolKind.Method || renamedSymbol.Kind != SymbolKind.Method));
AddConflictingSymbolLocations(otherThingsNamedTheSame, conflictResolution, reverseMappedLocations);
}
if (renamedSymbol.IsKind(SymbolKind.Namespace) && renamedSymbol.ContainingSymbol.IsKind(SymbolKind.Namespace))
{
var otherThingsNamedTheSame = ((INamespaceSymbol)renamedSymbol.ContainingSymbol).GetMembers(renamedSymbol.Name)
.Where(s => !s.Equals(renamedSymbol) &&
!s.IsKind(SymbolKind.Namespace) &&
string.Equals(s.MetadataName, renamedSymbol.MetadataName, StringComparison.Ordinal));
AddConflictingSymbolLocations(otherThingsNamedTheSame, conflictResolution, reverseMappedLocations);
}
if (renamedSymbol.IsKind(SymbolKind.NamedType) && renamedSymbol.ContainingSymbol is INamespaceOrTypeSymbol)
{
var otherThingsNamedTheSame = ((INamespaceOrTypeSymbol)renamedSymbol.ContainingSymbol).GetMembers(renamedSymbol.Name)
.Where(s => !s.Equals(renamedSymbol) &&
string.Equals(s.MetadataName, renamedSymbol.MetadataName, StringComparison.Ordinal));
var conflictingSymbolLocations = otherThingsNamedTheSame.Where(s => !s.IsKind(SymbolKind.Namespace));
if (otherThingsNamedTheSame.Any(s => s.IsKind(SymbolKind.Namespace)))
{
conflictingSymbolLocations = conflictingSymbolLocations.Concat(renamedSymbol);
}
AddConflictingSymbolLocations(conflictingSymbolLocations, conflictResolution, reverseMappedLocations);
}
// Some types of symbols (namespaces, cref stuff, etc) might not have ContainingAssemblies
if (renamedSymbol.ContainingAssembly != null)
{
var project = conflictResolution.NewSolution.GetProject(renamedSymbol.ContainingAssembly, cancellationToken);
// There also might be language specific rules we need to include
var languageRenameService = project.LanguageServices.GetService<IRenameRewriterLanguageService>();
var languageConflicts = await languageRenameService.ComputeDeclarationConflictsAsync(
conflictResolution.ReplacementText,
renamedSymbol,
renameSymbol,
referencedSymbols,
conflictResolution.OldSolution,
conflictResolution.NewSolution,
reverseMappedLocations,
cancellationToken).ConfigureAwait(false);
foreach (var languageConflict in languageConflicts)
{
conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(languageConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(languageConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
}
}
}
internal static void AddConflictingParametersOfProperties(
IEnumerable<ISymbol> properties, string newPropertyName, ArrayBuilder<Location> conflicts)
{
// check if the new property name conflicts with any parameter of the properties.
// Note: referencedSymbols come from the original solution, so there is no need to reverse map the locations of the parameters
foreach (var symbol in properties)
{
var prop = (IPropertySymbol)symbol;
var conflictingParameter = prop.Parameters.FirstOrDefault(param => string.Compare(param.Name, newPropertyName, StringComparison.OrdinalIgnoreCase) == 0);
if (conflictingParameter != null)
{
conflicts.AddRange(conflictingParameter.Locations);
}
}
}
private static void AddConflictingSymbolLocations(IEnumerable<ISymbol> conflictingSymbols, ConflictResolution conflictResolution, IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var newSymbol in conflictingSymbols)
{
foreach (var newLocation in newSymbol.Locations)
{
if (newLocation.IsInSource)
{
if (reverseMappedLocations.TryGetValue(newLocation, out var oldLocation))
{
conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(oldLocation.SourceSpan, conflictResolution.OldSolution.GetDocument(oldLocation.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
}
}
}
}
}
public static async Task<RenameDeclarationLocationReference[]> CreateDeclarationLocationAnnotationsAsync(
Solution solution,
IEnumerable<ISymbol> symbols,
CancellationToken cancellationToken)
{
var renameDeclarationLocations = new RenameDeclarationLocationReference[symbols.Count()];
int symbolIndex = 0;
foreach (var symbol in symbols)
{
var locations = symbol.Locations;
bool overriddenFromMetadata = false;
if (symbol.IsOverride)
{
var overriddenSymbol = symbol.OverriddenMember();
if (overriddenSymbol != null)
{
overriddenSymbol = await SymbolFinder.FindSourceDefinitionAsync(overriddenSymbol, solution, cancellationToken).ConfigureAwait(false);
overriddenFromMetadata = overriddenSymbol == null || overriddenSymbol.Locations.All(loc => loc.IsInMetadata);
}
}
var location = await GetSymbolLocationAsync(solution, symbol, cancellationToken).ConfigureAwait(false);
if (location != null && location.IsInSource)
{
renameDeclarationLocations[symbolIndex] = new RenameDeclarationLocationReference(solution.GetDocumentId(location.SourceTree), location.SourceSpan, overriddenFromMetadata, locations.Count());
}
else
{
renameDeclarationLocations[symbolIndex] = new RenameDeclarationLocationReference(GetString(symbol), locations.Count());
}
symbolIndex++;
}
return renameDeclarationLocations;
}
private static string GetString(ISymbol symbol)
{
if (symbol.IsAnonymousType())
{
return symbol.ToDisplayParts(s_metadataSymbolDisplayFormat)
.WhereAsArray(p => p.Kind != SymbolDisplayPartKind.PropertyName && p.Kind != SymbolDisplayPartKind.FieldName)
.ToDisplayString();
}
else
{
return symbol.ToDisplayString(s_metadataSymbolDisplayFormat);
}
}
/// <summary>
/// Gives the First Location for a given Symbol by ordering the locations using DocumentId first and Location starting position second
/// </summary>
private static async Task<Location> GetSymbolLocationAsync(Solution solution, ISymbol symbol, CancellationToken cancellationToken)
{
var locations = symbol.Locations;
var originalsourcesymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
if (originalsourcesymbol != null)
{
locations = originalsourcesymbol.Locations;
}
var orderedLocations = locations.OrderBy(l => l.IsInSource ? solution.GetDocumentId(l.SourceTree).Id : Guid.Empty)
.ThenBy(l => l.IsInSource ? l.SourceSpan.Start : int.MaxValue);
return orderedLocations.FirstOrDefault();
}
private static bool HeuristicMetadataNameEquivalenceCheck(
string oldMetadataName,
string newMetadataName,
string originalText,
string replacementText)
{
if (string.Equals(oldMetadataName, newMetadataName, StringComparison.Ordinal))
{
return true;
}
var index = 0;
index = newMetadataName.IndexOf(replacementText, 0);
StringBuilder newMetadataNameBuilder = new StringBuilder();
// Every loop updates the newMetadataName to resemble the oldMetadataName
while (index != -1 && index < oldMetadataName.Length)
{
// This check is to ses if the part of string before the string match, matches
if (!IsSubStringEqual(oldMetadataName, newMetadataName, index))
{
return false;
}
// Ok to replace
if (IsWholeIdentifier(newMetadataName, replacementText, index))
{
newMetadataNameBuilder.Append(newMetadataName, 0, index);
newMetadataNameBuilder.Append(originalText);
newMetadataNameBuilder.Append(newMetadataName, index + replacementText.Length, newMetadataName.Length - (index + replacementText.Length));
newMetadataName = newMetadataNameBuilder.ToString();
newMetadataNameBuilder.Clear();
}
index = newMetadataName.IndexOf(replacementText, index + 1);
}
return string.Equals(newMetadataName, oldMetadataName, StringComparison.Ordinal);
}
private static bool IsSubStringEqual(
string str1,
string str2,
int index)
{
Debug.Assert(index <= str1.Length && index <= str2.Length, "Index cannot be greater than the string");
int currentIndex = 0;
while (currentIndex < index)
{
if (str1[currentIndex] != str2[currentIndex])
{
return false;
}
currentIndex++;
}
return true;
}
private static bool IsWholeIdentifier(
string metadataName,
string searchText,
int index)
{
if (index == -1)
{
return false;
}
// Check for the previous char
if (index != 0)
{
var previousChar = metadataName[index - 1];
if (!IsIdentifierSeparator(previousChar))
{
return false;
}
}
// Check for the next char
if (index + searchText.Length != metadataName.Length)
{
var nextChar = metadataName[index + searchText.Length];
if (!IsIdentifierSeparator(nextChar))
{
return false;
}
}
return true;
}
private static bool IsIdentifierSeparator(char element)
{
return s_metadataNameSeparators.IndexOf(element) != -1;
}
}
}
| |
#region License
/*
Illusory Studios C# Crypto Library (CryptSharp)
Copyright (c) 2011 James F. Bellinger <jfb@zer7.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#endregion
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
namespace BitPool.Cryptography.KDF.CryptSharp
{
public class Pbkdf2 : Stream
{
#region PBKDF2
public delegate void ComputeHmacCallback(byte[] key, byte[] data, byte[] output);
byte[] _key, _saltBuf, _block, _blockT1, _blockT2;
ComputeHmacCallback _computeHmacCallback;
int _iterations;
public Pbkdf2(byte[] key, byte[] salt, int iterations,
ComputeHmacCallback computeHmacCallback, int hmacLength) {
Reopen(key, salt, iterations, computeHmacCallback, hmacLength);
}
static void Clear(Array arr) {
Array.Clear(arr, 0, arr.Length);
}
public void Read(byte[] output) {
Helper.CheckNull("output", output);
int bytes = Read(output, 0, output.Length);
if (bytes < output.Length) {
throw new ArgumentException("Can only return "
+ output.Length.ToString() + " bytes.", "output");
}
}
public static void ComputeKey(byte[] key, byte[] salt, int iterations,
ComputeHmacCallback computeHmacCallback, int hmacLength, byte[] output) {
using (Pbkdf2 kdf = new Pbkdf2
(key, salt, iterations, computeHmacCallback, hmacLength)) {
kdf.Read(output);
}
}
public static ComputeHmacCallback CallbackFromHmac<T>() where T : KeyedHashAlgorithm, new() {
return delegate(byte[] key, byte[] data, byte[] output) {
using (T hmac = new T()) {
Helper.CheckNull("key", key); Helper.CheckNull("data", data);
hmac.Key = key; byte[] hmacOutput = hmac.ComputeHash(data);
try {
Helper.CheckRange("output", output, hmacOutput.Length, hmacOutput.Length);
Array.Copy(hmacOutput, output, output.Length);
}
finally {
Clear(hmacOutput);
}
}
};
}
public void Reopen(byte[] key, byte[] salt, int iterations,
ComputeHmacCallback computeHmacCallback, int hmacLength) {
Helper.CheckNull("key", key);
Helper.CheckNull("salt", salt);
Helper.CheckNull("computeHmacCallback", computeHmacCallback);
Helper.CheckRange("salt", salt, 0, int.MaxValue - 4);
Helper.CheckRange("iterations", iterations, 1, int.MaxValue);
Helper.CheckRange("hmacLength", hmacLength, 1, int.MaxValue);
_key = new byte[key.Length]; Array.Copy(key, _key, key.Length);
_saltBuf = new byte[salt.Length + 4]; Array.Copy(salt, _saltBuf, salt.Length);
_iterations = iterations; _computeHmacCallback = computeHmacCallback;
_block = new byte[hmacLength]; _blockT1 = new byte[hmacLength]; _blockT2 = new byte[hmacLength];
ReopenStream();
}
public override void Close() {
Clear(_key); Clear(_saltBuf); Clear(_block);
}
void ComputeBlock(uint pos) {
Helper.UInt32ToBytes(pos, _saltBuf, _saltBuf.Length - 4);
ComputeHmac(_saltBuf, _blockT1);
Array.Copy(_blockT1, _block, _blockT1.Length);
for (int i = 1; i < _iterations; i++) {
ComputeHmac(_blockT1, _blockT2); // let's not require aliasing support
Array.Copy(_blockT2, _blockT1, _blockT2.Length);
for (int j = 0; j < _block.Length; j++) { _block[j] ^= _blockT1[j]; }
}
Clear(_blockT1); Clear(_blockT2);
}
void ComputeHmac(byte[] data, byte[] output) {
Debug.Assert(data != null && output != null);
_computeHmacCallback(_key, data, output);
}
#endregion
#region Stream
long _blockStart, _blockEnd, _pos;
void ReopenStream() {
_blockStart = _blockEnd = _pos = 0;
}
public override void Flush() {
}
public override int Read(byte[] buffer, int offset, int count) {
Helper.CheckBounds("buffer", buffer, offset, count); int bytes = 0;
while (count > 0) {
if (Position < _blockStart || Position >= _blockEnd) {
if (Position >= Length) { break; }
long pos = Position / _block.Length;
ComputeBlock((uint) (pos + 1));
_blockStart = pos * _block.Length;
_blockEnd = _blockStart + _block.Length;
}
int bytesSoFar = (int) (Position - _blockStart);
int bytesThisTime = (int) Math.Min(_block.Length - bytesSoFar, count);
Array.Copy(_block, bytesSoFar, buffer, bytes, bytesThisTime);
count -= bytesThisTime; bytes += bytesThisTime; Position += bytesThisTime;
}
return bytes;
}
public override long Seek(long offset, SeekOrigin origin) {
long pos;
switch (origin) {
case SeekOrigin.Begin: pos = offset; break;
case SeekOrigin.Current: pos = Position + offset; break;
case SeekOrigin.End: pos = Length + offset; break;
default: throw new ArgumentException("Unknown seek type.", "origin");
}
if (pos < 0) { throw new ArgumentException("Seeking before the stream start.", "offset"); }
Position = pos; return pos;
}
public override void SetLength(long value) {
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count) {
throw new NotSupportedException();
}
public override bool CanRead {
get { return true; }
}
public override bool CanSeek {
get { return true; }
}
public override bool CanWrite {
get { return false; }
}
public override long Length {
get { return (long) _block.Length * uint.MaxValue; }
}
public override long Position {
get { return _pos; }
set {
if (_pos < 0) { throw new ArgumentOutOfRangeException("value"); }
_pos = value;
}
}
#endregion
}
}
| |
using Gtk;
using System;
using System.IO;
using System.IO.Ports;
using System.Configuration;
using System.Configuration.Install;
namespace uploader
{
public delegate void LogEventHandler (string message,int level = 0);
public delegate void ProgressEventHandler (double completed);
public delegate void MonitorEventHandler (string portname);
public delegate void UploadEventHandler (string portname,string filename);
public delegate void QuitEventHandler ();
class MainClass
{
public static void Main (string[] args)
{
Application.Init (); // XXX requires Gtk#
new AppLogic ();
Application.Run (); // XXX requires Gtk#
}
}
class AppLogic
{
MainWindow win;
Mon mon;
IHex ihex;
Uploader upl;
SerialPort port;
bool upload_in_progress;
int logLevel = 0; // Adjust for more logging output
string config_name = "SiKUploader";
System.Configuration.Configuration config;
ConfigSection config_section;
public AppLogic ()
{
// Get the current configuration file.
config = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
// Look for our settings and add/create them if missing
if (config.Sections [config_name] == null) {
config_section = new ConfigSection ();
config.Sections.Add (config_name, config_section);
config_section.SectionInformation.ForceSave = true;
config.Save (ConfigurationSaveMode.Full);
}
config_section = config.GetSection (config_name) as ConfigSection;
// Hook up main window events
win = new MainWindow ();
win.MonitorEvent += show_monitor;
win.UploadEvent += do_upload;
win.LogEvent += log;
win.QuitEvent += at_exit;
// restore the last path that we uploaded
win.FileName = config_section.lastPath;
// restore the last port that we opened
win.PortName = config_section.lastPort;
// Create the intelhex loader
ihex = new IHex ();
ihex.LogEvent += log;
// And the uploader
upl = new Uploader ();
upl.LogEvent += log;
upl.ProgressEvent += win.set_progress;
// Emit some basic help
log ("Select a serial port and a .hex file to be uploaded, then hit Upload.\n");
win.Show ();
}
private void at_exit ()
{
log ("saving configuration");
config.Save (ConfigurationSaveMode.Modified);
}
private void set_port (string portname)
{
if (upload_in_progress)
throw new Exception ("attempt to change port while upload in progress");
// If the port name hasn't changed, keep the existing port
if ((port != null) && (portname.Equals (port.PortName)))
return;
// dispose of the old port
if (mon != null)
mon.disconnect ();
if ((port != null) && port.IsOpen)
port.Close ();
port = null;
try {
// create a new one
port = new SerialPort (portname, 115200, Parity.None, 8, StopBits.One);
log ("opening " + port.PortName + "\n", 1);
port.Open ();
log ("opened " + port.PortName + "\n", 1);
// remember that we successfully opened this port
config_section.lastPort = port.PortName;
} catch {
log ("FAIL: cannot open " + port.PortName + "\n");
port = null;
}
// if we have a port and a monitor, connect it to the new port
if ((port != null) && (mon != null))
mon.connect (port);
}
/// <summary>
/// Create a serial port monitor for the supplied port name, in response
/// to an event generated by the main window.
/// </summary>
/// <param name='portname'>
/// Name of the serial port to open.
/// </param>
private void show_monitor (string portname)
{
// ignore monitor activation requests while uploading
if (upload_in_progress)
return;
// set/switch port assignment
set_port (portname);
// create the monitor if it's not already open
if (mon == null) {
// create a new monitor
mon = new Mon (port);
//mon.QuitEvent += end_monitor; ??
mon.DeleteEvent += end_monitor;
mon.LogEvent += log;
// and connect it to the port
mon.connect (port);
} else {
// bring the window to the front
mon.Present ();
}
}
/// <summary>
/// Called when the monitor window is closed.
/// </summary>
/// <param name='obj'>
/// Object.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
private void end_monitor (object sender, DeleteEventArgs args)
{
// forget about the monitor
mon = null;
}
private void do_upload (string portname, string filename)
{
// ignore duplicate upload events
if (upload_in_progress)
return;
// disconnect the monitor so that we can connect the uploader
if (mon != null)
mon.disconnect ();
// set/switch serial port
set_port (portname);
upload_in_progress = true;
try {
try_upload (filename);
// remember that we successfully uploaded this path
config_section.lastPath = filename;
} catch (Exception e) {
log ("upload failed: " + e.Message, 1);
log (e.StackTrace, 1);
// don't log here, better errors should be logged by lower levels
}
upload_in_progress = false;
win.set_progress (0);
// if the monitor is still up, reconnect it, possibly to the
// device that was just uploaded to
if (mon != null) {
mon.connect (port);
} else {
// dispose of the port so that other tools can talk to the device
port.Close ();
port = null;
}
}
private void try_upload (string filename)
{
// load the intelhex file
ihex.load (filename);
// and try to upload it
upl.upload (port, ihex);
}
private void log (string message, int level = 0)
{
// log a message to the console
if (level <= logLevel)
Console.Write (message);
// level 0 messages go to the status bar
if (level == 0) {
win.set_status (message);
}
}
}
public sealed class ConfigSection : ConfigurationSection
{
public ConfigSection ()
{
}
[ConfigurationProperty("lastPath", DefaultValue = "")]
public string lastPath {
get {
return (string)this ["lastPath"];
}
set {
this ["lastPath"] = value;
}
}
[ConfigurationProperty("lastPort", DefaultValue = "")]
public string lastPort {
get {
return (string)this ["lastPort"];
}
set {
this ["lastPort"] = value;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="AndroidNativeHeadsetProvider.cs" company="Google Inc.">
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
// This provider is only available on an Android device.
#if UNITY_ANDROID && !UNITY_EDITOR
using Gvr;
using System;
using System.Runtime.InteropServices;
using UnityEngine;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR;
#else
using XRDevice = UnityEngine.VR.VRDevice;
#endif // UNITY_2017_2_OR_NEWER
/// @cond
namespace Gvr.Internal
{
class AndroidNativeHeadsetProvider : IHeadsetProvider
{
private IntPtr gvrContextPtr = XRDevice.GetNativePtr();
private GvrValue gvrValue = new GvrValue();
private gvr_event_header gvrEventHeader = new gvr_event_header();
private gvr_recenter_event_data gvrRecenterEventData = new gvr_recenter_event_data();
// |gvr_event| C struct is spec'd to be up to 512 bytes in size.
private byte[] gvrEventBuffer = new byte[512];
private GCHandle gvrEventHandle;
private IntPtr gvrEventPtr;
private IntPtr gvrPropertiesPtr;
private int supportsPositionalTracking = -1;
/// Used only as a temporary placeholder to avoid allocations.
/// Do not use this for storing state.
private MutablePose3D transientRecenteredPose3d = new MutablePose3D();
public bool SupportsPositionalTracking
{
get
{
if (supportsPositionalTracking < 0)
{
supportsPositionalTracking =
gvr_is_feature_supported(gvrContextPtr, (int)gvr_feature.HeadPose6dof) ? 1 : 0;
}
return supportsPositionalTracking > 0;
}
}
internal AndroidNativeHeadsetProvider()
{
gvrEventHandle = GCHandle.Alloc(gvrEventBuffer, GCHandleType.Pinned);
gvrEventPtr = gvrEventHandle.AddrOfPinnedObject();
}
~AndroidNativeHeadsetProvider()
{
gvrEventHandle.Free();
}
public void PollEventState(ref HeadsetState state)
{
GvrErrorType eventType;
try
{
eventType = (GvrErrorType)gvr_poll_event(gvrContextPtr, gvrEventPtr);
}
catch (EntryPointNotFoundException)
{
Debug.LogError("GvrHeadset not supported by this version of Unity. " +
"Support starts in 5.6.3p3 and 2017.1.1p1.");
throw;
}
if (eventType == GvrErrorType.NoEventAvailable)
{
state.eventType = GvrEventType.Invalid;
return;
}
Marshal.PtrToStructure(gvrEventPtr, gvrEventHeader);
state.eventFlags = gvrEventHeader.flags;
state.eventTimestampNs = gvrEventHeader.timestamp;
state.eventType = (GvrEventType)gvrEventHeader.type;
// Event data begins after header.
IntPtr eventDataPtr = new IntPtr(gvrEventPtr.ToInt64() + Marshal.SizeOf(gvrEventHeader));
if (state.eventType == GvrEventType.Recenter)
{
Marshal.PtrToStructure(eventDataPtr, gvrRecenterEventData);
_HandleRecenterEvent(ref state, gvrRecenterEventData);
return;
}
}
public bool TryGetFloorHeight(ref float floorHeight)
{
if (!_GvrGetProperty(gvr_property_type.TrackingFloorHeight, gvrValue))
{
return false;
}
floorHeight = gvrValue.ToFloat();
return true;
}
public bool TryGetRecenterTransform(ref Vector3 position, ref Quaternion rotation)
{
if (!_GvrGetProperty(gvr_property_type.RecenterTransform, gvrValue))
{
return false;
}
transientRecenteredPose3d.Set(gvrValue.ToMatrix4x4());
position = transientRecenteredPose3d.Position;
rotation = transientRecenteredPose3d.Orientation;
return true;
}
public bool TryGetSafetyRegionType(ref GvrSafetyRegionType safetyType)
{
if (!_GvrGetProperty(gvr_property_type.SafetyRegion, gvrValue))
{
return false;
}
safetyType = (GvrSafetyRegionType)gvrValue.ToInt32();
return true;
}
public bool TryGetSafetyCylinderInnerRadius(ref float innerRadius)
{
if (!_GvrGetProperty(gvr_property_type.SafetyCylinderInnerRadius, gvrValue))
{
return false;
}
innerRadius = gvrValue.ToFloat();
return true;
}
public bool TryGetSafetyCylinderOuterRadius(ref float outerRadius)
{
if (!_GvrGetProperty(gvr_property_type.SafetyCylinderOuterRadius, gvrValue))
{
return false;
}
outerRadius = gvrValue.ToFloat();
return true;
}
#region PRIVATE_HELPERS
/// Returns true if a property was available and retrieved.
private bool _GvrGetProperty(gvr_property_type propertyType, GvrValue valueOut)
{
gvr_value_type valueType = GetPropertyValueType(propertyType);
if (valueType == gvr_value_type.None)
{
Debug.LogError("Unknown gvr property " + propertyType + ". Unable to type check.");
}
if (gvrPropertiesPtr == IntPtr.Zero)
{
try
{
gvrPropertiesPtr = gvr_get_current_properties(gvrContextPtr);
}
catch (EntryPointNotFoundException)
{
Debug.LogError("GvrHeadset not supported by this version of Unity. " +
"Support starts in 5.6.3p3 and 2017.1.1p1.");
throw;
}
}
if (gvrPropertiesPtr == IntPtr.Zero)
{
return false;
}
// Assumes that gvr_properties_get (C API) will only ever return
// GvrErrorType.None or GvrErrorType.NoEventAvailable.
bool success =
(GvrErrorType.None ==
(GvrErrorType)gvr_properties_get(gvrPropertiesPtr, propertyType, valueOut.BufferPtr));
if (success)
{
valueOut.Parse();
success = (valueType == gvr_value_type.None || valueOut.TypeEnum == valueType);
if (!success)
{
Debug.LogError("GvrGetProperty " + propertyType + " type mismatch, expected "
+ valueType + " got " + valueOut.TypeEnum);
}
}
return success;
}
private void _HandleRecenterEvent(ref HeadsetState state, gvr_recenter_event_data eventData)
{
state.recenterEventType = (GvrRecenterEventType)eventData.recenter_event_type;
state.recenterEventFlags = eventData.recenter_event_flags;
Matrix4x4 gvrMatrix = GvrMathHelpers.ConvertFloatArrayToMatrix(eventData.pose_transform);
GvrMathHelpers.GvrMatrixToUnitySpace(
gvrMatrix, out state.recenteredPosition, out state.recenteredRotation);
}
#endregion // PRIVATE_HELPERS
#region GVR_TYPE_HELPERS
private gvr_value_type GetPropertyValueType(gvr_property_type propertyType)
{
gvr_value_type propType = gvr_value_type.None;
switch (propertyType)
{
case gvr_property_type.TrackingFloorHeight:
propType = gvr_value_type.Float;
break;
case gvr_property_type.RecenterTransform:
propType = gvr_value_type.Mat4f;
break;
case gvr_property_type.SafetyRegion:
propType = gvr_value_type.Int;
break;
case gvr_property_type.SafetyCylinderInnerRadius:
propType = gvr_value_type.Float;
break;
case gvr_property_type.SafetyCylinderOuterRadius:
propType = gvr_value_type.Float;
break;
}
return propType;
}
/// Helper class to parse |gvr_value| structs into the varied data types it could contain.
/// NOTE: Does NO type checking on value conversions. |_GvrGetProperty| checks types.
private class GvrValue
{
private static readonly int HEADER_SIZE = Marshal.SizeOf(typeof(gvr_value_header));
private gvr_value_header valueHeader = new gvr_value_header();
// |gvr_value| C struct is spec'd to be up to 256 bytes in size.
private byte[] buffer = new byte[256];
private IntPtr bufferPtr;
private IntPtr valuePtr;
private GCHandle bufferHandle;
public GvrValue()
{
bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
bufferPtr = bufferHandle.AddrOfPinnedObject();
// Value portion starts after the header.
valuePtr = new IntPtr(bufferPtr.ToInt64() + HEADER_SIZE);
}
~GvrValue()
{
bufferHandle.Free();
}
/// Gets the ptr to a buffer that can be used as an argument to |gvr_properties_get|.
public IntPtr BufferPtr
{
get
{
return bufferPtr;
}
}
public gvr_value_type TypeEnum
{
get
{
return valueHeader.value_type;
}
}
/// Parse the header of the current buffer. This should be called after the contents of
/// the buffer have been altered e.g. by a call to |gvr_properties_get|.
public void Parse()
{
Marshal.PtrToStructure(bufferPtr, valueHeader);
}
public int ToInt32()
{
return BitConverter.ToInt32(buffer, HEADER_SIZE);
}
public long ToInt64()
{
return BitConverter.ToInt64(buffer, HEADER_SIZE);
}
public float ToFloat()
{
return BitConverter.ToSingle(buffer, HEADER_SIZE);
}
public double ToDouble()
{
return BitConverter.ToDouble(buffer, HEADER_SIZE);
}
public Vector2 ToVector2()
{
return (Vector2)Marshal.PtrToStructure(valuePtr, typeof(Vector2));
}
public Vector3 ToVector3()
{
return (Vector3)Marshal.PtrToStructure(valuePtr, typeof(Vector3));
}
public Vector4 ToVector4()
{
return (Vector4)Marshal.PtrToStructure(valuePtr, typeof(Vector4));
}
public Quaternion ToQuaternion()
{
return (Quaternion)Marshal.PtrToStructure(valuePtr, typeof(Quaternion));
}
public gvr_rectf ToGvrRectf()
{
return (gvr_rectf)Marshal.PtrToStructure(valuePtr, typeof(gvr_rectf));
}
public gvr_recti ToGvrRecti()
{
return (gvr_recti)Marshal.PtrToStructure(valuePtr, typeof(gvr_recti));
}
public Matrix4x4 ToMatrix4x4()
{
Matrix4x4 mat4 = (Matrix4x4)Marshal.PtrToStructure(valuePtr, typeof(Matrix4x4));
// Transpose the matrix from row-major (GVR) to column-major (Unity),
// and change from LHS to RHS coordinates.
return Pose3D.FlipHandedness(mat4.transpose);
}
}
#endregion // GVR_TYPE_HELPERS
#region GVR_NATIVE_STRUCTS
[StructLayout(LayoutKind.Sequential)]
private class gvr_recenter_event_data
{
// gvr_recenter_event_type
internal int recenter_event_type;
// gvr_flags
internal uint recenter_event_flags;
// gvr_mat4f = float[4][4]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
internal float[] pose_transform = new float[16];
}
[StructLayout(LayoutKind.Explicit)]
private class gvr_event_header
{
[FieldOffset(0)]
internal long timestamp;
// gvr_event_type
[FieldOffset(8)]
internal int type;
// gvr_flags
[FieldOffset(12)]
internal int flags;
// Event specific data starts at offset 16.
}
[StructLayout(LayoutKind.Explicit)]
private class gvr_value_header
{
[FieldOffset(0)]
internal gvr_value_type value_type;
// gvr_flags
[FieldOffset(4)]
internal int flags;
// Value data starts at offset 8.
}
[StructLayout(LayoutKind.Sequential)]
public struct gvr_sizei
{
internal int width;
internal int height;
}
[StructLayout(LayoutKind.Sequential)]
public struct gvr_recti
{
internal int left;
internal int right;
internal int bottom;
internal int top;
}
[StructLayout(LayoutKind.Sequential)]
public struct gvr_rectf
{
internal float left;
internal float right;
internal float bottom;
internal float top;
}
#endregion // GVR_NATIVE_STRUCTS
#region GVR_C_API
private const string DLL_NAME = GvrActivityHelper.GVR_DLL_NAME;
[DllImport(DLL_NAME)]
private static extern bool gvr_is_feature_supported(IntPtr gvr_context, int feature);
[DllImport(DLL_NAME)]
private static extern int gvr_poll_event(IntPtr gvr_context, IntPtr event_out);
[DllImport(DLL_NAME)]
private static extern IntPtr gvr_get_current_properties(IntPtr gvr_context);
[DllImport(DLL_NAME)]
private static extern int gvr_properties_get(
IntPtr gvr_properties, gvr_property_type property_type, IntPtr value_out);
#endregion // GVR_C_API
}
}
/// @endcond
#endif // UNITY_ANDROID && !UNITY_EDITOR
| |
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// 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 Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
public class DefaultSerializationContextTest
{
[TestCase]
public void CompleteAllowedOnlyOnce()
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
var buffer = GetTestBuffer(10);
context.Complete(buffer);
Assert.Throws(typeof(InvalidOperationException), () => context.Complete(buffer));
Assert.Throws(typeof(InvalidOperationException), () => context.Complete());
}
}
[TestCase]
public void CompleteAllowedOnlyOnce2()
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
context.Complete();
Assert.Throws(typeof(InvalidOperationException), () => context.Complete(GetTestBuffer(10)));
Assert.Throws(typeof(InvalidOperationException), () => context.Complete());
}
}
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
[TestCase(1000)]
public void ByteArrayPayload(int payloadSize)
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
var origPayload = GetTestBuffer(payloadSize);
context.Complete(origPayload);
var nativePayload = context.GetPayload().ToByteArray();
CollectionAssert.AreEqual(origPayload, nativePayload);
}
}
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
[TestCase(1000)]
public void BufferWriter_OneSegment(int payloadSize)
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
var origPayload = GetTestBuffer(payloadSize);
var bufferWriter = context.GetBufferWriter();
origPayload.AsSpan().CopyTo(bufferWriter.GetSpan(payloadSize));
bufferWriter.Advance(payloadSize);
context.Complete();
var nativePayload = context.GetPayload().ToByteArray();
CollectionAssert.AreEqual(origPayload, nativePayload);
}
}
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
[TestCase(1000)]
public void BufferWriter_OneSegment_GetMemory(int payloadSize)
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
var origPayload = GetTestBuffer(payloadSize);
var bufferWriter = context.GetBufferWriter();
origPayload.AsSpan().CopyTo(bufferWriter.GetMemory(payloadSize).Span);
bufferWriter.Advance(payloadSize);
context.Complete();
var nativePayload = context.GetPayload().ToByteArray();
CollectionAssert.AreEqual(origPayload, nativePayload);
}
}
[TestCase(1, 4)] // small slice size tests grpc_slice with inline data
[TestCase(10, 4)]
[TestCase(100, 4)]
[TestCase(1000, 4)]
[TestCase(1, 64)] // larger slice size tests allocated grpc_slices
[TestCase(10, 64)]
[TestCase(1000, 50)]
[TestCase(1000, 64)]
public void BufferWriter_MultipleSegments(int payloadSize, int maxSliceSize)
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
var origPayload = GetTestBuffer(payloadSize);
var bufferWriter = context.GetBufferWriter();
for (int offset = 0; offset < payloadSize; offset += maxSliceSize)
{
var sliceSize = Math.Min(maxSliceSize, payloadSize - offset);
// we allocate last slice as too big intentionally to test that shrinking works
var dest = bufferWriter.GetSpan(maxSliceSize);
origPayload.AsSpan(offset, sliceSize).CopyTo(dest);
bufferWriter.Advance(sliceSize);
}
context.Complete();
var nativePayload = context.GetPayload().ToByteArray();
CollectionAssert.AreEqual(origPayload, nativePayload);
}
}
[TestCase]
public void ContextIsReusable()
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
Assert.Throws(typeof(NullReferenceException), () => context.GetPayload());
var origPayload1 = GetTestBuffer(10);
context.Complete(origPayload1);
CollectionAssert.AreEqual(origPayload1, context.GetPayload().ToByteArray());
context.Reset();
var origPayload2 = GetTestBuffer(20);
var bufferWriter = context.GetBufferWriter();
origPayload2.AsSpan().CopyTo(bufferWriter.GetMemory(origPayload2.Length).Span);
bufferWriter.Advance(origPayload2.Length);
context.Complete();
CollectionAssert.AreEqual(origPayload2, context.GetPayload().ToByteArray());
context.Reset();
Assert.Throws(typeof(NullReferenceException), () => context.GetPayload());
}
}
[TestCase]
public void GetBufferWriterThrowsForCompletedContext()
{
using (var scope = NewDefaultSerializationContextScope())
{
var context = scope.Context;
context.Complete(GetTestBuffer(10));
Assert.Throws(typeof(InvalidOperationException), () => context.GetBufferWriter());
}
}
private DefaultSerializationContext.UsageScope NewDefaultSerializationContextScope()
{
return new DefaultSerializationContext.UsageScope(new DefaultSerializationContext());
}
private byte[] GetTestBuffer(int length)
{
var testBuffer = new byte[length];
for (int i = 0; i < testBuffer.Length; i++)
{
testBuffer[i] = (byte) i;
}
return testBuffer;
}
}
}
| |
using System;
using System.Collections;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace xDockPanel
{
public abstract partial class AutoHideStripBase : Control
{
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected class Tab : IDisposable
{
private IDockContent m_content;
protected internal Tab(IDockContent content)
{
m_content = content;
}
~Tab()
{
Dispose(false);
}
public IDockContent Content
{
get { return m_content; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected sealed class TabCollection : IEnumerable<Tab>
{
#region IEnumerable Members
IEnumerator<Tab> IEnumerable<Tab>.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
#endregion
internal TabCollection(DockPane pane)
{
m_dockPane = pane;
}
private DockPane m_dockPane = null;
public DockPane DockPane
{
get { return m_dockPane; }
}
public DockPanel DockPanel
{
get { return DockPane.DockPanel; }
}
public int Count
{
get { return DockPane.DisplayingContents.Count; }
}
public Tab this[int index]
{
get
{
IDockContent content = DockPane.DisplayingContents[index];
if (content == null)
throw (new ArgumentOutOfRangeException("index"));
if (content.DockHandler.AutoHideTab == null)
content.DockHandler.AutoHideTab = (DockPanel.AutoHideStripControl.CreateTab(content));
return content.DockHandler.AutoHideTab as Tab;
}
}
public bool Contains(Tab tab)
{
return (IndexOf(tab) != -1);
}
public bool Contains(IDockContent content)
{
return (IndexOf(content) != -1);
}
public int IndexOf(Tab tab)
{
if (tab == null)
return -1;
return IndexOf(tab.Content);
}
public int IndexOf(IDockContent content)
{
return DockPane.DisplayingContents.IndexOf(content);
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected class Pane : IDisposable
{
private DockPane m_dockPane;
protected internal Pane(DockPane dockPane)
{
m_dockPane = dockPane;
}
~Pane()
{
Dispose(false);
}
public DockPane DockPane
{
get { return m_dockPane; }
}
public TabCollection AutoHideTabs
{
get
{
if (DockPane.AutoHideTabs == null)
DockPane.AutoHideTabs = new TabCollection(DockPane);
return DockPane.AutoHideTabs as TabCollection;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected sealed class PaneCollection : IEnumerable<Pane>
{
private class AutoHideState
{
public DockState m_dockState;
public bool m_selected = false;
public AutoHideState(DockState dockState)
{
m_dockState = dockState;
}
public DockState DockState
{
get { return m_dockState; }
}
public bool Selected
{
get { return m_selected; }
set { m_selected = value; }
}
}
private class AutoHideStateCollection
{
private AutoHideState[] m_states;
public AutoHideStateCollection()
{
m_states = new AutoHideState[] {
new AutoHideState(DockState.AutoHideTop),
new AutoHideState(DockState.AutoHideBottom),
new AutoHideState(DockState.AutoHideLeft),
new AutoHideState(DockState.AutoHideRight)
};
}
public AutoHideState this[DockState dockState]
{
get
{
for (int i = 0; i < m_states.Length; i++)
{
if (m_states[i].DockState == dockState)
return m_states[i];
}
throw new ArgumentOutOfRangeException("dockState");
}
}
public bool ContainsPane(DockPane pane)
{
if (pane.IsHidden)
return false;
for (int i = 0; i < m_states.Length; i++)
{
if (m_states[i].DockState == pane.DockState && m_states[i].Selected)
return true;
}
return false;
}
}
internal PaneCollection(DockPanel panel, DockState dockState)
{
m_dockPanel = panel;
m_states = new AutoHideStateCollection();
States[DockState.AutoHideTop].Selected = (dockState == DockState.AutoHideTop);
States[DockState.AutoHideBottom].Selected = (dockState == DockState.AutoHideBottom);
States[DockState.AutoHideLeft].Selected = (dockState == DockState.AutoHideLeft);
States[DockState.AutoHideRight].Selected = (dockState == DockState.AutoHideRight);
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private AutoHideStateCollection m_states;
private AutoHideStateCollection States
{
get { return m_states; }
}
public int Count
{
get
{
int count = 0;
foreach (DockPane pane in DockPanel.Panes)
{
if (States.ContainsPane(pane))
count++;
}
return count;
}
}
public Pane this[int index]
{
get
{
int count = 0;
foreach (DockPane pane in DockPanel.Panes)
{
if (!States.ContainsPane(pane))
continue;
if (count == index)
{
if (pane.AutoHidePane == null)
pane.AutoHidePane = DockPanel.AutoHideStripControl.CreatePane(pane);
return pane.AutoHidePane as Pane;
}
count++;
}
throw new ArgumentOutOfRangeException("index");
}
}
public bool Contains(Pane pane)
{
return (IndexOf(pane) != -1);
}
public int IndexOf(Pane pane)
{
if (pane == null)
return -1;
int index = 0;
foreach (DockPane dockPane in DockPanel.Panes)
{
if (!States.ContainsPane(pane.DockPane))
continue;
if (pane == dockPane.AutoHidePane)
return index;
index++;
}
return -1;
}
#region IEnumerable Members
IEnumerator<Pane> IEnumerable<Pane>.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
#endregion
}
protected AutoHideStripBase(DockPanel panel)
{
m_dockPanel = panel;
m_panesTop = new PaneCollection(panel, DockState.AutoHideTop);
m_panesBottom = new PaneCollection(panel, DockState.AutoHideBottom);
m_panesLeft = new PaneCollection(panel, DockState.AutoHideLeft);
m_panesRight = new PaneCollection(panel, DockState.AutoHideRight);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.Selectable, false);
}
private DockPanel m_dockPanel;
protected DockPanel DockPanel
{
get { return m_dockPanel; }
}
private PaneCollection m_panesTop;
protected PaneCollection PanesTop
{
get { return m_panesTop; }
}
private PaneCollection m_panesBottom;
protected PaneCollection PanesBottom
{
get { return m_panesBottom; }
}
private PaneCollection m_panesLeft;
protected PaneCollection PanesLeft
{
get { return m_panesLeft; }
}
private PaneCollection m_panesRight;
protected PaneCollection PanesRight
{
get { return m_panesRight; }
}
protected PaneCollection GetPanes(DockState dockState)
{
if (dockState == DockState.AutoHideTop)
return PanesTop;
else if (dockState == DockState.AutoHideBottom)
return PanesBottom;
else if (dockState == DockState.AutoHideLeft)
return PanesLeft;
else if (dockState == DockState.AutoHideRight)
return PanesRight;
else
throw new ArgumentOutOfRangeException("dockState");
}
internal int GetNumberOfPanes(DockState dockState)
{
return GetPanes(dockState).Count;
}
protected Rectangle RectangleTopLeft
{
get
{
int height = MeasureHeight();
return PanesTop.Count > 0 && PanesLeft.Count > 0 ? new Rectangle(0, 0, height, height) : Rectangle.Empty;
}
}
protected Rectangle RectangleTopRight
{
get
{
int height = MeasureHeight();
return PanesTop.Count > 0 && PanesRight.Count > 0 ? new Rectangle(Width - height, 0, height, height) : Rectangle.Empty;
}
}
protected Rectangle RectangleBottomLeft
{
get
{
int height = MeasureHeight();
return PanesBottom.Count > 0 && PanesLeft.Count > 0 ? new Rectangle(0, Height - height, height, height) : Rectangle.Empty;
}
}
protected Rectangle RectangleBottomRight
{
get
{
int height = MeasureHeight();
return PanesBottom.Count > 0 && PanesRight.Count > 0 ? new Rectangle(Width - height, Height - height, height, height) : Rectangle.Empty;
}
}
protected internal Rectangle GetTabStripRectangle(DockState dockState)
{
int height = MeasureHeight();
if (dockState == DockState.AutoHideTop && PanesTop.Count > 0)
return new Rectangle(RectangleTopLeft.Width, 0, Width - RectangleTopLeft.Width - RectangleTopRight.Width, height);
else if (dockState == DockState.AutoHideBottom && PanesBottom.Count > 0)
return new Rectangle(RectangleBottomLeft.Width, Height - height, Width - RectangleBottomLeft.Width - RectangleBottomRight.Width, height);
else if (dockState == DockState.AutoHideLeft && PanesLeft.Count > 0)
return new Rectangle(0, RectangleTopLeft.Width, height, Height - RectangleTopLeft.Height - RectangleBottomLeft.Height);
else if (dockState == DockState.AutoHideRight && PanesRight.Count > 0)
return new Rectangle(Width - height, RectangleTopRight.Width, height, Height - RectangleTopRight.Height - RectangleBottomRight.Height);
else
return Rectangle.Empty;
}
private GraphicsPath m_displayingArea = null;
private GraphicsPath DisplayingArea
{
get
{
if (m_displayingArea == null)
m_displayingArea = new GraphicsPath();
return m_displayingArea;
}
}
private void SetRegion()
{
DisplayingArea.Reset();
DisplayingArea.AddRectangle(RectangleTopLeft);
DisplayingArea.AddRectangle(RectangleTopRight);
DisplayingArea.AddRectangle(RectangleBottomLeft);
DisplayingArea.AddRectangle(RectangleBottomRight);
DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.AutoHideTop));
DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.AutoHideBottom));
DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.AutoHideLeft));
DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.AutoHideRight));
Region = new Region(DisplayingArea);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button != MouseButtons.Left)
return;
IDockContent content = HitTest();
if (content == null)
return;
SetActiveAutoHideContent(content);
content.DockHandler.Activate();
}
protected override void OnMouseHover(EventArgs e)
{
base.OnMouseHover(e);
if (!DockPanel.ShowAutoHideContentOnHover)
return;
IDockContent content = HitTest();
SetActiveAutoHideContent(content);
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
private void SetActiveAutoHideContent(IDockContent content)
{
if (content != null && DockPanel.ActiveAutoHideContent != content)
DockPanel.ActiveAutoHideContent = content;
}
protected override void OnLayout(LayoutEventArgs levent)
{
RefreshChanges();
base.OnLayout (levent);
}
internal void RefreshChanges()
{
if (IsDisposed)
return;
SetRegion();
OnRefreshChanges();
}
protected virtual void OnRefreshChanges()
{
}
protected internal abstract int MeasureHeight();
private IDockContent HitTest()
{
Point ptMouse = PointToClient(Control.MousePosition);
return HitTest(ptMouse);
}
protected virtual Tab CreateTab(IDockContent content)
{
return new Tab(content);
}
protected virtual Pane CreatePane(DockPane dockPane)
{
return new Pane(dockPane);
}
protected abstract IDockContent HitTest(Point point);
}
}
| |
namespace ZASM
{
static class Ops
{
static public OpcodeEncoding[] EncodingData =
{
// 00: NOP
new OpcodeEncoding { Function = CommandID.NOP,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x00,
},
// 01: LD rr, nn,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.WordReg | CommandID.Pos3, CommandID.WordData | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x01,
},
// 02: LD (BC), A,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.BC_Pointer, CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x02,
},
// 03: INC rr,
new OpcodeEncoding { Function = CommandID.INC,
Params = new CommandID[] { CommandID.WordReg | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x03,
},
// 04: INC r*,
new OpcodeEncoding { Function = CommandID.INC,
Params = new CommandID[] { CommandID.ByteRegIndex | CommandID.Pos2, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x04,
},
// 05: DEC r*,
new OpcodeEncoding { Function = CommandID.DEC,
Params = new CommandID[] { CommandID.ByteRegIndex | CommandID.Pos2, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x05,
},
// 06: LD r*, n,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.ByteRegIndex | CommandID.Pos2, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x06,
},
// 07: RLCA
new OpcodeEncoding { Function = CommandID.RLCA,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x07,
},
// 08: EX AF, AF,
new OpcodeEncoding { Function = CommandID.EX,
Params = new CommandID[] { CommandID.AF, CommandID.AF, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x08,
},
// 09: ADD HL*, rr,
new OpcodeEncoding { Function = CommandID.ADD,
Params = new CommandID[] { CommandID.Address_Registers, CommandID.WordReg | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x09,
},
// 0A: LD A, (BC),
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.A, CommandID.BC_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x0A,
},
// 0B: DEC rr,
new OpcodeEncoding { Function = CommandID.DEC,
Params = new CommandID[] { CommandID.WordReg | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x0B,
},
// 0F: RRCA
new OpcodeEncoding { Function = CommandID.RRCA,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x0F,
},
// 10: DJNZ e-2,
new OpcodeEncoding { Function = CommandID.DJNZ,
Params = new CommandID[] { CommandID.Displacment | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x10,
},
// 12: LD (DE), A,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.DE_Pointer, CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x12,
},
// 17: RLA
new OpcodeEncoding { Function = CommandID.RLA,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x17,
},
// 18: JR e-2,
new OpcodeEncoding { Function = CommandID.JR,
Params = new CommandID[] { CommandID.Displacment | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x18,
},
// 1A: LD A, (DE),
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.A, CommandID.DE_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x1A,
},
// 1F: RRA
new OpcodeEncoding { Function = CommandID.RRA,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x1F,
},
// 20: JR cc, e-2,
new OpcodeEncoding { Function = CommandID.JR,
Params = new CommandID[] { CommandID.HalfFlags | CommandID.Pos4, CommandID.Displacment | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x20,
},
// 22: LD (**), HL*,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.Address_Pointer | CommandID.ImmidateWord, CommandID.Address_Registers, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x22,
},
// 27: DAA
new OpcodeEncoding { Function = CommandID.DAA,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x27,
},
// 2A: LD HL*, (**),
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.Address_Registers, CommandID.Address_Pointer | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x2A,
},
// 2F: CPL A,
new OpcodeEncoding { Function = CommandID.CPL,
Params = new CommandID[] { CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x2F,
},
// 32: LD (**), A,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.Address_Pointer | CommandID.ImmidateWord, CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x32,
},
// 34: INC (HL*),
new OpcodeEncoding { Function = CommandID.INC,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x34,
},
// 35: DEC (HL*),
new OpcodeEncoding { Function = CommandID.DEC,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x35,
},
// 36: LD (HL*), n,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.Byte_Pointer, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x36,
},
// 37: SCF
new OpcodeEncoding { Function = CommandID.SCF,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x37,
},
// 3A: LD A, (**),
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.A, CommandID.Address_Pointer | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x3A,
},
// 3F: CCF
new OpcodeEncoding { Function = CommandID.CCF,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x3F,
},
// 40: LD r*, r*,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.ByteRegIndex | CommandID.Pos2, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x40,
},
// 46: LD r*, (HL*),
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.ByteRegIndex | CommandID.Pos2, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x46,
},
// 70: LD (HL*), r*,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.Byte_Pointer, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x70,
},
// 76: HALT
new OpcodeEncoding { Function = CommandID.HALT,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x76,
},
// 80: ADD A, r*,
new OpcodeEncoding { Function = CommandID.ADD,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x80,
},
// 86: ADD A, (HL*),
new OpcodeEncoding { Function = CommandID.ADD,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x86,
},
// 88: ADC A, r*,
new OpcodeEncoding { Function = CommandID.ADC,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x88,
},
// 8E: ADC A, (HL*),
new OpcodeEncoding { Function = CommandID.ADC,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x8E,
},
// 90: SUB A, r*,
new OpcodeEncoding { Function = CommandID.SUB,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x90,
},
// 96: SUB A, (HL*),
new OpcodeEncoding { Function = CommandID.SUB,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x96,
},
// 98: SBC A, r*,
new OpcodeEncoding { Function = CommandID.SBC,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x98,
},
// 9E: SBC A, (HL*),
new OpcodeEncoding { Function = CommandID.SBC,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0x9E,
},
// A0: AND A, r*,
new OpcodeEncoding { Function = CommandID.AND,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xA0,
},
// A6: AND A, (HL*),
new OpcodeEncoding { Function = CommandID.AND,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xA6,
},
// A8: XOR A, r*,
new OpcodeEncoding { Function = CommandID.XOR,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xA8,
},
// AE: XOR A, (HL*),
new OpcodeEncoding { Function = CommandID.XOR,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xAE,
},
// B0: OR A, r*,
new OpcodeEncoding { Function = CommandID.OR,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xB0,
},
// B6: OR A, (HL*),
new OpcodeEncoding { Function = CommandID.OR,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xB6,
},
// B8: CP A, r*,
new OpcodeEncoding { Function = CommandID.CP,
Params = new CommandID[] { CommandID.A, CommandID.ByteRegIndex | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xB8,
},
// BE: CP A, (HL*),
new OpcodeEncoding { Function = CommandID.CP,
Params = new CommandID[] { CommandID.A, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xBE,
},
// C0: RET cc,
new OpcodeEncoding { Function = CommandID.RET,
Params = new CommandID[] { CommandID.Flags | CommandID.Pos2, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC0,
},
// C1: POP rr,
new OpcodeEncoding { Function = CommandID.POP,
Params = new CommandID[] { CommandID.WordRegAF | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC1,
},
// C2: JP cc, nn,
new OpcodeEncoding { Function = CommandID.JP,
Params = new CommandID[] { CommandID.Flags | CommandID.Pos2, CommandID.Address | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC2,
},
// C3: JP nn,
new OpcodeEncoding { Function = CommandID.JP,
Params = new CommandID[] { CommandID.Address | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC3,
},
// C4: CALL cc, nn,
new OpcodeEncoding { Function = CommandID.CALL,
Params = new CommandID[] { CommandID.Flags | CommandID.Pos2, CommandID.Address | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC4,
},
// C5: PUSH rr,
new OpcodeEncoding { Function = CommandID.PUSH,
Params = new CommandID[] { CommandID.WordRegAF | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC5,
},
// C6: ADD A, n,
new OpcodeEncoding { Function = CommandID.ADD,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC6,
},
// C7: RST n,
new OpcodeEncoding { Function = CommandID.RST,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC7,
},
// C9: RET
new OpcodeEncoding { Function = CommandID.RET,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xC9,
},
// CD: CALL nn,
new OpcodeEncoding { Function = CommandID.CALL,
Params = new CommandID[] { CommandID.Address | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xCD,
},
// CE: ADC A, n,
new OpcodeEncoding { Function = CommandID.ADC,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xCE,
},
// D3: OUT n, A,
new OpcodeEncoding { Function = CommandID.OUT,
Params = new CommandID[] { CommandID.ByteData | CommandID.ImmidateByte, CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xD3,
},
// D6: SUB A, n,
new OpcodeEncoding { Function = CommandID.SUB,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xD6,
},
// D9: EXX
new OpcodeEncoding { Function = CommandID.EXX,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xD9,
},
// DB: IN A, n,
new OpcodeEncoding { Function = CommandID.IN,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xDB,
},
// DE: SBC A, n,
new OpcodeEncoding { Function = CommandID.SBC,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xDE,
},
// E3: EX (SP), HL*,
new OpcodeEncoding { Function = CommandID.EX,
Params = new CommandID[] { CommandID.SP_Pointer, CommandID.Address_Registers, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xE3,
},
// E6: AND A, n,
new OpcodeEncoding { Function = CommandID.AND,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xE6,
},
// E9: JP HL*,
new OpcodeEncoding { Function = CommandID.JP,
Params = new CommandID[] { CommandID.Address_Registers, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xE9,
},
// EB: EX DE, HL,
new OpcodeEncoding { Function = CommandID.EX,
Params = new CommandID[] { CommandID.DE, CommandID.HL, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xEB,
},
// EE: XOR A, n,
new OpcodeEncoding { Function = CommandID.XOR,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xEE,
},
// F3: DI
new OpcodeEncoding { Function = CommandID.DI,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xF3,
},
// F6: OR A, n,
new OpcodeEncoding { Function = CommandID.OR,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xF6,
},
// F9: LD SP, HL*,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.SP, CommandID.Address_Registers, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xF9,
},
// FB: EI
new OpcodeEncoding { Function = CommandID.EI,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xFB,
},
// FE: CP A, n,
new OpcodeEncoding { Function = CommandID.CP,
Params = new CommandID[] { CommandID.A, CommandID.ByteData | CommandID.ImmidateByte, },
Flags = ParamFlags.None,
Prefix = 0x00, Base = 0xFE,
},
// CB00: RLC r,
new OpcodeEncoding { Function = CommandID.RLC,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x00,
},
// CB00: RLC (IX*), r,
new OpcodeEncoding { Function = CommandID.RLC,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x00,
},
// CB06: RLC (HL*),
new OpcodeEncoding { Function = CommandID.RLC,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x06,
},
// CB08: RRC r,
new OpcodeEncoding { Function = CommandID.RRC,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x08,
},
// CB08: RRC (IX*), r,
new OpcodeEncoding { Function = CommandID.RRC,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x08,
},
// CB0E: RRC (HL*),
new OpcodeEncoding { Function = CommandID.RRC,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x0E,
},
// CB10: RL r,
new OpcodeEncoding { Function = CommandID.RL,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x10,
},
// CB10: RL (IX*), r,
new OpcodeEncoding { Function = CommandID.RL,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x10,
},
// CB16: RL (HL*),
new OpcodeEncoding { Function = CommandID.RL,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x16,
},
// CB18: RR r,
new OpcodeEncoding { Function = CommandID.RR,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x18,
},
// CB18: RR (IX*), r,
new OpcodeEncoding { Function = CommandID.RR,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x18,
},
// CB1E: RR (HL*),
new OpcodeEncoding { Function = CommandID.RR,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x1E,
},
// CB20: SLA r,
new OpcodeEncoding { Function = CommandID.SLA,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x20,
},
// CB20: SLA (IX*), r,
new OpcodeEncoding { Function = CommandID.SLA,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x20,
},
// CB26: SLA (HL*),
new OpcodeEncoding { Function = CommandID.SLA,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x26,
},
// CB28: SRA r,
new OpcodeEncoding { Function = CommandID.SRA,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x28,
},
// CB28: SRA (IX*), r,
new OpcodeEncoding { Function = CommandID.SRA,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x28,
},
// CB2E: SRA (HL*),
new OpcodeEncoding { Function = CommandID.SRA,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x2E,
},
// CB30: SLL r,
new OpcodeEncoding { Function = CommandID.SLL,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x30,
},
// CB30: SLL (IX*), r,
new OpcodeEncoding { Function = CommandID.SLL,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x30,
},
// CB36: SLL (HL*),
new OpcodeEncoding { Function = CommandID.SLL,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x36,
},
// CB38: SRL r,
new OpcodeEncoding { Function = CommandID.SRL,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x38,
},
// CB38: SRL (IX*), r,
new OpcodeEncoding { Function = CommandID.SRL,
Params = new CommandID[] { CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x38,
},
// CB3E: SRL (HL*),
new OpcodeEncoding { Function = CommandID.SRL,
Params = new CommandID[] { CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x3E,
},
// CB40: BIT n, r,
new OpcodeEncoding { Function = CommandID.BIT,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x40,
},
// CB40: BIT n, (IX*), r,
new OpcodeEncoding { Function = CommandID.BIT,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x40,
},
// CB46: BIT n, (HL*),
new OpcodeEncoding { Function = CommandID.BIT,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x46,
},
// CB80: RES n, r,
new OpcodeEncoding { Function = CommandID.RES,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x80,
},
// CB80: RES n, (IX*), r,
new OpcodeEncoding { Function = CommandID.RES,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x80,
},
// CB86: RES n, (HL*),
new OpcodeEncoding { Function = CommandID.RES,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0x86,
},
// CBC0: SET n, r,
new OpcodeEncoding { Function = CommandID.SET,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0xC0,
},
// CBC0: SET n, (IX*), r,
new OpcodeEncoding { Function = CommandID.SET,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.Index_Pointer, CommandID.ByteReg | CommandID.Pos1, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0xC0,
},
// CBC6: SET n, (HL*),
new OpcodeEncoding { Function = CommandID.SET,
Params = new CommandID[] { CommandID.Encoded | CommandID.Pos2, CommandID.Byte_Pointer, },
Flags = ParamFlags.None,
Prefix = 0xCB, Base = 0xC6,
},
// ED40: IN r, C,
new OpcodeEncoding { Function = CommandID.IN,
Params = new CommandID[] { CommandID.ByteReg | CommandID.Pos2, CommandID.C, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x40,
},
// ED41: OUT C, r,
new OpcodeEncoding { Function = CommandID.OUT,
Params = new CommandID[] { CommandID.C, CommandID.ByteReg | CommandID.Pos2, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x41,
},
// ED42: SBC HL, rr,
new OpcodeEncoding { Function = CommandID.SBC,
Params = new CommandID[] { CommandID.HL, CommandID.WordReg | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x42,
},
// ED43: LD (**), rr,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.Address_Pointer | CommandID.ImmidateWord, CommandID.WordReg | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x43,
},
// ED44: NEG A,
new OpcodeEncoding { Function = CommandID.NEG,
Params = new CommandID[] { CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x44,
},
// ED45: RETN
new OpcodeEncoding { Function = CommandID.RETN,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x45,
},
// ED46: IM 0,
new OpcodeEncoding { Function = CommandID.IM,
Params = new CommandID[] { (CommandID)((int)CommandID.Encoded + 00), },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x46,
},
// ED47: LD I, A,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.I, CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x47,
},
// ED4A: ADC HL, rr,
new OpcodeEncoding { Function = CommandID.ADC,
Params = new CommandID[] { CommandID.HL, CommandID.WordReg | CommandID.Pos3, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x4A,
},
// ED4B: LD rr, (**),
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.WordReg | CommandID.Pos3, CommandID.Address_Pointer | CommandID.ImmidateWord, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x4B,
},
// ED4D: RETI
new OpcodeEncoding { Function = CommandID.RETI,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x4D,
},
// ED4F: LD R, A,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.R, CommandID.A, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x4F,
},
// ED56: IM 1,
new OpcodeEncoding { Function = CommandID.IM,
Params = new CommandID[] { (CommandID)((int)CommandID.Encoded + 01), },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x56,
},
// ED57: LD A, I,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.A, CommandID.I, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x57,
},
// ED5E: IM 2,
new OpcodeEncoding { Function = CommandID.IM,
Params = new CommandID[] { (CommandID)((int)CommandID.Encoded + 02), },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x5E,
},
// ED5F: LD A, R,
new OpcodeEncoding { Function = CommandID.LD,
Params = new CommandID[] { CommandID.A, CommandID.R, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x5F,
},
// ED67: RRD
new OpcodeEncoding { Function = CommandID.RRD,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x67,
},
// ED6F: RLD
new OpcodeEncoding { Function = CommandID.RLD,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x6F,
},
// ED70: IN C,
new OpcodeEncoding { Function = CommandID.IN,
Params = new CommandID[] { CommandID.C, },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x70,
},
// ED71: OUT C, 0,
new OpcodeEncoding { Function = CommandID.OUT,
Params = new CommandID[] { CommandID.C, (CommandID)((int)CommandID.Encoded + 00), },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0x71,
},
// EDA0: LDI
new OpcodeEncoding { Function = CommandID.LDI,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xA0,
},
// EDA1: CPI
new OpcodeEncoding { Function = CommandID.CPI,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xA1,
},
// EDA2: INI
new OpcodeEncoding { Function = CommandID.INI,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xA2,
},
// EDA3: OUTI
new OpcodeEncoding { Function = CommandID.OUTI,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xA3,
},
// EDA8: LDD
new OpcodeEncoding { Function = CommandID.LDD,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xA8,
},
// EDA9: CPD
new OpcodeEncoding { Function = CommandID.CPD,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xA9,
},
// EDAA: IND
new OpcodeEncoding { Function = CommandID.IND,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xAA,
},
// EDAB: OUTD
new OpcodeEncoding { Function = CommandID.OUTD,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xAB,
},
// EDB0: LDIR
new OpcodeEncoding { Function = CommandID.LDIR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xB0,
},
// EDB1: CPIR
new OpcodeEncoding { Function = CommandID.CPIR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xB1,
},
// EDB2: INIR
new OpcodeEncoding { Function = CommandID.INIR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xB2,
},
// EDB3: OTIR
new OpcodeEncoding { Function = CommandID.OTIR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xB3,
},
// EDB8: LDDR
new OpcodeEncoding { Function = CommandID.LDDR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xB8,
},
// EDB9: CPDR
new OpcodeEncoding { Function = CommandID.CPDR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xB9,
},
// EDBA: INDR
new OpcodeEncoding { Function = CommandID.INDR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xBA,
},
// EDBB: OTDR
new OpcodeEncoding { Function = CommandID.OTDR,
Params = new CommandID[] { },
Flags = ParamFlags.None,
Prefix = 0xED, Base = 0xBB,
},
};
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Y2LCore
{
public sealed class Scanner
{
const char EOF = '\0';
private IList<Token> result;
int _line = 1, _col = 0;
char ch;
int _index = -1;
string _buffer;
int _tokenIndex = -1;
public Scanner(TextReader input)
{
this.result = new List<Token>();
this._buffer = input.ReadToEnd();
input.Dispose();
this.Scan();
}
public Token Peek()
{
if (_tokenIndex >= result.Count - 1)
return new Token("EOF", TokenType.EOF);
return result[_tokenIndex + 1];
}
public Token Next()
{
if (_tokenIndex >= result.Count - 1)
return new Token("EOF", TokenType.EOF, result[_tokenIndex].Line, result[_tokenIndex].Column);
_tokenIndex++;
return result[_tokenIndex];
}
private char PeekChar()
{
if (_index >= _buffer.Length)
{
return EOF;
}
return _buffer[_index + 1];
}
private void NextChar()
{
if (_index >= _buffer.Length - 1)
{
ch = EOF;
return;
}
_index++;
ch = _buffer[_index];
if ((ch == '\n'))
{
_line++;
_col = 0;
}
else
_col++;
}
private void Scan()
{
NextChar();
while (true)
{
// Scan individual tokens
while (char.IsWhiteSpace(ch))
{
NextChar();
}
if (ch == EOF)
break;
if (char.IsLetter(ch) || ch == '_')
{
// keyword or identifier
this.result.Add(KeywordAndIdent());
}
else if (ch == '"')
{
// string literal
Token token = StringLiteral();
this.result.Add(token);
}
else if (char.IsDigit(ch))
{
// numeric literal
Token token = NumbericLiteral();
this.result.Add(token);
}
else
{
Terminal();
}
}
}
private void Terminal()
{
switch (ch)
{
case '+':
NextChar();
this.result.Add(new Token("+", TokenType.Plus, _line, _col));
break;
case '-':
NextChar();
this.result.Add(new Token("-", TokenType.Minus, _line, _col));
break;
case '*':
NextChar();
this.result.Add(new Token("*", TokenType.Multiply, _line, _col));
break;
case '/':
NextChar();
this.result.Add(new Token("/", TokenType.Divide, _line, _col));
break;
case '=':
NextChar();
if (ch == '=')
{
NextChar();
this.result.Add(new Token("==", TokenType.Equal, _line, _col));
}
else
this.result.Add(new Token("=", TokenType.Assign, _line, _col));
break;
case ';':
NextChar();
this.result.Add(new Token(";", TokenType.SemiColon, _line, _col));
break;
case '(':
NextChar();
this.result.Add(new Token("(", TokenType.LParen, _line, _col));
break;
case ')':
NextChar();
this.result.Add(new Token(")", TokenType.RParen, _line, _col));
break;
case '{':
NextChar();
this.result.Add(new Token("{", TokenType.LBracket, _line, _col));
break;
case '}':
NextChar();
this.result.Add(new Token("}", TokenType.RBracket, _line, _col));
break;
case ',':
NextChar();
this.result.Add(new Token(",", TokenType.Comma, _line, _col));
break;
case '<':
NextChar();
if (ch == '=')
{
NextChar();
this.result.Add(new Token("<=", TokenType.LessThanOrEqual, _line, _col));
}
else
this.result.Add(new Token("<", TokenType.LessThan, _line, _col));
break;
case '>':
NextChar();
if (ch == '=')
{
NextChar();
this.result.Add(new Token(">=", TokenType.GreaterThanOrEqual, _line, _col));
}
else
this.result.Add(new Token(">", TokenType.GreaterThan, _line, _col));
break;
default:
throw new System.Exception("Scanner encountered unrecognized character '" + ch + "'");
}
}
private Token NumbericLiteral()
{
StringBuilder str = new StringBuilder();
int line = _line;
int col = _col;
while (char.IsDigit(ch) || ch == '.')
{
str.Append(ch);
NextChar();
if (ch == EOF)
{
break;
}
}
Token token = new Token(str.ToString(), TokenType.Number, line, col);
return token;
}
private Token StringLiteral()
{
StringBuilder str = new StringBuilder();
int line = _line;
int col = _col;
NextChar(); // skip the '"'
if (ch == EOF)
{
throw new System.Exception("unterminated string literal");
}
while (ch != '"')
{
str.Append(ch);
NextChar();
if (ch == EOF)
{
throw new System.Exception("unterminated string literal");
}
}
// skip the terminating "
NextChar();
Token token = new Token(str.ToString(), TokenType.StringLiteral);
token.Line = line;
token.Column = col;
return token;
}
private Token KeywordAndIdent()
{
StringBuilder strB = new StringBuilder();
int line = _line;
int col = _col;
while (char.IsLetter(ch) || ch == '_' || char.IsDigit(ch))
{
strB.Append(ch);
NextChar();
if (ch == EOF)
{
break;
}
}
string str = strB.ToString();
Token token;
switch (str.ToUpper())
{
case "DUNG":
token = new Token(str, TokenType.True);
break;
case "SAI":
token = new Token(str, TokenType.False);
break;
case "TRAVE": // return
token = new Token(str, TokenType.Return);
break;
case "VIET": // print
token = new Token(str, TokenType.Write);
break;
case "LOP": // class
token = new Token(str, TokenType.Class);
break;
case "HAM": // function
token = new Token(str, TokenType.Function);
break;
case "LAP": // for
token = new Token(str, TokenType.For);
break;
case "INT":
token = new PrimitiveToken(str, PrimitiveType.Integer);
break;
case "DOUBLE":
token = new PrimitiveToken(str, PrimitiveType.Double);
break;
case "BOOL":
token = new PrimitiveToken(str, PrimitiveType.Boolean);
break;
case "STRING":
token = new PrimitiveToken(str, PrimitiveType.String);
break;
case "VOID":
token = new PrimitiveToken(str, PrimitiveType.Void);
break;
default:
token = new Token(str, TokenType.Identifier);
break;
}
token.Line = line;
token.Column = col;
return token;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace OpenLiveWriter.ApplicationFramework
{
/// <summary>
/// The TabPageControl control provides a convenient means of getting a control and an optional
/// TabPageCommandBarLightweightControl to appear as a page on a TabLightweightControl.
/// </summary>
public class TabPageControl : UserControl
{
#region Private Member Variables
/// <summary>
/// Required designer cruft.
/// </summary>
private IContainer components;
/// <summary>
/// The tab bitmap.
/// </summary>
private Bitmap tabBitmap;
/// <summary>
/// A value which indicates whether the tab is drag-and-drop selectable.
/// </summary>
private bool dragDropSelectable = true;
/// <summary>
/// The tab text.
/// </summary>
private string tabText;
/// <summary>
/// The tab ToolTip text.
/// </summary>
private string tabToolTipText;
/// <summary>
/// Keeps track of whether the tab is selected or not
/// </summary>
private bool _tabSelected = false;
#endregion Private Member Variables
#region Public Events
/// <summary>
/// Occurs when the TabPageControl is selected.
/// </summary>
[
Category("Action"),
Description("Occurs when the TabPageControl is selected.")
]
public event EventHandler Selected;
/// <summary>
/// Occurs when the TabPageControl is selected.
/// </summary>
[
Category("Action"),
Description("Occurs when the TabPageControl is unselected.")
]
public event EventHandler Unselected;
#endregion Public Events
#region Class Initialization & Termination
/// <summary>
/// Initializes a new instance of the TabPage class.
/// </summary>
public TabPageControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
Visible = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#endregion Class Initialization & Termination
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
//
// TabPageControl
//
this.Name = "TabPageControl";
this.Size = new System.Drawing.Size(268, 298);
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the tab bitmap.
/// </summary>
[
Category("Appearance"),
Localizable(false),
DefaultValue(null),
Description("Specifies the tab bitmap.")
]
public Bitmap TabBitmap
{
get
{
return tabBitmap;
}
set
{
tabBitmap = value;
}
}
/// <summary>
/// Gets or sets the tab text.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the tab text.")
]
public string TabText
{
get
{
return tabText;
}
set
{
tabText = value;
AccessibleName = value;
}
}
/// <summary>
/// Gets or sets the tab ToolTip text.
/// </summary>
[
Category("Appearance"),
Localizable(true),
DefaultValue(null),
Description("Specifies the tab ToolTip text.")
]
public string TabToolTipText
{
get
{
return tabToolTipText;
}
set
{
tabToolTipText = value;
}
}
/// <summary>
/// Gets or sets a value which indicates whether the tab is drag-and-drop selectable.
/// </summary>
[
Category("Behavior"),
Localizable(false),
DefaultValue(true),
Description("Specifies whether the tab is drag-and-drop selectable.")
]
public bool DragDropSelectable
{
get
{
return dragDropSelectable;
}
set
{
dragDropSelectable = value;
}
}
public virtual ApplicationStyle ApplicationStyle
{
get
{
return ApplicationManager.ApplicationStyle;
}
}
public bool IsSelected
{
get
{
return _tabSelected;
}
}
#endregion Public Properties
#region Protected Events
/// <summary>
/// Raises the Selected event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnSelected(EventArgs e)
{
_tabSelected = true;
if (Selected != null)
Selected(this, e);
}
/// <summary>
/// Raises the Unselected event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnUnselected(EventArgs e)
{
_tabSelected = false;
if (Unselected != null)
Unselected(this, e);
}
#endregion Protected Events
#region Internal Methods
/// <summary>
/// Helper method to raise the Selected event.
/// </summary>
internal void RaiseSelected()
{
OnSelected(EventArgs.Empty);
}
/// <summary>
/// Helper method to raise the Unselected event.
/// </summary>
internal void RaiseUnselected()
{
OnUnselected(EventArgs.Empty);
}
#endregion Internal Methods
#region Accessibility
private TabPageAccessibility _accessibleObject;
protected override AccessibleObject CreateAccessibilityInstance()
{
if (_accessibleObject == null)
_accessibleObject = new TabPageAccessibility(this);
return _accessibleObject;
}
class TabPageAccessibility : ControlAccessibleObject
{
TabPageControl _tabpage;
public TabPageAccessibility(TabPageControl ownerControl) : base(ownerControl)
{
_tabpage = ownerControl;
}
public override Rectangle Bounds
{
get
{
if (_tabpage.Visible)
return base.Bounds;
else
{
//return empty rect when not visible to prevent bugs with MSAA info
//returning info on the wrong controls when mousing over tab controls
return Rectangle.Empty;
}
}
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
public class MyCqListener<TKey, TResult> : ICqListener<TKey, TResult>
{
#region Private members
private bool m_failedOver = false;
private UInt32 m_eventCountBefore = 0;
private UInt32 m_errorCountBefore = 0;
private UInt32 m_eventCountAfter = 0;
private UInt32 m_errorCountAfter = 0;
#endregion
#region Public accessors
public void failedOver()
{
m_failedOver = true;
}
public UInt32 getEventCountBefore()
{
return m_eventCountBefore;
}
public UInt32 getErrorCountBefore()
{
return m_errorCountBefore;
}
public UInt32 getEventCountAfter()
{
return m_eventCountAfter;
}
public UInt32 getErrorCountAfter()
{
return m_errorCountAfter;
}
#endregion
public virtual void OnEvent(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqListener::OnEvent called");
if (m_failedOver == true)
m_eventCountAfter++;
else
m_eventCountBefore++;
//IGeodeSerializable val = ev.getNewValue();
//ICacheableKey key = ev.getKey();
TResult val = (TResult)ev.getNewValue();
/*ICacheableKey*/
TKey key = ev.getKey();
CqOperation opType = ev.getQueryOperation();
//CacheableString keyS = key as CacheableString;
string keyS = key.ToString(); //as string;
Portfolio pval = val as Portfolio;
PortfolioPdx pPdxVal = val as PortfolioPdx;
Assert.IsTrue((pPdxVal != null) || (pval != null));
//string opStr = "DESTROY";
/*if (opType == CqOperation.OP_TYPE_CREATE)
opStr = "CREATE";
else if (opType == CqOperation.OP_TYPE_UPDATE)
opStr = "UPDATE";*/
//Util.Log("key {0}, value ({1},{2}), op {3}.", keyS,
// pval.ID, pval.Pkid, opStr);
}
public virtual void OnError(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqListener::OnError called");
if (m_failedOver == true)
m_errorCountAfter++;
else
m_errorCountBefore++;
}
public virtual void Close()
{
Util.Log("MyCqListener::close called");
}
public virtual void Clear()
{
Util.Log("MyCqListener::Clear called");
m_eventCountBefore = 0;
m_errorCountBefore = 0;
m_eventCountAfter = 0;
m_errorCountAfter = 0;
}
}
public class MyCqListener1<TKey, TResult> : ICqListener<TKey, TResult>
{
public static UInt32 m_cntEvents = 0;
public virtual void OnEvent(CqEvent<TKey, TResult> ev)
{
m_cntEvents++;
Util.Log("MyCqListener1::OnEvent called");
Object val = (Object)ev.getNewValue();
Object pkey = (Object)ev.getKey();
int value = (int)val;
int key = (int)pkey;
CqOperation opType = ev.getQueryOperation();
String opStr = "Default";
if (opType == CqOperation.OP_TYPE_CREATE)
opStr = "CREATE";
else if (opType == CqOperation.OP_TYPE_UPDATE)
opStr = "UPDATE";
Util.Log("MyCqListener1::OnEvent called with {0} , key = {1}, value = {2} ",
opStr, key, value);
}
public virtual void OnError(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqListener1::OnError called");
}
public virtual void Close()
{
Util.Log("MyCqListener1::close called");
}
}
public class MyCqStatusListener<TKey, TResult> : ICqStatusListener<TKey, TResult>
{
#region Private members
private bool m_failedOver = false;
private UInt32 m_eventCountBefore = 0;
private UInt32 m_errorCountBefore = 0;
private UInt32 m_eventCountAfter = 0;
private UInt32 m_errorCountAfter = 0;
private UInt32 m_CqConnectedCount = 0;
private UInt32 m_CqDisConnectedCount = 0;
#endregion
#region Public accessors
public MyCqStatusListener(int id)
{
}
public void failedOver()
{
m_failedOver = true;
}
public UInt32 getEventCountBefore()
{
return m_eventCountBefore;
}
public UInt32 getErrorCountBefore()
{
return m_errorCountBefore;
}
public UInt32 getEventCountAfter()
{
return m_eventCountAfter;
}
public UInt32 getErrorCountAfter()
{
return m_errorCountAfter;
}
public UInt32 getCqConnectedCount()
{
return m_CqConnectedCount;
}
public UInt32 getCqDisConnectedCount()
{
return m_CqDisConnectedCount;
}
#endregion
public virtual void OnEvent(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqStatusListener::OnEvent called");
if (m_failedOver == true)
m_eventCountAfter++;
else
m_eventCountBefore++;
TResult val = (TResult)ev.getNewValue();
TKey key = ev.getKey();
CqOperation opType = ev.getQueryOperation();
string keyS = key.ToString(); //as string;
}
public virtual void OnError(CqEvent<TKey, TResult> ev)
{
Util.Log("MyCqStatusListener::OnError called");
if (m_failedOver == true)
m_errorCountAfter++;
else
m_errorCountBefore++;
}
public virtual void Close()
{
Util.Log("MyCqStatusListener::close called");
}
public virtual void OnCqConnected()
{
m_CqConnectedCount++;
Util.Log("MyCqStatusListener::OnCqConnected called");
}
public virtual void OnCqDisconnected()
{
m_CqDisConnectedCount++;
Util.Log("MyCqStatusListener::OnCqDisconnected called");
}
public virtual void Clear()
{
Util.Log("MyCqStatusListener::Clear called");
m_eventCountBefore = 0;
m_errorCountBefore = 0;
m_eventCountAfter = 0;
m_errorCountAfter = 0;
m_CqConnectedCount = 0;
m_CqDisConnectedCount = 0;
}
}
[TestFixture]
[Category("group3")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientCqTests : ThinClientRegionSteps
{
#region Private members
private static bool m_usePdxObjects = false;
private UnitProcess m_client1;
private UnitProcess m_client2;
private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2",
"Portfolios3" };
private static string QERegionName = "Portfolios";
private static string CqName = "MyCq";
private static string CqName1 = "testCQAllServersLeave";
private static string CqName2 = "testCQAllServersLeave1";
private static string CqQuery1 = "select * from /DistRegionAck";
private static string CqQuery2 = "select * from /DistRegionAck1";
//private static string CqName1 = "MyCq1";
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
[TestFixtureSetUp]
public override void InitTests()
{
base.InitTests();
m_client1.Call(InitClient);
m_client2.Call(InitClient);
}
[TearDown]
public override void EndTest()
{
CacheHelper.StopJavaServers();
base.EndTest();
}
public void InitClient()
{
CacheHelper.Init();
try
{
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Portfolio.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Position.CreateDeserializable);
}
catch (IllegalStateException)
{
// ignore since we run multiple iterations for pool and non pool configs
}
}
public void StepOne(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>("DistRegionAck", true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes;
region.CreateSubRegion(QueryRegionNames[1], regattrs);
}
public void StepTwo(bool usePdxObject)
{
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]);
IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]);
IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]);
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
Util.Log("Object type is pdx = " + m_usePdxObjects);
Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize,
qh.PortfolioNumSets);
if (!usePdxObject)
{
qh.PopulatePortfolioData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
else
{
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PortfolioPdx.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PositionPdx.CreateDeserializable);
qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
}
public void StepTwoQT()
{
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]);
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
qh.PopulatePortfolioData(region0, 100, 20, 100);
qh.PopulatePositionData(subRegion0, 100, 20);
}
public void StepOneQE(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName);
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 100);
Portfolio p3 = new Portfolio(3, 100);
Portfolio p4 = new Portfolio(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
ICqListener<object, object> cqLstner = new MyCqListener<object, object>();
cqFac.AddCqListener(cqLstner);
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(CqName, "select * from /" + QERegionName + " p where p.ID!=2", cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq<object, object>(CqName);
CqServiceStatistics cqSvcStats = qs.GetCqStatistics();
Assert.AreEqual(1, cqSvcStats.numCqsActive());
Assert.AreEqual(1, cqSvcStats.numCqsCreated());
Assert.AreEqual(1, cqSvcStats.numCqsOnClient());
cqAttr = qry.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore());
CqStatistics cqStats = qry.GetStatistics();
Assert.AreEqual(cqStats.numEvents(), myLisner.getEventCountBefore());
if (myLisner.getEventCountBefore() + myLisner.getErrorCountBefore() == 0)
{
Assert.Fail("cq before count zero");
}
qry.Stop();
Assert.AreEqual(1, cqSvcStats.numCqsStopped());
qry.Close();
Assert.AreEqual(1, cqSvcStats.numCqsClosed());
// Bring down the region
region.GetLocalView().DestroyRegion();
}
public void StepOnePdxQE(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName);
PortfolioPdx p1 = new PortfolioPdx(1, 100);
PortfolioPdx p2 = new PortfolioPdx(2, 100);
PortfolioPdx p3 = new PortfolioPdx(3, 100);
PortfolioPdx p4 = new PortfolioPdx(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
ICqListener<object, object> cqLstner = new MyCqListener<object, object>();
cqFac.AddCqListener(cqLstner);
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(CqName, "select * from /" + QERegionName + " p where p.ID!=2", cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq<object, object>(CqName);
CqServiceStatistics cqSvcStats = qs.GetCqStatistics();
Assert.AreEqual(1, cqSvcStats.numCqsActive());
Assert.AreEqual(1, cqSvcStats.numCqsCreated());
Assert.AreEqual(1, cqSvcStats.numCqsOnClient());
cqAttr = qry.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore());
CqStatistics cqStats = qry.GetStatistics();
Assert.AreEqual(cqStats.numEvents(), myLisner.getEventCountBefore());
if (myLisner.getEventCountBefore() + myLisner.getErrorCountBefore() == 0)
{
Assert.Fail("cq before count zero");
}
qry.Stop();
Assert.AreEqual(1, cqSvcStats.numCqsStopped());
qry.Close();
Assert.AreEqual(1, cqSvcStats.numCqsClosed());
// Bring down the region
region.GetLocalView().DestroyRegion();
}
public void KillServer()
{
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
public delegate void KillServerDelegate();
/*
public void StepOneFailover()
{
// This is here so that Client1 registers information of the cacheserver
// that has been already started
CacheHelper.SetupJavaServers("remotequery.xml",
"cqqueryfailover.xml");
CacheHelper.StartJavaServer(1, "GFECS1");
Util.Log("Cacheserver 1 started.");
CacheHelper.CreateTCRegion(QueryRegionNames[0], true, true, null, true);
Region region = CacheHelper.GetVerifyRegion(QueryRegionNames[0]);
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 200);
Portfolio p3 = new Portfolio(3, 300);
Portfolio p4 = new Portfolio(4, 400);
region.Put("1", p1);
region.Put("2", p2);
region.Put("3", p3);
region.Put("4", p4);
}
*/
/*
public void StepTwoFailover()
{
CacheHelper.StartJavaServer(2, "GFECS2");
Util.Log("Cacheserver 2 started.");
IAsyncResult killRes = null;
KillServerDelegate ksd = new KillServerDelegate(KillServer);
CacheHelper.CreateTCRegion(QueryRegionNames[0], true, true, null, true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QueryRegionNames[0]);
var qs = CacheHelper.DCache.GetQueryService();
CqAttributesFactory cqFac = new CqAttributesFactory();
ICqListener cqLstner = new MyCqListener();
cqFac.AddCqListener(cqLstner);
CqAttributes cqAttr = cqFac.Create();
CqQuery qry = qs.NewCq(CqName1, "select * from /" + QERegionName + " p where p.ID!<4", cqAttr, true);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq(CqName1);
cqAttr = qry.GetCqAttributes();
ICqListener[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener myLisner = cqLstner as MyCqListener;
if (myLisner.getEventCountAfter() + myLisner.getErrorCountAfter() != 0)
{
Assert.Fail("cq after count not zero");
}
killRes = ksd.BeginInvoke(null, null);
Thread.Sleep(18000); // sleep 0.3min to allow failover complete
myLisner.failedOver();
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 200);
Portfolio p3 = new Portfolio(3, 300);
Portfolio p4 = new Portfolio(4, 400);
region.Put("4", p1);
region.Put("3", p2);
region.Put("2", p3);
region.Put("1", p4);
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry = qs.GetCq(CqName1);
cqAttr = qry.GetCqAttributes();
vl = cqAttr.getCqListeners();
cqLstner = vl[0];
Assert.IsNotNull(vl);
Assert.AreEqual(1, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
myLisner = cqLstner as MyCqListener;
if (myLisner.getEventCountAfter() + myLisner.getErrorCountAfter() == 0)
{
Assert.Fail("no cq after failover");
}
killRes.AsyncWaitHandle.WaitOne();
ksd.EndInvoke(killRes);
qry.Stop();
qry.Close();
}
*/
public void ProcessCQ(string locators)
{
CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName);
Portfolio p1 = new Portfolio(1, 100);
Portfolio p2 = new Portfolio(2, 100);
Portfolio p3 = new Portfolio(3, 100);
Portfolio p4 = new Portfolio(4, 100);
region["1"] = p1;
region["2"] = p2;
region["3"] = p3;
region["4"] = p4;
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
ICqListener<object, object> cqLstner = new MyCqListener<object, object>();
ICqStatusListener<object, object> cqStatusLstner = new MyCqStatusListener<object, object>(1);
ICqListener<object, object>[] v = new ICqListener<object, object>[2];
cqFac.AddCqListener(cqLstner);
v[0] = cqLstner;
v[1] = cqStatusLstner;
cqFac.InitCqListeners(v);
Util.Log("InitCqListeners called");
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry1 = qs.NewCq("CQ1", "select * from /" + QERegionName + " p where p.ID >= 1", cqAttr, false);
qry1.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry1 = qs.GetCq<object, object>("CQ1");
cqAttr = qry1.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
Assert.IsNotNull(vl);
Assert.AreEqual(2, vl.Length);
cqLstner = vl[0];
Assert.IsNotNull(cqLstner);
MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore());
Assert.AreEqual(4, myLisner.getEventCountBefore());
cqStatusLstner = (ICqStatusListener<object, object>)vl[1];
Assert.IsNotNull(cqStatusLstner);
MyCqStatusListener<object, object> myStatLisner = (MyCqStatusListener<object, object>)cqStatusLstner;// as MyCqStatusListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myStatLisner.getEventCountBefore(), myStatLisner.getErrorCountBefore());
Assert.AreEqual(1, myStatLisner.getCqConnectedCount());
Assert.AreEqual(4, myStatLisner.getEventCountBefore());
CqAttributesMutator<object, object> mutator = qry1.GetCqAttributesMutator();
mutator.RemoveCqListener(cqLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(1, cqAttr.getCqListeners().Length);
mutator.RemoveCqListener(cqStatusLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("1 cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(0, cqAttr.getCqListeners().Length);
ICqListener<object, object>[] v2 = new ICqListener<object, object>[2];
v2[0] = cqLstner;
v2[1] = cqStatusLstner;
MyCqListener<object, object> myLisner2 = (MyCqListener<object, object>)cqLstner;
myLisner2.Clear();
MyCqStatusListener<object, object> myStatLisner2 = (MyCqStatusListener<object, object>)cqStatusLstner;
myStatLisner2.Clear();
mutator.SetCqListeners(v2);
cqAttr = qry1.GetCqAttributes();
Assert.AreEqual(2, cqAttr.getCqListeners().Length);
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry1 = qs.GetCq<object, object>("CQ1");
cqAttr = qry1.GetCqAttributes();
ICqListener<object, object>[] v3 = cqAttr.getCqListeners();
Assert.IsNotNull(v3);
Assert.AreEqual(2, vl.Length);
cqLstner = v3[0];
Assert.IsNotNull(cqLstner);
myLisner2 = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myLisner2.getEventCountBefore(), myLisner2.getErrorCountBefore());
Assert.AreEqual(4, myLisner2.getEventCountBefore());
cqStatusLstner = (ICqStatusListener<object, object>)v3[1];
Assert.IsNotNull(cqStatusLstner);
myStatLisner2 = (MyCqStatusListener<object, object>)cqStatusLstner;// as MyCqStatusListener<object, object>;
Util.Log("event count:{0}, error count {1}.", myStatLisner2.getEventCountBefore(), myStatLisner2.getErrorCountBefore());
Assert.AreEqual(0, myStatLisner2.getCqConnectedCount());
Assert.AreEqual(4, myStatLisner2.getEventCountBefore());
mutator = qry1.GetCqAttributesMutator();
mutator.RemoveCqListener(cqLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(1, cqAttr.getCqListeners().Length);
mutator.RemoveCqListener(cqStatusLstner);
cqAttr = qry1.GetCqAttributes();
Util.Log("1 cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length);
Assert.AreEqual(0, cqAttr.getCqListeners().Length);
region["4"] = p1;
region["3"] = p2;
region["2"] = p3;
region["1"] = p4;
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
qry1 = qs.GetCq<object, object>("CQ1");
cqAttr = qry1.GetCqAttributes();
ICqListener<object, object>[] v4 = cqAttr.getCqListeners();
Assert.IsNotNull(v4);
Assert.AreEqual(0, v4.Length);
Util.Log("cqAttr.getCqListeners() done");
}
public void CreateAndExecuteCQ_StatusListener(string poolName, string cqName, string cqQuery, int id)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
cqFac.AddCqListener(new MyCqStatusListener<object, object>(id));
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(cqName, cqQuery, cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
}
public void CreateAndExecuteCQ_Listener(string poolName, string cqName, string cqQuery, int id)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>();
cqFac.AddCqListener(new MyCqListener<object, object>(/*id*/));
CqAttributes<object, object> cqAttr = cqFac.Create();
CqQuery<object, object> qry = qs.NewCq(cqName, cqQuery, cqAttr, false);
qry.Execute();
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
}
public void CheckCQStatusOnConnect(string poolName, string cqName, int onCqStatusConnect)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqQuery<object, object> query = qs.GetCq<object, object>(cqName);
CqAttributes<object, object> cqAttr = query.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>) vl[0];
Util.Log("CheckCQStatusOnConnect = {0} ", myCqStatusLstr.getCqConnectedCount());
Assert.AreEqual(onCqStatusConnect, myCqStatusLstr.getCqConnectedCount());
}
public void CheckCQStatusOnDisConnect(string poolName, string cqName, int onCqStatusDisConnect)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqQuery<object, object> query = qs.GetCq<object, object>(cqName);
CqAttributes<object, object> cqAttr = query.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>)vl[0];
Util.Log("CheckCQStatusOnDisConnect = {0} ", myCqStatusLstr.getCqDisConnectedCount());
Assert.AreEqual(onCqStatusDisConnect, myCqStatusLstr.getCqDisConnectedCount());
}
public void PutEntries(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
for (int i = 1; i <= 10; i++) {
region["key-" + i] = "val-" + i;
}
Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete
}
public void CheckCQStatusOnPutEvent(string poolName, string cqName, int onCreateCount)
{
var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService();
CqQuery<object, object> query = qs.GetCq<object, object>(cqName);
CqAttributes<object, object> cqAttr = query.GetCqAttributes();
ICqListener<object, object>[] vl = cqAttr.getCqListeners();
MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>)vl[0];
Util.Log("CheckCQStatusOnPutEvent = {0} ", myCqStatusLstr.getEventCountBefore());
Assert.AreEqual(onCreateCount, myCqStatusLstr.getEventCountBefore());
}
public void CreateRegion(string locators, string servergroup, string regionName, string poolName)
{
CacheHelper.CreateTCRegion_Pool<object, object>(regionName, true, true,
null, locators, poolName, true, servergroup);
}
void runCqQueryTest()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(StepOne, CacheHelper.Locators);
Util.Log("StepOne complete.");
m_client1.Call(StepTwo, m_usePdxObjects);
Util.Log("StepTwo complete.");
if (!m_usePdxObjects)
m_client1.Call(StepOneQE, CacheHelper.Locators);
else
m_client1.Call(StepOnePdxQE, CacheHelper.Locators);
Util.Log("StepOne complete.");
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runCqQueryStatusTest()
{
CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(StepOne, CacheHelper.Locators);
Util.Log("StepOne complete.");
m_client1.Call(CreateAndExecuteCQ_StatusListener, "__TESTPOOL1_", CqName1, CqQuery1, 100);
Util.Log("CreateAndExecuteCQ complete.");
m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL1_", CqName1, 1);
Util.Log("CheckCQStatusOnConnect complete.");
m_client1.Call(PutEntries, "DistRegionAck");
Util.Log("PutEntries complete.");
m_client1.Call(CheckCQStatusOnPutEvent, "__TESTPOOL1_", CqName1, 10);
Util.Log("CheckCQStatusOnPutEvent complete.");
CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("start server 2 complete.");
Thread.Sleep(20000);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
Thread.Sleep(20000);
m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 0);
Util.Log("CheckCQStatusOnDisConnect complete.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
Thread.Sleep(20000);
m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 1);
Util.Log("CheckCQStatusOnDisConnect complete.");
CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
Thread.Sleep(20000);
m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL1_", CqName1, 2);
Util.Log("CheckCQStatusOnConnect complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
Thread.Sleep(20000);
m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 2);
Util.Log("CheckCQStatusOnDisConnect complete.");
m_client1.Call(Close);
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runCqQueryStatusTest2()
{
CacheHelper.SetupJavaServers(true, "cacheserver_servergroup.xml", "cacheserver_servergroup2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("start server 1 complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("start server 2 complete.");
m_client1.Call(CreateRegion, CacheHelper.Locators, "group1", "DistRegionAck", "__TESTPOOL1_");
Util.Log("CreateRegion DistRegionAck complete.");
m_client1.Call(CreateRegion, CacheHelper.Locators, "group2", "DistRegionAck1", "__TESTPOOL2_");
Util.Log("CreateRegion DistRegionAck1 complete.");
m_client1.Call(CreateAndExecuteCQ_StatusListener, "__TESTPOOL1_", CqName1, CqQuery1, 100);
Util.Log("CreateAndExecuteCQ1 complete.");
m_client1.Call(CreateAndExecuteCQ_StatusListener, "__TESTPOOL2_", CqName2, CqQuery2, 101);
Util.Log("CreateAndExecuteCQ2 complete.");
m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL1_", CqName1, 1);
Util.Log("CheckCQStatusOnConnect1 complete.");
m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL2_", CqName2, 1);
Util.Log("CheckCQStatusOnConnect2 complete.");
m_client1.Call(PutEntries, "DistRegionAck");
Util.Log("PutEntries1 complete.");
m_client1.Call(PutEntries, "DistRegionAck1");
Util.Log("PutEntries2 complete.");
m_client1.Call(CheckCQStatusOnPutEvent, "__TESTPOOL1_", CqName1, 10);
Util.Log("CheckCQStatusOnPutEvent complete.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
Thread.Sleep(20000);
m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 1);
Util.Log("CheckCQStatusOnDisConnect complete.");
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
Thread.Sleep(20000);
m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL2_", CqName2, 1);
Util.Log("CheckCQStatusOnDisConnect complete.");
m_client1.Call(Close);
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
void runCqQueryStatusTest3()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(ProcessCQ, CacheHelper.Locators);
Util.Log("ProcessCQ complete.");
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
[Test]
public void CqQueryTest()
{
runCqQueryTest();
}
[Test]
public void CqQueryPdxTest()
{
m_usePdxObjects = true;
runCqQueryTest();
m_usePdxObjects = false;
}
// [Test]
// public void CqFailover()
// {
// try
// {
// m_client1.Call(StepOneFailover);
// Util.Log("StepOneFailover complete.");
//
// m_client1.Call(StepTwoFailover);
// Util.Log("StepTwoFailover complete.");
// }
// finally
// {
// m_client1.Call(CacheHelper.StopJavaServers);
// }
// }
[Test]
public void CqQueryStatusTest()
{
runCqQueryStatusTest();
}
[Test]
public void CqQueryStatusTest2()
{
runCqQueryStatusTest2();
}
[Test]
public void CqQueryStatusTest3()
{
runCqQueryStatusTest3();
}
}
}
| |
//
// 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 Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations to manage Azure SQL Database and Database
/// Server Security Alert policy. Contains operations to: Create,
/// Retrieve and Update policy.
/// </summary>
internal partial class SecurityAlertPolicyOperations : IServiceOperations<SqlManagementClient>, ISecurityAlertPolicyOperations
{
/// <summary>
/// Initializes a new instance of the SecurityAlertPolicyOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SecurityAlertPolicyOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Database security alert policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the security
/// alert policy applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Azure
/// SQL Database security alert policy.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdateDatabaseSecurityAlertPolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseSecurityAlertPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatabaseSecurityAlertPolicyAsync", 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(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/securityAlertPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject databaseSecurityAlertPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = databaseSecurityAlertPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
databaseSecurityAlertPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.State != null)
{
propertiesValue["state"] = parameters.Properties.State;
}
if (parameters.Properties.DisabledAlerts != null)
{
propertiesValue["disabledAlerts"] = parameters.Properties.DisabledAlerts;
}
if (parameters.Properties.EmailAddresses != null)
{
propertiesValue["emailAddresses"] = parameters.Properties.EmailAddresses;
}
if (parameters.Properties.EmailAccountAdmins != null)
{
propertiesValue["emailAccountAdmins"] = parameters.Properties.EmailAccountAdmins;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// 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 && statusCode != HttpStatusCode.Created)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
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>
/// Returns an Azure SQL Database security alert policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the security
/// alert policy applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get database security alert policy
/// request.
/// </returns>
public async Task<DatabaseSecurityAlertPolicyGetResponse> GetDatabaseSecurityAlertPolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetDatabaseSecurityAlertPolicyAsync", 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(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/securityAlertPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// 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
DatabaseSecurityAlertPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseSecurityAlertPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DatabaseSecurityAlertPolicy securityAlertPolicyInstance = new DatabaseSecurityAlertPolicy();
result.SecurityAlertPolicy = securityAlertPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DatabaseSecurityAlertPolicyProperties propertiesInstance = new DatabaseSecurityAlertPolicyProperties();
securityAlertPolicyInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken disabledAlertsValue = propertiesValue["disabledAlerts"];
if (disabledAlertsValue != null && disabledAlertsValue.Type != JTokenType.Null)
{
string disabledAlertsInstance = ((string)disabledAlertsValue);
propertiesInstance.DisabledAlerts = disabledAlertsInstance;
}
JToken emailAddressesValue = propertiesValue["emailAddresses"];
if (emailAddressesValue != null && emailAddressesValue.Type != JTokenType.Null)
{
string emailAddressesInstance = ((string)emailAddressesValue);
propertiesInstance.EmailAddresses = emailAddressesInstance;
}
JToken emailAccountAdminsValue = propertiesValue["emailAccountAdmins"];
if (emailAccountAdminsValue != null && emailAccountAdminsValue.Type != JTokenType.Null)
{
string emailAccountAdminsInstance = ((string)emailAccountAdminsValue);
propertiesInstance.EmailAccountAdmins = emailAccountAdminsInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
securityAlertPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
securityAlertPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
securityAlertPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
securityAlertPolicyInstance.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);
securityAlertPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
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.Generic;
using System.Linq;
using ModestTree;
using UnityEngine;
using UnityEditor;
using UnityEngine.Profiling;
using Zenject;
namespace Zenject.MemoryPoolMonitor
{
public class MpmView : IGuiRenderable, ITickable, IInitializable
{
readonly Settings _settings;
readonly MpmWindow _window;
readonly List<IMemoryPool> _pools = new List<IMemoryPool>();
const int NumColumns = 6;
static string[] ColumnTitles = new string[]
{
"Pool Type", "Num Total", "Num Active", "Num Inactive", "", ""
};
int _controlID;
int _sortColumn = 0;
float _scrollPosition;
bool _poolListDirty;
bool _sortDescending;
Texture2D _rowBackground1;
Texture2D _rowBackground2;
Texture2D _rowBackgroundHighlighted;
Texture2D _rowBackgroundSelected;
Texture2D _lineTexture;
Type _selectedPoolType;
string _searchFilter = "";
string _actualFilter = "";
public MpmView(
MpmWindow window,
Settings settings)
{
_settings = settings;
_window = window;
}
public float HeaderTop
{
get { return _settings.HeaderHeight + _settings.FilterHeight; }
}
public float TotalWidth
{
get { return _window.position.width; }
}
public float TotalHeight
{
get { return _window.position.height; }
}
string GetName(IMemoryPool pool)
{
var type = pool.GetType();
return "{0}.{1}".Fmt(type.Namespace, type.PrettyName());
}
Texture2D CreateColorTexture(Color color)
{
var texture = new Texture2D(1, 1);
texture.SetPixel(1, 1, color);
texture.Apply();
return texture;
}
Texture2D RowBackground1
{
get
{
if (_rowBackground1 == null)
{
_rowBackground1 = CreateColorTexture(_settings.RowBackground1);
}
return _rowBackground1;
}
}
Texture2D RowBackground2
{
get
{
if (_rowBackground2 == null)
{
_rowBackground2 = CreateColorTexture(_settings.RowBackground2);
}
return _rowBackground2;
}
}
Texture2D RowBackgroundHighlighted
{
get
{
if (_rowBackgroundHighlighted == null)
{
_rowBackgroundHighlighted = CreateColorTexture(_settings.RowBackgroundHighlighted);
}
return _rowBackgroundHighlighted;
}
}
Texture2D RowBackgroundSelected
{
get
{
if (_rowBackgroundSelected == null)
{
_rowBackgroundSelected = CreateColorTexture(_settings.RowBackgroundSelected);
}
return _rowBackgroundSelected;
}
}
Texture2D LineTexture
{
get
{
if (_lineTexture == null)
{
_lineTexture = CreateColorTexture(_settings.LineColor);
}
return _lineTexture;
}
}
public void Initialize()
{
StaticMemoryPoolRegistry.PoolAdded += OnPoolListChanged;
StaticMemoryPoolRegistry.PoolRemoved += OnPoolListChanged;
_poolListDirty = true;
}
void OnPoolListChanged(IMemoryPool pool)
{
_poolListDirty = true;
}
public void Tick()
{
if (_poolListDirty)
{
_poolListDirty = false;
_pools.Clear();
_pools.AddRange(StaticMemoryPoolRegistry.Pools.Where(ShouldIncludePool));
}
InPlaceStableSort<IMemoryPool>.Sort(_pools, ComparePools);
}
bool ShouldIncludePool(IMemoryPool pool)
{
//var poolType = pool.GetType();
//if (poolType.Namespace == "Zenject")
//{
//return false;
//}
if (_actualFilter.IsEmpty())
{
return true;
}
return GetName(pool).ToLowerInvariant().Contains(_actualFilter);
}
public void GuiRender()
{
_controlID = GUIUtility.GetControlID(FocusType.Passive);
Rect windowBounds = new Rect(0, 0, TotalWidth, _window.position.height);
Vector2 scrollbarSize = new Vector2(
GUI.skin.horizontalScrollbar.CalcSize(GUIContent.none).y,
GUI.skin.verticalScrollbar.CalcSize(GUIContent.none).x);
GUI.Label(new Rect(
0, 0, _settings.FilterPaddingLeft, _settings.FilterHeight), "Filter:", _settings.FilterTextStyle);
var searchFilter = GUI.TextField(
new Rect(_settings.FilterPaddingLeft, _settings.FilterPaddingTop, _settings.FilterWidth, _settings.FilterInputHeight), _searchFilter, 999);
if (searchFilter != _searchFilter)
{
_searchFilter = searchFilter;
_actualFilter = _searchFilter.Trim().ToLowerInvariant();
_poolListDirty = true;
}
Rect viewArea = new Rect(0, HeaderTop, TotalWidth - scrollbarSize.y, _window.position.height - HeaderTop);
Rect contentRect = new Rect(
0, 0, viewArea.width, _pools.Count() * _settings.RowHeight);
Rect vScrRect = new Rect(
windowBounds.x + viewArea.width, HeaderTop, scrollbarSize.y, viewArea.height);
_scrollPosition = GUI.VerticalScrollbar(
vScrRect, _scrollPosition, viewArea.height, 0, contentRect.height);
DrawColumnHeaders(viewArea.width);
GUI.BeginGroup(viewArea);
{
contentRect.y = -_scrollPosition;
GUI.BeginGroup(contentRect);
{
DrawContent(contentRect.width);
}
GUI.EndGroup();
}
GUI.EndGroup();
HandleEvents();
}
void DrawColumnHeaders(float width)
{
GUI.DrawTexture(new Rect(
0, _settings.FilterHeight - 0.5f * _settings.SplitterWidth, width, _settings.SplitterWidth), LineTexture);
GUI.DrawTexture(new Rect(
0, HeaderTop - 0.5f * _settings.SplitterWidth, width, _settings.SplitterWidth), LineTexture);
var columnPos = 0.0f;
for (int i = 0; i < NumColumns; i++)
{
var columnWidth = GetColumnWidth(i);
DrawColumn1(i, columnPos, columnWidth);
columnPos += columnWidth;
}
}
void DrawColumn1(
int index, float position, float width)
{
var columnHeight = _settings.HeaderHeight + _pools.Count() * _settings.RowHeight;
if (index < 4)
{
GUI.DrawTexture(new Rect(
position + width - _settings.SplitterWidth * 0.5f, _settings.FilterHeight,
_settings.SplitterWidth, columnHeight), LineTexture);
}
var headerBounds = new Rect(
position + 0.5f * _settings.SplitterWidth,
_settings.FilterHeight,
width - _settings.SplitterWidth, _settings.HeaderHeight);
DrawColumnHeader(index, headerBounds, ColumnTitles[index]);
}
void HandleEvents()
{
switch (Event.current.GetTypeForControl(_controlID))
{
case EventType.ScrollWheel:
{
_scrollPosition = Mathf.Clamp(_scrollPosition + Event.current.delta.y * _settings.ScrollSpeed, 0, TotalHeight);
break;
}
case EventType.MouseDown:
{
_selectedPoolType = TryGetPoolTypeUnderMouse();
break;
}
}
}
Type TryGetPoolTypeUnderMouse()
{
var mousePositionInContent = Event.current.mousePosition + Vector2.up * _scrollPosition;
for (int i = 0; i < _pools.Count; i++)
{
var pool = _pools[i];
var rowRect = GetPoolRowRect(i);
rowRect.y += HeaderTop;
if (rowRect.Contains(mousePositionInContent))
{
return pool.GetType();
}
}
return null;
}
Rect GetPoolRowRect(int index)
{
return new Rect(
0, index * _settings.RowHeight, TotalWidth, _settings.RowHeight);
}
void DrawRowBackgrounds()
{
var mousePositionInContent = Event.current.mousePosition;
for (int i = 0; i < _pools.Count; i++)
{
var pool = _pools[i];
var rowRect = GetPoolRowRect(i);
Texture2D background;
if (pool.GetType() == _selectedPoolType)
{
background = RowBackgroundSelected;
}
else
{
if (rowRect.Contains(mousePositionInContent))
{
background = RowBackgroundHighlighted;
}
else if (i % 2 == 0)
{
background = RowBackground1;
}
else
{
background = RowBackground2;
}
}
GUI.DrawTexture(rowRect, background);
}
}
float GetColumnWidth(int index)
{
if (index == 0)
{
return TotalWidth - (NumColumns - 1) * _settings.NormalColumnWidth;
}
return _settings.NormalColumnWidth;
}
void DrawContent(float width)
{
DrawRowBackgrounds();
var columnPos = 0.0f;
for (int i = 0; i < NumColumns; i++)
{
var columnWidth = GetColumnWidth(i);
DrawColumn(i, columnPos, columnWidth);
columnPos += columnWidth;
}
}
void DrawColumn(
int index, float position, float width)
{
var columnHeight = _settings.HeaderHeight + _pools.Count() * _settings.RowHeight;
if (index < 4)
{
GUI.DrawTexture(new Rect(
position + width - _settings.SplitterWidth * 0.5f, 0,
_settings.SplitterWidth, columnHeight), LineTexture);
}
var columnBounds = new Rect(
position + 0.5f * _settings.SplitterWidth, 0, width - _settings.SplitterWidth, columnHeight);
GUI.BeginGroup(columnBounds);
{
for (int i = 0; i < _pools.Count; i++)
{
var pool = _pools[i];
var cellBounds = new Rect(
0, _settings.RowHeight * i,
columnBounds.width, _settings.RowHeight);
DrawColumnContents(index, cellBounds, pool);
}
}
GUI.EndGroup();
}
void DrawColumnContents(
int index, Rect bounds, IMemoryPool pool)
{
switch (index)
{
case 0:
{
GUI.Label(bounds, GetName(pool), _settings.ContentNameTextStyle);
break;
}
case 1:
{
GUI.Label(bounds, pool.NumTotal.ToString(), _settings.ContentNumberTextStyle);
break;
}
case 2:
{
GUI.Label(bounds, pool.NumActive.ToString(), _settings.ContentNumberTextStyle);
break;
}
case 3:
{
GUI.Label(bounds, pool.NumInactive.ToString(), _settings.ContentNumberTextStyle);
break;
}
case 4:
{
var buttonBounds = new Rect(
bounds.x + _settings.ButtonMargin, bounds.y, bounds.width - _settings.ButtonMargin, bounds.height);
if (GUI.Button(buttonBounds, "Clear"))
{
pool.Clear();
}
break;
}
case 5:
{
var buttonBounds = new Rect(
bounds.x, bounds.y, bounds.width - 15.0f, bounds.height);
if (GUI.Button(buttonBounds, "Expand"))
{
pool.ExpandBy(5);
}
break;
}
default:
{
throw Assert.CreateException();
}
}
}
void DrawColumnHeader(int index, Rect bounds, string text)
{
if (index > 3)
{
return;
}
if (_sortColumn == index)
{
var offset = _settings.TriangleOffset;
var image = _sortDescending ? _settings.TriangleDown : _settings.TriangleUp;
GUI.DrawTexture(new Rect(bounds.x + offset.x, bounds.y + offset.y, image.width, image.height), image);
}
if (GUI.Button(bounds, text, index == 0 ? _settings.HeaderTextStyleName : _settings.HeaderTextStyle))
{
if (_sortColumn == index)
{
_sortDescending = !_sortDescending;
}
else
{
_sortColumn = index;
}
}
}
int ComparePools(IMemoryPool left, IMemoryPool right)
{
if (_sortDescending)
{
var temp = right;
right = left;
left = temp;
}
switch (_sortColumn)
{
case 4:
case 5:
case 0:
{
return GetName(left).CompareTo(GetName(right));
}
case 1:
{
return left.NumTotal.CompareTo(right.NumTotal);
}
case 2:
{
return left.NumActive.CompareTo(right.NumActive);
}
case 3:
{
return left.NumInactive.CompareTo(right.NumInactive);
}
}
throw Assert.CreateException();
}
[Serializable]
public class Settings
{
public Texture2D TriangleUp;
public Texture2D TriangleDown;
public Vector2 TriangleOffset;
public GUIStyle FilterTextStyle;
public GUIStyle HeaderTextStyleName;
public GUIStyle HeaderTextStyle;
public GUIStyle ContentNumberTextStyle;
public GUIStyle ContentNameTextStyle;
public Color RowBackground1;
public Color RowBackground2;
public Color RowBackgroundHighlighted;
public Color RowBackgroundSelected;
public Color LineColor;
public float ScrollSpeed = 1.5f;
public float NormalColumnWidth;
public float HeaderHeight;
public float FilterHeight;
public float FilterInputHeight;
public float FilterWidth;
public float FilterPaddingLeft;
public float FilterPaddingTop = 10;
public float SplitterWidth;
public float RowHeight;
public float ButtonMargin = 3;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xunit;
namespace System.Linq.Tests
{
public class WhereTests : EnumerableTests
{
#region Null arguments
[Fact]
public void Where_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int> source = null;
Func<int, bool> simplePredicate = (value) => true;
Func<int, int, bool> complexPredicate = (value, index) => true;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.Where(simplePredicate));
AssertExtensions.Throws<ArgumentNullException>("source", () => source.Where(complexPredicate));
}
[Fact]
public void Where_PredicateIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int> source = Enumerable.Range(1, 10);
Func<int, bool> simplePredicate = null;
Func<int, int, bool> complexPredicate = null;
AssertExtensions.Throws<ArgumentNullException>("predicate", () => source.Where(simplePredicate));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => source.Where(complexPredicate));
}
#endregion
#region Deferred execution
[Fact]
public void Where_Array_ExecutionIsDeferred()
{
bool funcCalled = false;
Func<bool>[] source = { () => { funcCalled = true; return true; } };
IEnumerable<Func<bool>> query = source.Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void Where_List_ExecutionIsDeferred()
{
bool funcCalled = false;
List<Func<bool>> source = new List<Func<bool>>() { () => { funcCalled = true; return true; } };
IEnumerable<Func<bool>> query = source.Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void Where_IReadOnlyCollection_ExecutionIsDeferred()
{
bool funcCalled = false;
IReadOnlyCollection<Func<bool>> source = new ReadOnlyCollection<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } });
IEnumerable<Func<bool>> query = source.Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void Where_ICollection_ExecutionIsDeferred()
{
bool funcCalled = false;
ICollection<Func<bool>> source = new LinkedList<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } });
IEnumerable<Func<bool>> query = source.Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void Where_IEnumerable_ExecutionIsDeferred()
{
bool funcCalled = false;
IEnumerable<Func<bool>> source = Enumerable.Repeat((Func<bool>)(() => { funcCalled = true; return true; }), 1);
IEnumerable<Func<bool>> query = source.Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void WhereWhere_Array_ExecutionIsDeferred()
{
bool funcCalled = false;
Func<bool>[] source = new Func<bool>[] { () => { funcCalled = true; return true; } };
IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void WhereWhere_List_ExecutionIsDeferred()
{
bool funcCalled = false;
List<Func<bool>> source = new List<Func<bool>>() { () => { funcCalled = true; return true; } };
IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void WhereWhere_IReadOnlyCollection_ExecutionIsDeferred()
{
bool funcCalled = false;
IReadOnlyCollection<Func<bool>> source = new ReadOnlyCollection<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } });
IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void WhereWhere_ICollection_ExecutionIsDeferred()
{
bool funcCalled = false;
ICollection<Func<bool>> source = new LinkedList<Func<bool>>(new List<Func<bool>>() { () => { funcCalled = true; return true; } });
IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
[Fact]
public void WhereWhere_IEnumerable_ExecutionIsDeferred()
{
bool funcCalled = false;
IEnumerable<Func<bool>> source = Enumerable.Repeat((Func<bool>)(() => { funcCalled = true; return true; }), 1);
IEnumerable<Func<bool>> query = source.Where(value => value()).Where(value => value());
Assert.False(funcCalled);
query = source.Where((value, index) => value());
Assert.False(funcCalled);
}
#endregion
#region Expected return value
[Fact]
public void Where_Array_ReturnsExpectedValues_True()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
Func<int, bool> truePredicate = (value) => true;
IEnumerable<int> result = source.Where(truePredicate);
Assert.Equal(source.Length, result.Count());
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source.ElementAt(i), result.ElementAt(i));
}
}
[Fact]
public void Where_Array_ReturnsExpectedValues_False()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
Func<int, bool> falsePredicate = (value) => false;
IEnumerable<int> result = source.Where(falsePredicate);
Assert.Equal(0, result.Count());
}
[Fact]
public void Where_Array_ReturnsExpectedValues_Complex()
{
int[] source = new[] { 2, 1, 3, 5, 4 };
Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); };
IEnumerable<int> result = source.Where(complexPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(1, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void Where_List_ReturnsExpectedValues_True()
{
List<int> source = new List<int> { 1, 2, 3, 4, 5 };
Func<int, bool> truePredicate = (value) => true;
IEnumerable<int> result = source.Where(truePredicate);
Assert.Equal(source.Count, result.Count());
for (int i = 0; i < source.Count; i++)
{
Assert.Equal(source.ElementAt(i), result.ElementAt(i));
}
}
[Fact]
public void Where_List_ReturnsExpectedValues_False()
{
List<int> source = new List<int> { 1, 2, 3, 4, 5 };
Func<int, bool> falsePredicate = (value) => false;
IEnumerable<int> result = source.Where(falsePredicate);
Assert.Equal(0, result.Count());
}
[Fact]
public void Where_List_ReturnsExpectedValues_Complex()
{
List<int> source = new List<int> { 2, 1, 3, 5, 4 };
Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); };
IEnumerable<int> result = source.Where(complexPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(1, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void Where_IReadOnlyCollection_ReturnsExpectedValues_True()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> truePredicate = (value) => true;
IEnumerable<int> result = source.Where(truePredicate);
Assert.Equal(source.Count, result.Count());
for (int i = 0; i < source.Count; i++)
{
Assert.Equal(source.ElementAt(i), result.ElementAt(i));
}
}
[Fact]
public void Where_IReadOnlyCollection_ReturnsExpectedValues_False()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> falsePredicate = (value) => false;
IEnumerable<int> result = source.Where(falsePredicate);
Assert.Equal(0, result.Count());
}
[Fact]
public void Where_IReadOnlyCollection_ReturnsExpectedValues_Complex()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 2, 1, 3, 5, 4 });
Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); };
IEnumerable<int> result = source.Where(complexPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(1, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void Where_ICollection_ReturnsExpectedValues_True()
{
ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> truePredicate = (value) => true;
IEnumerable<int> result = source.Where(truePredicate);
Assert.Equal(source.Count, result.Count());
for (int i = 0; i < source.Count; i++)
{
Assert.Equal(source.ElementAt(i), result.ElementAt(i));
}
}
[Fact]
public void Where_ICollection_ReturnsExpectedValues_False()
{
ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> falsePredicate = (value) => false;
IEnumerable<int> result = source.Where(falsePredicate);
Assert.Equal(0, result.Count());
}
[Fact]
public void Where_ICollection_ReturnsExpectedValues_Complex()
{
ICollection<int> source = new LinkedList<int>(new List<int> { 2, 1, 3, 5, 4 });
Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); };
IEnumerable<int> result = source.Where(complexPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(1, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void Where_IEnumerable_ReturnsExpectedValues_True()
{
IEnumerable<int> source = Enumerable.Range(1, 5);
Func<int, bool> truePredicate = (value) => true;
IEnumerable<int> result = source.Where(truePredicate);
Assert.Equal(source.Count(), result.Count());
for (int i = 0; i < source.Count(); i++)
{
Assert.Equal(source.ElementAt(i), result.ElementAt(i));
}
}
[Fact]
public void Where_IEnumerable_ReturnsExpectedValues_False()
{
IEnumerable<int> source = Enumerable.Range(1, 5);
Func<int, bool> falsePredicate = (value) => false;
IEnumerable<int> result = source.Where(falsePredicate);
Assert.Equal(0, result.Count());
}
[Fact]
public void Where_IEnumerable_ReturnsExpectedValues_Complex()
{
IEnumerable<int> source = new LinkedList<int>(new List<int> { 2, 1, 3, 5, 4 });
Func<int, int, bool> complexPredicate = (value, index) => { return (value == index); };
IEnumerable<int> result = source.Where(complexPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(1, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void Where_EmptyEnumerable_ReturnsNoElements()
{
IEnumerable<int> source = Enumerable.Empty<int>();
bool wasSelectorCalled = false;
IEnumerable<int> result = source.Where(value => { wasSelectorCalled = true; return true; });
Assert.Equal(0, result.Count());
Assert.False(wasSelectorCalled);
}
[Fact]
public void Where_EmptyEnumerable_ReturnsNoElementsWithIndex()
{
Assert.Empty(Enumerable.Empty<int>().Where((e, i) => true));
}
[Fact]
public void Where_Array_CurrentIsDefaultOfTAfterEnumeration()
{
int[] source = new[] { 1 };
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.Equal(default(int), enumerator.Current);
}
[Fact]
public void Where_List_CurrentIsDefaultOfTAfterEnumeration()
{
List<int> source = new List<int>() { 1 };
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.Equal(default(int), enumerator.Current);
}
[Fact]
public void Where_IReadOnlyCollection_CurrentIsDefaultOfTAfterEnumeration()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int>() { 1 });
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.Equal(default(int), enumerator.Current);
}
[Fact]
public void Where_ICollection_CurrentIsDefaultOfTAfterEnumeration()
{
ICollection<int> source = new LinkedList<int>(new List<int>() { 1 });
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.Equal(default(int), enumerator.Current);
}
[Fact]
public void Where_IEnumerable_CurrentIsDefaultOfTAfterEnumeration()
{
IEnumerable<int> source = Enumerable.Repeat(1, 1);
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.Equal(default(int), enumerator.Current);
}
[Fact]
public void WhereWhere_Array_ReturnsExpectedValues()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void WhereWhere_List_ReturnsExpectedValues()
{
List<int> source = new List<int> { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void WhereWhere_IReadOnlyCollection_ReturnsExpectedValues()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void WhereWhere_ICollection_ReturnsExpectedValues()
{
ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void WhereWhere_IEnumerable_ReturnsExpectedValues()
{
IEnumerable<int> source = Enumerable.Range(1, 5);
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
IEnumerable<int> result = source.Where(evenPredicate).Where(evenPredicate);
Assert.Equal(2, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
}
[Fact]
public void WhereSelect_Array_ReturnsExpectedValues()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelectSelect_Array_ReturnsExpectedValues()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelect_List_ReturnsExpectedValues()
{
List<int> source = new List<int> { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelectSelect_List_ReturnsExpectedValues()
{
List<int> source = new List<int> { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelect_IReadOnlyCollection_ReturnsExpectedValues()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelectSelect_IReadOnlyCollection_ReturnsExpectedValues()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelect_ICollection_ReturnsExpectedValues()
{
ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelectSelect_ICollection_ReturnsExpectedValues()
{
ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelect_IEnumerable_ReturnsExpectedValues()
{
IEnumerable<int> source = Enumerable.Range(1, 5);
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void WhereSelectSelect_IEnumerable_ReturnsExpectedValues()
{
IEnumerable<int> source = Enumerable.Range(1, 5);
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Where(evenPredicate).Select(i => i).Select(addSelector);
Assert.Equal(2, result.Count());
Assert.Equal(3, result.ElementAt(0));
Assert.Equal(5, result.ElementAt(1));
}
[Fact]
public void SelectWhere_Array_ReturnsExpectedValues()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate);
Assert.Equal(3, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
Assert.Equal(6, result.ElementAt(2));
}
[Fact]
public void SelectWhere_List_ReturnsExpectedValues()
{
List<int> source = new List<int> { 1, 2, 3, 4, 5 };
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate);
Assert.Equal(3, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
Assert.Equal(6, result.ElementAt(2));
}
[Fact]
public void SelectWhere_IReadOnlyCollection_ReturnsExpectedValues()
{
IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate);
Assert.Equal(3, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
Assert.Equal(6, result.ElementAt(2));
}
[Fact]
public void SelectWhere_ICollection_ReturnsExpectedValues()
{
ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 });
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate);
Assert.Equal(3, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
Assert.Equal(6, result.ElementAt(2));
}
[Fact]
public void SelectWhere_IEnumerable_ReturnsExpectedValues()
{
IEnumerable<int> source = Enumerable.Range(1, 5);
Func<int, bool> evenPredicate = (value) => value % 2 == 0;
Func<int, int> addSelector = (value) => value + 1;
IEnumerable<int> result = source.Select(addSelector).Where(evenPredicate);
Assert.Equal(3, result.Count());
Assert.Equal(2, result.ElementAt(0));
Assert.Equal(4, result.ElementAt(1));
Assert.Equal(6, result.ElementAt(2));
}
#endregion
#region Exceptions
[Fact]
public void Where_PredicateThrowsException()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
Func<int, bool> predicate = value =>
{
if (value == 1)
{
throw new InvalidOperationException();
}
return true;
};
var enumerator = source.Where(predicate).GetEnumerator();
// Ensure the first MoveNext call throws an exception
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
// Ensure Current is set to the default value of type T
int currentValue = enumerator.Current;
Assert.Equal(default(int), currentValue);
// Ensure subsequent MoveNext calls succeed
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
}
[Fact]
public void Where_SourceThrowsOnCurrent()
{
IEnumerable<int> source = new ThrowsOnCurrentEnumerator();
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
// Ensure the first MoveNext call throws an exception
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
// Ensure subsequent MoveNext calls succeed
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
}
[Fact]
public void Where_SourceThrowsOnMoveNext()
{
IEnumerable<int> source = new ThrowsOnMoveNext();
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
// Ensure the first MoveNext call throws an exception
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
// Ensure Current is set to the default value of type T
int currentValue = enumerator.Current;
Assert.Equal(default(int), currentValue);
// Ensure subsequent MoveNext calls succeed
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
}
[Fact]
public void Where_SourceThrowsOnGetEnumerator()
{
IEnumerable<int> source = new ThrowsOnGetEnumerator();
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
// Ensure the first MoveNext call throws an exception
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
// Ensure Current is set to the default value of type T
int currentValue = enumerator.Current;
Assert.Equal(default(int), currentValue);
// Ensure subsequent MoveNext calls succeed
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
}
[Fact]
public void Select_ResetEnumerator_ThrowsException()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
IEnumerator<int> enumerator = source.Where(value => true).GetEnumerator();
// The full .NET Framework throws a NotImplementedException.
// See https://github.com/dotnet/corefx/pull/2959.
if (PlatformDetection.IsFullFramework)
{
Assert.Throws<NotImplementedException>(() => enumerator.Reset());
}
else
{
Assert.Throws<NotSupportedException>(() => enumerator.Reset());
}
}
[Fact]
public void Where_SourceThrowsOnConcurrentModification()
{
List<int> source = new List<int>() { 1, 2, 3, 4, 5 };
Func<int, bool> truePredicate = (value) => true;
var enumerator = source.Where(truePredicate).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
source.Add(6);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
#endregion
[Fact]
public void Where_GetEnumeratorReturnsUniqueInstances()
{
int[] source = new[] { 1, 2, 3, 4, 5 };
var result = source.Where(value => true);
using (var enumerator1 = result.GetEnumerator())
using (var enumerator2 = result.GetEnumerator())
{
Assert.Same(result, enumerator1);
Assert.NotSame(enumerator1, enumerator2);
}
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.Where(IsEven), q.Where(IsEven));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", null, "SoS", String.Empty }
select x;
Assert.Equal(q.Where(string.IsNullOrEmpty), q.Where(string.IsNullOrEmpty));
}
[Fact]
public void SingleElementPredicateFalse()
{
int[] source = { 3 };
Assert.Empty(source.Where(IsEven));
}
[Fact]
public void PredicateFalseForAll()
{
int[] source = { 9, 7, 15, 3, 27 };
Assert.Empty(source.Where(IsEven));
}
[Fact]
public void PredicateTrueFirstOnly()
{
int[] source = { 10, 9, 7, 15, 3, 27 };
Assert.Equal(source.Take(1), source.Where(IsEven));
}
[Fact]
public void PredicateTrueLastOnly()
{
int[] source = { 9, 7, 15, 3, 27, 20 };
Assert.Equal(source.Skip(source.Length - 1), source.Where(IsEven));
}
[Fact]
public void PredicateTrueFirstThirdSixth()
{
int[] source = { 20, 7, 18, 9, 7, 10, 21 };
int[] expected = { 20, 18, 10 };
Assert.Equal(expected, source.Where(IsEven));
}
[Fact]
public void RunOnce()
{
int[] source = { 20, 7, 18, 9, 7, 10, 21 };
int[] expected = { 20, 18, 10 };
Assert.Equal(expected, source.RunOnce().Where(IsEven));
}
[Fact]
public void SourceAllNullsPredicateTrue()
{
int?[] source = { null, null, null, null };
Assert.Equal(source, source.Where(num => true));
}
[Fact]
public void SourceEmptyIndexedPredicate()
{
Assert.Empty(Enumerable.Empty<int>().Where((e, i) => i % 2 == 0));
}
[Fact]
public void SingleElementIndexedPredicateTrue()
{
int[] source = { 2 };
Assert.Equal(source, source.Where((e, i) => e % 2 == 0));
}
[Fact]
public void SingleElementIndexedPredicateFalse()
{
int[] source = { 3 };
Assert.Empty(source.Where((e, i) => e % 2 == 0));
}
[Fact]
public void IndexedPredicateFalseForAll()
{
int[] source = { 9, 7, 15, 3, 27 };
Assert.Empty(source.Where((e, i) => e % 2 == 0));
}
[Fact]
public void IndexedPredicateTrueFirstOnly()
{
int[] source = { 10, 9, 7, 15, 3, 27 };
Assert.Equal(source.Take(1), source.Where((e, i) => e % 2 == 0));
}
[Fact]
public void IndexedPredicateTrueLastOnly()
{
int[] source = { 9, 7, 15, 3, 27, 20 };
Assert.Equal(source.Skip(source.Length - 1), source.Where((e, i) => e % 2 == 0));
}
[Fact]
public void IndexedPredicateTrueFirstThirdSixth()
{
int[] source = { 20, 7, 18, 9, 7, 10, 21 };
int[] expected = { 20, 18, 10 };
Assert.Equal(expected, source.Where((e, i) => e % 2 == 0));
}
[Fact]
public void SourceAllNullsIndexedPredicateTrue()
{
int?[] source = { null, null, null, null };
Assert.Equal(source, source.Where((num, index) => true));
}
[Fact]
public void PredicateSelectsFirst()
{
int[] source = { -40, 20, 100, 5, 4, 9 };
Assert.Equal(source.Take(1), source.Where((e, i) => i == 0));
}
[Fact]
public void PredicateSelectsLast()
{
int[] source = { -40, 20, 100, 5, 4, 9 };
Assert.Equal(source.Skip(source.Length - 1), source.Where((e, i) => i == source.Length - 1));
}
[Fact(Skip = "Valid test but too intensive to enable even in OuterLoop")]
public void IndexOverflows()
{
var infiniteWhere = new FastInfiniteEnumerator<int>().Where((e, i) => true);
using (var en = infiniteWhere.GetEnumerator())
Assert.Throws<OverflowException>(() =>
{
while (en.MoveNext())
{
}
});
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Where(i => true);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateArray()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToArray().Where(i => true);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateList()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Where(i => true);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateIndexed()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Where((e, i) => true);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateWhereSelect()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Where(i => true).Select(i => i);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateWhereSelectArray()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToArray().Where(i => true).Select(i => i);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateWhereSelectList()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Where(i => true).Select(i => i);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Theory]
[MemberData(nameof(ToCollectionData))]
public void ToCollection(IEnumerable<int> source)
{
foreach (IEnumerable<int> equivalent in new[] { source.Where(s => true), source.Where(s => true).Select(s => s) })
{
Assert.Equal(source, equivalent);
Assert.Equal(source, equivalent.ToArray());
Assert.Equal(source, equivalent.ToList());
Assert.Equal(source.Count(), equivalent.Count()); // Count may be optimized. The above asserts do not imply this will pass.
using (IEnumerator<int> en = equivalent.GetEnumerator())
{
for (int i = 0; i < equivalent.Count(); i++)
{
Assert.True(en.MoveNext());
}
Assert.False(en.MoveNext()); // No more items, this should dispose.
Assert.Equal(0, en.Current); // Reset to default value
Assert.False(en.MoveNext()); // Want to be sure MoveNext after disposing still works.
Assert.Equal(0, en.Current);
}
}
}
public static IEnumerable<object[]> ToCollectionData()
{
IEnumerable<int> seq = GenerateRandomSequnce(seed: 0xdeadbeef, count: 10);
foreach (IEnumerable<int> seq2 in IdentityTransforms<int>().Select(t => t(seq)))
{
yield return new object[] { seq2 };
}
}
private static IEnumerable<int> GenerateRandomSequnce(uint seed, int count)
{
var random = new Random(unchecked((int)seed));
for (int i = 0; i < count; i++)
{
yield return random.Next(int.MinValue, int.MaxValue);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace OpenMetaverse.TestClient
{
public class LoginDetails
{
public string FirstName;
public string LastName;
public string Password;
public string StartLocation;
public bool GroupCommands;
public string MasterName;
public UUID MasterKey;
public string URI;
}
public class StartPosition
{
public string sim;
public int x;
public int y;
public int z;
public StartPosition()
{
this.sim = null;
this.x = 0;
this.y = 0;
this.z = 0;
}
}
// WOW WHAT A HACK!
public static class ClientManagerRef
{
public static ClientManager ClientManager;
}
public class ClientManager
{
public Dictionary<UUID, TestClient> Clients = new Dictionary<UUID, TestClient>();
public Dictionary<Simulator, Dictionary<uint, Primitive>> SimPrims = new Dictionary<Simulator, Dictionary<uint, Primitive>>();
public bool Running = true;
public bool GetTextures = false;
string version = "1.0.0";
/// <summary>
///
/// </summary>
/// <param name="accounts"></param>
public ClientManager(List<LoginDetails> accounts, bool getTextures)
{
ClientManagerRef.ClientManager = this;
GetTextures = getTextures;
foreach (LoginDetails account in accounts)
Login(account);
}
/// <summary>
///
/// </summary>
/// <param name="account"></param>
/// <returns></returns>
public TestClient Login(LoginDetails account)
{
// Check if this client is already logged in
foreach (TestClient c in Clients.Values)
{
if (c.Self.FirstName == account.FirstName && c.Self.LastName == account.LastName)
{
Logout(c);
break;
}
}
TestClient client = new TestClient(this);
// Optimize the throttle
client.Throttle.Wind = 0;
client.Throttle.Cloud = 0;
client.Throttle.Land = 1000000;
client.Throttle.Task = 1000000;
client.GroupCommands = account.GroupCommands;
client.MasterName = account.MasterName;
client.MasterKey = account.MasterKey;
client.AllowObjectMaster = client.MasterKey != UUID.Zero; // Require UUID for object master.
LoginParams loginParams = client.Network.DefaultLoginParams(
account.FirstName, account.LastName, account.Password, "TestClient", version);
if (!String.IsNullOrEmpty(account.StartLocation))
loginParams.Start = account.StartLocation;
if (!String.IsNullOrEmpty(account.URI))
loginParams.URI = account.URI;
if (client.Network.Login(loginParams))
{
Clients[client.Self.AgentID] = client;
if (client.MasterKey == UUID.Zero)
{
UUID query = UUID.Random();
DirectoryManager.DirPeopleReplyCallback peopleDirCallback =
delegate(UUID queryID, List<DirectoryManager.AgentSearchData> matchedPeople)
{
if (queryID == query)
{
if (matchedPeople.Count != 1)
{
Logger.Log("Unable to resolve master key from " + client.MasterName, Helpers.LogLevel.Warning);
}
else
{
client.MasterKey = matchedPeople[0].AgentID;
Logger.Log("Master key resolved to " + client.MasterKey, Helpers.LogLevel.Info);
}
}
};
client.Directory.OnDirPeopleReply += peopleDirCallback;
client.Directory.StartPeopleSearch(DirectoryManager.DirFindFlags.People, client.MasterName, 0, query);
}
Logger.Log("Logged in " + client.ToString(), Helpers.LogLevel.Info);
}
else
{
Logger.Log("Failed to login " + account.FirstName + " " + account.LastName + ": " +
client.Network.LoginMessage, Helpers.LogLevel.Warning);
}
return client;
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public TestClient Login(string[] args)
{
LoginDetails account = new LoginDetails();
account.FirstName = args[0];
account.LastName = args[1];
account.Password = args[2];
if (args.Length > 3)
account.StartLocation = NetworkManager.StartLocation(args[3], 128, 128, 40);
if (args.Length > 4)
account.URI = args[4];
return Login(account);
}
/// <summary>
///
/// </summary>
public void Run()
{
Console.WriteLine("Type quit to exit. Type help for a command list.");
while (Running)
{
PrintPrompt();
string input = Console.ReadLine();
DoCommandAll(input, UUID.Zero);
}
foreach (GridClient client in Clients.Values)
{
if (client.Network.Connected)
client.Network.Logout();
}
}
private void PrintPrompt()
{
int online = 0;
foreach (GridClient client in Clients.Values)
{
if (client.Network.Connected) online++;
}
Console.Write(online + " avatars online> ");
}
/// <summary>
///
/// </summary>
/// <param name="cmd"></param>
/// <param name="fromAgentID"></param>
/// <param name="imSessionID"></param>
public void DoCommandAll(string cmd, UUID fromAgentID)
{
string[] tokens = cmd.Trim().Split(new char[] { ' ', '\t' });
if (tokens.Length == 0)
return;
string firstToken = tokens[0].ToLower();
if (String.IsNullOrEmpty(firstToken))
return;
string[] args = new string[tokens.Length - 1];
if (args.Length > 0)
Array.Copy(tokens, 1, args, 0, args.Length);
if (firstToken == "login")
{
Login(args);
}
else if (firstToken == "quit")
{
Quit();
Logger.Log("All clients logged out and program finished running.", Helpers.LogLevel.Info);
}
else if (firstToken == "help")
{
if (Clients.Count > 0)
{
foreach (TestClient client in Clients.Values)
{
Console.WriteLine(client.Commands["help"].Execute(args, UUID.Zero));
break;
}
}
else
{
Console.WriteLine("You must login at least one bot to use the help command");
}
}
else if (firstToken == "script")
{
// No reason to pass this to all bots, and we also want to allow it when there are no bots
ScriptCommand command = new ScriptCommand(null);
Logger.Log(command.Execute(args, UUID.Zero), Helpers.LogLevel.Info);
}
else
{
// Make an immutable copy of the Clients dictionary to safely iterate over
Dictionary<UUID, TestClient> clientsCopy = new Dictionary<UUID, TestClient>(Clients);
int completed = 0;
foreach (TestClient client in clientsCopy.Values)
{
ThreadPool.QueueUserWorkItem((WaitCallback)
delegate(object state)
{
TestClient testClient = (TestClient)state;
if (testClient.Commands.ContainsKey(firstToken))
Logger.Log(testClient.Commands[firstToken].Execute(args, fromAgentID),
Helpers.LogLevel.Info, testClient);
else
Logger.Log("Unknown command " + firstToken, Helpers.LogLevel.Warning);
++completed;
},
client);
}
while (completed < clientsCopy.Count)
Thread.Sleep(50);
}
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public void Logout(TestClient client)
{
Clients.Remove(client.Self.AgentID);
client.Network.Logout();
}
/// <summary>
///
/// </summary>
public void Quit()
{
Running = false;
// TODO: It would be really nice if we could figure out a way to abort the ReadLine here in so that Run() will exit.
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using NodeContent = Microsoft.Xna.Framework.Content.Pipeline.Graphics.NodeContent;
using ModelContent = Microsoft.Xna.Framework.Content.Pipeline.Processors.ModelContent;
using KiloWatt.Animation.Animation;
using System.Diagnostics;
// The problem is this:
// The indices in the mesh are based on the flattened skeleton hierarchy.
// This skeleton hierarchy excludes certain elements of the "bones" array
// of the model.
// Thus, a different index list is used for the skin palette, than for all
// the hierarchically animated data.
namespace AnimationProcessor
{
/// <summary>
/// This model processor includes all the fixes from the Dxt5ModelProcessor, as well
/// as adds support for baking animations into the Tag dictionary.
/// </summary>
[ContentProcessor(DisplayName = "Animation Processor - KiloWatt")]
public class AnimationProcessor : LevelProcessor.Dxt5ModelProcessor
{
public override ModelContent Process(NodeContent input, ContentProcessorContext context)
{
CompileRegularExpressions();
context.Logger.LogMessage("Output Platform: {0}", context.TargetPlatform);
maxScale_ = 0;
maxOffset_ = 0;
BoneContent skeleton = MeshHelper.FindSkeleton(input);
FlattenTransforms(input, skeleton, context);
SkinnedBone[] inverseBindPose = GetInverseBindPose(input, context, skeleton);
context.Logger.LogMessage("Found {0} skinned bones in skeleton.", (inverseBindPose == null) ? 0 : inverseBindPose.Length);
ModelContent output = base.Process(input, context);
if (output.Tag == null)
output.Tag = new Dictionary<string, object>();
if (FoundSkinning)
{
#if DEBUG
StringBuilder strb = new StringBuilder();
#endif
if (inverseBindPose == null)
throw new System.Exception("Could not find skeleton although there is skinned data.");
for (int i = 0; i != inverseBindPose.Length; ++i)
{
SkinnedBone sb = inverseBindPose[i];
int q = 0;
sb.Index = -1;
foreach (ModelBoneContent mbc in output.Bones)
{
if (mbc.Name == sb.Name)
{
sb.Index = mbc.Index;
break;
}
++q;
}
if (sb.Index == -1)
throw new System.ArgumentException(
String.Format("Can't find the index for animated bone named {0}.", sb.Name));
inverseBindPose[i] = sb;
}
((Dictionary<string, object>)output.Tag).Add("InverseBindPose", inverseBindPose);
}
((Dictionary<string, object>)output.Tag).Add("AnimationSet",
BuildAnimationSet(input, ref output, context));
((Dictionary<string, object>)output.Tag).Add("BoundsInfo",
new BoundsInfo(maxScale_, maxOffset_));
return output;
}
float maxScale_;
float maxOffset_;
protected virtual void CompileRegularExpressions()
{
excludeAnimationsExpressions_ = MakeExclusion(excludeAnimations_);
excludeBonesExpressions_ = MakeExclusion(excludeBones_);
trimAnimationExpressions_ = MakeExclusion(trimAnimations_);
}
Regex[] MakeExclusion(string str)
{
if (String.IsNullOrEmpty(str))
return null;
string[] exprs = str.Split(';');
Regex[] ret = new Regex[exprs.Length];
for (int i = 0; i != exprs.Length; ++i)
{
ret[i] = new Regex(exprs[i], RegexOptions.IgnoreCase);
}
return ret;
}
protected virtual void FlattenTransforms(NodeContent node, NodeContent stopper, ContentProcessorContext context)
{
if (node == stopper)
{
BakeTransformsToTop(node.Parent);
return;
}
MeshContent mc = node as MeshContent;
if (mc != null)
{
foreach (GeometryContent gc in mc.Geometry)
{
if (VerticesAreSkinned(gc.Vertices, context))
{
BakeTransformsToTop(node);
break;
}
}
}
foreach (NodeContent child in node.Children)
FlattenTransforms(child, stopper, context);
}
// If there are articulating bones above the skinned mesh or skeleton in the mesh,
// those will be flattened. Put them further down in the hierarchy if you care.
protected virtual void BakeTransformsToTop(NodeContent node)
{
while (node != null)
{
if (!node.Transform.Equals(Matrix.Identity))
{
MeshHelper.TransformScene(node, node.Transform);
node.Transform = Matrix.Identity;
// because I baked this node, I can't animate it!
node.Animations.Clear();
}
node = node.Parent;
}
}
protected virtual SkinnedBone[] GetInverseBindPose(NodeContent input, ContentProcessorContext context, BoneContent skeleton)
{
if (skeleton == null)
return null;
IList<BoneContent> original = MeshHelper.FlattenSkeleton(skeleton);
if (original.Count > maxNumBones_)
throw new System.ArgumentException(String.Format(
"The animation processor found {0} bones in the skeleton; a maximum of {1} is allowed.",
original.Count, maxNumBones_));
List<SkinnedBone> inversePose = new List<SkinnedBone>();
foreach (BoneContent bc in original)
{
SkinnedBone sb = new SkinnedBone();
sb.Name = bc.Name;
if (sb.Name == null)
throw new System.ArgumentNullException("Bone with null name found.");
sb.InverseBindTransform = Matrix.Invert(GetAbsoluteTransform(bc, null));
inversePose.Add(sb);
}
return inversePose.ToArray();
}
protected int nBonesGenerated_;
protected Dictionary<ModelBoneContent, string> boneNames_ = new Dictionary<ModelBoneContent, string>();
protected virtual string GetBoneName(ModelBoneContent mbc)
{
if (mbc.Name != null)
return mbc.Name;
string ret;
if (!boneNames_.TryGetValue(mbc, out ret))
{
ret = String.Format("_GenBone{0}", ++nBonesGenerated_);
boneNames_.Add(mbc, ret);
}
return ret;
}
/// <summary>
/// The workhorse of the animation processor. It loops through all
/// animations, all tracks, and all keyframes, and converts to the format
/// expected by the runtime animation classes.
/// </summary>
/// <param name="input">The NodeContent to process. Comes from the base ModelProcessor.</param>
/// <param name="output">The ModelContent that was produced. You don't typically change this.</param>
/// <param name="context">The build context (logger, etc).</param>
/// <returns>An allocated AnimationSet with the animations to include.</returns>
public virtual AnimationSet BuildAnimationSet(NodeContent input, ref ModelContent output,
ContentProcessorContext context)
{
AnimationSet ret = new AnimationSet();
if (!DoAnimations)
{
context.Logger.LogImportantMessage("DoAnimation is set to false for {0}; not generating animations.", input.Name);
return ret;
}
// go from name to index
Dictionary<string, ModelBoneContent> nameToIndex = new Dictionary<string, ModelBoneContent>();
foreach (ModelBoneContent mbc in output.Bones)
nameToIndex.Add(GetBoneName(mbc), mbc);
AnimationContentDictionary adict = MergeAnimatedBones(input);
if (adict == null || adict.Count == 0)
{
context.Logger.LogWarning("http://kwxport.sourceforge.net/", input.Identity,
"Model processed with AnimationProcessor has no animations.");
return ret;
}
foreach (AnimationContent ac in adict.Values)
{
if (!IncludeAnimation(ac))
{
context.Logger.LogImportantMessage(String.Format("Not including animation named {0}.", ac.Name));
continue;
}
context.Logger.LogImportantMessage(
"Processing animation {0} duration {1} sample rate {2} reduction tolerance {3}.",
ac.Name, ac.Duration, SampleRate, Tolerance);
AnimationChannelDictionary acdict = ac.Channels;
AnimationTrackDictionary tracks = new AnimationTrackDictionary();
TimeSpan longestUniqueDuration = new TimeSpan(0);
foreach (string name in acdict.Keys)
{
if (!IncludeTrack(name))
{
context.Logger.LogImportantMessage(String.Format("Not including track named {0}.", name));
continue;
}
int ix = 0;
AnimationChannel achan = acdict[name];
int bix = nameToIndex[name].Index;
context.Logger.LogMessage("Processing bone {0}:{1}.", name, bix);
AnimationTrack at;
if (tracks.TryGetValue(bix, out at))
{
throw new System.ArgumentException(
String.Format("Bone index {0} is used by multiple animations in the same clip (name {1}).",
bix, name));
}
// Sample at given frame rate from 0 .. Duration
List<Keyframe> kfl = new List<Keyframe>();
int nFrames = (int)Math.Floor(ac.Duration.TotalSeconds * SampleRate + 0.5);
for (int i = 0; i < nFrames; ++i)
{
Keyframe k = SampleChannel(achan, i / SampleRate, ref ix);
kfl.Add(k);
}
// Run keyframe elimitation
Keyframe[] frames = kfl.ToArray();
int nReduced = 0;
if (tolerance_ > 0)
nReduced = ReduceKeyframes(frames, tolerance_);
if (nReduced > 0)
context.Logger.LogMessage("Reduced '{2}' from {0} to {1} frames.",
frames.Length, frames.Length - nReduced, name);
// Create an AnimationTrack
at = new AnimationTrack(bix, frames);
Debug.Assert(name != null);
at.Name = name;
tracks.Add(bix, at);
}
if (ShouldTrimAnimation(ac))
{
TrimAnimationTracks(ac.Name, tracks, context);
}
Animation a = new Animation(ac.Name, tracks, SampleRate);
ret.AddAnimation(a);
}
// build the special "identity" and "bind pose" animations
AnimationTrackDictionary atd_id = new AnimationTrackDictionary();
AnimationTrackDictionary atd_bind = new AnimationTrackDictionary();
foreach (KeyValuePair<string, ModelBoneContent> nip in nameToIndex)
{
if (!IncludeTrack(nip.Key))
continue;
Keyframe[] frames_id = new Keyframe[2];
frames_id[0] = new Keyframe();
frames_id[1] = new Keyframe();
AnimationTrack at_id = new AnimationTrack(nip.Value.Index, frames_id);
at_id.Name = nip.Key;
atd_id.Add(nip.Value.Index, at_id);
Keyframe[] frames_bind = new Keyframe[2];
Matrix mat = nip.Value.Transform;
frames_bind[0] = Keyframe.CreateFromMatrix(mat);
frames_bind[1] = new Keyframe();
frames_bind[1].CopyFrom(frames_bind[0]);
AnimationTrack at_bind = new AnimationTrack(nip.Value.Index, frames_bind);
at_bind.Name = nip.Key;
atd_bind.Add(nip.Value.Index, at_bind);
}
ret.AddAnimation(new Animation("$id$", atd_id, 1.0f));
ret.AddAnimation(new Animation("$bind$", atd_bind, 1.0f));
return ret;
}
/// <summary>
/// Given the animation tracks in the dictionary (for an animation with the given
/// name), figure out what the latest frame is that contains unique data for any
/// track, and trim the animation from the end to that length.
/// </summary>
/// <param name="name">name of the animation to trim</param>
/// <param name="tracks">the tracks of the animation to trim</param>
/// <param name="context">for logging etc</param>
protected virtual void TrimAnimationTracks(string name, AnimationTrackDictionary tracks,
ContentProcessorContext context)
{
int latestUnique = 1;
int latestFrame = 0;
foreach (AnimationTrack at in tracks.Values)
{
Keyframe last = at.Keyframes[0];
int latestCurrent = 0;
int index = 0;
if (at.NumFrames > latestFrame)
{
latestFrame = at.NumFrames;
}
foreach (Keyframe kf in at.Keyframes)
{
if (kf != null && last.DifferenceFrom(kf) >= tolerance_)
{
latestCurrent = index;
last = kf;
}
++index;
}
if (latestCurrent > latestUnique)
{
latestUnique = latestCurrent;
}
}
if (latestUnique + 1 < latestFrame)
{
context.Logger.LogMessage("Trimming animation {0} from {1} to {2} frames.",
name, latestFrame, latestUnique + 1);
foreach (AnimationTrack at in tracks.Values)
{
at.ChopToLength(latestUnique + 1);
}
}
}
protected static Matrix GetAbsoluteTransform(NodeContent mbc, NodeContent relativeTo)
{
Matrix mat = Matrix.Identity;
// avoid recursion
while (mbc != null && mbc != relativeTo)
{
mat = mat * mbc.Transform;
mbc = mbc.Parent;
}
return mat;
}
protected virtual AnimationContentDictionary MergeAnimatedBones(NodeContent root)
{
AnimationContentDictionary ret = new AnimationContentDictionary();
CollectAnimatedBones(ret, root);
return ret;
}
protected virtual void CollectAnimatedBones(AnimationContentDictionary dict, NodeContent bone)
{
AnimationContentDictionary acd = bone.Animations;
if (acd != null)
{
foreach (string name in acd.Keys)
{
// merge each animation into the dictionary
AnimationContent ac = acd[name];
AnimationContent xac;
if (!dict.TryGetValue(name, out xac))
{
// create it if we haven't already seen it, and there's something there
if (ac.Channels.Count > 0)
{
xac = ac;
dict.Add(name, xac);
}
}
else
{
// merge the animation content
foreach (KeyValuePair<string, AnimationChannel> kvp in ac.Channels)
{
AnimationChannel ov;
if (xac.Channels.TryGetValue(kvp.Key, out ov))
{
throw new System.ArgumentException(
String.Format("The animation {0} has multiple channels named {1}.",
name, kvp.Key));
}
xac.Channels.Add(kvp.Key, kvp.Value);
}
xac.Duration = new TimeSpan((long)
(Math.Max(xac.Duration.TotalSeconds, ac.Duration.TotalSeconds) * 1e7));
}
}
}
foreach (NodeContent nc in bone.Children)
CollectAnimatedBones(dict, nc);
}
/// <summary>
/// Return true if you want to trim the given animation, removing identical frames
/// from the end. This is necessay for short animations imported through the .X
/// importer, which somehow manages to add blank padding to the duration.
/// </summary>
/// <param name="ac">The animation to test against the list of animation name patterns</param>
/// <returns></returns>
protected virtual bool ShouldTrimAnimation(AnimationContent ac)
{
if (trimAnimationExpressions_ != null)
foreach (Regex re in trimAnimationExpressions_)
if (re.IsMatch(ac.Name))
return true;
return false;
}
/// <summary>
/// Return true if you want to include the specific animation in the output animation set.
/// </summary>
/// <param name="ac">The animation to check.</param>
/// <returns>true unless the animation name is in a semicolon-separated list called ExcludeAnimations</returns>
protected virtual bool IncludeAnimation(AnimationContent ac)
{
if (excludeAnimationsExpressions_ != null)
foreach (Regex re in excludeAnimationsExpressions_)
if (re.IsMatch(ac.Name))
return false;
return true;
}
/// <summary>
/// Return true if you want to include the specific track (bone) in the output animation set.
/// </summary>
/// <param name="ac">The animation to check.</param>
/// <returns>true unless the bone name is in a semicolon-separated list called ExcludeBones</returns>
protected virtual bool IncludeTrack(string name)
{
if (excludeBonesExpressions_ != null)
foreach (Regex re in excludeBonesExpressions_)
if (re.IsMatch(name))
return false;
return true;
}
[DefaultValue("")]
[Description("List of regex for animation names to filter out (; separates)")]
public string ExcludeAnimations { get { return excludeAnimations_; } set { excludeAnimations_ = value; } }
string excludeAnimations_ = "";
Regex[] excludeAnimationsExpressions_;
[DefaultValue("")]
[Description("List of regex for animation bones to filter out (; separates)")]
public string ExcludeBones { get { return excludeBones_; } set { excludeBones_ = value; } }
string excludeBones_ = "";
Regex[] excludeBonesExpressions_;
[DefaultValue("")]
[Description("List of regex for animation animations to trim static frames from the end of (; separates)")]
public string TrimAnimations { get { return trimAnimations_; } set { trimAnimations_ = value; } }
string trimAnimations_ = "";
Regex[] trimAnimationExpressions_;
/// <summary>
/// SampleChannel will be called to sample the transformation of a given channel
/// at a given Clock. The given index parameter is for use by the sample function,
/// to avoid having to look for the "base" frame each call. It will start out as
/// zero in the first call for a given channel. "Clock" will be monotonically
/// increasing for a given channel.
/// </summary>
/// <param name="achan">The channel to sample from.</param>
/// <param name="Clock">The Clock to sample at (monotonically increasing).</param>
/// <param name="ix">For use by SampleChannel (starts at 0 for each new channel).</param>
/// <returns>The sampled keyframe output (allocated by this function).</returns>
protected virtual Keyframe SampleChannel(AnimationChannel achan, float time, ref int ix)
{
Keyframe ret = new Keyframe();
AnimationKeyframe akf0 = achan[ix];
float scale = CalcTransformScale(akf0.Transform);
//todo: really should be done in world space, but I'm giving up now
float offset = akf0.Transform.Translation.Length();
if (scale > maxScale_)
maxScale_ = scale;
if (offset > maxOffset_)
maxOffset_ = offset;
again:
if (ix == achan.Count - 1)
return KeyframeFromMatrix(akf0.Transform, ret);
AnimationKeyframe akf1 = achan[ix+1];
if (akf1.Time.TotalSeconds <= time)
{
akf0 = akf1;
++ix;
goto again;
}
KeyframeFromMatrix(akf0.Transform, tmpA_);
KeyframeFromMatrix(akf1.Transform, tmpB_);
Keyframe.Interpolate(tmpA_, tmpB_,
(float)((time - akf0.Time.TotalSeconds) / (akf1.Time.TotalSeconds - akf0.Time.TotalSeconds)),
ret);
return ret;
}
protected virtual float CalcTransformScale(Matrix mat)
{
return (float)Math.Pow(
mat.Right.Length() *
mat.Up.Length() *
mat.Backward.Length(),
1.0 / 3);
}
protected Keyframe tmpA_ = new Keyframe();
protected Keyframe tmpB_ = new Keyframe();
/// <summary>
/// Decompose the given matrix into a scale/rotation/translation
/// keyframe.
/// </summary>
/// <param name="xform">The transform to decompose.</param>
/// <param name="ret">The keyframe to decompose into.</param>
/// <returns>ret (for convenience)</returns>
protected Keyframe KeyframeFromMatrix(Matrix xform, Keyframe ret)
{
return Keyframe.CreateFromMatrix(ref xform, ret);
}
protected virtual int ReduceKeyframes(Keyframe[] frames, float tolerance)
{
#if DEBUG
if (frames == null)
throw new ArgumentNullException("frames");
#endif
int nReduced = 0;
Keyframe lerp = new Keyframe();
int nFrames = frames.Length;
int prevFrame = 0;
Keyframe prevData = frames[0];
for (int curFrame = 1; curFrame < nFrames-1; ++curFrame)
{
Keyframe curData = frames[curFrame];
int nextFrame = curFrame+1;
Keyframe nextData = frames[nextFrame];
Keyframe.Interpolate(prevData, nextData,
(float)(curFrame - prevFrame)/(float)(nextFrame - prevFrame),
lerp);
if (lerp.DifferenceFrom(curData) < tolerance)
{
frames[curFrame] = null;
++nReduced;
}
else
{
prevFrame = curFrame;
prevData = curData;
}
}
return nReduced;
}
bool doAnimations_ = true;
[DefaultValue(true)]
public bool DoAnimations { get { return doAnimations_; } set { doAnimations_ = value; } }
float sampleRate_ = 30.0f;
[DefaultValue(30.0f)]
public float SampleRate { get { return sampleRate_; } set { sampleRate_ = value; } }
float tolerance_ = 0.001f;
[DefaultValue(0.001f)]
public float Tolerance { get { return tolerance_; } set { tolerance_ = value; } }
int maxNumBones_ = 72;
[DefaultValue(72)]
public int MaxNumBones { get { return maxNumBones_; } set { maxNumBones_ = value; } }
}
}
| |
//
// GeneralEncapsulatedObjectFrame.cs:
//
// Author:
// Brian Nickel (brian.nickel@gmail.com)
//
// Original Source:
// generalencapsulatedobjectframe.cpp from TagLib
//
// Copyright (C) 2007 Brian Nickel
// Copyright (C) 2007 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.Collections;
using System;
namespace TagLib.Id3v2 {
/// <summary>
/// This class extends <see cref="Frame" />, implementing support for
/// ID3v2 General Encapsulated Object (GEOB) Frames.
/// </summary>
/// <remarks>
/// <para>A <see cref="GeneralEncapsulatedObjectFrame" /> should be
/// used for storing files and other objects relevant to the file but
/// not supported by other frames.</para>
/// </remarks>
public class GeneralEncapsulatedObjectFrame : Frame
{
#region Private Fields
/// <summary>
/// Contains the text encoding to use when rendering the
/// current instance.
/// </summary>
private StringType encoding = Tag.DefaultEncoding;
/// <summary>
/// Contains the mime type of <see cref="data" />.
/// </summary>
private string mime_type = null;
/// <summary>
/// Contains the original file name.
/// </summary>
string file_name = null;
/// <summary>
/// Contains the description.
/// </summary>
private string description = null;
/// <summary>
/// Contains the data.
/// </summary>
private ByteVector data = null;
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="GeneralEncapsulatedObjectFrame" /> with no
/// contents.
/// </summary>
public GeneralEncapsulatedObjectFrame ()
: base (FrameType.GEOB, 4)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="GeneralEncapsulatedObjectFrame" /> by reading its
/// raw data in a specified ID3v2 version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object starting with the raw
/// representation of the new frame.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// raw frame is encoded in.
/// </param>
public GeneralEncapsulatedObjectFrame (ByteVector data,
byte version)
: base (data, version)
{
SetData (data, 0, version, true);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="GeneralEncapsulatedObjectFrame" /> by reading its
/// raw data in a specified ID3v2 version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the raw
/// representation of the new frame.
/// </param>
/// <param name="offset">
/// A <see cref="int" /> indicating at what offset in
/// <paramref name="data" /> the frame actually begins.
/// </param>
/// <param name="header">
/// A <see cref="FrameHeader" /> containing the header of the
/// frame found at <paramref name="offset" /> in the data.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// raw frame is encoded in.
/// </param>
protected internal GeneralEncapsulatedObjectFrame (ByteVector data,
int offset,
FrameHeader header,
byte version)
: base(header)
{
SetData (data, offset, version, false);
}
#endregion
#region Public Properties
/// <summary>
/// Gets and sets the text encoding to use when storing the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the text encoding to
/// use when storing the current instance.
/// </value>
/// <remarks>
/// This encoding is overridden when rendering if <see
/// cref="Tag.ForceDefaultEncoding" /> is <see
/// langword="true" /> or the render version does not support
/// it.
/// </remarks>
public StringType TextEncoding {
get {return encoding;}
set {encoding = value;}
}
/// <summary>
/// Gets and sets the mime-type of the object stored in the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the mime-type of the
/// object stored in the current instance.
/// </value>
public string MimeType {
get {
if (mime_type != null)
return mime_type;
return string.Empty;
}
set {mime_type = value;}
}
/// <summary>
/// Gets and sets the file name of the object stored in the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the file name of the
/// object stored in the current instance.
/// </value>
public string FileName {
get {
if (file_name != null)
return file_name;
return string.Empty;
}
set {file_name = value;}
}
/// <summary>
/// Gets and sets the description stored in the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the description
/// stored in the current instance.
/// </value>
/// <remarks>
/// There should only be one frame with a matching
/// description and type per tag.
/// </remarks>
public string Description {
get {
if (description != null)
return description;
return string.Empty;
}
set {description = value;}
}
/// <summary>
/// Gets and sets the object data stored in the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="ByteVector" /> containing the object data
/// stored in the current instance.
/// </value>
public ByteVector Object {
get {return data != null ? data : new ByteVector ();}
set {data = value;}
}
#endregion
#region Public Methods
/// <summary>
/// Creates a text description of the current instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> object containing a description
/// of the current instance.
/// </returns>
public override string ToString ()
{
System.Text.StringBuilder builder
= new System.Text.StringBuilder ();
if (Description.Length == 0) {
builder.Append (Description);
builder.Append (" ");
}
builder.AppendFormat (
System.Globalization.CultureInfo.InvariantCulture,
"[{0}] {1} bytes", MimeType, Object.Count);
return builder.ToString ();
}
#endregion
#region Public Static Methods
/// <summary>
/// Gets a specified encapsulated object frame from the
/// specified tag, optionally creating it if it does not
/// exist.
/// </summary>
/// <param name="tag">
/// A <see cref="Tag" /> object to search in.
/// </param>
/// <param name="description">
/// A <see cref="string" /> specifying the description to
/// match.
/// </param>
/// <param name="create">
/// A <see cref="bool" /> specifying whether or not to create
/// and add a new frame to the tag if a match is not found.
/// </param>
/// <returns>
/// A <see cref="GeneralEncapsulatedObjectFrame" /> object
/// containing the matching frame, or <see langword="null" />
/// if a match wasn't found and <paramref name="create" /> is
/// <see langword="false" />.
/// </returns>
public static GeneralEncapsulatedObjectFrame Get (Tag tag,
string description,
bool create)
{
GeneralEncapsulatedObjectFrame geob;
foreach (Frame frame in tag.GetFrames (FrameType.GEOB)) {
geob = frame as GeneralEncapsulatedObjectFrame;
if (geob == null)
continue;
if (geob.Description != description)
continue;
return geob;
}
if (!create)
return null;
geob = new GeneralEncapsulatedObjectFrame ();
geob.Description = description;
tag.AddFrame (geob);
return geob;
}
#endregion
#region Protected Methods
/// <summary>
/// Populates the values in the current instance by parsing
/// its field data in a specified version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the
/// extracted field data.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// field data is encoded in.
/// </param>
/// <exception cref="CorruptFileException">
/// <paramref name="data" /> contains less than 5 bytes.
/// </exception>
protected override void ParseFields (ByteVector data,
byte version)
{
if (data.Count < 4)
throw new CorruptFileException (
"An object frame must contain at least 4 bytes.");
int start = 0;
encoding = (StringType) data [start++];
int end = data.Find (
ByteVector.TextDelimiter (StringType.Latin1),
start);
if (end < start)
return;
mime_type = data.ToString (StringType.Latin1, start,
end - start);
ByteVector delim = ByteVector.TextDelimiter (
encoding);
start = end + 1;
end = data.Find (delim, start, delim.Count);
if (end < start)
return;
file_name = data.ToString (encoding, start,
end - start);
start = end + delim.Count;
end = data.Find (delim, start, delim.Count);
if (end < start)
return;
description = data.ToString (encoding, start,
end - start);
start = end + delim.Count;
data.RemoveRange (0, start);
this.data = data;
}
/// <summary>
/// Renders the values in the current instance into field
/// data for a specified version.
/// </summary>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// field data is to be encoded in.
/// </param>
/// <returns>
/// A <see cref="ByteVector" /> object containing the
/// rendered field data.
/// </returns>
protected override ByteVector RenderFields (byte version)
{
StringType encoding = CorrectEncoding (this.encoding,
version);
ByteVector v = new ByteVector ();
v.Add ((byte) encoding);
if (MimeType != null)
v.Add (ByteVector.FromString (MimeType,
StringType.Latin1));
v.Add (ByteVector.TextDelimiter (StringType.Latin1));
if (FileName != null)
v.Add (ByteVector.FromString (FileName,
encoding));
v.Add (ByteVector.TextDelimiter (encoding));
if (Description != null)
v.Add (ByteVector.FromString (Description,
encoding));
v.Add (ByteVector.TextDelimiter (encoding));
v.Add (data);
return v;
}
#endregion
#region ICloneable
/// <summary>
/// Creates a deep copy of the current instance.
/// </summary>
/// <returns>
/// A new <see cref="Frame" /> object identical to the
/// current instance.
/// </returns>
public override Frame Clone ()
{
GeneralEncapsulatedObjectFrame frame =
new GeneralEncapsulatedObjectFrame ();
frame.encoding = encoding;
frame.mime_type = mime_type;
frame.file_name = file_name;
frame.description = description;
if (data != null)
frame.data = new ByteVector (data);
return frame;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.